1 \input texinfo @c -*-texinfo-*-
3 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c GNAT DOCUMENTATION o
9 @c Copyright (C) 1992-2008, AdaCore o
11 @c GNAT is free software; you can redistribute it and/or modify it under o
12 @c terms of the GNU General Public License as published by the Free Soft- o
13 @c ware Foundation; either version 2, or (at your option) any later ver- o
14 @c sion. GNAT is distributed in the hope that it will be useful, but WITH- o
15 @c OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY o
16 @c or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License o
17 @c for more details. You should have received a copy of the GNU General o
18 @c Public License distributed with GNAT; see file COPYING. If not, write o
19 @c to the Free Software Foundation, 51 Franklin Street, Fifth Floor, o
20 @c Boston, MA 02110-1301, USA. o
22 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
24 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
26 @c GNAT_UGN Style Guide
28 @c 1. Always put a @noindent on the line before the first paragraph
29 @c after any of these commands:
41 @c 2. DO NOT use @example. Use @smallexample instead.
42 @c a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
43 @c context. These can interfere with the readability of the texi
44 @c source file. Instead, use one of the following annotated
45 @c @smallexample commands, and preprocess the texi file with the
46 @c ada2texi tool (which generates appropriate highlighting):
47 @c @smallexample @c ada
48 @c @smallexample @c adanocomment
49 @c @smallexample @c projectfile
50 @c b) The "@c ada" markup will result in boldface for reserved words
51 @c and italics for comments
52 @c c) The "@c adanocomment" markup will result only in boldface for
53 @c reserved words (comments are left alone)
54 @c d) The "@c projectfile" markup is like "@c ada" except that the set
55 @c of reserved words include the new reserved words for project files
57 @c 3. Each @chapter, @section, @subsection, @subsubsection, etc.
58 @c command must be preceded by two empty lines
60 @c 4. The @item command should be on a line of its own if it is in an
61 @c @itemize or @enumerate command.
63 @c 5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
66 @c 6. DO NOT put trailing spaces at the end of a line. Such spaces will
67 @c cause the document build to fail.
69 @c 7. DO NOT use @cartouche for examples that are longer than around 10 lines.
70 @c This command inhibits page breaks, so long examples in a @cartouche can
71 @c lead to large, ugly patches of empty space on a page.
73 @c NOTE: This file should be submitted to xgnatugn with either the vms flag
74 @c or the unw flag set. The unw flag covers topics for both Unix and
77 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
79 @setfilename gnat_ugn.info
82 @c This flag is used where the text refers to conditions that exist when the
83 @c text was entered into the document but which may change over time.
84 @c Update the setting for the flag, and (if necessary) the text surrounding,
85 @c the references to the flag, on future doc revisions:
86 @c search for @value{NOW}.
90 @set DEFAULTLANGUAGEVERSION Ada 2005
91 @set NONDEFAULTLANGUAGEVERSION Ada 95
101 @settitle @value{EDITION} User's Guide @value{PLATFORM}
102 @dircategory GNU Ada tools
104 * @value{EDITION} User's Guide (gnat_ugn) @value{PLATFORM}
107 @include gcc-common.texi
109 @setchapternewpage odd
114 Copyright @copyright{} 1995-2005, 2006, 2007, 2008 Free Software Foundation,
117 Permission is granted to copy, distribute and/or modify this document
118 under the terms of the GNU Free Documentation License, Version 1.2
119 or any later version published by the Free Software Foundation;
120 with the Invariant Sections being ``GNU Free Documentation License'', with the
121 Front-Cover Texts being
122 ``@value{EDITION} User's Guide'',
123 and with no Back-Cover Texts.
124 A copy of the license is included in the section entitled
125 ``GNU Free Documentation License''.
129 @title @value{EDITION} User's Guide
133 @titlefont{@i{@value{PLATFORM}}}
139 @subtitle GNAT, The GNU Ada Compiler
144 @vskip 0pt plus 1filll
151 @node Top, About This Guide, (dir), (dir)
152 @top @value{EDITION} User's Guide
155 @value{EDITION} User's Guide @value{PLATFORM}
158 GNAT, The GNU Ada Compiler@*
159 GCC version @value{version-GCC}@*
166 * Getting Started with GNAT::
167 * The GNAT Compilation Model::
168 * Compiling Using gcc::
169 * Binding Using gnatbind::
170 * Linking Using gnatlink::
171 * The GNAT Make Program gnatmake::
172 * Improving Performance::
173 * Renaming Files Using gnatchop::
174 * Configuration Pragmas::
175 * Handling Arbitrary File Naming Conventions Using gnatname::
176 * GNAT Project Manager::
177 * The Cross-Referencing Tools gnatxref and gnatfind::
178 * The GNAT Pretty-Printer gnatpp::
179 * The GNAT Metric Tool gnatmetric::
180 * File Name Krunching Using gnatkr::
181 * Preprocessing Using gnatprep::
183 * The GNAT Run-Time Library Builder gnatlbr::
185 * The GNAT Library Browser gnatls::
186 * Cleaning Up Using gnatclean::
188 * GNAT and Libraries::
189 * Using the GNU make Utility::
191 * Memory Management Issues::
192 * Stack Related Facilities::
193 * Verifying Properties Using gnatcheck::
194 * Creating Sample Bodies Using gnatstub::
195 * Other Utility Programs::
196 * Running and Debugging Ada Programs::
198 * Code Coverage and Profiling::
201 * Compatibility with HP Ada::
203 * Platform-Specific Information for the Run-Time Libraries::
204 * Example of Binder Output File::
205 * Elaboration Order Handling in GNAT::
206 * Conditional Compilation::
208 * Compatibility and Porting Guide::
210 * Microsoft Windows Topics::
212 * GNU Free Documentation License::
215 --- The Detailed Node Listing ---
219 * What This Guide Contains::
220 * What You Should Know before Reading This Guide::
221 * Related Information::
224 Getting Started with GNAT
227 * Running a Simple Ada Program::
228 * Running a Program with Multiple Units::
229 * Using the gnatmake Utility::
231 * Editing with Emacs::
234 * Introduction to GPS::
237 The GNAT Compilation Model
239 * Source Representation::
240 * Foreign Language Representation::
241 * File Naming Rules::
242 * Using Other File Names::
243 * Alternative File Naming Schemes::
244 * Generating Object Files::
245 * Source Dependencies::
246 * The Ada Library Information Files::
247 * Binding an Ada Program::
248 * Mixed Language Programming::
250 * Building Mixed Ada & C++ Programs::
251 * Comparison between GNAT and C/C++ Compilation Models::
253 * Comparison between GNAT and Conventional Ada Library Models::
255 * Placement of temporary files::
258 Foreign Language Representation
261 * Other 8-Bit Codes::
262 * Wide Character Encodings::
264 Compiling Ada Programs With gcc
266 * Compiling Programs::
268 * Search Paths and the Run-Time Library (RTL)::
269 * Order of Compilation Issues::
274 * Output and Error Message Control::
275 * Warning Message Control::
276 * Debugging and Assertion Control::
277 * Validity Checking::
280 * Using gcc for Syntax Checking::
281 * Using gcc for Semantic Checking::
282 * Compiling Different Versions of Ada::
283 * Character Set Control::
284 * File Naming Control::
285 * Subprogram Inlining Control::
286 * Auxiliary Output Control::
287 * Debugging Control::
288 * Exception Handling Control::
289 * Units to Sources Mapping Files::
290 * Integrated Preprocessing::
295 Binding Ada Programs With gnatbind
298 * Switches for gnatbind::
299 * Command-Line Access::
300 * Search Paths for gnatbind::
301 * Examples of gnatbind Usage::
303 Switches for gnatbind
305 * Consistency-Checking Modes::
306 * Binder Error Message Control::
307 * Elaboration Control::
309 * Binding with Non-Ada Main Programs::
310 * Binding Programs with No Main Subprogram::
312 Linking Using gnatlink
315 * Switches for gnatlink::
317 The GNAT Make Program gnatmake
320 * Switches for gnatmake::
321 * Mode Switches for gnatmake::
322 * Notes on the Command Line::
323 * How gnatmake Works::
324 * Examples of gnatmake Usage::
326 Improving Performance
327 * Performance Considerations::
328 * Text_IO Suggestions::
329 * Reducing Size of Ada Executables with gnatelim::
330 * Reducing Size of Executables with unused subprogram/data elimination::
332 Performance Considerations
333 * Controlling Run-Time Checks::
334 * Use of Restrictions::
335 * Optimization Levels::
336 * Debugging Optimized Code::
337 * Inlining of Subprograms::
338 * Other Optimization Switches::
339 * Optimization and Strict Aliasing::
341 * Coverage Analysis::
344 Reducing Size of Ada Executables with gnatelim
347 * Correcting the List of Eliminate Pragmas::
348 * Making Your Executables Smaller::
349 * Summary of the gnatelim Usage Cycle::
351 Reducing Size of Executables with unused subprogram/data elimination
352 * About unused subprogram/data elimination::
353 * Compilation options::
355 Renaming Files Using gnatchop
357 * Handling Files with Multiple Units::
358 * Operating gnatchop in Compilation Mode::
359 * Command Line for gnatchop::
360 * Switches for gnatchop::
361 * Examples of gnatchop Usage::
363 Configuration Pragmas
365 * Handling of Configuration Pragmas::
366 * The Configuration Pragmas Files::
368 Handling Arbitrary File Naming Conventions Using gnatname
370 * Arbitrary File Naming Conventions::
372 * Switches for gnatname::
373 * Examples of gnatname Usage::
378 * Examples of Project Files::
379 * Project File Syntax::
380 * Objects and Sources in Project Files::
381 * Importing Projects::
382 * Project Extension::
383 * Project Hierarchy Extension::
384 * External References in Project Files::
385 * Packages in Project Files::
386 * Variables from Imported Projects::
389 * Stand-alone Library Projects::
390 * Switches Related to Project Files::
391 * Tools Supporting Project Files::
392 * An Extended Example::
393 * Project File Complete Syntax::
395 The Cross-Referencing Tools gnatxref and gnatfind
397 * gnatxref Switches::
398 * gnatfind Switches::
399 * Project Files for gnatxref and gnatfind::
400 * Regular Expressions in gnatfind and gnatxref::
401 * Examples of gnatxref Usage::
402 * Examples of gnatfind Usage::
404 The GNAT Pretty-Printer gnatpp
406 * Switches for gnatpp::
409 The GNAT Metrics Tool gnatmetric
411 * Switches for gnatmetric::
413 File Name Krunching Using gnatkr
418 * Examples of gnatkr Usage::
420 Preprocessing Using gnatprep
421 * Preprocessing Symbols::
423 * Switches for gnatprep::
424 * Form of Definitions File::
425 * Form of Input Text for gnatprep::
428 The GNAT Run-Time Library Builder gnatlbr
431 * Switches for gnatlbr::
432 * Examples of gnatlbr Usage::
435 The GNAT Library Browser gnatls
438 * Switches for gnatls::
439 * Examples of gnatls Usage::
441 Cleaning Up Using gnatclean
443 * Running gnatclean::
444 * Switches for gnatclean::
445 @c * Examples of gnatclean Usage::
451 * Introduction to Libraries in GNAT::
452 * General Ada Libraries::
453 * Stand-alone Ada Libraries::
454 * Rebuilding the GNAT Run-Time Library::
456 Using the GNU make Utility
458 * Using gnatmake in a Makefile::
459 * Automatically Creating a List of Directories::
460 * Generating the Command Line Switches::
461 * Overcoming Command Line Length Limits::
464 Memory Management Issues
466 * Some Useful Memory Pools::
467 * The GNAT Debug Pool Facility::
472 Stack Related Facilities
474 * Stack Overflow Checking::
475 * Static Stack Usage Analysis::
476 * Dynamic Stack Usage Analysis::
478 Some Useful Memory Pools
480 The GNAT Debug Pool Facility
486 * Switches for gnatmem::
487 * Example of gnatmem Usage::
490 Verifying Properties Using gnatcheck
492 * Format of the Report File::
493 * General gnatcheck Switches::
494 * gnatcheck Rule Options::
495 * Adding the Results of Compiler Checks to gnatcheck Output::
496 * Project-Wide Checks::
499 Sample Bodies Using gnatstub
502 * Switches for gnatstub::
504 Other Utility Programs
506 * Using Other Utility Programs with GNAT::
507 * The External Symbol Naming Scheme of GNAT::
508 * Converting Ada Files to html with gnathtml::
511 Code Coverage and Profiling
513 * Code Coverage of Ada Programs using gcov::
514 * Profiling an Ada Program using gprof::
517 Running and Debugging Ada Programs
519 * The GNAT Debugger GDB::
521 * Introduction to GDB Commands::
522 * Using Ada Expressions::
523 * Calling User-Defined Subprograms::
524 * Using the Next Command in a Function::
527 * Debugging Generic Units::
528 * GNAT Abnormal Termination or Failure to Terminate::
529 * Naming Conventions for GNAT Source Files::
530 * Getting Internal Debugging Information::
538 Compatibility with HP Ada
540 * Ada Language Compatibility::
541 * Differences in the Definition of Package System::
542 * Language-Related Features::
543 * The Package STANDARD::
544 * The Package SYSTEM::
545 * Tasking and Task-Related Features::
546 * Pragmas and Pragma-Related Features::
547 * Library of Predefined Units::
549 * Main Program Definition::
550 * Implementation-Defined Attributes::
551 * Compiler and Run-Time Interfacing::
552 * Program Compilation and Library Management::
554 * Implementation Limits::
555 * Tools and Utilities::
557 Language-Related Features
559 * Integer Types and Representations::
560 * Floating-Point Types and Representations::
561 * Pragmas Float_Representation and Long_Float::
562 * Fixed-Point Types and Representations::
563 * Record and Array Component Alignment::
565 * Other Representation Clauses::
567 Tasking and Task-Related Features
569 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
570 * Assigning Task IDs::
571 * Task IDs and Delays::
572 * Task-Related Pragmas::
573 * Scheduling and Task Priority::
575 * External Interrupts::
577 Pragmas and Pragma-Related Features
579 * Restrictions on the Pragma INLINE::
580 * Restrictions on the Pragma INTERFACE::
581 * Restrictions on the Pragma SYSTEM_NAME::
583 Library of Predefined Units
585 * Changes to DECLIB::
589 * Shared Libraries and Options Files::
593 Platform-Specific Information for the Run-Time Libraries
595 * Summary of Run-Time Configurations::
596 * Specifying a Run-Time Library::
597 * Choosing the Scheduling Policy::
598 * Solaris-Specific Considerations::
599 * Linux-Specific Considerations::
600 * AIX-Specific Considerations::
601 * Irix-Specific Considerations::
603 Example of Binder Output File
605 Elaboration Order Handling in GNAT
608 * Checking the Elaboration Order::
609 * Controlling the Elaboration Order::
610 * Controlling Elaboration in GNAT - Internal Calls::
611 * Controlling Elaboration in GNAT - External Calls::
612 * Default Behavior in GNAT - Ensuring Safety::
613 * Treatment of Pragma Elaborate::
614 * Elaboration Issues for Library Tasks::
615 * Mixing Elaboration Models::
616 * What to Do If the Default Elaboration Behavior Fails::
617 * Elaboration for Access-to-Subprogram Values::
618 * Summary of Procedures for Elaboration Control::
619 * Other Elaboration Order Considerations::
621 Conditional Compilation
622 * Use of Boolean Constants::
623 * Debugging - A Special Case::
624 * Conditionalizing Declarations::
625 * Use of Alternative Implementations::
630 * Basic Assembler Syntax::
631 * A Simple Example of Inline Assembler::
632 * Output Variables in Inline Assembler::
633 * Input Variables in Inline Assembler::
634 * Inlining Inline Assembler Code::
635 * Other Asm Functionality::
637 Compatibility and Porting Guide
639 * Compatibility with Ada 83::
640 * Compatibility between Ada 95 and Ada 2005::
641 * Implementation-dependent characteristics::
643 @c This brief section is only in the non-VMS version
644 @c The complete chapter on HP Ada issues is in the VMS version
645 * Compatibility with HP Ada 83::
647 * Compatibility with Other Ada Systems::
648 * Representation Clauses::
650 * Transitioning to 64-Bit GNAT for OpenVMS::
654 Microsoft Windows Topics
656 * Using GNAT on Windows::
657 * CONSOLE and WINDOWS subsystems::
659 * Mixed-Language Programming on Windows::
660 * Windows Calling Conventions::
661 * Introduction to Dynamic Link Libraries (DLLs)::
662 * Using DLLs with GNAT::
663 * Building DLLs with GNAT::
664 * GNAT and Windows Resources::
666 * Setting Stack Size from gnatlink::
667 * Setting Heap Size from gnatlink::
674 @node About This Guide
675 @unnumbered About This Guide
679 This guide describes the use of @value{EDITION},
680 a compiler and software development toolset for the full Ada
681 programming language, implemented on OpenVMS for HP's Alpha and
682 Integrity server (I64) platforms.
685 This guide describes the use of @value{EDITION},
686 a compiler and software development
687 toolset for the full Ada programming language.
689 It documents the features of the compiler and tools, and explains
690 how to use them to build Ada applications.
692 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
693 Ada 83 compatibility mode.
694 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
695 but you can override with a compiler switch
696 (@pxref{Compiling Different Versions of Ada})
697 to explicitly specify the language version.
698 Throughout this manual, references to ``Ada'' without a year suffix
699 apply to both the Ada 95 and Ada 2005 versions of the language.
703 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
704 ``GNAT'' in the remainder of this document.
711 * What This Guide Contains::
712 * What You Should Know before Reading This Guide::
713 * Related Information::
717 @node What This Guide Contains
718 @unnumberedsec What This Guide Contains
721 This guide contains the following chapters:
725 @ref{Getting Started with GNAT}, describes how to get started compiling
726 and running Ada programs with the GNAT Ada programming environment.
728 @ref{The GNAT Compilation Model}, describes the compilation model used
732 @ref{Compiling Using gcc}, describes how to compile
733 Ada programs with @command{gcc}, the Ada compiler.
736 @ref{Binding Using gnatbind}, describes how to
737 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
741 @ref{Linking Using gnatlink},
742 describes @command{gnatlink}, a
743 program that provides for linking using the GNAT run-time library to
744 construct a program. @command{gnatlink} can also incorporate foreign language
745 object units into the executable.
748 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
749 utility that automatically determines the set of sources
750 needed by an Ada compilation unit, and executes the necessary compilations
754 @ref{Improving Performance}, shows various techniques for making your
755 Ada program run faster or take less space.
756 It discusses the effect of the compiler's optimization switch and
757 also describes the @command{gnatelim} tool and unused subprogram/data
761 @ref{Renaming Files Using gnatchop}, describes
762 @code{gnatchop}, a utility that allows you to preprocess a file that
763 contains Ada source code, and split it into one or more new files, one
764 for each compilation unit.
767 @ref{Configuration Pragmas}, describes the configuration pragmas
771 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
772 shows how to override the default GNAT file naming conventions,
773 either for an individual unit or globally.
776 @ref{GNAT Project Manager}, describes how to use project files
777 to organize large projects.
780 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
781 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
782 way to navigate through sources.
785 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
786 version of an Ada source file with control over casing, indentation,
787 comment placement, and other elements of program presentation style.
790 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
791 metrics for an Ada source file, such as the number of types and subprograms,
792 and assorted complexity measures.
795 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
796 file name krunching utility, used to handle shortened
797 file names on operating systems with a limit on the length of names.
800 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
801 preprocessor utility that allows a single source file to be used to
802 generate multiple or parameterized source files by means of macro
807 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
808 a tool for rebuilding the GNAT run time with user-supplied
809 configuration pragmas.
813 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
814 utility that displays information about compiled units, including dependences
815 on the corresponding sources files, and consistency of compilations.
818 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
819 to delete files that are produced by the compiler, binder and linker.
823 @ref{GNAT and Libraries}, describes the process of creating and using
824 Libraries with GNAT. It also describes how to recompile the GNAT run-time
828 @ref{Using the GNU make Utility}, describes some techniques for using
829 the GNAT toolset in Makefiles.
833 @ref{Memory Management Issues}, describes some useful predefined storage pools
834 and in particular the GNAT Debug Pool facility, which helps detect incorrect
837 It also describes @command{gnatmem}, a utility that monitors dynamic
838 allocation and deallocation and helps detect ``memory leaks''.
842 @ref{Stack Related Facilities}, describes some useful tools associated with
843 stack checking and analysis.
846 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
847 a utility that checks Ada code against a set of rules.
850 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
851 a utility that generates empty but compilable bodies for library units.
854 @ref{Other Utility Programs}, discusses several other GNAT utilities,
855 including @code{gnathtml}.
859 @ref{Code Coverage and Profiling}, describes how to perform a structural
860 coverage and profile the execution of Ada programs.
864 @ref{Running and Debugging Ada Programs}, describes how to run and debug
869 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
870 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
871 developed by Digital Equipment Corporation and currently supported by HP.}
872 for OpenVMS Alpha. This product was formerly known as DEC Ada,
875 historical compatibility reasons, the relevant libraries still use the
880 @ref{Platform-Specific Information for the Run-Time Libraries},
881 describes the various run-time
882 libraries supported by GNAT on various platforms and explains how to
883 choose a particular library.
886 @ref{Example of Binder Output File}, shows the source code for the binder
887 output file for a sample program.
890 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
891 you deal with elaboration order issues.
894 @ref{Conditional Compilation}, describes how to model conditional compilation,
895 both with Ada in general and with GNAT facilities in particular.
898 @ref{Inline Assembler}, shows how to use the inline assembly facility
902 @ref{Compatibility and Porting Guide}, contains sections on compatibility
903 of GNAT with other Ada development environments (including Ada 83 systems),
904 to assist in porting code from those environments.
908 @ref{Microsoft Windows Topics}, presents information relevant to the
909 Microsoft Windows platform.
913 @c *************************************************
914 @node What You Should Know before Reading This Guide
915 @c *************************************************
916 @unnumberedsec What You Should Know before Reading This Guide
918 @cindex Ada 95 Language Reference Manual
919 @cindex Ada 2005 Language Reference Manual
921 This guide assumes a basic familiarity with the Ada 95 language, as
922 described in the International Standard ANSI/ISO/IEC-8652:1995, January
924 It does not require knowledge of the new features introduced by Ada 2005,
925 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
927 Both reference manuals are included in the GNAT documentation
930 @node Related Information
931 @unnumberedsec Related Information
934 For further information about related tools, refer to the following
939 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
940 Reference Manual}, which contains all reference material for the GNAT
941 implementation of Ada.
945 @cite{Using the GNAT Programming Studio}, which describes the GPS
946 Integrated Development Environment.
949 @cite{GNAT Programming Studio Tutorial}, which introduces the
950 main GPS features through examples.
954 @cite{Ada 95 Reference Manual}, which contains reference
955 material for the Ada 95 programming language.
958 @cite{Ada 2005 Reference Manual}, which contains reference
959 material for the Ada 2005 programming language.
962 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
964 in the GNU:[DOCS] directory,
966 for all details on the use of the GNU source-level debugger.
969 @xref{Top,, The extensible self-documenting text editor, emacs,
972 located in the GNU:[DOCS] directory if the EMACS kit is installed,
974 for full information on the extensible editor and programming
981 @unnumberedsec Conventions
983 @cindex Typographical conventions
986 Following are examples of the typographical and graphic conventions used
991 @code{Functions}, @command{utility program names}, @code{standard names},
995 @option{Option flags}
998 @file{File names}, @samp{button names}, and @samp{field names}.
1001 @code{Variables}, @env{environment variables}, and @var{metasyntactic
1008 [optional information or parameters]
1011 Examples are described by text
1013 and then shown this way.
1018 Commands that are entered by the user are preceded in this manual by the
1019 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1020 uses this sequence as a prompt, then the commands will appear exactly as
1021 you see them in the manual. If your system uses some other prompt, then
1022 the command will appear with the @code{$} replaced by whatever prompt
1023 character you are using.
1026 Full file names are shown with the ``@code{/}'' character
1027 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1028 If you are using GNAT on a Windows platform, please note that
1029 the ``@code{\}'' character should be used instead.
1032 @c ****************************
1033 @node Getting Started with GNAT
1034 @chapter Getting Started with GNAT
1037 This chapter describes some simple ways of using GNAT to build
1038 executable Ada programs.
1040 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1041 show how to use the command line environment.
1042 @ref{Introduction to GPS}, provides a brief
1043 introduction to the GNAT Programming Studio, a visually-oriented
1044 Integrated Development Environment for GNAT.
1045 GPS offers a graphical ``look and feel'', support for development in
1046 other programming languages, comprehensive browsing features, and
1047 many other capabilities.
1048 For information on GPS please refer to
1049 @cite{Using the GNAT Programming Studio}.
1054 * Running a Simple Ada Program::
1055 * Running a Program with Multiple Units::
1056 * Using the gnatmake Utility::
1058 * Editing with Emacs::
1061 * Introduction to GPS::
1066 @section Running GNAT
1069 Three steps are needed to create an executable file from an Ada source
1074 The source file(s) must be compiled.
1076 The file(s) must be bound using the GNAT binder.
1078 All appropriate object files must be linked to produce an executable.
1082 All three steps are most commonly handled by using the @command{gnatmake}
1083 utility program that, given the name of the main program, automatically
1084 performs the necessary compilation, binding and linking steps.
1086 @node Running a Simple Ada Program
1087 @section Running a Simple Ada Program
1090 Any text editor may be used to prepare an Ada program.
1092 used, the optional Ada mode may be helpful in laying out the program.)
1094 program text is a normal text file. We will assume in our initial
1095 example that you have used your editor to prepare the following
1096 standard format text file:
1098 @smallexample @c ada
1100 with Ada.Text_IO; use Ada.Text_IO;
1103 Put_Line ("Hello WORLD!");
1109 This file should be named @file{hello.adb}.
1110 With the normal default file naming conventions, GNAT requires
1112 contain a single compilation unit whose file name is the
1114 with periods replaced by hyphens; the
1115 extension is @file{ads} for a
1116 spec and @file{adb} for a body.
1117 You can override this default file naming convention by use of the
1118 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1119 Alternatively, if you want to rename your files according to this default
1120 convention, which is probably more convenient if you will be using GNAT
1121 for all your compilations, then the @code{gnatchop} utility
1122 can be used to generate correctly-named source files
1123 (@pxref{Renaming Files Using gnatchop}).
1125 You can compile the program using the following command (@code{$} is used
1126 as the command prompt in the examples in this document):
1133 @command{gcc} is the command used to run the compiler. This compiler is
1134 capable of compiling programs in several languages, including Ada and
1135 C. It assumes that you have given it an Ada program if the file extension is
1136 either @file{.ads} or @file{.adb}, and it will then call
1137 the GNAT compiler to compile the specified file.
1140 The @option{-c} switch is required. It tells @command{gcc} to only do a
1141 compilation. (For C programs, @command{gcc} can also do linking, but this
1142 capability is not used directly for Ada programs, so the @option{-c}
1143 switch must always be present.)
1146 This compile command generates a file
1147 @file{hello.o}, which is the object
1148 file corresponding to your Ada program. It also generates
1149 an ``Ada Library Information'' file @file{hello.ali},
1150 which contains additional information used to check
1151 that an Ada program is consistent.
1152 To build an executable file,
1153 use @code{gnatbind} to bind the program
1154 and @command{gnatlink} to link it. The
1155 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1156 @file{ALI} file, but the default extension of @file{.ali} can
1157 be omitted. This means that in the most common case, the argument
1158 is simply the name of the main program:
1166 A simpler method of carrying out these steps is to use
1168 a master program that invokes all the required
1169 compilation, binding and linking tools in the correct order. In particular,
1170 @command{gnatmake} automatically recompiles any sources that have been
1171 modified since they were last compiled, or sources that depend
1172 on such modified sources, so that ``version skew'' is avoided.
1173 @cindex Version skew (avoided by @command{gnatmake})
1176 $ gnatmake hello.adb
1180 The result is an executable program called @file{hello}, which can be
1188 assuming that the current directory is on the search path
1189 for executable programs.
1192 and, if all has gone well, you will see
1199 appear in response to this command.
1201 @c ****************************************
1202 @node Running a Program with Multiple Units
1203 @section Running a Program with Multiple Units
1206 Consider a slightly more complicated example that has three files: a
1207 main program, and the spec and body of a package:
1209 @smallexample @c ada
1212 package Greetings is
1217 with Ada.Text_IO; use Ada.Text_IO;
1218 package body Greetings is
1221 Put_Line ("Hello WORLD!");
1224 procedure Goodbye is
1226 Put_Line ("Goodbye WORLD!");
1243 Following the one-unit-per-file rule, place this program in the
1244 following three separate files:
1248 spec of package @code{Greetings}
1251 body of package @code{Greetings}
1254 body of main program
1258 To build an executable version of
1259 this program, we could use four separate steps to compile, bind, and link
1260 the program, as follows:
1264 $ gcc -c greetings.adb
1270 Note that there is no required order of compilation when using GNAT.
1271 In particular it is perfectly fine to compile the main program first.
1272 Also, it is not necessary to compile package specs in the case where
1273 there is an accompanying body; you only need to compile the body. If you want
1274 to submit these files to the compiler for semantic checking and not code
1275 generation, then use the
1276 @option{-gnatc} switch:
1279 $ gcc -c greetings.ads -gnatc
1283 Although the compilation can be done in separate steps as in the
1284 above example, in practice it is almost always more convenient
1285 to use the @command{gnatmake} tool. All you need to know in this case
1286 is the name of the main program's source file. The effect of the above four
1287 commands can be achieved with a single one:
1290 $ gnatmake gmain.adb
1294 In the next section we discuss the advantages of using @command{gnatmake} in
1297 @c *****************************
1298 @node Using the gnatmake Utility
1299 @section Using the @command{gnatmake} Utility
1302 If you work on a program by compiling single components at a time using
1303 @command{gcc}, you typically keep track of the units you modify. In order to
1304 build a consistent system, you compile not only these units, but also any
1305 units that depend on the units you have modified.
1306 For example, in the preceding case,
1307 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1308 you edit @file{greetings.ads}, you must recompile both
1309 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1310 units that depend on @file{greetings.ads}.
1312 @code{gnatbind} will warn you if you forget one of these compilation
1313 steps, so that it is impossible to generate an inconsistent program as a
1314 result of forgetting to do a compilation. Nevertheless it is tedious and
1315 error-prone to keep track of dependencies among units.
1316 One approach to handle the dependency-bookkeeping is to use a
1317 makefile. However, makefiles present maintenance problems of their own:
1318 if the dependencies change as you change the program, you must make
1319 sure that the makefile is kept up-to-date manually, which is also an
1320 error-prone process.
1322 The @command{gnatmake} utility takes care of these details automatically.
1323 Invoke it using either one of the following forms:
1326 $ gnatmake gmain.adb
1327 $ gnatmake ^gmain^GMAIN^
1331 The argument is the name of the file containing the main program;
1332 you may omit the extension. @command{gnatmake}
1333 examines the environment, automatically recompiles any files that need
1334 recompiling, and binds and links the resulting set of object files,
1335 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1336 In a large program, it
1337 can be extremely helpful to use @command{gnatmake}, because working out by hand
1338 what needs to be recompiled can be difficult.
1340 Note that @command{gnatmake}
1341 takes into account all the Ada rules that
1342 establish dependencies among units. These include dependencies that result
1343 from inlining subprogram bodies, and from
1344 generic instantiation. Unlike some other
1345 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1346 found by the compiler on a previous compilation, which may possibly
1347 be wrong when sources change. @command{gnatmake} determines the exact set of
1348 dependencies from scratch each time it is run.
1351 @node Editing with Emacs
1352 @section Editing with Emacs
1356 Emacs is an extensible self-documenting text editor that is available in a
1357 separate VMSINSTAL kit.
1359 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1360 click on the Emacs Help menu and run the Emacs Tutorial.
1361 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1362 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1364 Documentation on Emacs and other tools is available in Emacs under the
1365 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1366 use the middle mouse button to select a topic (e.g.@: Emacs).
1368 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1369 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1370 get to the Emacs manual.
1371 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1374 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1375 which is sufficiently extensible to provide for a complete programming
1376 environment and shell for the sophisticated user.
1380 @node Introduction to GPS
1381 @section Introduction to GPS
1382 @cindex GPS (GNAT Programming Studio)
1383 @cindex GNAT Programming Studio (GPS)
1385 Although the command line interface (@command{gnatmake}, etc.) alone
1386 is sufficient, a graphical Interactive Development
1387 Environment can make it easier for you to compose, navigate, and debug
1388 programs. This section describes the main features of GPS
1389 (``GNAT Programming Studio''), the GNAT graphical IDE.
1390 You will see how to use GPS to build and debug an executable, and
1391 you will also learn some of the basics of the GNAT ``project'' facility.
1393 GPS enables you to do much more than is presented here;
1394 e.g., you can produce a call graph, interface to a third-party
1395 Version Control System, and inspect the generated assembly language
1397 Indeed, GPS also supports languages other than Ada.
1398 Such additional information, and an explanation of all of the GPS menu
1399 items. may be found in the on-line help, which includes
1400 a user's guide and a tutorial (these are also accessible from the GNAT
1404 * Building a New Program with GPS::
1405 * Simple Debugging with GPS::
1408 @node Building a New Program with GPS
1409 @subsection Building a New Program with GPS
1411 GPS invokes the GNAT compilation tools using information
1412 contained in a @emph{project} (also known as a @emph{project file}):
1413 a collection of properties such
1414 as source directories, identities of main subprograms, tool switches, etc.,
1415 and their associated values.
1416 See @ref{GNAT Project Manager} for details.
1417 In order to run GPS, you will need to either create a new project
1418 or else open an existing one.
1420 This section will explain how you can use GPS to create a project,
1421 to associate Ada source files with a project, and to build and run
1425 @item @emph{Creating a project}
1427 Invoke GPS, either from the command line or the platform's IDE.
1428 After it starts, GPS will display a ``Welcome'' screen with three
1433 @code{Start with default project in directory}
1436 @code{Create new project with wizard}
1439 @code{Open existing project}
1443 Select @code{Create new project with wizard} and press @code{OK}.
1444 A new window will appear. In the text box labeled with
1445 @code{Enter the name of the project to create}, type @file{sample}
1446 as the project name.
1447 In the next box, browse to choose the directory in which you
1448 would like to create the project file.
1449 After selecting an appropriate directory, press @code{Forward}.
1451 A window will appear with the title
1452 @code{Version Control System Configuration}.
1453 Simply press @code{Forward}.
1455 A window will appear with the title
1456 @code{Please select the source directories for this project}.
1457 The directory that you specified for the project file will be selected
1458 by default as the one to use for sources; simply press @code{Forward}.
1460 A window will appear with the title
1461 @code{Please select the build directory for this project}.
1462 The directory that you specified for the project file will be selected
1463 by default for object files and executables;
1464 simply press @code{Forward}.
1466 A window will appear with the title
1467 @code{Please select the main units for this project}.
1468 You will supply this information later, after creating the source file.
1469 Simply press @code{Forward} for now.
1471 A window will appear with the title
1472 @code{Please select the switches to build the project}.
1473 Press @code{Apply}. This will create a project file named
1474 @file{sample.prj} in the directory that you had specified.
1476 @item @emph{Creating and saving the source file}
1478 After you create the new project, a GPS window will appear, which is
1479 partitioned into two main sections:
1483 A @emph{Workspace area}, initially greyed out, which you will use for
1484 creating and editing source files
1487 Directly below, a @emph{Messages area}, which initially displays a
1488 ``Welcome'' message.
1489 (If the Messages area is not visible, drag its border upward to expand it.)
1493 Select @code{File} on the menu bar, and then the @code{New} command.
1494 The Workspace area will become white, and you can now
1495 enter the source program explicitly.
1496 Type the following text
1498 @smallexample @c ada
1500 with Ada.Text_IO; use Ada.Text_IO;
1503 Put_Line("Hello from GPS!");
1509 Select @code{File}, then @code{Save As}, and enter the source file name
1511 The file will be saved in the same directory you specified as the
1512 location of the default project file.
1514 @item @emph{Updating the project file}
1516 You need to add the new source file to the project.
1518 the @code{Project} menu and then @code{Edit project properties}.
1519 Click the @code{Main files} tab on the left, and then the
1521 Choose @file{hello.adb} from the list, and press @code{Open}.
1522 The project settings window will reflect this action.
1525 @item @emph{Building and running the program}
1527 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1528 and select @file{hello.adb}.
1529 The Messages window will display the resulting invocations of @command{gcc},
1530 @command{gnatbind}, and @command{gnatlink}
1531 (reflecting the default switch settings from the
1532 project file that you created) and then a ``successful compilation/build''
1535 To run the program, choose the @code{Build} menu, then @code{Run}, and
1536 select @command{hello}.
1537 An @emph{Arguments Selection} window will appear.
1538 There are no command line arguments, so just click @code{OK}.
1540 The Messages window will now display the program's output (the string
1541 @code{Hello from GPS}), and at the bottom of the GPS window a status
1542 update is displayed (@code{Run: hello}).
1543 Close the GPS window (or select @code{File}, then @code{Exit}) to
1544 terminate this GPS session.
1547 @node Simple Debugging with GPS
1548 @subsection Simple Debugging with GPS
1550 This section illustrates basic debugging techniques (setting breakpoints,
1551 examining/modifying variables, single stepping).
1554 @item @emph{Opening a project}
1556 Start GPS and select @code{Open existing project}; browse to
1557 specify the project file @file{sample.prj} that you had created in the
1560 @item @emph{Creating a source file}
1562 Select @code{File}, then @code{New}, and type in the following program:
1564 @smallexample @c ada
1566 with Ada.Text_IO; use Ada.Text_IO;
1567 procedure Example is
1568 Line : String (1..80);
1571 Put_Line("Type a line of text at each prompt; an empty line to exit");
1575 Put_Line (Line (1..N) );
1583 Select @code{File}, then @code{Save as}, and enter the file name
1586 @item @emph{Updating the project file}
1588 Add @code{Example} as a new main unit for the project:
1591 Select @code{Project}, then @code{Edit Project Properties}.
1594 Select the @code{Main files} tab, click @code{Add}, then
1595 select the file @file{example.adb} from the list, and
1597 You will see the file name appear in the list of main units
1603 @item @emph{Building/running the executable}
1605 To build the executable
1606 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1608 Run the program to see its effect (in the Messages area).
1609 Each line that you enter is displayed; an empty line will
1610 cause the loop to exit and the program to terminate.
1612 @item @emph{Debugging the program}
1614 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1615 which are required for debugging, are on by default when you create
1617 Thus unless you intentionally remove these settings, you will be able
1618 to debug any program that you develop using GPS.
1621 @item @emph{Initializing}
1623 Select @code{Debug}, then @code{Initialize}, then @file{example}
1625 @item @emph{Setting a breakpoint}
1627 After performing the initialization step, you will observe a small
1628 icon to the right of each line number.
1629 This serves as a toggle for breakpoints; clicking the icon will
1630 set a breakpoint at the corresponding line (the icon will change to
1631 a red circle with an ``x''), and clicking it again
1632 will remove the breakpoint / reset the icon.
1634 For purposes of this example, set a breakpoint at line 10 (the
1635 statement @code{Put_Line@ (Line@ (1..N));}
1637 @item @emph{Starting program execution}
1639 Select @code{Debug}, then @code{Run}. When the
1640 @code{Program Arguments} window appears, click @code{OK}.
1641 A console window will appear; enter some line of text,
1642 e.g.@: @code{abcde}, at the prompt.
1643 The program will pause execution when it gets to the
1644 breakpoint, and the corresponding line is highlighted.
1646 @item @emph{Examining a variable}
1648 Move the mouse over one of the occurrences of the variable @code{N}.
1649 You will see the value (5) displayed, in ``tool tip'' fashion.
1650 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1651 You will see information about @code{N} appear in the @code{Debugger Data}
1652 pane, showing the value as 5.
1654 @item @emph{Assigning a new value to a variable}
1656 Right click on the @code{N} in the @code{Debugger Data} pane, and
1657 select @code{Set value of N}.
1658 When the input window appears, enter the value @code{4} and click
1660 This value does not automatically appear in the @code{Debugger Data}
1661 pane; to see it, right click again on the @code{N} in the
1662 @code{Debugger Data} pane and select @code{Update value}.
1663 The new value, 4, will appear in red.
1665 @item @emph{Single stepping}
1667 Select @code{Debug}, then @code{Next}.
1668 This will cause the next statement to be executed, in this case the
1669 call of @code{Put_Line} with the string slice.
1670 Notice in the console window that the displayed string is simply
1671 @code{abcd} and not @code{abcde} which you had entered.
1672 This is because the upper bound of the slice is now 4 rather than 5.
1674 @item @emph{Removing a breakpoint}
1676 Toggle the breakpoint icon at line 10.
1678 @item @emph{Resuming execution from a breakpoint}
1680 Select @code{Debug}, then @code{Continue}.
1681 The program will reach the next iteration of the loop, and
1682 wait for input after displaying the prompt.
1683 This time, just hit the @kbd{Enter} key.
1684 The value of @code{N} will be 0, and the program will terminate.
1685 The console window will disappear.
1690 @node The GNAT Compilation Model
1691 @chapter The GNAT Compilation Model
1692 @cindex GNAT compilation model
1693 @cindex Compilation model
1696 * Source Representation::
1697 * Foreign Language Representation::
1698 * File Naming Rules::
1699 * Using Other File Names::
1700 * Alternative File Naming Schemes::
1701 * Generating Object Files::
1702 * Source Dependencies::
1703 * The Ada Library Information Files::
1704 * Binding an Ada Program::
1705 * Mixed Language Programming::
1707 * Building Mixed Ada & C++ Programs::
1708 * Comparison between GNAT and C/C++ Compilation Models::
1710 * Comparison between GNAT and Conventional Ada Library Models::
1712 * Placement of temporary files::
1717 This chapter describes the compilation model used by GNAT. Although
1718 similar to that used by other languages, such as C and C++, this model
1719 is substantially different from the traditional Ada compilation models,
1720 which are based on a library. The model is initially described without
1721 reference to the library-based model. If you have not previously used an
1722 Ada compiler, you need only read the first part of this chapter. The
1723 last section describes and discusses the differences between the GNAT
1724 model and the traditional Ada compiler models. If you have used other
1725 Ada compilers, this section will help you to understand those
1726 differences, and the advantages of the GNAT model.
1728 @node Source Representation
1729 @section Source Representation
1733 Ada source programs are represented in standard text files, using
1734 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1735 7-bit ASCII set, plus additional characters used for
1736 representing foreign languages (@pxref{Foreign Language Representation}
1737 for support of non-USA character sets). The format effector characters
1738 are represented using their standard ASCII encodings, as follows:
1743 Vertical tab, @code{16#0B#}
1747 Horizontal tab, @code{16#09#}
1751 Carriage return, @code{16#0D#}
1755 Line feed, @code{16#0A#}
1759 Form feed, @code{16#0C#}
1763 Source files are in standard text file format. In addition, GNAT will
1764 recognize a wide variety of stream formats, in which the end of
1765 physical lines is marked by any of the following sequences:
1766 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1767 in accommodating files that are imported from other operating systems.
1769 @cindex End of source file
1770 @cindex Source file, end
1772 The end of a source file is normally represented by the physical end of
1773 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1774 recognized as signalling the end of the source file. Again, this is
1775 provided for compatibility with other operating systems where this
1776 code is used to represent the end of file.
1778 Each file contains a single Ada compilation unit, including any pragmas
1779 associated with the unit. For example, this means you must place a
1780 package declaration (a package @dfn{spec}) and the corresponding body in
1781 separate files. An Ada @dfn{compilation} (which is a sequence of
1782 compilation units) is represented using a sequence of files. Similarly,
1783 you will place each subunit or child unit in a separate file.
1785 @node Foreign Language Representation
1786 @section Foreign Language Representation
1789 GNAT supports the standard character sets defined in Ada as well as
1790 several other non-standard character sets for use in localized versions
1791 of the compiler (@pxref{Character Set Control}).
1794 * Other 8-Bit Codes::
1795 * Wide Character Encodings::
1803 The basic character set is Latin-1. This character set is defined by ISO
1804 standard 8859, part 1. The lower half (character codes @code{16#00#}
1805 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1806 is used to represent additional characters. These include extended letters
1807 used by European languages, such as French accents, the vowels with umlauts
1808 used in German, and the extra letter A-ring used in Swedish.
1810 @findex Ada.Characters.Latin_1
1811 For a complete list of Latin-1 codes and their encodings, see the source
1812 file of library unit @code{Ada.Characters.Latin_1} in file
1813 @file{a-chlat1.ads}.
1814 You may use any of these extended characters freely in character or
1815 string literals. In addition, the extended characters that represent
1816 letters can be used in identifiers.
1818 @node Other 8-Bit Codes
1819 @subsection Other 8-Bit Codes
1822 GNAT also supports several other 8-bit coding schemes:
1825 @item ISO 8859-2 (Latin-2)
1828 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1831 @item ISO 8859-3 (Latin-3)
1834 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1837 @item ISO 8859-4 (Latin-4)
1840 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1843 @item ISO 8859-5 (Cyrillic)
1846 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1847 lowercase equivalence.
1849 @item ISO 8859-15 (Latin-9)
1852 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1853 lowercase equivalence
1855 @item IBM PC (code page 437)
1856 @cindex code page 437
1857 This code page is the normal default for PCs in the U.S. It corresponds
1858 to the original IBM PC character set. This set has some, but not all, of
1859 the extended Latin-1 letters, but these letters do not have the same
1860 encoding as Latin-1. In this mode, these letters are allowed in
1861 identifiers with uppercase and lowercase equivalence.
1863 @item IBM PC (code page 850)
1864 @cindex code page 850
1865 This code page is a modification of 437 extended to include all the
1866 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1867 mode, all these letters are allowed in identifiers with uppercase and
1868 lowercase equivalence.
1870 @item Full Upper 8-bit
1871 Any character in the range 80-FF allowed in identifiers, and all are
1872 considered distinct. In other words, there are no uppercase and lowercase
1873 equivalences in this range. This is useful in conjunction with
1874 certain encoding schemes used for some foreign character sets (e.g.,
1875 the typical method of representing Chinese characters on the PC).
1878 No upper-half characters in the range 80-FF are allowed in identifiers.
1879 This gives Ada 83 compatibility for identifier names.
1883 For precise data on the encodings permitted, and the uppercase and lowercase
1884 equivalences that are recognized, see the file @file{csets.adb} in
1885 the GNAT compiler sources. You will need to obtain a full source release
1886 of GNAT to obtain this file.
1888 @node Wide Character Encodings
1889 @subsection Wide Character Encodings
1892 GNAT allows wide character codes to appear in character and string
1893 literals, and also optionally in identifiers, by means of the following
1894 possible encoding schemes:
1899 In this encoding, a wide character is represented by the following five
1907 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1908 characters (using uppercase letters) of the wide character code. For
1909 example, ESC A345 is used to represent the wide character with code
1911 This scheme is compatible with use of the full Wide_Character set.
1913 @item Upper-Half Coding
1914 @cindex Upper-Half Coding
1915 The wide character with encoding @code{16#abcd#} where the upper bit is on
1916 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1917 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1918 character, but is not required to be in the upper half. This method can
1919 be also used for shift-JIS or EUC, where the internal coding matches the
1922 @item Shift JIS Coding
1923 @cindex Shift JIS Coding
1924 A wide character is represented by a two-character sequence,
1926 @code{16#cd#}, with the restrictions described for upper-half encoding as
1927 described above. The internal character code is the corresponding JIS
1928 character according to the standard algorithm for Shift-JIS
1929 conversion. Only characters defined in the JIS code set table can be
1930 used with this encoding method.
1934 A wide character is represented by a two-character sequence
1936 @code{16#cd#}, with both characters being in the upper half. The internal
1937 character code is the corresponding JIS character according to the EUC
1938 encoding algorithm. Only characters defined in the JIS code set table
1939 can be used with this encoding method.
1942 A wide character is represented using
1943 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1944 10646-1/Am.2. Depending on the character value, the representation
1945 is a one, two, or three byte sequence:
1950 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1951 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1952 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1957 where the @var{xxx} bits correspond to the left-padded bits of the
1958 16-bit character value. Note that all lower half ASCII characters
1959 are represented as ASCII bytes and all upper half characters and
1960 other wide characters are represented as sequences of upper-half
1961 (The full UTF-8 scheme allows for encoding 31-bit characters as
1962 6-byte sequences, but in this implementation, all UTF-8 sequences
1963 of four or more bytes length will be treated as illegal).
1964 @item Brackets Coding
1965 In this encoding, a wide character is represented by the following eight
1973 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1974 characters (using uppercase letters) of the wide character code. For
1975 example, [``A345''] is used to represent the wide character with code
1976 @code{16#A345#}. It is also possible (though not required) to use the
1977 Brackets coding for upper half characters. For example, the code
1978 @code{16#A3#} can be represented as @code{[``A3'']}.
1980 This scheme is compatible with use of the full Wide_Character set,
1981 and is also the method used for wide character encoding in the standard
1982 ACVC (Ada Compiler Validation Capability) test suite distributions.
1987 Note: Some of these coding schemes do not permit the full use of the
1988 Ada character set. For example, neither Shift JIS, nor EUC allow the
1989 use of the upper half of the Latin-1 set.
1991 @node File Naming Rules
1992 @section File Naming Rules
1995 The default file name is determined by the name of the unit that the
1996 file contains. The name is formed by taking the full expanded name of
1997 the unit and replacing the separating dots with hyphens and using
1998 ^lowercase^uppercase^ for all letters.
2000 An exception arises if the file name generated by the above rules starts
2001 with one of the characters
2003 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
2006 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
2008 and the second character is a
2009 minus. In this case, the character ^tilde^dollar sign^ is used in place
2010 of the minus. The reason for this special rule is to avoid clashes with
2011 the standard names for child units of the packages System, Ada,
2012 Interfaces, and GNAT, which use the prefixes
2014 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2017 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
2021 The file extension is @file{.ads} for a spec and
2022 @file{.adb} for a body. The following list shows some
2023 examples of these rules.
2030 @item arith_functions.ads
2031 Arith_Functions (package spec)
2032 @item arith_functions.adb
2033 Arith_Functions (package body)
2035 Func.Spec (child package spec)
2037 Func.Spec (child package body)
2039 Sub (subunit of Main)
2040 @item ^a~bad.adb^A$BAD.ADB^
2041 A.Bad (child package body)
2045 Following these rules can result in excessively long
2046 file names if corresponding
2047 unit names are long (for example, if child units or subunits are
2048 heavily nested). An option is available to shorten such long file names
2049 (called file name ``krunching''). This may be particularly useful when
2050 programs being developed with GNAT are to be used on operating systems
2051 with limited file name lengths. @xref{Using gnatkr}.
2053 Of course, no file shortening algorithm can guarantee uniqueness over
2054 all possible unit names; if file name krunching is used, it is your
2055 responsibility to ensure no name clashes occur. Alternatively you
2056 can specify the exact file names that you want used, as described
2057 in the next section. Finally, if your Ada programs are migrating from a
2058 compiler with a different naming convention, you can use the gnatchop
2059 utility to produce source files that follow the GNAT naming conventions.
2060 (For details @pxref{Renaming Files Using gnatchop}.)
2062 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2063 systems, case is not significant. So for example on @code{Windows XP}
2064 if the canonical name is @code{main-sub.adb}, you can use the file name
2065 @code{Main-Sub.adb} instead. However, case is significant for other
2066 operating systems, so for example, if you want to use other than
2067 canonically cased file names on a Unix system, you need to follow
2068 the procedures described in the next section.
2070 @node Using Other File Names
2071 @section Using Other File Names
2075 In the previous section, we have described the default rules used by
2076 GNAT to determine the file name in which a given unit resides. It is
2077 often convenient to follow these default rules, and if you follow them,
2078 the compiler knows without being explicitly told where to find all
2081 However, in some cases, particularly when a program is imported from
2082 another Ada compiler environment, it may be more convenient for the
2083 programmer to specify which file names contain which units. GNAT allows
2084 arbitrary file names to be used by means of the Source_File_Name pragma.
2085 The form of this pragma is as shown in the following examples:
2086 @cindex Source_File_Name pragma
2088 @smallexample @c ada
2090 pragma Source_File_Name (My_Utilities.Stacks,
2091 Spec_File_Name => "myutilst_a.ada");
2092 pragma Source_File_name (My_Utilities.Stacks,
2093 Body_File_Name => "myutilst.ada");
2098 As shown in this example, the first argument for the pragma is the unit
2099 name (in this example a child unit). The second argument has the form
2100 of a named association. The identifier
2101 indicates whether the file name is for a spec or a body;
2102 the file name itself is given by a string literal.
2104 The source file name pragma is a configuration pragma, which means that
2105 normally it will be placed in the @file{gnat.adc}
2106 file used to hold configuration
2107 pragmas that apply to a complete compilation environment.
2108 For more details on how the @file{gnat.adc} file is created and used
2109 see @ref{Handling of Configuration Pragmas}.
2110 @cindex @file{gnat.adc}
2113 GNAT allows completely arbitrary file names to be specified using the
2114 source file name pragma. However, if the file name specified has an
2115 extension other than @file{.ads} or @file{.adb} it is necessary to use
2116 a special syntax when compiling the file. The name in this case must be
2117 preceded by the special sequence @option{-x} followed by a space and the name
2118 of the language, here @code{ada}, as in:
2121 $ gcc -c -x ada peculiar_file_name.sim
2126 @command{gnatmake} handles non-standard file names in the usual manner (the
2127 non-standard file name for the main program is simply used as the
2128 argument to gnatmake). Note that if the extension is also non-standard,
2129 then it must be included in the @command{gnatmake} command, it may not
2132 @node Alternative File Naming Schemes
2133 @section Alternative File Naming Schemes
2134 @cindex File naming schemes, alternative
2137 In the previous section, we described the use of the @code{Source_File_Name}
2138 pragma to allow arbitrary names to be assigned to individual source files.
2139 However, this approach requires one pragma for each file, and especially in
2140 large systems can result in very long @file{gnat.adc} files, and also create
2141 a maintenance problem.
2143 GNAT also provides a facility for specifying systematic file naming schemes
2144 other than the standard default naming scheme previously described. An
2145 alternative scheme for naming is specified by the use of
2146 @code{Source_File_Name} pragmas having the following format:
2147 @cindex Source_File_Name pragma
2149 @smallexample @c ada
2150 pragma Source_File_Name (
2151 Spec_File_Name => FILE_NAME_PATTERN
2152 [,Casing => CASING_SPEC]
2153 [,Dot_Replacement => STRING_LITERAL]);
2155 pragma Source_File_Name (
2156 Body_File_Name => FILE_NAME_PATTERN
2157 [,Casing => CASING_SPEC]
2158 [,Dot_Replacement => STRING_LITERAL]);
2160 pragma Source_File_Name (
2161 Subunit_File_Name => FILE_NAME_PATTERN
2162 [,Casing => CASING_SPEC]
2163 [,Dot_Replacement => STRING_LITERAL]);
2165 FILE_NAME_PATTERN ::= STRING_LITERAL
2166 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2170 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2171 It contains a single asterisk character, and the unit name is substituted
2172 systematically for this asterisk. The optional parameter
2173 @code{Casing} indicates
2174 whether the unit name is to be all upper-case letters, all lower-case letters,
2175 or mixed-case. If no
2176 @code{Casing} parameter is used, then the default is all
2177 ^lower-case^upper-case^.
2179 The optional @code{Dot_Replacement} string is used to replace any periods
2180 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2181 argument is used then separating dots appear unchanged in the resulting
2183 Although the above syntax indicates that the
2184 @code{Casing} argument must appear
2185 before the @code{Dot_Replacement} argument, but it
2186 is also permissible to write these arguments in the opposite order.
2188 As indicated, it is possible to specify different naming schemes for
2189 bodies, specs, and subunits. Quite often the rule for subunits is the
2190 same as the rule for bodies, in which case, there is no need to give
2191 a separate @code{Subunit_File_Name} rule, and in this case the
2192 @code{Body_File_name} rule is used for subunits as well.
2194 The separate rule for subunits can also be used to implement the rather
2195 unusual case of a compilation environment (e.g.@: a single directory) which
2196 contains a subunit and a child unit with the same unit name. Although
2197 both units cannot appear in the same partition, the Ada Reference Manual
2198 allows (but does not require) the possibility of the two units coexisting
2199 in the same environment.
2201 The file name translation works in the following steps:
2206 If there is a specific @code{Source_File_Name} pragma for the given unit,
2207 then this is always used, and any general pattern rules are ignored.
2210 If there is a pattern type @code{Source_File_Name} pragma that applies to
2211 the unit, then the resulting file name will be used if the file exists. If
2212 more than one pattern matches, the latest one will be tried first, and the
2213 first attempt resulting in a reference to a file that exists will be used.
2216 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2217 for which the corresponding file exists, then the standard GNAT default
2218 naming rules are used.
2223 As an example of the use of this mechanism, consider a commonly used scheme
2224 in which file names are all lower case, with separating periods copied
2225 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2226 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2229 @smallexample @c ada
2230 pragma Source_File_Name
2231 (Spec_File_Name => "*.1.ada");
2232 pragma Source_File_Name
2233 (Body_File_Name => "*.2.ada");
2237 The default GNAT scheme is actually implemented by providing the following
2238 default pragmas internally:
2240 @smallexample @c ada
2241 pragma Source_File_Name
2242 (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2243 pragma Source_File_Name
2244 (Body_File_Name => "*.adb", Dot_Replacement => "-");
2248 Our final example implements a scheme typically used with one of the
2249 Ada 83 compilers, where the separator character for subunits was ``__''
2250 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2251 by adding @file{.ADA}, and subunits by
2252 adding @file{.SEP}. All file names were
2253 upper case. Child units were not present of course since this was an
2254 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2255 the same double underscore separator for child units.
2257 @smallexample @c ada
2258 pragma Source_File_Name
2259 (Spec_File_Name => "*_.ADA",
2260 Dot_Replacement => "__",
2261 Casing = Uppercase);
2262 pragma Source_File_Name
2263 (Body_File_Name => "*.ADA",
2264 Dot_Replacement => "__",
2265 Casing = Uppercase);
2266 pragma Source_File_Name
2267 (Subunit_File_Name => "*.SEP",
2268 Dot_Replacement => "__",
2269 Casing = Uppercase);
2272 @node Generating Object Files
2273 @section Generating Object Files
2276 An Ada program consists of a set of source files, and the first step in
2277 compiling the program is to generate the corresponding object files.
2278 These are generated by compiling a subset of these source files.
2279 The files you need to compile are the following:
2283 If a package spec has no body, compile the package spec to produce the
2284 object file for the package.
2287 If a package has both a spec and a body, compile the body to produce the
2288 object file for the package. The source file for the package spec need
2289 not be compiled in this case because there is only one object file, which
2290 contains the code for both the spec and body of the package.
2293 For a subprogram, compile the subprogram body to produce the object file
2294 for the subprogram. The spec, if one is present, is as usual in a
2295 separate file, and need not be compiled.
2299 In the case of subunits, only compile the parent unit. A single object
2300 file is generated for the entire subunit tree, which includes all the
2304 Compile child units independently of their parent units
2305 (though, of course, the spec of all the ancestor unit must be present in order
2306 to compile a child unit).
2310 Compile generic units in the same manner as any other units. The object
2311 files in this case are small dummy files that contain at most the
2312 flag used for elaboration checking. This is because GNAT always handles generic
2313 instantiation by means of macro expansion. However, it is still necessary to
2314 compile generic units, for dependency checking and elaboration purposes.
2318 The preceding rules describe the set of files that must be compiled to
2319 generate the object files for a program. Each object file has the same
2320 name as the corresponding source file, except that the extension is
2323 You may wish to compile other files for the purpose of checking their
2324 syntactic and semantic correctness. For example, in the case where a
2325 package has a separate spec and body, you would not normally compile the
2326 spec. However, it is convenient in practice to compile the spec to make
2327 sure it is error-free before compiling clients of this spec, because such
2328 compilations will fail if there is an error in the spec.
2330 GNAT provides an option for compiling such files purely for the
2331 purposes of checking correctness; such compilations are not required as
2332 part of the process of building a program. To compile a file in this
2333 checking mode, use the @option{-gnatc} switch.
2335 @node Source Dependencies
2336 @section Source Dependencies
2339 A given object file clearly depends on the source file which is compiled
2340 to produce it. Here we are using @dfn{depends} in the sense of a typical
2341 @code{make} utility; in other words, an object file depends on a source
2342 file if changes to the source file require the object file to be
2344 In addition to this basic dependency, a given object may depend on
2345 additional source files as follows:
2349 If a file being compiled @code{with}'s a unit @var{X}, the object file
2350 depends on the file containing the spec of unit @var{X}. This includes
2351 files that are @code{with}'ed implicitly either because they are parents
2352 of @code{with}'ed child units or they are run-time units required by the
2353 language constructs used in a particular unit.
2356 If a file being compiled instantiates a library level generic unit, the
2357 object file depends on both the spec and body files for this generic
2361 If a file being compiled instantiates a generic unit defined within a
2362 package, the object file depends on the body file for the package as
2363 well as the spec file.
2367 @cindex @option{-gnatn} switch
2368 If a file being compiled contains a call to a subprogram for which
2369 pragma @code{Inline} applies and inlining is activated with the
2370 @option{-gnatn} switch, the object file depends on the file containing the
2371 body of this subprogram as well as on the file containing the spec. Note
2372 that for inlining to actually occur as a result of the use of this switch,
2373 it is necessary to compile in optimizing mode.
2375 @cindex @option{-gnatN} switch
2376 The use of @option{-gnatN} activates a more extensive inlining optimization
2377 that is performed by the front end of the compiler. This inlining does
2378 not require that the code generation be optimized. Like @option{-gnatn},
2379 the use of this switch generates additional dependencies.
2381 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
2382 to specify both options.
2385 If an object file @file{O} depends on the proper body of a subunit through
2386 inlining or instantiation, it depends on the parent unit of the subunit.
2387 This means that any modification of the parent unit or one of its subunits
2388 affects the compilation of @file{O}.
2391 The object file for a parent unit depends on all its subunit body files.
2394 The previous two rules meant that for purposes of computing dependencies and
2395 recompilation, a body and all its subunits are treated as an indivisible whole.
2398 These rules are applied transitively: if unit @code{A} @code{with}'s
2399 unit @code{B}, whose elaboration calls an inlined procedure in package
2400 @code{C}, the object file for unit @code{A} will depend on the body of
2401 @code{C}, in file @file{c.adb}.
2403 The set of dependent files described by these rules includes all the
2404 files on which the unit is semantically dependent, as dictated by the
2405 Ada language standard. However, it is a superset of what the
2406 standard describes, because it includes generic, inline, and subunit
2409 An object file must be recreated by recompiling the corresponding source
2410 file if any of the source files on which it depends are modified. For
2411 example, if the @code{make} utility is used to control compilation,
2412 the rule for an Ada object file must mention all the source files on
2413 which the object file depends, according to the above definition.
2414 The determination of the necessary
2415 recompilations is done automatically when one uses @command{gnatmake}.
2418 @node The Ada Library Information Files
2419 @section The Ada Library Information Files
2420 @cindex Ada Library Information files
2421 @cindex @file{ALI} files
2424 Each compilation actually generates two output files. The first of these
2425 is the normal object file that has a @file{.o} extension. The second is a
2426 text file containing full dependency information. It has the same
2427 name as the source file, but an @file{.ali} extension.
2428 This file is known as the Ada Library Information (@file{ALI}) file.
2429 The following information is contained in the @file{ALI} file.
2433 Version information (indicates which version of GNAT was used to compile
2434 the unit(s) in question)
2437 Main program information (including priority and time slice settings,
2438 as well as the wide character encoding used during compilation).
2441 List of arguments used in the @command{gcc} command for the compilation
2444 Attributes of the unit, including configuration pragmas used, an indication
2445 of whether the compilation was successful, exception model used etc.
2448 A list of relevant restrictions applying to the unit (used for consistency)
2452 Categorization information (e.g.@: use of pragma @code{Pure}).
2455 Information on all @code{with}'ed units, including presence of
2456 @code{Elaborate} or @code{Elaborate_All} pragmas.
2459 Information from any @code{Linker_Options} pragmas used in the unit
2462 Information on the use of @code{Body_Version} or @code{Version}
2463 attributes in the unit.
2466 Dependency information. This is a list of files, together with
2467 time stamp and checksum information. These are files on which
2468 the unit depends in the sense that recompilation is required
2469 if any of these units are modified.
2472 Cross-reference data. Contains information on all entities referenced
2473 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2474 provide cross-reference information.
2479 For a full detailed description of the format of the @file{ALI} file,
2480 see the source of the body of unit @code{Lib.Writ}, contained in file
2481 @file{lib-writ.adb} in the GNAT compiler sources.
2483 @node Binding an Ada Program
2484 @section Binding an Ada Program
2487 When using languages such as C and C++, once the source files have been
2488 compiled the only remaining step in building an executable program
2489 is linking the object modules together. This means that it is possible to
2490 link an inconsistent version of a program, in which two units have
2491 included different versions of the same header.
2493 The rules of Ada do not permit such an inconsistent program to be built.
2494 For example, if two clients have different versions of the same package,
2495 it is illegal to build a program containing these two clients.
2496 These rules are enforced by the GNAT binder, which also determines an
2497 elaboration order consistent with the Ada rules.
2499 The GNAT binder is run after all the object files for a program have
2500 been created. It is given the name of the main program unit, and from
2501 this it determines the set of units required by the program, by reading the
2502 corresponding ALI files. It generates error messages if the program is
2503 inconsistent or if no valid order of elaboration exists.
2505 If no errors are detected, the binder produces a main program, in Ada by
2506 default, that contains calls to the elaboration procedures of those
2507 compilation unit that require them, followed by
2508 a call to the main program. This Ada program is compiled to generate the
2509 object file for the main program. The name of
2510 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2511 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2514 Finally, the linker is used to build the resulting executable program,
2515 using the object from the main program from the bind step as well as the
2516 object files for the Ada units of the program.
2518 @node Mixed Language Programming
2519 @section Mixed Language Programming
2520 @cindex Mixed Language Programming
2523 This section describes how to develop a mixed-language program,
2524 specifically one that comprises units in both Ada and C.
2527 * Interfacing to C::
2528 * Calling Conventions::
2531 @node Interfacing to C
2532 @subsection Interfacing to C
2534 Interfacing Ada with a foreign language such as C involves using
2535 compiler directives to import and/or export entity definitions in each
2536 language---using @code{extern} statements in C, for instance, and the
2537 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2538 A full treatment of these topics is provided in Appendix B, section 1
2539 of the Ada Reference Manual.
2541 There are two ways to build a program using GNAT that contains some Ada
2542 sources and some foreign language sources, depending on whether or not
2543 the main subprogram is written in Ada. Here is a source example with
2544 the main subprogram in Ada:
2550 void print_num (int num)
2552 printf ("num is %d.\n", num);
2558 /* num_from_Ada is declared in my_main.adb */
2559 extern int num_from_Ada;
2563 return num_from_Ada;
2567 @smallexample @c ada
2569 procedure My_Main is
2571 -- Declare then export an Integer entity called num_from_Ada
2572 My_Num : Integer := 10;
2573 pragma Export (C, My_Num, "num_from_Ada");
2575 -- Declare an Ada function spec for Get_Num, then use
2576 -- C function get_num for the implementation.
2577 function Get_Num return Integer;
2578 pragma Import (C, Get_Num, "get_num");
2580 -- Declare an Ada procedure spec for Print_Num, then use
2581 -- C function print_num for the implementation.
2582 procedure Print_Num (Num : Integer);
2583 pragma Import (C, Print_Num, "print_num");
2586 Print_Num (Get_Num);
2592 To build this example, first compile the foreign language files to
2593 generate object files:
2595 ^gcc -c file1.c^gcc -c FILE1.C^
2596 ^gcc -c file2.c^gcc -c FILE2.C^
2600 Then, compile the Ada units to produce a set of object files and ALI
2603 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2607 Run the Ada binder on the Ada main program:
2609 gnatbind my_main.ali
2613 Link the Ada main program, the Ada objects and the other language
2616 gnatlink my_main.ali file1.o file2.o
2620 The last three steps can be grouped in a single command:
2622 gnatmake my_main.adb -largs file1.o file2.o
2625 @cindex Binder output file
2627 If the main program is in a language other than Ada, then you may have
2628 more than one entry point into the Ada subsystem. You must use a special
2629 binder option to generate callable routines that initialize and
2630 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2631 Calls to the initialization and finalization routines must be inserted
2632 in the main program, or some other appropriate point in the code. The
2633 call to initialize the Ada units must occur before the first Ada
2634 subprogram is called, and the call to finalize the Ada units must occur
2635 after the last Ada subprogram returns. The binder will place the
2636 initialization and finalization subprograms into the
2637 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2638 sources. To illustrate, we have the following example:
2642 extern void adainit (void);
2643 extern void adafinal (void);
2644 extern int add (int, int);
2645 extern int sub (int, int);
2647 int main (int argc, char *argv[])
2653 /* Should print "21 + 7 = 28" */
2654 printf ("%d + %d = %d\n", a, b, add (a, b));
2655 /* Should print "21 - 7 = 14" */
2656 printf ("%d - %d = %d\n", a, b, sub (a, b));
2662 @smallexample @c ada
2665 function Add (A, B : Integer) return Integer;
2666 pragma Export (C, Add, "add");
2670 package body Unit1 is
2671 function Add (A, B : Integer) return Integer is
2679 function Sub (A, B : Integer) return Integer;
2680 pragma Export (C, Sub, "sub");
2684 package body Unit2 is
2685 function Sub (A, B : Integer) return Integer is
2694 The build procedure for this application is similar to the last
2695 example's. First, compile the foreign language files to generate object
2698 ^gcc -c main.c^gcc -c main.c^
2702 Next, compile the Ada units to produce a set of object files and ALI
2705 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2706 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2710 Run the Ada binder on every generated ALI file. Make sure to use the
2711 @option{-n} option to specify a foreign main program:
2713 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2717 Link the Ada main program, the Ada objects and the foreign language
2718 objects. You need only list the last ALI file here:
2720 gnatlink unit2.ali main.o -o exec_file
2723 This procedure yields a binary executable called @file{exec_file}.
2727 Depending on the circumstances (for example when your non-Ada main object
2728 does not provide symbol @code{main}), you may also need to instruct the
2729 GNAT linker not to include the standard startup objects by passing the
2730 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2732 @node Calling Conventions
2733 @subsection Calling Conventions
2734 @cindex Foreign Languages
2735 @cindex Calling Conventions
2736 GNAT follows standard calling sequence conventions and will thus interface
2737 to any other language that also follows these conventions. The following
2738 Convention identifiers are recognized by GNAT:
2741 @cindex Interfacing to Ada
2742 @cindex Other Ada compilers
2743 @cindex Convention Ada
2745 This indicates that the standard Ada calling sequence will be
2746 used and all Ada data items may be passed without any limitations in the
2747 case where GNAT is used to generate both the caller and callee. It is also
2748 possible to mix GNAT generated code and code generated by another Ada
2749 compiler. In this case, the data types should be restricted to simple
2750 cases, including primitive types. Whether complex data types can be passed
2751 depends on the situation. Probably it is safe to pass simple arrays, such
2752 as arrays of integers or floats. Records may or may not work, depending
2753 on whether both compilers lay them out identically. Complex structures
2754 involving variant records, access parameters, tasks, or protected types,
2755 are unlikely to be able to be passed.
2757 Note that in the case of GNAT running
2758 on a platform that supports HP Ada 83, a higher degree of compatibility
2759 can be guaranteed, and in particular records are layed out in an identical
2760 manner in the two compilers. Note also that if output from two different
2761 compilers is mixed, the program is responsible for dealing with elaboration
2762 issues. Probably the safest approach is to write the main program in the
2763 version of Ada other than GNAT, so that it takes care of its own elaboration
2764 requirements, and then call the GNAT-generated adainit procedure to ensure
2765 elaboration of the GNAT components. Consult the documentation of the other
2766 Ada compiler for further details on elaboration.
2768 However, it is not possible to mix the tasking run time of GNAT and
2769 HP Ada 83, All the tasking operations must either be entirely within
2770 GNAT compiled sections of the program, or entirely within HP Ada 83
2771 compiled sections of the program.
2773 @cindex Interfacing to Assembly
2774 @cindex Convention Assembler
2776 Specifies assembler as the convention. In practice this has the
2777 same effect as convention Ada (but is not equivalent in the sense of being
2778 considered the same convention).
2780 @cindex Convention Asm
2783 Equivalent to Assembler.
2785 @cindex Interfacing to COBOL
2786 @cindex Convention COBOL
2789 Data will be passed according to the conventions described
2790 in section B.4 of the Ada Reference Manual.
2793 @cindex Interfacing to C
2794 @cindex Convention C
2796 Data will be passed according to the conventions described
2797 in section B.3 of the Ada Reference Manual.
2799 A note on interfacing to a C ``varargs'' function:
2800 @findex C varargs function
2801 @cindex Interfacing to C varargs function
2802 @cindex varargs function interfaces
2806 In C, @code{varargs} allows a function to take a variable number of
2807 arguments. There is no direct equivalent in this to Ada. One
2808 approach that can be used is to create a C wrapper for each
2809 different profile and then interface to this C wrapper. For
2810 example, to print an @code{int} value using @code{printf},
2811 create a C function @code{printfi} that takes two arguments, a
2812 pointer to a string and an int, and calls @code{printf}.
2813 Then in the Ada program, use pragma @code{Import} to
2814 interface to @code{printfi}.
2817 It may work on some platforms to directly interface to
2818 a @code{varargs} function by providing a specific Ada profile
2819 for a particular call. However, this does not work on
2820 all platforms, since there is no guarantee that the
2821 calling sequence for a two argument normal C function
2822 is the same as for calling a @code{varargs} C function with
2823 the same two arguments.
2826 @cindex Convention Default
2831 @cindex Convention External
2838 @cindex Interfacing to C++
2839 @cindex Convention C++
2840 @item C_Plus_Plus (or CPP)
2841 This stands for C++. For most purposes this is identical to C.
2842 See the separate description of the specialized GNAT pragmas relating to
2843 C++ interfacing for further details.
2847 @cindex Interfacing to Fortran
2848 @cindex Convention Fortran
2850 Data will be passed according to the conventions described
2851 in section B.5 of the Ada Reference Manual.
2854 This applies to an intrinsic operation, as defined in the Ada
2855 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2856 this means that the body of the subprogram is provided by the compiler itself,
2857 usually by means of an efficient code sequence, and that the user does not
2858 supply an explicit body for it. In an application program, the pragma may
2859 be applied to the following sets of names:
2863 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2864 Shift_Right_Arithmetic. The corresponding subprogram declaration must have
2865 two formal parameters. The
2866 first one must be a signed integer type or a modular type with a binary
2867 modulus, and the second parameter must be of type Natural.
2868 The return type must be the same as the type of the first argument. The size
2869 of this type can only be 8, 16, 32, or 64.
2872 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2873 The corresponding operator declaration must have parameters and result type
2874 that have the same root numeric type (for example, all three are long_float
2875 types). This simplifies the definition of operations that use type checking
2876 to perform dimensional checks:
2878 @smallexample @c ada
2879 type Distance is new Long_Float;
2880 type Time is new Long_Float;
2881 type Velocity is new Long_Float;
2882 function "/" (D : Distance; T : Time)
2884 pragma Import (Intrinsic, "/");
2888 This common idiom is often programmed with a generic definition and an
2889 explicit body. The pragma makes it simpler to introduce such declarations.
2890 It incurs no overhead in compilation time or code size, because it is
2891 implemented as a single machine instruction.
2894 General subprogram entities, to bind an Ada subprogram declaration to
2895 a compiler builtin by name with back-ends where such interfaces are
2896 available. A typical example is the set of ``__builtin'' functions
2897 exposed by the GCC back-end, as in the following example:
2899 @smallexample @c ada
2900 function builtin_sqrt (F : Float) return Float;
2901 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2904 Most of the GCC builtins are accessible this way, and as for other
2905 import conventions (e.g. C), it is the user's responsibility to ensure
2906 that the Ada subprogram profile matches the underlying builtin
2914 @cindex Convention Stdcall
2916 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2917 and specifies that the @code{Stdcall} calling sequence will be used,
2918 as defined by the NT API. Nevertheless, to ease building
2919 cross-platform bindings this convention will be handled as a @code{C} calling
2920 convention on non-Windows platforms.
2923 @cindex Convention DLL
2925 This is equivalent to @code{Stdcall}.
2928 @cindex Convention Win32
2930 This is equivalent to @code{Stdcall}.
2934 @cindex Convention Stubbed
2936 This is a special convention that indicates that the compiler
2937 should provide a stub body that raises @code{Program_Error}.
2941 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2942 that can be used to parametrize conventions and allow additional synonyms
2943 to be specified. For example if you have legacy code in which the convention
2944 identifier Fortran77 was used for Fortran, you can use the configuration
2947 @smallexample @c ada
2948 pragma Convention_Identifier (Fortran77, Fortran);
2952 And from now on the identifier Fortran77 may be used as a convention
2953 identifier (for example in an @code{Import} pragma) with the same
2957 @node Building Mixed Ada & C++ Programs
2958 @section Building Mixed Ada and C++ Programs
2961 A programmer inexperienced with mixed-language development may find that
2962 building an application containing both Ada and C++ code can be a
2963 challenge. This section gives a few
2964 hints that should make this task easier. The first section addresses
2965 the differences between interfacing with C and interfacing with C++.
2967 looks into the delicate problem of linking the complete application from
2968 its Ada and C++ parts. The last section gives some hints on how the GNAT
2969 run-time library can be adapted in order to allow inter-language dispatching
2970 with a new C++ compiler.
2973 * Interfacing to C++::
2974 * Linking a Mixed C++ & Ada Program::
2975 * A Simple Example::
2976 * Interfacing with C++ at the Class Level::
2979 @node Interfacing to C++
2980 @subsection Interfacing to C++
2983 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2984 generating code that is compatible with the G++ Application Binary
2985 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2988 Interfacing can be done at 3 levels: simple data, subprograms, and
2989 classes. In the first two cases, GNAT offers a specific @code{Convention
2990 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2991 Usually, C++ mangles the names of subprograms, and currently, GNAT does
2992 not provide any help to solve the demangling problem. This problem can be
2993 addressed in two ways:
2996 by modifying the C++ code in order to force a C convention using
2997 the @code{extern "C"} syntax.
3000 by figuring out the mangled name and use it as the Link_Name argument of
3005 Interfacing at the class level can be achieved by using the GNAT specific
3006 pragmas such as @code{CPP_Constructor}. @xref{Interfacing to C++,,,
3007 gnat_rm, GNAT Reference Manual}, for additional information.
3009 @node Linking a Mixed C++ & Ada Program
3010 @subsection Linking a Mixed C++ & Ada Program
3013 Usually the linker of the C++ development system must be used to link
3014 mixed applications because most C++ systems will resolve elaboration
3015 issues (such as calling constructors on global class instances)
3016 transparently during the link phase. GNAT has been adapted to ease the
3017 use of a foreign linker for the last phase. Three cases can be
3022 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3023 The C++ linker can simply be called by using the C++ specific driver
3024 called @code{c++}. Note that this setup is not very common because it
3025 may involve recompiling the whole GCC tree from sources, which makes it
3026 harder to upgrade the compilation system for one language without
3027 destabilizing the other.
3032 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
3036 Using GNAT and G++ from two different GCC installations: If both
3037 compilers are on the @env{PATH}, the previous method may be used. It is
3038 important to note that environment variables such as
3039 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3040 @env{GCC_ROOT} will affect both compilers
3041 at the same time and may make one of the two compilers operate
3042 improperly if set during invocation of the wrong compiler. It is also
3043 very important that the linker uses the proper @file{libgcc.a} GCC
3044 library -- that is, the one from the C++ compiler installation. The
3045 implicit link command as suggested in the @command{gnatmake} command
3046 from the former example can be replaced by an explicit link command with
3047 the full-verbosity option in order to verify which library is used:
3050 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3052 If there is a problem due to interfering environment variables, it can
3053 be worked around by using an intermediate script. The following example
3054 shows the proper script to use when GNAT has not been installed at its
3055 default location and g++ has been installed at its default location:
3063 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3067 Using a non-GNU C++ compiler: The commands previously described can be
3068 used to insure that the C++ linker is used. Nonetheless, you need to add
3069 a few more parameters to the link command line, depending on the exception
3072 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3073 to the libgcc libraries are required:
3078 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3079 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3082 Where CC is the name of the non-GNU C++ compiler.
3084 If the @code{zero cost} exception mechanism is used, and the platform
3085 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3086 paths to more objects are required:
3091 CC `gcc -print-file-name=crtbegin.o` $* \
3092 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3093 `gcc -print-file-name=crtend.o`
3094 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3097 If the @code{zero cost} exception mechanism is used, and the platform
3098 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3099 Tru64 or AIX), the simple approach described above will not work and
3100 a pre-linking phase using GNAT will be necessary.
3104 @node A Simple Example
3105 @subsection A Simple Example
3107 The following example, provided as part of the GNAT examples, shows how
3108 to achieve procedural interfacing between Ada and C++ in both
3109 directions. The C++ class A has two methods. The first method is exported
3110 to Ada by the means of an extern C wrapper function. The second method
3111 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3112 a limited record with a layout comparable to the C++ class. The Ada
3113 subprogram, in turn, calls the C++ method. So, starting from the C++
3114 main program, the process passes back and forth between the two
3118 Here are the compilation commands:
3120 $ gnatmake -c simple_cpp_interface
3123 $ gnatbind -n simple_cpp_interface
3124 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3125 -lstdc++ ex7.o cpp_main.o
3129 Here are the corresponding sources:
3137 void adainit (void);
3138 void adafinal (void);
3139 void method1 (A *t);
3161 class A : public Origin @{
3163 void method1 (void);
3164 void method2 (int v);
3174 extern "C" @{ void ada_method2 (A *t, int v);@}
3176 void A::method1 (void)
3179 printf ("in A::method1, a_value = %d \n",a_value);
3183 void A::method2 (int v)
3185 ada_method2 (this, v);
3186 printf ("in A::method2, a_value = %d \n",a_value);
3193 printf ("in A::A, a_value = %d \n",a_value);
3197 @smallexample @c ada
3199 package body Simple_Cpp_Interface is
3201 procedure Ada_Method2 (This : in out A; V : Integer) is
3207 end Simple_Cpp_Interface;
3210 package Simple_Cpp_Interface is
3213 Vptr : System.Address;
3217 pragma Convention (C, A);
3219 procedure Method1 (This : in out A);
3220 pragma Import (C, Method1);
3222 procedure Ada_Method2 (This : in out A; V : Integer);
3223 pragma Export (C, Ada_Method2);
3225 end Simple_Cpp_Interface;
3228 @node Interfacing with C++ at the Class Level
3229 @subsection Interfacing with C++ at the Class Level
3231 In this section we demonstrate the GNAT features for interfacing with
3232 C++ by means of an example making use of Ada 2005 abstract interface
3233 types. This example consists of a classification of animals; classes
3234 have been used to model our main classification of animals, and
3235 interfaces provide support for the management of secondary
3236 classifications. We first demonstrate a case in which the types and
3237 constructors are defined on the C++ side and imported from the Ada
3238 side, and latter the reverse case.
3240 The root of our derivation will be the @code{Animal} class, with a
3241 single private attribute (the @code{Age} of the animal) and two public
3242 primitives to set and get the value of this attribute.
3247 @b{virtual} void Set_Age (int New_Age);
3248 @b{virtual} int Age ();
3254 Abstract interface types are defined in C++ by means of classes with pure
3255 virtual functions and no data members. In our example we will use two
3256 interfaces that provide support for the common management of @code{Carnivore}
3257 and @code{Domestic} animals:
3260 @b{class} Carnivore @{
3262 @b{virtual} int Number_Of_Teeth () = 0;
3265 @b{class} Domestic @{
3267 @b{virtual void} Set_Owner (char* Name) = 0;
3271 Using these declarations, we can now say that a @code{Dog} is an animal that is
3272 both Carnivore and Domestic, that is:
3275 @b{class} Dog : Animal, Carnivore, Domestic @{
3277 @b{virtual} int Number_Of_Teeth ();
3278 @b{virtual} void Set_Owner (char* Name);
3280 Dog(); // Constructor
3287 In the following examples we will assume that the previous declarations are
3288 located in a file named @code{animals.h}. The following package demonstrates
3289 how to import these C++ declarations from the Ada side:
3291 @smallexample @c ada
3292 with Interfaces.C.Strings; use Interfaces.C.Strings;
3294 type Carnivore is interface;
3295 pragma Convention (C_Plus_Plus, Carnivore);
3296 function Number_Of_Teeth (X : Carnivore)
3297 return Natural is abstract;
3299 type Domestic is interface;
3300 pragma Convention (C_Plus_Plus, Set_Owner);
3302 (X : in out Domestic;
3303 Name : Chars_Ptr) is abstract;
3305 type Animal is tagged record
3308 pragma Import (C_Plus_Plus, Animal);
3310 procedure Set_Age (X : in out Animal; Age : Integer);
3311 pragma Import (C_Plus_Plus, Set_Age);
3313 function Age (X : Animal) return Integer;
3314 pragma Import (C_Plus_Plus, Age);
3316 type Dog is new Animal and Carnivore and Domestic with record
3317 Tooth_Count : Natural;
3318 Owner : String (1 .. 30);
3320 pragma Import (C_Plus_Plus, Dog);
3322 function Number_Of_Teeth (A : Dog) return Integer;
3323 pragma Import (C_Plus_Plus, Number_Of_Teeth);
3325 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3326 pragma Import (C_Plus_Plus, Set_Owner);
3328 function New_Dog return Dog'Class;
3329 pragma CPP_Constructor (New_Dog);
3330 pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3334 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3335 interfacing with these C++ classes is easy. The only requirement is that all
3336 the primitives and components must be declared exactly in the same order in
3339 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3340 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3341 the arguments to the called primitives will be the same as for C++. For the
3342 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3343 to indicate that they have been defined on the C++ side; this is required
3344 because the dispatch table associated with these tagged types will be built
3345 in the C++ side and therefore will not contain the predefined Ada primitives
3346 which Ada would otherwise expect.
3348 As the reader can see there is no need to indicate the C++ mangled names
3349 associated with each subprogram because it is assumed that all the calls to
3350 these primitives will be dispatching calls. The only exception is the
3351 constructor, which must be registered with the compiler by means of
3352 @code{pragma CPP_Constructor} and needs to provide its associated C++
3353 mangled name because the Ada compiler generates direct calls to it.
3355 With the above packages we can now declare objects of type Dog on the Ada side
3356 and dispatch calls to the corresponding subprograms on the C++ side. We can
3357 also extend the tagged type Dog with further fields and primitives, and
3358 override some of its C++ primitives on the Ada side. For example, here we have
3359 a type derivation defined on the Ada side that inherits all the dispatching
3360 primitives of the ancestor from the C++ side.
3363 @b{with} Animals; @b{use} Animals;
3364 @b{package} Vaccinated_Animals @b{is}
3365 @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3366 @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3367 @b{end} Vaccinated_Animals;
3370 It is important to note that, because of the ABI compatibility, the programmer
3371 does not need to add any further information to indicate either the object
3372 layout or the dispatch table entry associated with each dispatching operation.
3374 Now let us define all the types and constructors on the Ada side and export
3375 them to C++, using the same hierarchy of our previous example:
3377 @smallexample @c ada
3378 with Interfaces.C.Strings;
3379 use Interfaces.C.Strings;
3381 type Carnivore is interface;
3382 pragma Convention (C_Plus_Plus, Carnivore);
3383 function Number_Of_Teeth (X : Carnivore)
3384 return Natural is abstract;
3386 type Domestic is interface;
3387 pragma Convention (C_Plus_Plus, Set_Owner);
3389 (X : in out Domestic;
3390 Name : Chars_Ptr) is abstract;
3392 type Animal is tagged record
3395 pragma Convention (C_Plus_Plus, Animal);
3397 procedure Set_Age (X : in out Animal; Age : Integer);
3398 pragma Export (C_Plus_Plus, Set_Age);
3400 function Age (X : Animal) return Integer;
3401 pragma Export (C_Plus_Plus, Age);
3403 type Dog is new Animal and Carnivore and Domestic with record
3404 Tooth_Count : Natural;
3405 Owner : String (1 .. 30);
3407 pragma Convention (C_Plus_Plus, Dog);
3409 function Number_Of_Teeth (A : Dog) return Integer;
3410 pragma Export (C_Plus_Plus, Number_Of_Teeth);
3412 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3413 pragma Export (C_Plus_Plus, Set_Owner);
3415 function New_Dog return Dog'Class;
3416 pragma Export (C_Plus_Plus, New_Dog);
3420 Compared with our previous example the only difference is the use of
3421 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3422 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3423 nothing else to be done; as explained above, the only requirement is that all
3424 the primitives and components are declared in exactly the same order.
3426 For completeness, let us see a brief C++ main program that uses the
3427 declarations available in @code{animals.h} (presented in our first example) to
3428 import and use the declarations from the Ada side, properly initializing and
3429 finalizing the Ada run-time system along the way:
3432 @b{#include} "animals.h"
3433 @b{#include} <iostream>
3434 @b{using namespace} std;
3436 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3437 void Check_Domestic (Domestic *obj) @{@dots{}@}
3438 void Check_Animal (Animal *obj) @{@dots{}@}
3439 void Check_Dog (Dog *obj) @{@dots{}@}
3442 void adainit (void);
3443 void adafinal (void);
3449 Dog *obj = new_dog(); // Ada constructor
3450 Check_Carnivore (obj); // Check secondary DT
3451 Check_Domestic (obj); // Check secondary DT
3452 Check_Animal (obj); // Check primary DT
3453 Check_Dog (obj); // Check primary DT
3458 adainit (); test(); adafinal ();
3463 @node Comparison between GNAT and C/C++ Compilation Models
3464 @section Comparison between GNAT and C/C++ Compilation Models
3467 The GNAT model of compilation is close to the C and C++ models. You can
3468 think of Ada specs as corresponding to header files in C. As in C, you
3469 don't need to compile specs; they are compiled when they are used. The
3470 Ada @code{with} is similar in effect to the @code{#include} of a C
3473 One notable difference is that, in Ada, you may compile specs separately
3474 to check them for semantic and syntactic accuracy. This is not always
3475 possible with C headers because they are fragments of programs that have
3476 less specific syntactic or semantic rules.
3478 The other major difference is the requirement for running the binder,
3479 which performs two important functions. First, it checks for
3480 consistency. In C or C++, the only defense against assembling
3481 inconsistent programs lies outside the compiler, in a makefile, for
3482 example. The binder satisfies the Ada requirement that it be impossible
3483 to construct an inconsistent program when the compiler is used in normal
3486 @cindex Elaboration order control
3487 The other important function of the binder is to deal with elaboration
3488 issues. There are also elaboration issues in C++ that are handled
3489 automatically. This automatic handling has the advantage of being
3490 simpler to use, but the C++ programmer has no control over elaboration.
3491 Where @code{gnatbind} might complain there was no valid order of
3492 elaboration, a C++ compiler would simply construct a program that
3493 malfunctioned at run time.
3496 @node Comparison between GNAT and Conventional Ada Library Models
3497 @section Comparison between GNAT and Conventional Ada Library Models
3500 This section is intended for Ada programmers who have
3501 used an Ada compiler implementing the traditional Ada library
3502 model, as described in the Ada Reference Manual.
3504 @cindex GNAT library
3505 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3506 source files themselves acts as the library. Compiling Ada programs does
3507 not generate any centralized information, but rather an object file and
3508 a ALI file, which are of interest only to the binder and linker.
3509 In a traditional system, the compiler reads information not only from
3510 the source file being compiled, but also from the centralized library.
3511 This means that the effect of a compilation depends on what has been
3512 previously compiled. In particular:
3516 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3517 to the version of the unit most recently compiled into the library.
3520 Inlining is effective only if the necessary body has already been
3521 compiled into the library.
3524 Compiling a unit may obsolete other units in the library.
3528 In GNAT, compiling one unit never affects the compilation of any other
3529 units because the compiler reads only source files. Only changes to source
3530 files can affect the results of a compilation. In particular:
3534 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3535 to the source version of the unit that is currently accessible to the
3540 Inlining requires the appropriate source files for the package or
3541 subprogram bodies to be available to the compiler. Inlining is always
3542 effective, independent of the order in which units are complied.
3545 Compiling a unit never affects any other compilations. The editing of
3546 sources may cause previous compilations to be out of date if they
3547 depended on the source file being modified.
3551 The most important result of these differences is that order of compilation
3552 is never significant in GNAT. There is no situation in which one is
3553 required to do one compilation before another. What shows up as order of
3554 compilation requirements in the traditional Ada library becomes, in
3555 GNAT, simple source dependencies; in other words, there is only a set
3556 of rules saying what source files must be present when a file is
3560 @node Placement of temporary files
3561 @section Placement of temporary files
3562 @cindex Temporary files (user control over placement)
3565 GNAT creates temporary files in the directory designated by the environment
3566 variable @env{TMPDIR}.
3567 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3568 for detailed information on how environment variables are resolved.
3569 For most users the easiest way to make use of this feature is to simply
3570 define @env{TMPDIR} as a job level logical name).
3571 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3572 for compiler temporary files, then you can include something like the
3573 following command in your @file{LOGIN.COM} file:
3576 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3580 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3581 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3582 designated by @env{TEMP}.
3583 If none of these environment variables are defined then GNAT uses the
3584 directory designated by the logical name @code{SYS$SCRATCH:}
3585 (by default the user's home directory). If all else fails
3586 GNAT uses the current directory for temporary files.
3589 @c *************************
3590 @node Compiling Using gcc
3591 @chapter Compiling Using @command{gcc}
3594 This chapter discusses how to compile Ada programs using the @command{gcc}
3595 command. It also describes the set of switches
3596 that can be used to control the behavior of the compiler.
3598 * Compiling Programs::
3599 * Switches for gcc::
3600 * Search Paths and the Run-Time Library (RTL)::
3601 * Order of Compilation Issues::
3605 @node Compiling Programs
3606 @section Compiling Programs
3609 The first step in creating an executable program is to compile the units
3610 of the program using the @command{gcc} command. You must compile the
3615 the body file (@file{.adb}) for a library level subprogram or generic
3619 the spec file (@file{.ads}) for a library level package or generic
3620 package that has no body
3623 the body file (@file{.adb}) for a library level package
3624 or generic package that has a body
3629 You need @emph{not} compile the following files
3634 the spec of a library unit which has a body
3641 because they are compiled as part of compiling related units. GNAT
3643 when the corresponding body is compiled, and subunits when the parent is
3646 @cindex cannot generate code
3647 If you attempt to compile any of these files, you will get one of the
3648 following error messages (where @var{fff} is the name of the file you compiled):
3651 cannot generate code for file @var{fff} (package spec)
3652 to check package spec, use -gnatc
3654 cannot generate code for file @var{fff} (missing subunits)
3655 to check parent unit, use -gnatc
3657 cannot generate code for file @var{fff} (subprogram spec)
3658 to check subprogram spec, use -gnatc
3660 cannot generate code for file @var{fff} (subunit)
3661 to check subunit, use -gnatc
3665 As indicated by the above error messages, if you want to submit
3666 one of these files to the compiler to check for correct semantics
3667 without generating code, then use the @option{-gnatc} switch.
3669 The basic command for compiling a file containing an Ada unit is
3672 $ gcc -c [@var{switches}] @file{file name}
3676 where @var{file name} is the name of the Ada file (usually
3678 @file{.ads} for a spec or @file{.adb} for a body).
3681 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3683 The result of a successful compilation is an object file, which has the
3684 same name as the source file but an extension of @file{.o} and an Ada
3685 Library Information (ALI) file, which also has the same name as the
3686 source file, but with @file{.ali} as the extension. GNAT creates these
3687 two output files in the current directory, but you may specify a source
3688 file in any directory using an absolute or relative path specification
3689 containing the directory information.
3692 @command{gcc} is actually a driver program that looks at the extensions of
3693 the file arguments and loads the appropriate compiler. For example, the
3694 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3695 These programs are in directories known to the driver program (in some
3696 configurations via environment variables you set), but need not be in
3697 your path. The @command{gcc} driver also calls the assembler and any other
3698 utilities needed to complete the generation of the required object
3701 It is possible to supply several file names on the same @command{gcc}
3702 command. This causes @command{gcc} to call the appropriate compiler for
3703 each file. For example, the following command lists three separate
3704 files to be compiled:
3707 $ gcc -c x.adb y.adb z.c
3711 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3712 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3713 The compiler generates three object files @file{x.o}, @file{y.o} and
3714 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3715 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3718 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3721 @node Switches for gcc
3722 @section Switches for @command{gcc}
3725 The @command{gcc} command accepts switches that control the
3726 compilation process. These switches are fully described in this section.
3727 First we briefly list all the switches, in alphabetical order, then we
3728 describe the switches in more detail in functionally grouped sections.
3730 More switches exist for GCC than those documented here, especially
3731 for specific targets. However, their use is not recommended as
3732 they may change code generation in ways that are incompatible with
3733 the Ada run-time library, or can cause inconsistencies between
3737 * Output and Error Message Control::
3738 * Warning Message Control::
3739 * Debugging and Assertion Control::
3740 * Validity Checking::
3743 * Using gcc for Syntax Checking::
3744 * Using gcc for Semantic Checking::
3745 * Compiling Different Versions of Ada::
3746 * Character Set Control::
3747 * File Naming Control::
3748 * Subprogram Inlining Control::
3749 * Auxiliary Output Control::
3750 * Debugging Control::
3751 * Exception Handling Control::
3752 * Units to Sources Mapping Files::
3753 * Integrated Preprocessing::
3754 * Code Generation Control::
3763 @cindex @option{-b} (@command{gcc})
3764 @item -b @var{target}
3765 Compile your program to run on @var{target}, which is the name of a
3766 system configuration. You must have a GNAT cross-compiler built if
3767 @var{target} is not the same as your host system.
3770 @cindex @option{-B} (@command{gcc})
3771 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3772 from @var{dir} instead of the default location. Only use this switch
3773 when multiple versions of the GNAT compiler are available.
3774 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3775 GNU Compiler Collection (GCC)}, for further details. You would normally
3776 use the @option{-b} or @option{-V} switch instead.
3779 @cindex @option{-c} (@command{gcc})
3780 Compile. Always use this switch when compiling Ada programs.
3782 Note: for some other languages when using @command{gcc}, notably in
3783 the case of C and C++, it is possible to use
3784 use @command{gcc} without a @option{-c} switch to
3785 compile and link in one step. In the case of GNAT, you
3786 cannot use this approach, because the binder must be run
3787 and @command{gcc} cannot be used to run the GNAT binder.
3791 @cindex @option{-fno-inline} (@command{gcc})
3792 Suppresses all back-end inlining, even if other optimization or inlining
3794 This includes suppression of inlining that results
3795 from the use of the pragma @code{Inline_Always}.
3796 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3797 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3798 effect if this switch is present.
3800 @item -fno-inline-functions
3801 @cindex @option{-fno-inline-functions} (@command{gcc})
3802 Suppresses automatic inlining of small subprograms, which is enabled
3803 if @option{-O3} is used.
3805 @item -fno-inline-functions-called-once
3806 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
3807 Suppresses inlining of subprograms local to the unit and called once
3808 from within it, which is enabled if @option{-O1} is used.
3810 @item -fno-strict-aliasing
3811 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3812 Causes the compiler to avoid assumptions regarding non-aliasing
3813 of objects of different types. See
3814 @ref{Optimization and Strict Aliasing} for details.
3817 @cindex @option{-fstack-check} (@command{gcc})
3818 Activates stack checking.
3819 See @ref{Stack Overflow Checking} for details.
3822 @cindex @option{-fstack-usage} (@command{gcc})
3823 Makes the compiler output stack usage information for the program, on a
3824 per-function basis. See @ref{Static Stack Usage Analysis} for details.
3826 @item -fcallgraph-info[=su]
3827 @cindex @option{-fcallgraph-info} (@command{gcc})
3828 Makes the compiler output callgraph information for the program, on a
3829 per-file basis. The information is generated in the VCG format. It can
3830 be decorated with stack-usage per-node information.
3833 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3834 Generate debugging information. This information is stored in the object
3835 file and copied from there to the final executable file by the linker,
3836 where it can be read by the debugger. You must use the
3837 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3840 @cindex @option{-gnat83} (@command{gcc})
3841 Enforce Ada 83 restrictions.
3844 @cindex @option{-gnat95} (@command{gcc})
3845 Enforce Ada 95 restrictions.
3848 @cindex @option{-gnat05} (@command{gcc})
3849 Allow full Ada 2005 features.
3852 @cindex @option{-gnata} (@command{gcc})
3853 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3854 activated. Note that these pragmas can also be controlled using the
3855 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3856 It also activates pragmas @code{Check}, @code{Precondition}, and
3857 @code{Postcondition}. Note that these pragmas can also be controlled
3858 using the configuration pragma @code{Check_Policy}.
3861 @cindex @option{-gnatA} (@command{gcc})
3862 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
3866 @cindex @option{-gnatb} (@command{gcc})
3867 Generate brief messages to @file{stderr} even if verbose mode set.
3870 @cindex @option{-gnatc} (@command{gcc})
3871 Check syntax and semantics only (no code generation attempted).
3874 @cindex @option{-gnatd} (@command{gcc})
3875 Specify debug options for the compiler. The string of characters after
3876 the @option{-gnatd} specify the specific debug options. The possible
3877 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3878 compiler source file @file{debug.adb} for details of the implemented
3879 debug options. Certain debug options are relevant to applications
3880 programmers, and these are documented at appropriate points in this
3884 @cindex @option{-gnatD} (@command{gcc})
3885 Create expanded source files for source level debugging. This switch
3886 also suppress generation of cross-reference information
3887 (see @option{-gnatx}).
3889 @item -gnatec=@var{path}
3890 @cindex @option{-gnatec} (@command{gcc})
3891 Specify a configuration pragma file
3893 (the equal sign is optional)
3895 (@pxref{The Configuration Pragmas Files}).
3897 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
3898 @cindex @option{-gnateD} (@command{gcc})
3899 Defines a symbol, associated with value, for preprocessing.
3900 (@pxref{Integrated Preprocessing}).
3903 @cindex @option{-gnatef} (@command{gcc})
3904 Display full source path name in brief error messages.
3906 @item -gnatem=@var{path}
3907 @cindex @option{-gnatem} (@command{gcc})
3908 Specify a mapping file
3910 (the equal sign is optional)
3912 (@pxref{Units to Sources Mapping Files}).
3914 @item -gnatep=@var{file}
3915 @cindex @option{-gnatep} (@command{gcc})
3916 Specify a preprocessing data file
3918 (the equal sign is optional)
3920 (@pxref{Integrated Preprocessing}).
3923 @cindex @option{-gnatE} (@command{gcc})
3924 Full dynamic elaboration checks.
3927 @cindex @option{-gnatf} (@command{gcc})
3928 Full errors. Multiple errors per line, all undefined references, do not
3929 attempt to suppress cascaded errors.
3932 @cindex @option{-gnatF} (@command{gcc})
3933 Externals names are folded to all uppercase.
3935 @item ^-gnatg^/GNAT_INTERNAL^
3936 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
3937 Internal GNAT implementation mode. This should not be used for
3938 applications programs, it is intended only for use by the compiler
3939 and its run-time library. For documentation, see the GNAT sources.
3940 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
3941 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
3942 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
3943 so that all standard warnings and all standard style options are turned on.
3944 All warnings and style error messages are treated as errors.
3947 @cindex @option{-gnatG} (@command{gcc})
3948 List generated expanded code in source form.
3950 @item ^-gnath^/HELP^
3951 @cindex @option{^-gnath^/HELP^} (@command{gcc})
3952 Output usage information. The output is written to @file{stdout}.
3954 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3955 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
3956 Identifier character set
3958 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3960 For details of the possible selections for @var{c},
3961 see @ref{Character Set Control}.
3963 @item ^-gnatI^/IGNORE_REP_CLAUSES^
3964 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
3965 Ignore representation clauses. When this switch is used, all
3966 representation clauses are treated as comments. This is useful
3967 when initially porting code where you want to ignore rep clause
3968 problems, and also for compiling foreign code (particularly
3972 @cindex @option{-gnatjnn} (@command{gcc})
3973 Reformat error messages to fit on nn character lines
3975 @item -gnatk=@var{n}
3976 @cindex @option{-gnatk} (@command{gcc})
3977 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3980 @cindex @option{-gnatl} (@command{gcc})
3981 Output full source listing with embedded error messages.
3984 @cindex @option{-gnatL} (@command{gcc})
3985 Used in conjunction with -gnatG or -gnatD to intersperse original
3986 source lines (as comment lines with line numbers) in the expanded
3989 @item -gnatm=@var{n}
3990 @cindex @option{-gnatm} (@command{gcc})
3991 Limit number of detected error or warning messages to @var{n}
3992 where @var{n} is in the range 1..999_999. The default setting if
3993 no switch is given is 9999. Compilation is terminated if this
3994 limit is exceeded. The equal sign here is optional.
3997 @cindex @option{-gnatn} (@command{gcc})
3998 Activate inlining for subprograms for which
3999 pragma @code{inline} is specified. This inlining is performed
4000 by the GCC back-end.
4003 @cindex @option{-gnatN} (@command{gcc})
4004 Activate front end inlining for subprograms for which
4005 pragma @code{Inline} is specified. This inlining is performed
4006 by the front end and will be visible in the
4007 @option{-gnatG} output.
4008 In some cases, this has proved more effective than the back end
4009 inlining resulting from the use of
4012 @option{-gnatN} automatically implies
4013 @option{-gnatn} so it is not necessary
4014 to specify both options. There are a few cases that the back-end inlining
4015 catches that cannot be dealt with in the front-end.
4018 @cindex @option{-gnato} (@command{gcc})
4019 Enable numeric overflow checking (which is not normally enabled by
4020 default). Not that division by zero is a separate check that is not
4021 controlled by this switch (division by zero checking is on by default).
4024 @cindex @option{-gnatp} (@command{gcc})
4025 Suppress all checks.
4028 @cindex @option{-gnatP} (@command{gcc})
4029 Enable polling. This is required on some systems (notably Windows NT) to
4030 obtain asynchronous abort and asynchronous transfer of control capability.
4031 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4035 @cindex @option{-gnatq} (@command{gcc})
4036 Don't quit; try semantics, even if parse errors.
4039 @cindex @option{-gnatQ} (@command{gcc})
4040 Don't quit; generate @file{ALI} and tree files even if illegalities.
4043 @cindex @option{-gnatr} (@command{gcc})
4044 Treat pragma Restrictions as Restriction_Warnings.
4046 @item ^-gnatR[0/1/2/3[s]]^/REPRESENTATION_INFO^
4047 @cindex @option{-gnatR} (@command{gcc})
4048 Output representation information for declared types and objects.
4051 @cindex @option{-gnats} (@command{gcc})
4055 @cindex @option{-gnatS} (@command{gcc})
4056 Print package Standard.
4059 @cindex @option{-gnatt} (@command{gcc})
4060 Generate tree output file.
4062 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4063 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4064 All compiler tables start at @var{nnn} times usual starting size.
4067 @cindex @option{-gnatu} (@command{gcc})
4068 List units for this compilation.
4071 @cindex @option{-gnatU} (@command{gcc})
4072 Tag all error messages with the unique string ``error:''
4075 @cindex @option{-gnatv} (@command{gcc})
4076 Verbose mode. Full error output with source lines to @file{stdout}.
4079 @cindex @option{-gnatV} (@command{gcc})
4080 Control level of validity checking. See separate section describing
4083 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}[,@dots{}])^
4084 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4086 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4087 the exact warnings that
4088 are enabled or disabled (@pxref{Warning Message Control}).
4090 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4091 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4092 Wide character encoding method
4094 (@var{e}=n/h/u/s/e/8).
4097 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4101 @cindex @option{-gnatx} (@command{gcc})
4102 Suppress generation of cross-reference information.
4104 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4105 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4106 Enable built-in style checks (@pxref{Style Checking}).
4108 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4109 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4110 Distribution stub generation and compilation
4112 (@var{m}=r/c for receiver/caller stubs).
4115 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4116 to be generated and compiled).
4119 @item ^-I^/SEARCH=^@var{dir}
4120 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4122 Direct GNAT to search the @var{dir} directory for source files needed by
4123 the current compilation
4124 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4126 @item ^-I-^/NOCURRENT_DIRECTORY^
4127 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4129 Except for the source file named in the command line, do not look for source
4130 files in the directory containing the source file named in the command line
4131 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4135 @cindex @option{-mbig-switch} (@command{gcc})
4136 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4137 This standard gcc switch causes the compiler to use larger offsets in its
4138 jump table representation for @code{case} statements.
4139 This may result in less efficient code, but is sometimes necessary
4140 (for example on HP-UX targets)
4141 @cindex HP-UX and @option{-mbig-switch} option
4142 in order to compile large and/or nested @code{case} statements.
4145 @cindex @option{-o} (@command{gcc})
4146 This switch is used in @command{gcc} to redirect the generated object file
4147 and its associated ALI file. Beware of this switch with GNAT, because it may
4148 cause the object file and ALI file to have different names which in turn
4149 may confuse the binder and the linker.
4153 @cindex @option{-nostdinc} (@command{gcc})
4154 Inhibit the search of the default location for the GNAT Run Time
4155 Library (RTL) source files.
4158 @cindex @option{-nostdlib} (@command{gcc})
4159 Inhibit the search of the default location for the GNAT Run Time
4160 Library (RTL) ALI files.
4164 @cindex @option{-O} (@command{gcc})
4165 @var{n} controls the optimization level.
4169 No optimization, the default setting if no @option{-O} appears
4172 Normal optimization, the default if you specify @option{-O} without
4173 an operand. A good compromise between code quality and compilation
4177 Extensive optimization, may improve execution time, possibly at the cost of
4178 substantially increased compilation time.
4181 Same as @option{-O2}, and also includes inline expansion for small subprograms
4185 Optimize space usage
4189 See also @ref{Optimization Levels}.
4194 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4195 Equivalent to @option{/OPTIMIZE=NONE}.
4196 This is the default behavior in the absence of an @option{/OPTIMIZE}
4199 @item /OPTIMIZE[=(keyword[,@dots{}])]
4200 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4201 Selects the level of optimization for your program. The supported
4202 keywords are as follows:
4205 Perform most optimizations, including those that
4207 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4208 without keyword options.
4211 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4214 Perform some optimizations, but omit ones that are costly.
4217 Same as @code{SOME}.
4220 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4221 automatic inlining of small subprograms within a unit
4224 Try to unroll loops. This keyword may be specified together with
4225 any keyword above other than @code{NONE}. Loop unrolling
4226 usually, but not always, improves the performance of programs.
4229 Optimize space usage
4233 See also @ref{Optimization Levels}.
4237 @item -pass-exit-codes
4238 @cindex @option{-pass-exit-codes} (@command{gcc})
4239 Catch exit codes from the compiler and use the most meaningful as
4243 @item --RTS=@var{rts-path}
4244 @cindex @option{--RTS} (@command{gcc})
4245 Specifies the default location of the runtime library. Same meaning as the
4246 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4249 @cindex @option{^-S^/ASM^} (@command{gcc})
4250 ^Used in place of @option{-c} to^Used to^
4251 cause the assembler source file to be
4252 generated, using @file{^.s^.S^} as the extension,
4253 instead of the object file.
4254 This may be useful if you need to examine the generated assembly code.
4256 @item ^-fverbose-asm^/VERBOSE_ASM^
4257 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4258 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4259 to cause the generated assembly code file to be annotated with variable
4260 names, making it significantly easier to follow.
4263 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4264 Show commands generated by the @command{gcc} driver. Normally used only for
4265 debugging purposes or if you need to be sure what version of the
4266 compiler you are executing.
4270 @cindex @option{-V} (@command{gcc})
4271 Execute @var{ver} version of the compiler. This is the @command{gcc}
4272 version, not the GNAT version.
4275 @item ^-w^/NO_BACK_END_WARNINGS^
4276 @cindex @option{-w} (@command{gcc})
4277 Turn off warnings generated by the back end of the compiler. Use of
4278 this switch also causes the default for front end warnings to be set
4279 to suppress (as though @option{-gnatws} had appeared at the start of
4285 @c Combining qualifiers does not work on VMS
4286 You may combine a sequence of GNAT switches into a single switch. For
4287 example, the combined switch
4289 @cindex Combining GNAT switches
4295 is equivalent to specifying the following sequence of switches:
4298 -gnato -gnatf -gnati3
4303 The following restrictions apply to the combination of switches
4308 The switch @option{-gnatc} if combined with other switches must come
4309 first in the string.
4312 The switch @option{-gnats} if combined with other switches must come
4313 first in the string.
4317 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4318 may not be combined with any other switches.
4322 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4323 switch), then all further characters in the switch are interpreted
4324 as style modifiers (see description of @option{-gnaty}).
4327 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4328 switch), then all further characters in the switch are interpreted
4329 as debug flags (see description of @option{-gnatd}).
4332 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4333 switch), then all further characters in the switch are interpreted
4334 as warning mode modifiers (see description of @option{-gnatw}).
4337 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4338 switch), then all further characters in the switch are interpreted
4339 as validity checking options (see description of @option{-gnatV}).
4343 @node Output and Error Message Control
4344 @subsection Output and Error Message Control
4348 The standard default format for error messages is called ``brief format''.
4349 Brief format messages are written to @file{stderr} (the standard error
4350 file) and have the following form:
4353 e.adb:3:04: Incorrect spelling of keyword "function"
4354 e.adb:4:20: ";" should be "is"
4358 The first integer after the file name is the line number in the file,
4359 and the second integer is the column number within the line.
4361 @code{GPS} can parse the error messages
4362 and point to the referenced character.
4364 The following switches provide control over the error message
4370 @cindex @option{-gnatv} (@command{gcc})
4373 The v stands for verbose.
4375 The effect of this setting is to write long-format error
4376 messages to @file{stdout} (the standard output file.
4377 The same program compiled with the
4378 @option{-gnatv} switch would generate:
4382 3. funcion X (Q : Integer)
4384 >>> Incorrect spelling of keyword "function"
4387 >>> ";" should be "is"
4392 The vertical bar indicates the location of the error, and the @samp{>>>}
4393 prefix can be used to search for error messages. When this switch is
4394 used the only source lines output are those with errors.
4397 @cindex @option{-gnatl} (@command{gcc})
4399 The @code{l} stands for list.
4401 This switch causes a full listing of
4402 the file to be generated. In the case where a body is
4403 compiled, the corresponding spec is also listed, along
4404 with any subunits. Typical output from compiling a package
4405 body @file{p.adb} might look like:
4407 @smallexample @c ada
4411 1. package body p is
4413 3. procedure a is separate;
4424 2. pragma Elaborate_Body
4448 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4449 standard output is redirected, a brief summary is written to
4450 @file{stderr} (standard error) giving the number of error messages and
4451 warning messages generated.
4453 @item -^gnatl^OUTPUT_FILE^=file
4454 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4455 This has the same effect as @option{-gnatl} except that the output is
4456 written to a file instead of to standard output. If the given name
4457 @file{fname} does not start with a period, then it is the full name
4458 of the file to be written. If @file{fname} is an extension, it is
4459 appended to the name of the file being compiled. For example, if
4460 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4461 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4464 @cindex @option{-gnatU} (@command{gcc})
4465 This switch forces all error messages to be preceded by the unique
4466 string ``error:''. This means that error messages take a few more
4467 characters in space, but allows easy searching for and identification
4471 @cindex @option{-gnatb} (@command{gcc})
4473 The @code{b} stands for brief.
4475 This switch causes GNAT to generate the
4476 brief format error messages to @file{stderr} (the standard error
4477 file) as well as the verbose
4478 format message or full listing (which as usual is written to
4479 @file{stdout} (the standard output file).
4481 @item -gnatm=@var{n}
4482 @cindex @option{-gnatm} (@command{gcc})
4484 The @code{m} stands for maximum.
4486 @var{n} is a decimal integer in the
4487 range of 1 to 999 and limits the number of error messages to be
4488 generated. For example, using @option{-gnatm2} might yield
4491 e.adb:3:04: Incorrect spelling of keyword "function"
4492 e.adb:5:35: missing ".."
4493 fatal error: maximum errors reached
4494 compilation abandoned
4498 Note that the equal sign is optional, so the switches
4499 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4502 @cindex @option{-gnatf} (@command{gcc})
4503 @cindex Error messages, suppressing
4505 The @code{f} stands for full.
4507 Normally, the compiler suppresses error messages that are likely to be
4508 redundant. This switch causes all error
4509 messages to be generated. In particular, in the case of
4510 references to undefined variables. If a given variable is referenced
4511 several times, the normal format of messages is
4513 e.adb:7:07: "V" is undefined (more references follow)
4517 where the parenthetical comment warns that there are additional
4518 references to the variable @code{V}. Compiling the same program with the
4519 @option{-gnatf} switch yields
4522 e.adb:7:07: "V" is undefined
4523 e.adb:8:07: "V" is undefined
4524 e.adb:8:12: "V" is undefined
4525 e.adb:8:16: "V" is undefined
4526 e.adb:9:07: "V" is undefined
4527 e.adb:9:12: "V" is undefined
4531 The @option{-gnatf} switch also generates additional information for
4532 some error messages. Some examples are:
4536 Full details on entities not available in high integrity mode
4538 Details on possibly non-portable unchecked conversion
4540 List possible interpretations for ambiguous calls
4542 Additional details on incorrect parameters
4546 @cindex @option{-gnatjnn} (@command{gcc})
4547 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4548 with continuation lines are treated as though the continuation lines were
4549 separate messages (and so a warning with two continuation lines counts as
4550 three warnings, and is listed as three separate messages).
4552 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4553 messages are output in a different manner. A message and all its continuation
4554 lines are treated as a unit, and count as only one warning or message in the
4555 statistics totals. Furthermore, the message is reformatted so that no line
4556 is longer than nn characters.
4559 @cindex @option{-gnatq} (@command{gcc})
4561 The @code{q} stands for quit (really ``don't quit'').
4563 In normal operation mode, the compiler first parses the program and
4564 determines if there are any syntax errors. If there are, appropriate
4565 error messages are generated and compilation is immediately terminated.
4567 GNAT to continue with semantic analysis even if syntax errors have been
4568 found. This may enable the detection of more errors in a single run. On
4569 the other hand, the semantic analyzer is more likely to encounter some
4570 internal fatal error when given a syntactically invalid tree.
4573 @cindex @option{-gnatQ} (@command{gcc})
4574 In normal operation mode, the @file{ALI} file is not generated if any
4575 illegalities are detected in the program. The use of @option{-gnatQ} forces
4576 generation of the @file{ALI} file. This file is marked as being in
4577 error, so it cannot be used for binding purposes, but it does contain
4578 reasonably complete cross-reference information, and thus may be useful
4579 for use by tools (e.g., semantic browsing tools or integrated development
4580 environments) that are driven from the @file{ALI} file. This switch
4581 implies @option{-gnatq}, since the semantic phase must be run to get a
4582 meaningful ALI file.
4584 In addition, if @option{-gnatt} is also specified, then the tree file is
4585 generated even if there are illegalities. It may be useful in this case
4586 to also specify @option{-gnatq} to ensure that full semantic processing
4587 occurs. The resulting tree file can be processed by ASIS, for the purpose
4588 of providing partial information about illegal units, but if the error
4589 causes the tree to be badly malformed, then ASIS may crash during the
4592 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4593 being in error, @command{gnatmake} will attempt to recompile the source when it
4594 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4596 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4597 since ALI files are never generated if @option{-gnats} is set.
4601 @node Warning Message Control
4602 @subsection Warning Message Control
4603 @cindex Warning messages
4605 In addition to error messages, which correspond to illegalities as defined
4606 in the Ada Reference Manual, the compiler detects two kinds of warning
4609 First, the compiler considers some constructs suspicious and generates a
4610 warning message to alert you to a possible error. Second, if the
4611 compiler detects a situation that is sure to raise an exception at
4612 run time, it generates a warning message. The following shows an example
4613 of warning messages:
4615 e.adb:4:24: warning: creation of object may raise Storage_Error
4616 e.adb:10:17: warning: static value out of range
4617 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4621 GNAT considers a large number of situations as appropriate
4622 for the generation of warning messages. As always, warnings are not
4623 definite indications of errors. For example, if you do an out-of-range
4624 assignment with the deliberate intention of raising a
4625 @code{Constraint_Error} exception, then the warning that may be
4626 issued does not indicate an error. Some of the situations for which GNAT
4627 issues warnings (at least some of the time) are given in the following
4628 list. This list is not complete, and new warnings are often added to
4629 subsequent versions of GNAT. The list is intended to give a general idea
4630 of the kinds of warnings that are generated.
4634 Possible infinitely recursive calls
4637 Out-of-range values being assigned
4640 Possible order of elaboration problems
4643 Assertions (pragma Assert) that are sure to fail
4649 Address clauses with possibly unaligned values, or where an attempt is
4650 made to overlay a smaller variable with a larger one.
4653 Fixed-point type declarations with a null range
4656 Direct_IO or Sequential_IO instantiated with a type that has access values
4659 Variables that are never assigned a value
4662 Variables that are referenced before being initialized
4665 Task entries with no corresponding @code{accept} statement
4668 Duplicate accepts for the same task entry in a @code{select}
4671 Objects that take too much storage
4674 Unchecked conversion between types of differing sizes
4677 Missing @code{return} statement along some execution path in a function
4680 Incorrect (unrecognized) pragmas
4683 Incorrect external names
4686 Allocation from empty storage pool
4689 Potentially blocking operation in protected type
4692 Suspicious parenthesization of expressions
4695 Mismatching bounds in an aggregate
4698 Attempt to return local value by reference
4701 Premature instantiation of a generic body
4704 Attempt to pack aliased components
4707 Out of bounds array subscripts
4710 Wrong length on string assignment
4713 Violations of style rules if style checking is enabled
4716 Unused @code{with} clauses
4719 @code{Bit_Order} usage that does not have any effect
4722 @code{Standard.Duration} used to resolve universal fixed expression
4725 Dereference of possibly null value
4728 Declaration that is likely to cause storage error
4731 Internal GNAT unit @code{with}'ed by application unit
4734 Values known to be out of range at compile time
4737 Unreferenced labels and variables
4740 Address overlays that could clobber memory
4743 Unexpected initialization when address clause present
4746 Bad alignment for address clause
4749 Useless type conversions
4752 Redundant assignment statements and other redundant constructs
4755 Useless exception handlers
4758 Accidental hiding of name by child unit
4761 Access before elaboration detected at compile time
4764 A range in a @code{for} loop that is known to be null or might be null
4769 The following section lists compiler switches that are available
4770 to control the handling of warning messages. It is also possible
4771 to exercise much finer control over what warnings are issued and
4772 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
4773 gnat_rm, GNAT Reference manual}.
4778 @emph{Activate all optional errors.}
4779 @cindex @option{-gnatwa} (@command{gcc})
4780 This switch activates most optional warning messages, see remaining list
4781 in this section for details on optional warning messages that can be
4782 individually controlled. The warnings that are not turned on by this
4784 @option{-gnatwd} (implicit dereferencing),
4785 @option{-gnatwh} (hiding),
4786 @option{-gnatwl} (elaboration warnings),
4787 @option{-gnatw.o} (warn on values set by out parameters ignored)
4788 and @option{-gnatwt} (tracking of deleted conditional code).
4789 All other optional warnings are turned on.
4792 @emph{Suppress all optional errors.}
4793 @cindex @option{-gnatwA} (@command{gcc})
4794 This switch suppresses all optional warning messages, see remaining list
4795 in this section for details on optional warning messages that can be
4796 individually controlled.
4799 @emph{Activate warnings on failing assertions.}
4800 @cindex @option{-gnatw.a} (@command{gcc})
4801 @cindex Assert failures
4802 This switch activates warnings for assertions where the compiler can tell at
4803 compile time that the assertion will fail. Note that this warning is given
4804 even if assertions are disabled. The default is that such warnings are
4808 @emph{Suppress warnings on failing assertions.}
4809 @cindex @option{-gnatw.A} (@command{gcc})
4810 @cindex Assert failures
4811 This switch suppresses warnings for assertions where the compiler can tell at
4812 compile time that the assertion will fail.
4815 @emph{Activate warnings on bad fixed values.}
4816 @cindex @option{-gnatwb} (@command{gcc})
4817 @cindex Bad fixed values
4818 @cindex Fixed-point Small value
4820 This switch activates warnings for static fixed-point expressions whose
4821 value is not an exact multiple of Small. Such values are implementation
4822 dependent, since an implementation is free to choose either of the multiples
4823 that surround the value. GNAT always chooses the closer one, but this is not
4824 required behavior, and it is better to specify a value that is an exact
4825 multiple, ensuring predictable execution. The default is that such warnings
4829 @emph{Suppress warnings on bad fixed values.}
4830 @cindex @option{-gnatwB} (@command{gcc})
4831 This switch suppresses warnings for static fixed-point expressions whose
4832 value is not an exact multiple of Small.
4835 @emph{Activate warnings on conditionals.}
4836 @cindex @option{-gnatwc} (@command{gcc})
4837 @cindex Conditionals, constant
4838 This switch activates warnings for conditional expressions used in
4839 tests that are known to be True or False at compile time. The default
4840 is that such warnings are not generated.
4841 Note that this warning does
4842 not get issued for the use of boolean variables or constants whose
4843 values are known at compile time, since this is a standard technique
4844 for conditional compilation in Ada, and this would generate too many
4845 false positive warnings.
4847 This warning option also activates a special test for comparisons using
4848 the operators ``>='' and`` <=''.
4849 If the compiler can tell that only the equality condition is possible,
4850 then it will warn that the ``>'' or ``<'' part of the test
4851 is useless and that the operator could be replaced by ``=''.
4852 An example would be comparing a @code{Natural} variable <= 0.
4854 This warning option also generates warnings if
4855 one or both tests is optimized away in a membership test for integer
4856 values if the result can be determined at compile time. Range tests on
4857 enumeration types are not included, since it is common for such tests
4858 to include an end point.
4860 This warning can also be turned on using @option{-gnatwa}.
4863 @emph{Suppress warnings on conditionals.}
4864 @cindex @option{-gnatwC} (@command{gcc})
4865 This switch suppresses warnings for conditional expressions used in
4866 tests that are known to be True or False at compile time.
4869 @emph{Activate warnings on missing component clauses.}
4870 @cindex @option{-gnatw.c} (@command{gcc})
4871 @cindex Component clause, missing
4872 This switch activates warnings for record components where a record
4873 representation clause is present and has component clauses for the
4874 majority, but not all, of the components. A warning is given for each
4875 component for which no component clause is present.
4877 This warning can also be turned on using @option{-gnatwa}.
4880 @emph{Suppress warnings on missing component clauses.}
4881 @cindex @option{-gnatwC} (@command{gcc})
4882 This switch suppresses warnings for record components that are
4883 missing a component clause in the situation described above.
4886 @emph{Activate warnings on implicit dereferencing.}
4887 @cindex @option{-gnatwd} (@command{gcc})
4888 If this switch is set, then the use of a prefix of an access type
4889 in an indexed component, slice, or selected component without an
4890 explicit @code{.all} will generate a warning. With this warning
4891 enabled, access checks occur only at points where an explicit
4892 @code{.all} appears in the source code (assuming no warnings are
4893 generated as a result of this switch). The default is that such
4894 warnings are not generated.
4895 Note that @option{-gnatwa} does not affect the setting of
4896 this warning option.
4899 @emph{Suppress warnings on implicit dereferencing.}
4900 @cindex @option{-gnatwD} (@command{gcc})
4901 @cindex Implicit dereferencing
4902 @cindex Dereferencing, implicit
4903 This switch suppresses warnings for implicit dereferences in
4904 indexed components, slices, and selected components.
4907 @emph{Treat warnings as errors.}
4908 @cindex @option{-gnatwe} (@command{gcc})
4909 @cindex Warnings, treat as error
4910 This switch causes warning messages to be treated as errors.
4911 The warning string still appears, but the warning messages are counted
4912 as errors, and prevent the generation of an object file.
4915 @emph{Activate every optional warning}
4916 @cindex @option{-gnatw.e} (@command{gcc})
4917 @cindex Warnings, activate every optional warning
4918 This switch activates all optional warnings, including those which
4919 are not activated by @code{-gnatwa}.
4922 @emph{Activate warnings on unreferenced formals.}
4923 @cindex @option{-gnatwf} (@command{gcc})
4924 @cindex Formals, unreferenced
4925 This switch causes a warning to be generated if a formal parameter
4926 is not referenced in the body of the subprogram. This warning can
4927 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
4928 default is that these warnings are not generated.
4931 @emph{Suppress warnings on unreferenced formals.}
4932 @cindex @option{-gnatwF} (@command{gcc})
4933 This switch suppresses warnings for unreferenced formal
4934 parameters. Note that the
4935 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4936 effect of warning on unreferenced entities other than subprogram
4940 @emph{Activate warnings on unrecognized pragmas.}
4941 @cindex @option{-gnatwg} (@command{gcc})
4942 @cindex Pragmas, unrecognized
4943 This switch causes a warning to be generated if an unrecognized
4944 pragma is encountered. Apart from issuing this warning, the
4945 pragma is ignored and has no effect. This warning can
4946 also be turned on using @option{-gnatwa}. The default
4947 is that such warnings are issued (satisfying the Ada Reference
4948 Manual requirement that such warnings appear).
4951 @emph{Suppress warnings on unrecognized pragmas.}
4952 @cindex @option{-gnatwG} (@command{gcc})
4953 This switch suppresses warnings for unrecognized pragmas.
4956 @emph{Activate warnings on hiding.}
4957 @cindex @option{-gnatwh} (@command{gcc})
4958 @cindex Hiding of Declarations
4959 This switch activates warnings on hiding declarations.
4960 A declaration is considered hiding
4961 if it is for a non-overloadable entity, and it declares an entity with the
4962 same name as some other entity that is directly or use-visible. The default
4963 is that such warnings are not generated.
4964 Note that @option{-gnatwa} does not affect the setting of this warning option.
4967 @emph{Suppress warnings on hiding.}
4968 @cindex @option{-gnatwH} (@command{gcc})
4969 This switch suppresses warnings on hiding declarations.
4972 @emph{Activate warnings on implementation units.}
4973 @cindex @option{-gnatwi} (@command{gcc})
4974 This switch activates warnings for a @code{with} of an internal GNAT
4975 implementation unit, defined as any unit from the @code{Ada},
4976 @code{Interfaces}, @code{GNAT},
4977 ^^@code{DEC},^ or @code{System}
4978 hierarchies that is not
4979 documented in either the Ada Reference Manual or the GNAT
4980 Programmer's Reference Manual. Such units are intended only
4981 for internal implementation purposes and should not be @code{with}'ed
4982 by user programs. The default is that such warnings are generated
4983 This warning can also be turned on using @option{-gnatwa}.
4986 @emph{Disable warnings on implementation units.}
4987 @cindex @option{-gnatwI} (@command{gcc})
4988 This switch disables warnings for a @code{with} of an internal GNAT
4989 implementation unit.
4992 @emph{Activate warnings on obsolescent features (Annex J).}
4993 @cindex @option{-gnatwj} (@command{gcc})
4994 @cindex Features, obsolescent
4995 @cindex Obsolescent features
4996 If this warning option is activated, then warnings are generated for
4997 calls to subprograms marked with @code{pragma Obsolescent} and
4998 for use of features in Annex J of the Ada Reference Manual. In the
4999 case of Annex J, not all features are flagged. In particular use
5000 of the renamed packages (like @code{Text_IO}) and use of package
5001 @code{ASCII} are not flagged, since these are very common and
5002 would generate many annoying positive warnings. The default is that
5003 such warnings are not generated. This warning is also turned on by
5004 the use of @option{-gnatwa}.
5006 In addition to the above cases, warnings are also generated for
5007 GNAT features that have been provided in past versions but which
5008 have been superseded (typically by features in the new Ada standard).
5009 For example, @code{pragma Ravenscar} will be flagged since its
5010 function is replaced by @code{pragma Profile(Ravenscar)}.
5012 Note that this warning option functions differently from the
5013 restriction @code{No_Obsolescent_Features} in two respects.
5014 First, the restriction applies only to annex J features.
5015 Second, the restriction does flag uses of package @code{ASCII}.
5018 @emph{Suppress warnings on obsolescent features (Annex J).}
5019 @cindex @option{-gnatwJ} (@command{gcc})
5020 This switch disables warnings on use of obsolescent features.
5023 @emph{Activate warnings on variables that could be constants.}
5024 @cindex @option{-gnatwk} (@command{gcc})
5025 This switch activates warnings for variables that are initialized but
5026 never modified, and then could be declared constants. The default is that
5027 such warnings are not given.
5028 This warning can also be turned on using @option{-gnatwa}.
5031 @emph{Suppress warnings on variables that could be constants.}
5032 @cindex @option{-gnatwK} (@command{gcc})
5033 This switch disables warnings on variables that could be declared constants.
5036 @emph{Activate warnings for elaboration pragmas.}
5037 @cindex @option{-gnatwl} (@command{gcc})
5038 @cindex Elaboration, warnings
5039 This switch activates warnings on missing
5040 @code{Elaborate_All} and @code{Elaborate} pragmas.
5041 See the section in this guide on elaboration checking for details on
5042 when such pragmas should be used. In dynamic elaboration mode, this switch
5043 generations warnings about the need to add elaboration pragmas. Note however,
5044 that if you blindly follow these warnings, and add @code{Elaborate_All}
5045 warnings wherever they are recommended, you basically end up with the
5046 equivalent of the static elaboration model, which may not be what you want for
5047 legacy code for which the static model does not work.
5049 For the static model, the messages generated are labeled "info:" (for
5050 information messages). They are not warnings to add elaboration pragmas,
5051 merely informational messages showing what implicit elaboration pragmas
5052 have been added, for use in analyzing elaboration circularity problems.
5054 Warnings are also generated if you
5055 are using the static mode of elaboration, and a @code{pragma Elaborate}
5056 is encountered. The default is that such warnings
5058 This warning is not automatically turned on by the use of @option{-gnatwa}.
5061 @emph{Suppress warnings for elaboration pragmas.}
5062 @cindex @option{-gnatwL} (@command{gcc})
5063 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5064 See the section in this guide on elaboration checking for details on
5065 when such pragmas should be used.
5068 @emph{Activate warnings on modified but unreferenced variables.}
5069 @cindex @option{-gnatwm} (@command{gcc})
5070 This switch activates warnings for variables that are assigned (using
5071 an initialization value or with one or more assignment statements) but
5072 whose value is never read. The warning is suppressed for volatile
5073 variables and also for variables that are renamings of other variables
5074 or for which an address clause is given.
5075 This warning can also be turned on using @option{-gnatwa}.
5076 The default is that these warnings are not given.
5079 @emph{Disable warnings on modified but unreferenced variables.}
5080 @cindex @option{-gnatwM} (@command{gcc})
5081 This switch disables warnings for variables that are assigned or
5082 initialized, but never read.
5085 @emph{Set normal warnings mode.}
5086 @cindex @option{-gnatwn} (@command{gcc})
5087 This switch sets normal warning mode, in which enabled warnings are
5088 issued and treated as warnings rather than errors. This is the default
5089 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5090 an explicit @option{-gnatws} or
5091 @option{-gnatwe}. It also cancels the effect of the
5092 implicit @option{-gnatwe} that is activated by the
5093 use of @option{-gnatg}.
5096 @emph{Activate warnings on address clause overlays.}
5097 @cindex @option{-gnatwo} (@command{gcc})
5098 @cindex Address Clauses, warnings
5099 This switch activates warnings for possibly unintended initialization
5100 effects of defining address clauses that cause one variable to overlap
5101 another. The default is that such warnings are generated.
5102 This warning can also be turned on using @option{-gnatwa}.
5105 @emph{Suppress warnings on address clause overlays.}
5106 @cindex @option{-gnatwO} (@command{gcc})
5107 This switch suppresses warnings on possibly unintended initialization
5108 effects of defining address clauses that cause one variable to overlap
5112 @emph{Activate warnings on modified but unreferenced out parameters.}
5113 @cindex @option{-gnatw.o} (@command{gcc})
5114 This switch activates warnings for variables that are modified by using
5115 them as actuals for a call to a procedure with an out mode formal, where
5116 the resulting assigned value is never read. It is applicable in the case
5117 where there is more than one out mode formal. If there is only one out
5118 mode formal, the warning is issued by default (controlled by -gnatwu).
5119 The warning is suppressed for volatile
5120 variables and also for variables that are renamings of other variables
5121 or for which an address clause is given.
5122 The default is that these warnings are not given. Note that this warning
5123 is not included in -gnatwa, it must be activated explicitly.
5126 @emph{Disable warnings on modified but unreferenced out parameters.}
5127 @cindex @option{-gnatw.O} (@command{gcc})
5128 This switch suppresses warnings for variables that are modified by using
5129 them as actuals for a call to a procedure with an out mode formal, where
5130 the resulting assigned value is never read.
5133 @emph{Activate warnings on ineffective pragma Inlines.}
5134 @cindex @option{-gnatwp} (@command{gcc})
5135 @cindex Inlining, warnings
5136 This switch activates warnings for failure of front end inlining
5137 (activated by @option{-gnatN}) to inline a particular call. There are
5138 many reasons for not being able to inline a call, including most
5139 commonly that the call is too complex to inline. The default is
5140 that such warnings are not given.
5141 This warning can also be turned on using @option{-gnatwa}.
5142 Warnings on ineffective inlining by the gcc back-end can be activated
5143 separately, using the gcc switch -Winline.
5146 @emph{Suppress warnings on ineffective pragma Inlines.}
5147 @cindex @option{-gnatwP} (@command{gcc})
5148 This switch suppresses warnings on ineffective pragma Inlines. If the
5149 inlining mechanism cannot inline a call, it will simply ignore the
5153 @emph{Activate warnings on parameter ordering.}
5154 @cindex @option{-gnatw.p} (@command{gcc})
5155 @cindex Parameter order, warnings
5156 This switch activates warnings for cases of suspicious parameter
5157 ordering when the list of arguments are all simple identifiers that
5158 match the names of the formals, but are in a different order. The
5159 warning is suppressed if any use of named parameter notation is used,
5160 so this is the appropriate way to suppress a false positive (and
5161 serves to emphasize that the "misordering" is deliberate). The
5163 that such warnings are not given.
5164 This warning can also be turned on using @option{-gnatwa}.
5167 @emph{Suppress warnings on parameter ordering.}
5168 @cindex @option{-gnatw.P} (@command{gcc})
5169 This switch suppresses warnings on cases of suspicious parameter
5173 @emph{Activate warnings on questionable missing parentheses.}
5174 @cindex @option{-gnatwq} (@command{gcc})
5175 @cindex Parentheses, warnings
5176 This switch activates warnings for cases where parentheses are not used and
5177 the result is potential ambiguity from a readers point of view. For example
5178 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5179 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5180 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5181 follow the rule of always parenthesizing to make the association clear, and
5182 this warning switch warns if such parentheses are not present. The default
5183 is that these warnings are given.
5184 This warning can also be turned on using @option{-gnatwa}.
5187 @emph{Suppress warnings on questionable missing parentheses.}
5188 @cindex @option{-gnatwQ} (@command{gcc})
5189 This switch suppresses warnings for cases where the association is not
5190 clear and the use of parentheses is preferred.
5193 @emph{Activate warnings on redundant constructs.}
5194 @cindex @option{-gnatwr} (@command{gcc})
5195 This switch activates warnings for redundant constructs. The following
5196 is the current list of constructs regarded as redundant:
5200 Assignment of an item to itself.
5202 Type conversion that converts an expression to its own type.
5204 Use of the attribute @code{Base} where @code{typ'Base} is the same
5207 Use of pragma @code{Pack} when all components are placed by a record
5208 representation clause.
5210 Exception handler containing only a reraise statement (raise with no
5211 operand) which has no effect.
5213 Use of the operator abs on an operand that is known at compile time
5216 Comparison of boolean expressions to an explicit True value.
5219 This warning can also be turned on using @option{-gnatwa}.
5220 The default is that warnings for redundant constructs are not given.
5223 @emph{Suppress warnings on redundant constructs.}
5224 @cindex @option{-gnatwR} (@command{gcc})
5225 This switch suppresses warnings for redundant constructs.
5228 @emph{Suppress all warnings.}
5229 @cindex @option{-gnatws} (@command{gcc})
5230 This switch completely suppresses the
5231 output of all warning messages from the GNAT front end.
5232 Note that it does not suppress warnings from the @command{gcc} back end.
5233 To suppress these back end warnings as well, use the switch @option{-w}
5234 in addition to @option{-gnatws}.
5237 @emph{Activate warnings for tracking of deleted conditional code.}
5238 @cindex @option{-gnatwt} (@command{gcc})
5239 @cindex Deactivated code, warnings
5240 @cindex Deleted code, warnings
5241 This switch activates warnings for tracking of code in conditionals (IF and
5242 CASE statements) that is detected to be dead code which cannot be executed, and
5243 which is removed by the front end. This warning is off by default, and is not
5244 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5245 useful for detecting deactivated code in certified applications.
5248 @emph{Suppress warnings for tracking of deleted conditional code.}
5249 @cindex @option{-gnatwT} (@command{gcc})
5250 This switch suppresses warnings for tracking of deleted conditional code.
5253 @emph{Activate warnings on unused entities.}
5254 @cindex @option{-gnatwu} (@command{gcc})
5255 This switch activates warnings to be generated for entities that
5256 are declared but not referenced, and for units that are @code{with}'ed
5258 referenced. In the case of packages, a warning is also generated if
5259 no entities in the package are referenced. This means that if the package
5260 is referenced but the only references are in @code{use}
5261 clauses or @code{renames}
5262 declarations, a warning is still generated. A warning is also generated
5263 for a generic package that is @code{with}'ed but never instantiated.
5264 In the case where a package or subprogram body is compiled, and there
5265 is a @code{with} on the corresponding spec
5266 that is only referenced in the body,
5267 a warning is also generated, noting that the
5268 @code{with} can be moved to the body. The default is that
5269 such warnings are not generated.
5270 This switch also activates warnings on unreferenced formals
5271 (it includes the effect of @option{-gnatwf}).
5272 This warning can also be turned on using @option{-gnatwa}.
5275 @emph{Suppress warnings on unused entities.}
5276 @cindex @option{-gnatwU} (@command{gcc})
5277 This switch suppresses warnings for unused entities and packages.
5278 It also turns off warnings on unreferenced formals (and thus includes
5279 the effect of @option{-gnatwF}).
5282 @emph{Activate warnings on unassigned variables.}
5283 @cindex @option{-gnatwv} (@command{gcc})
5284 @cindex Unassigned variable warnings
5285 This switch activates warnings for access to variables which
5286 may not be properly initialized. The default is that
5287 such warnings are generated.
5288 This warning can also be turned on using @option{-gnatwa}.
5291 @emph{Suppress warnings on unassigned variables.}
5292 @cindex @option{-gnatwV} (@command{gcc})
5293 This switch suppresses warnings for access to variables which
5294 may not be properly initialized.
5295 For variables of a composite type, the warning can also be suppressed in
5296 Ada 2005 by using a default initialization with a box. For example, if
5297 Table is an array of records whose components are only partially uninitialized,
5298 then the following code:
5300 @smallexample @c ada
5301 Tab : Table := (others => <>);
5304 will suppress warnings on subsequent statements that access components
5308 @emph{Activate warnings on wrong low bound assumption.}
5309 @cindex @option{-gnatww} (@command{gcc})
5310 @cindex String indexing warnings
5311 This switch activates warnings for indexing an unconstrained string parameter
5312 with a literal or S'Length. This is a case where the code is assuming that the
5313 low bound is one, which is in general not true (for example when a slice is
5314 passed). The default is that such warnings are generated.
5315 This warning can also be turned on using @option{-gnatwa}.
5318 @emph{Suppress warnings on wrong low bound assumption.}
5319 @cindex @option{-gnatwW} (@command{gcc})
5320 This switch suppresses warnings for indexing an unconstrained string parameter
5321 with a literal or S'Length. Note that this warning can also be suppressed
5322 in a particular case by adding an
5323 assertion that the lower bound is 1,
5324 as shown in the following example.
5326 @smallexample @c ada
5327 procedure K (S : String) is
5328 pragma Assert (S'First = 1);
5333 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5334 @cindex @option{-gnatw.w} (@command{gcc})
5335 @cindex Warnings Off control
5336 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5337 where either the pragma is entirely useless (because it suppresses no
5338 warnings), or it could be replaced by @code{pragma Unreferenced} or
5339 @code{pragma Unmodified}.The default is that these warnings are not given.
5340 Note that this warning is not included in -gnatwa, it must be
5341 activated explicitly.
5344 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5345 @cindex @option{-gnatw.W} (@command{gcc})
5346 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5349 @emph{Activate warnings on Export/Import pragmas.}
5350 @cindex @option{-gnatwx} (@command{gcc})
5351 @cindex Export/Import pragma warnings
5352 This switch activates warnings on Export/Import pragmas when
5353 the compiler detects a possible conflict between the Ada and
5354 foreign language calling sequences. For example, the use of
5355 default parameters in a convention C procedure is dubious
5356 because the C compiler cannot supply the proper default, so
5357 a warning is issued. The default is that such warnings are
5359 This warning can also be turned on using @option{-gnatwa}.
5362 @emph{Suppress warnings on Export/Import pragmas.}
5363 @cindex @option{-gnatwX} (@command{gcc})
5364 This switch suppresses warnings on Export/Import pragmas.
5365 The sense of this is that you are telling the compiler that
5366 you know what you are doing in writing the pragma, and it
5367 should not complain at you.
5370 @emph{Activate warnings for No_Exception_Propagation mode.}
5371 @cindex @option{-gnatwm} (@command{gcc})
5372 This switch activates warnings for exception usage when pragma Restrictions
5373 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5374 explicit exception raises which are not covered by a local handler, and for
5375 exception handlers which do not cover a local raise. The default is that these
5376 warnings are not given.
5379 @emph{Disable warnings for No_Exception_Propagation mode.}
5380 This switch disables warnings for exception usage when pragma Restrictions
5381 (No_Exception_Propagation) is in effect.
5384 @emph{Activate warnings for Ada 2005 compatibility issues.}
5385 @cindex @option{-gnatwy} (@command{gcc})
5386 @cindex Ada 2005 compatibility issues warnings
5387 For the most part Ada 2005 is upwards compatible with Ada 95,
5388 but there are some exceptions (for example the fact that
5389 @code{interface} is now a reserved word in Ada 2005). This
5390 switch activates several warnings to help in identifying
5391 and correcting such incompatibilities. The default is that
5392 these warnings are generated. Note that at one point Ada 2005
5393 was called Ada 0Y, hence the choice of character.
5394 This warning can also be turned on using @option{-gnatwa}.
5397 @emph{Disable warnings for Ada 2005 compatibility issues.}
5398 @cindex @option{-gnatwY} (@command{gcc})
5399 @cindex Ada 2005 compatibility issues warnings
5400 This switch suppresses several warnings intended to help in identifying
5401 incompatibilities between Ada 95 and Ada 2005.
5404 @emph{Activate warnings on unchecked conversions.}
5405 @cindex @option{-gnatwz} (@command{gcc})
5406 @cindex Unchecked_Conversion warnings
5407 This switch activates warnings for unchecked conversions
5408 where the types are known at compile time to have different
5410 is that such warnings are generated. Warnings are also
5411 generated for subprogram pointers with different conventions,
5412 and, on VMS only, for data pointers with different conventions.
5413 This warning can also be turned on using @option{-gnatwa}.
5416 @emph{Suppress warnings on unchecked conversions.}
5417 @cindex @option{-gnatwZ} (@command{gcc})
5418 This switch suppresses warnings for unchecked conversions
5419 where the types are known at compile time to have different
5420 sizes or conventions.
5422 @item ^-Wunused^WARNINGS=UNUSED^
5423 @cindex @option{-Wunused}
5424 The warnings controlled by the @option{-gnatw} switch are generated by
5425 the front end of the compiler. The @option{GCC} back end can provide
5426 additional warnings and they are controlled by the @option{-W} switch.
5427 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5428 warnings for entities that are declared but not referenced.
5430 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5431 @cindex @option{-Wuninitialized}
5432 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5433 the back end warning for uninitialized variables. This switch must be
5434 used in conjunction with an optimization level greater than zero.
5436 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5437 @cindex @option{-Wall}
5438 This switch enables all the above warnings from the @option{GCC} back end.
5439 The code generator detects a number of warning situations that are missed
5440 by the @option{GNAT} front end, and this switch can be used to activate them.
5441 The use of this switch also sets the default front end warning mode to
5442 @option{-gnatwa}, that is, most front end warnings activated as well.
5444 @item ^-w^/NO_BACK_END_WARNINGS^
5446 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5447 The use of this switch also sets the default front end warning mode to
5448 @option{-gnatws}, that is, front end warnings suppressed as well.
5454 A string of warning parameters can be used in the same parameter. For example:
5461 will turn on all optional warnings except for elaboration pragma warnings,
5462 and also specify that warnings should be treated as errors.
5464 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5489 @node Debugging and Assertion Control
5490 @subsection Debugging and Assertion Control
5494 @cindex @option{-gnata} (@command{gcc})
5500 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5501 are ignored. This switch, where @samp{a} stands for assert, causes
5502 @code{Assert} and @code{Debug} pragmas to be activated.
5504 The pragmas have the form:
5508 @b{pragma} Assert (@var{Boolean-expression} [,
5509 @var{static-string-expression}])
5510 @b{pragma} Debug (@var{procedure call})
5515 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5516 If the result is @code{True}, the pragma has no effect (other than
5517 possible side effects from evaluating the expression). If the result is
5518 @code{False}, the exception @code{Assert_Failure} declared in the package
5519 @code{System.Assertions} is
5520 raised (passing @var{static-string-expression}, if present, as the
5521 message associated with the exception). If no string expression is
5522 given the default is a string giving the file name and line number
5525 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5526 @code{pragma Debug} may appear within a declaration sequence, allowing
5527 debugging procedures to be called between declarations.
5530 @item /DEBUG[=debug-level]
5532 Specifies how much debugging information is to be included in
5533 the resulting object file where 'debug-level' is one of the following:
5536 Include both debugger symbol records and traceback
5538 This is the default setting.
5540 Include both debugger symbol records and traceback in
5543 Excludes both debugger symbol records and traceback
5544 the object file. Same as /NODEBUG.
5546 Includes only debugger symbol records in the object
5547 file. Note that this doesn't include traceback information.
5552 @node Validity Checking
5553 @subsection Validity Checking
5554 @findex Validity Checking
5557 The Ada Reference Manual has specific requirements for checking
5558 for invalid values. In particular, RM 13.9.1 requires that the
5559 evaluation of invalid values (for example from unchecked conversions),
5560 not result in erroneous execution. In GNAT, the result of such an
5561 evaluation in normal default mode is to either use the value
5562 unmodified, or to raise Constraint_Error in those cases where use
5563 of the unmodified value would cause erroneous execution. The cases
5564 where unmodified values might lead to erroneous execution are case
5565 statements (where a wild jump might result from an invalid value),
5566 and subscripts on the left hand side (where memory corruption could
5567 occur as a result of an invalid value).
5569 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5572 The @code{x} argument is a string of letters that
5573 indicate validity checks that are performed or not performed in addition
5574 to the default checks described above.
5577 The options allowed for this qualifier
5578 indicate validity checks that are performed or not performed in addition
5579 to the default checks described above.
5585 @emph{All validity checks.}
5586 @cindex @option{-gnatVa} (@command{gcc})
5587 All validity checks are turned on.
5589 That is, @option{-gnatVa} is
5590 equivalent to @option{gnatVcdfimorst}.
5594 @emph{Validity checks for copies.}
5595 @cindex @option{-gnatVc} (@command{gcc})
5596 The right hand side of assignments, and the initializing values of
5597 object declarations are validity checked.
5600 @emph{Default (RM) validity checks.}
5601 @cindex @option{-gnatVd} (@command{gcc})
5602 Some validity checks are done by default following normal Ada semantics
5604 A check is done in case statements that the expression is within the range
5605 of the subtype. If it is not, Constraint_Error is raised.
5606 For assignments to array components, a check is done that the expression used
5607 as index is within the range. If it is not, Constraint_Error is raised.
5608 Both these validity checks may be turned off using switch @option{-gnatVD}.
5609 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5610 switch @option{-gnatVd} will leave the checks turned on.
5611 Switch @option{-gnatVD} should be used only if you are sure that all such
5612 expressions have valid values. If you use this switch and invalid values
5613 are present, then the program is erroneous, and wild jumps or memory
5614 overwriting may occur.
5617 @emph{Validity checks for elementary components.}
5618 @cindex @option{-gnatVe} (@command{gcc})
5619 In the absence of this switch, assignments to record or array components are
5620 not validity checked, even if validity checks for assignments generally
5621 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5622 require valid data, but assignment of individual components does. So for
5623 example, there is a difference between copying the elements of an array with a
5624 slice assignment, compared to assigning element by element in a loop. This
5625 switch allows you to turn off validity checking for components, even when they
5626 are assigned component by component.
5629 @emph{Validity checks for floating-point values.}
5630 @cindex @option{-gnatVf} (@command{gcc})
5631 In the absence of this switch, validity checking occurs only for discrete
5632 values. If @option{-gnatVf} is specified, then validity checking also applies
5633 for floating-point values, and NaNs and infinities are considered invalid,
5634 as well as out of range values for constrained types. Note that this means
5635 that standard IEEE infinity mode is not allowed. The exact contexts
5636 in which floating-point values are checked depends on the setting of other
5637 options. For example,
5638 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5639 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5640 (the order does not matter) specifies that floating-point parameters of mode
5641 @code{in} should be validity checked.
5644 @emph{Validity checks for @code{in} mode parameters}
5645 @cindex @option{-gnatVi} (@command{gcc})
5646 Arguments for parameters of mode @code{in} are validity checked in function
5647 and procedure calls at the point of call.
5650 @emph{Validity checks for @code{in out} mode parameters.}
5651 @cindex @option{-gnatVm} (@command{gcc})
5652 Arguments for parameters of mode @code{in out} are validity checked in
5653 procedure calls at the point of call. The @code{'m'} here stands for
5654 modify, since this concerns parameters that can be modified by the call.
5655 Note that there is no specific option to test @code{out} parameters,
5656 but any reference within the subprogram will be tested in the usual
5657 manner, and if an invalid value is copied back, any reference to it
5658 will be subject to validity checking.
5661 @emph{No validity checks.}
5662 @cindex @option{-gnatVn} (@command{gcc})
5663 This switch turns off all validity checking, including the default checking
5664 for case statements and left hand side subscripts. Note that the use of
5665 the switch @option{-gnatp} suppresses all run-time checks, including
5666 validity checks, and thus implies @option{-gnatVn}. When this switch
5667 is used, it cancels any other @option{-gnatV} previously issued.
5670 @emph{Validity checks for operator and attribute operands.}
5671 @cindex @option{-gnatVo} (@command{gcc})
5672 Arguments for predefined operators and attributes are validity checked.
5673 This includes all operators in package @code{Standard},
5674 the shift operators defined as intrinsic in package @code{Interfaces}
5675 and operands for attributes such as @code{Pos}. Checks are also made
5676 on individual component values for composite comparisons, and on the
5677 expressions in type conversions and qualified expressions. Checks are
5678 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
5681 @emph{Validity checks for parameters.}
5682 @cindex @option{-gnatVp} (@command{gcc})
5683 This controls the treatment of parameters within a subprogram (as opposed
5684 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5685 of parameters on a call. If either of these call options is used, then
5686 normally an assumption is made within a subprogram that the input arguments
5687 have been validity checking at the point of call, and do not need checking
5688 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5689 is not made, and parameters are not assumed to be valid, so their validity
5690 will be checked (or rechecked) within the subprogram.
5693 @emph{Validity checks for function returns.}
5694 @cindex @option{-gnatVr} (@command{gcc})
5695 The expression in @code{return} statements in functions is validity
5699 @emph{Validity checks for subscripts.}
5700 @cindex @option{-gnatVs} (@command{gcc})
5701 All subscripts expressions are checked for validity, whether they appear
5702 on the right side or left side (in default mode only left side subscripts
5703 are validity checked).
5706 @emph{Validity checks for tests.}
5707 @cindex @option{-gnatVt} (@command{gcc})
5708 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5709 statements are checked, as well as guard expressions in entry calls.
5714 The @option{-gnatV} switch may be followed by
5715 ^a string of letters^a list of options^
5716 to turn on a series of validity checking options.
5718 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5719 specifies that in addition to the default validity checking, copies and
5720 function return expressions are to be validity checked.
5721 In order to make it easier
5722 to specify the desired combination of effects,
5724 the upper case letters @code{CDFIMORST} may
5725 be used to turn off the corresponding lower case option.
5728 the prefix @code{NO} on an option turns off the corresponding validity
5731 @item @code{NOCOPIES}
5732 @item @code{NODEFAULT}
5733 @item @code{NOFLOATS}
5734 @item @code{NOIN_PARAMS}
5735 @item @code{NOMOD_PARAMS}
5736 @item @code{NOOPERANDS}
5737 @item @code{NORETURNS}
5738 @item @code{NOSUBSCRIPTS}
5739 @item @code{NOTESTS}
5743 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5744 turns on all validity checking options except for
5745 checking of @code{@b{in out}} procedure arguments.
5747 The specification of additional validity checking generates extra code (and
5748 in the case of @option{-gnatVa} the code expansion can be substantial).
5749 However, these additional checks can be very useful in detecting
5750 uninitialized variables, incorrect use of unchecked conversion, and other
5751 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5752 is useful in conjunction with the extra validity checking, since this
5753 ensures that wherever possible uninitialized variables have invalid values.
5755 See also the pragma @code{Validity_Checks} which allows modification of
5756 the validity checking mode at the program source level, and also allows for
5757 temporary disabling of validity checks.
5759 @node Style Checking
5760 @subsection Style Checking
5761 @findex Style checking
5764 The @option{-gnaty^x^(option,option,@dots{})^} switch
5765 @cindex @option{-gnaty} (@command{gcc})
5766 causes the compiler to
5767 enforce specified style rules. A limited set of style rules has been used
5768 in writing the GNAT sources themselves. This switch allows user programs
5769 to activate all or some of these checks. If the source program fails a
5770 specified style check, an appropriate warning message is given, preceded by
5771 the character sequence ``(style)''.
5773 @code{(option,option,@dots{})} is a sequence of keywords
5776 The string @var{x} is a sequence of letters or digits
5778 indicating the particular style
5779 checks to be performed. The following checks are defined:
5784 @emph{Specify indentation level.}
5785 If a digit from 1-9 appears
5786 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5787 then proper indentation is checked, with the digit indicating the
5788 indentation level required. A value of zero turns off this style check.
5789 The general style of required indentation is as specified by
5790 the examples in the Ada Reference Manual. Full line comments must be
5791 aligned with the @code{--} starting on a column that is a multiple of
5792 the alignment level, or they may be aligned the same way as the following
5793 non-blank line (this is useful when full line comments appear in the middle
5797 @emph{Check attribute casing.}
5798 Attribute names, including the case of keywords such as @code{digits}
5799 used as attributes names, must be written in mixed case, that is, the
5800 initial letter and any letter following an underscore must be uppercase.
5801 All other letters must be lowercase.
5803 @item ^A^ARRAY_INDEXES^
5804 @emph{Use of array index numbers in array attributes.}
5805 When using the array attributes First, Last, Range,
5806 or Length, the index number must be omitted for one-dimensional arrays
5807 and is required for multi-dimensional arrays.
5810 @emph{Blanks not allowed at statement end.}
5811 Trailing blanks are not allowed at the end of statements. The purpose of this
5812 rule, together with h (no horizontal tabs), is to enforce a canonical format
5813 for the use of blanks to separate source tokens.
5816 @emph{Check comments.}
5817 Comments must meet the following set of rules:
5822 The ``@code{--}'' that starts the column must either start in column one,
5823 or else at least one blank must precede this sequence.
5826 Comments that follow other tokens on a line must have at least one blank
5827 following the ``@code{--}'' at the start of the comment.
5830 Full line comments must have two blanks following the ``@code{--}'' that
5831 starts the comment, with the following exceptions.
5834 A line consisting only of the ``@code{--}'' characters, possibly preceded
5835 by blanks is permitted.
5838 A comment starting with ``@code{--x}'' where @code{x} is a special character
5840 This allows proper processing of the output generated by specialized tools
5841 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5843 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5844 special character is defined as being in one of the ASCII ranges
5845 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
5846 Note that this usage is not permitted
5847 in GNAT implementation units (i.e., when @option{-gnatg} is used).
5850 A line consisting entirely of minus signs, possibly preceded by blanks, is
5851 permitted. This allows the construction of box comments where lines of minus
5852 signs are used to form the top and bottom of the box.
5855 A comment that starts and ends with ``@code{--}'' is permitted as long as at
5856 least one blank follows the initial ``@code{--}''. Together with the preceding
5857 rule, this allows the construction of box comments, as shown in the following
5860 ---------------------------
5861 -- This is a box comment --
5862 -- with two text lines. --
5863 ---------------------------
5867 @item ^d^DOS_LINE_ENDINGS^
5868 @emph{Check no DOS line terminators present.}
5869 All lines must be terminated by a single ASCII.LF
5870 character (in particular the DOS line terminator sequence CR/LF is not
5874 @emph{Check end/exit labels.}
5875 Optional labels on @code{end} statements ending subprograms and on
5876 @code{exit} statements exiting named loops, are required to be present.
5879 @emph{No form feeds or vertical tabs.}
5880 Neither form feeds nor vertical tab characters are permitted
5884 @emph{GNAT style mode}
5885 The set of style check switches is set to match that used by the GNAT sources.
5886 This may be useful when developing code that is eventually intended to be
5887 incorporated into GNAT. For further details, see GNAT sources.
5890 @emph{No horizontal tabs.}
5891 Horizontal tab characters are not permitted in the source text.
5892 Together with the b (no blanks at end of line) check, this
5893 enforces a canonical form for the use of blanks to separate
5897 @emph{Check if-then layout.}
5898 The keyword @code{then} must appear either on the same
5899 line as corresponding @code{if}, or on a line on its own, lined
5900 up under the @code{if} with at least one non-blank line in between
5901 containing all or part of the condition to be tested.
5904 @emph{check mode IN keywords}
5905 Mode @code{in} (the default mode) is not
5906 allowed to be given explicitly. @code{in out} is fine,
5907 but not @code{in} on its own.
5910 @emph{Check keyword casing.}
5911 All keywords must be in lower case (with the exception of keywords
5912 such as @code{digits} used as attribute names to which this check
5916 @emph{Check layout.}
5917 Layout of statement and declaration constructs must follow the
5918 recommendations in the Ada Reference Manual, as indicated by the
5919 form of the syntax rules. For example an @code{else} keyword must
5920 be lined up with the corresponding @code{if} keyword.
5922 There are two respects in which the style rule enforced by this check
5923 option are more liberal than those in the Ada Reference Manual. First
5924 in the case of record declarations, it is permissible to put the
5925 @code{record} keyword on the same line as the @code{type} keyword, and
5926 then the @code{end} in @code{end record} must line up under @code{type}.
5927 This is also permitted when the type declaration is split on two lines.
5928 For example, any of the following three layouts is acceptable:
5930 @smallexample @c ada
5953 Second, in the case of a block statement, a permitted alternative
5954 is to put the block label on the same line as the @code{declare} or
5955 @code{begin} keyword, and then line the @code{end} keyword up under
5956 the block label. For example both the following are permitted:
5958 @smallexample @c ada
5976 The same alternative format is allowed for loops. For example, both of
5977 the following are permitted:
5979 @smallexample @c ada
5981 Clear : while J < 10 loop
5992 @item ^Lnnn^MAX_NESTING=nnn^
5993 @emph{Set maximum nesting level}
5994 The maximum level of nesting of constructs (including subprograms, loops,
5995 blocks, packages, and conditionals) may not exceed the given value
5996 @option{nnn}. A value of zero disconnects this style check.
5998 @item ^m^LINE_LENGTH^
5999 @emph{Check maximum line length.}
6000 The length of source lines must not exceed 79 characters, including
6001 any trailing blanks. The value of 79 allows convenient display on an
6002 80 character wide device or window, allowing for possible special
6003 treatment of 80 character lines. Note that this count is of
6004 characters in the source text. This means that a tab character counts
6005 as one character in this count but a wide character sequence counts as
6006 a single character (however many bytes are needed in the encoding).
6008 @item ^Mnnn^MAX_LENGTH=nnn^
6009 @emph{Set maximum line length.}
6010 The length of lines must not exceed the
6011 given value @option{nnn}. The maximum value that can be specified is 32767.
6013 @item ^n^STANDARD_CASING^
6014 @emph{Check casing of entities in Standard.}
6015 Any identifier from Standard must be cased
6016 to match the presentation in the Ada Reference Manual (for example,
6017 @code{Integer} and @code{ASCII.NUL}).
6020 @emph{Turn off all style checks}
6021 All style check options are turned off.
6023 @item ^o^ORDERED_SUBPROGRAMS^
6024 @emph{Check order of subprogram bodies.}
6025 All subprogram bodies in a given scope
6026 (e.g.@: a package body) must be in alphabetical order. The ordering
6027 rule uses normal Ada rules for comparing strings, ignoring casing
6028 of letters, except that if there is a trailing numeric suffix, then
6029 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6033 @emph{Check pragma casing.}
6034 Pragma names must be written in mixed case, that is, the
6035 initial letter and any letter following an underscore must be uppercase.
6036 All other letters must be lowercase.
6038 @item ^r^REFERENCES^
6039 @emph{Check references.}
6040 All identifier references must be cased in the same way as the
6041 corresponding declaration. No specific casing style is imposed on
6042 identifiers. The only requirement is for consistency of references
6045 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6046 @emph{Check no statements after THEN/ELSE.}
6047 No statements are allowed
6048 on the same line as a THEN or ELSE keyword following the
6049 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6050 and a special exception allows a pragma to appear after ELSE.
6053 @emph{Check separate specs.}
6054 Separate declarations (``specs'') are required for subprograms (a
6055 body is not allowed to serve as its own declaration). The only
6056 exception is that parameterless library level procedures are
6057 not required to have a separate declaration. This exception covers
6058 the most frequent form of main program procedures.
6061 @emph{Check token spacing.}
6062 The following token spacing rules are enforced:
6067 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6070 The token @code{=>} must be surrounded by spaces.
6073 The token @code{<>} must be preceded by a space or a left parenthesis.
6076 Binary operators other than @code{**} must be surrounded by spaces.
6077 There is no restriction on the layout of the @code{**} binary operator.
6080 Colon must be surrounded by spaces.
6083 Colon-equal (assignment, initialization) must be surrounded by spaces.
6086 Comma must be the first non-blank character on the line, or be
6087 immediately preceded by a non-blank character, and must be followed
6091 If the token preceding a left parenthesis ends with a letter or digit, then
6092 a space must separate the two tokens.
6095 A right parenthesis must either be the first non-blank character on
6096 a line, or it must be preceded by a non-blank character.
6099 A semicolon must not be preceded by a space, and must not be followed by
6100 a non-blank character.
6103 A unary plus or minus may not be followed by a space.
6106 A vertical bar must be surrounded by spaces.
6109 @item ^u^UNNECESSARY_BLANK_LINES^
6110 @emph{Check unnecessary blank lines.}
6111 Unnecessary blank lines are not allowed. A blank line is considered
6112 unnecessary if it appears at the end of the file, or if more than
6113 one blank line occurs in sequence.
6115 @item ^x^XTRA_PARENS^
6116 @emph{Check extra parentheses.}
6117 Unnecessary extra level of parentheses (C-style) are not allowed
6118 around conditions in @code{if} statements, @code{while} statements and
6119 @code{exit} statements.
6121 @item ^y^ALL_BUILTIN^
6122 @emph{Set all standard style check options}
6123 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6124 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6125 @option{-gnatyS}, @option{-gnatyLnnn},
6126 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6130 @emph{Remove style check options}
6131 This causes any subsequent options in the string to act as canceling the
6132 corresponding style check option. To cancel maximum nesting level control,
6133 use @option{L} parameter witout any integer value after that, because any
6134 digit following @option{-} in the parameter string of the @option{-gnaty}
6135 option will be threated as canceling indentation check. The same is true
6136 for @option{M} parameter. @option{y} and @option{N} parameters are not
6137 allowed after @option{-}.
6140 This causes any subsequent options in the string to enable the corresponding
6141 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6147 @emph{Removing style check options}
6148 If the name of a style check is preceded by @option{NO} then the corresponding
6149 style check is turned off. For example @option{NOCOMMENTS} turns off style
6150 checking for comments.
6155 In the above rules, appearing in column one is always permitted, that is,
6156 counts as meeting either a requirement for a required preceding space,
6157 or as meeting a requirement for no preceding space.
6159 Appearing at the end of a line is also always permitted, that is, counts
6160 as meeting either a requirement for a following space, or as meeting
6161 a requirement for no following space.
6164 If any of these style rules is violated, a message is generated giving
6165 details on the violation. The initial characters of such messages are
6166 always ``@code{(style)}''. Note that these messages are treated as warning
6167 messages, so they normally do not prevent the generation of an object
6168 file. The @option{-gnatwe} switch can be used to treat warning messages,
6169 including style messages, as fatal errors.
6173 @option{-gnaty} on its own (that is not
6174 followed by any letters or digits), then the effect is equivalent
6175 to the use of @option{-gnatyy}, as described above, that is all
6176 built-in standard style check options are enabled.
6180 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6181 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6182 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6194 clears any previously set style checks.
6196 @node Run-Time Checks
6197 @subsection Run-Time Checks
6198 @cindex Division by zero
6199 @cindex Access before elaboration
6200 @cindex Checks, division by zero
6201 @cindex Checks, access before elaboration
6202 @cindex Checks, stack overflow checking
6205 If you compile with the default options, GNAT will insert many run-time
6206 checks into the compiled code, including code that performs range
6207 checking against constraints, but not arithmetic overflow checking for
6208 integer operations (including division by zero), checks for access
6209 before elaboration on subprogram calls, or stack overflow checking. All
6210 other run-time checks, as required by the Ada Reference Manual, are
6211 generated by default. The following @command{gcc} switches refine this
6217 @cindex @option{-gnatp} (@command{gcc})
6218 @cindex Suppressing checks
6219 @cindex Checks, suppressing
6221 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
6222 had been present in the source. Validity checks are also suppressed (in
6223 other words @option{-gnatp} also implies @option{-gnatVn}.
6224 Use this switch to improve the performance
6225 of the code at the expense of safety in the presence of invalid data or
6229 @cindex @option{-gnato} (@command{gcc})
6230 @cindex Overflow checks
6231 @cindex Check, overflow
6232 Enables overflow checking for integer operations.
6233 This causes GNAT to generate slower and larger executable
6234 programs by adding code to check for overflow (resulting in raising
6235 @code{Constraint_Error} as required by standard Ada
6236 semantics). These overflow checks correspond to situations in which
6237 the true value of the result of an operation may be outside the base
6238 range of the result type. The following example shows the distinction:
6240 @smallexample @c ada
6241 X1 : Integer := Integer'Last;
6242 X2 : Integer range 1 .. 5 := 5;
6243 X3 : Integer := Integer'Last;
6244 X4 : Integer range 1 .. 5 := 5;
6245 F : Float := 2.0E+20;
6254 Here the first addition results in a value that is outside the base range
6255 of Integer, and hence requires an overflow check for detection of the
6256 constraint error. Thus the first assignment to @code{X1} raises a
6257 @code{Constraint_Error} exception only if @option{-gnato} is set.
6259 The second increment operation results in a violation
6260 of the explicit range constraint, and such range checks are always
6261 performed (unless specifically suppressed with a pragma @code{suppress}
6262 or the use of @option{-gnatp}).
6264 The two conversions of @code{F} both result in values that are outside
6265 the base range of type @code{Integer} and thus will raise
6266 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6267 The fact that the result of the second conversion is assigned to
6268 variable @code{X4} with a restricted range is irrelevant, since the problem
6269 is in the conversion, not the assignment.
6271 Basically the rule is that in the default mode (@option{-gnato} not
6272 used), the generated code assures that all integer variables stay
6273 within their declared ranges, or within the base range if there is
6274 no declared range. This prevents any serious problems like indexes
6275 out of range for array operations.
6277 What is not checked in default mode is an overflow that results in
6278 an in-range, but incorrect value. In the above example, the assignments
6279 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6280 range of the target variable, but the result is wrong in the sense that
6281 it is too large to be represented correctly. Typically the assignment
6282 to @code{X1} will result in wrap around to the largest negative number.
6283 The conversions of @code{F} will result in some @code{Integer} value
6284 and if that integer value is out of the @code{X4} range then the
6285 subsequent assignment would generate an exception.
6287 @findex Machine_Overflows
6288 Note that the @option{-gnato} switch does not affect the code generated
6289 for any floating-point operations; it applies only to integer
6291 For floating-point, GNAT has the @code{Machine_Overflows}
6292 attribute set to @code{False} and the normal mode of operation is to
6293 generate IEEE NaN and infinite values on overflow or invalid operations
6294 (such as dividing 0.0 by 0.0).
6296 The reason that we distinguish overflow checking from other kinds of
6297 range constraint checking is that a failure of an overflow check, unlike
6298 for example the failure of a range check, can result in an incorrect
6299 value, but cannot cause random memory destruction (like an out of range
6300 subscript), or a wild jump (from an out of range case value). Overflow
6301 checking is also quite expensive in time and space, since in general it
6302 requires the use of double length arithmetic.
6304 Note again that @option{-gnato} is off by default, so overflow checking is
6305 not performed in default mode. This means that out of the box, with the
6306 default settings, GNAT does not do all the checks expected from the
6307 language description in the Ada Reference Manual. If you want all constraint
6308 checks to be performed, as described in this Manual, then you must
6309 explicitly use the -gnato switch either on the @command{gnatmake} or
6310 @command{gcc} command.
6313 @cindex @option{-gnatE} (@command{gcc})
6314 @cindex Elaboration checks
6315 @cindex Check, elaboration
6316 Enables dynamic checks for access-before-elaboration
6317 on subprogram calls and generic instantiations.
6318 For full details of the effect and use of this switch,
6319 @xref{Compiling Using gcc}.
6322 @cindex @option{-fstack-check} (@command{gcc})
6323 @cindex Stack Overflow Checking
6324 @cindex Checks, stack overflow checking
6325 Activates stack overflow checking. For full details of the effect and use of
6326 this switch see @ref{Stack Overflow Checking}.
6331 The setting of these switches only controls the default setting of the
6332 checks. You may modify them using either @code{Suppress} (to remove
6333 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6336 @node Using gcc for Syntax Checking
6337 @subsection Using @command{gcc} for Syntax Checking
6340 @cindex @option{-gnats} (@command{gcc})
6344 The @code{s} stands for ``syntax''.
6347 Run GNAT in syntax checking only mode. For
6348 example, the command
6351 $ gcc -c -gnats x.adb
6355 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6356 series of files in a single command
6358 , and can use wild cards to specify such a group of files.
6359 Note that you must specify the @option{-c} (compile
6360 only) flag in addition to the @option{-gnats} flag.
6363 You may use other switches in conjunction with @option{-gnats}. In
6364 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6365 format of any generated error messages.
6367 When the source file is empty or contains only empty lines and/or comments,
6368 the output is a warning:
6371 $ gcc -c -gnats -x ada toto.txt
6372 toto.txt:1:01: warning: empty file, contains no compilation units
6376 Otherwise, the output is simply the error messages, if any. No object file or
6377 ALI file is generated by a syntax-only compilation. Also, no units other
6378 than the one specified are accessed. For example, if a unit @code{X}
6379 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6380 check only mode does not access the source file containing unit
6383 @cindex Multiple units, syntax checking
6384 Normally, GNAT allows only a single unit in a source file. However, this
6385 restriction does not apply in syntax-check-only mode, and it is possible
6386 to check a file containing multiple compilation units concatenated
6387 together. This is primarily used by the @code{gnatchop} utility
6388 (@pxref{Renaming Files Using gnatchop}).
6391 @node Using gcc for Semantic Checking
6392 @subsection Using @command{gcc} for Semantic Checking
6395 @cindex @option{-gnatc} (@command{gcc})
6399 The @code{c} stands for ``check''.
6401 Causes the compiler to operate in semantic check mode,
6402 with full checking for all illegalities specified in the
6403 Ada Reference Manual, but without generation of any object code
6404 (no object file is generated).
6406 Because dependent files must be accessed, you must follow the GNAT
6407 semantic restrictions on file structuring to operate in this mode:
6411 The needed source files must be accessible
6412 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6415 Each file must contain only one compilation unit.
6418 The file name and unit name must match (@pxref{File Naming Rules}).
6421 The output consists of error messages as appropriate. No object file is
6422 generated. An @file{ALI} file is generated for use in the context of
6423 cross-reference tools, but this file is marked as not being suitable
6424 for binding (since no object file is generated).
6425 The checking corresponds exactly to the notion of
6426 legality in the Ada Reference Manual.
6428 Any unit can be compiled in semantics-checking-only mode, including
6429 units that would not normally be compiled (subunits,
6430 and specifications where a separate body is present).
6433 @node Compiling Different Versions of Ada
6434 @subsection Compiling Different Versions of Ada
6437 The switches described in this section allow you to explicitly specify
6438 the version of the Ada language that your programs are written in.
6439 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6440 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6441 indicate Ada 83 compatibility mode.
6444 @cindex Compatibility with Ada 83
6446 @item -gnat83 (Ada 83 Compatibility Mode)
6447 @cindex @option{-gnat83} (@command{gcc})
6448 @cindex ACVC, Ada 83 tests
6452 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6453 specifies that the program is to be compiled in Ada 83 mode. With
6454 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6455 semantics where this can be done easily.
6456 It is not possible to guarantee this switch does a perfect
6457 job; some subtle tests, such as are
6458 found in earlier ACVC tests (and that have been removed from the ACATS suite
6459 for Ada 95), might not compile correctly.
6460 Nevertheless, this switch may be useful in some circumstances, for example
6461 where, due to contractual reasons, existing code needs to be maintained
6462 using only Ada 83 features.
6464 With few exceptions (most notably the need to use @code{<>} on
6465 @cindex Generic formal parameters
6466 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6467 reserved words, and the use of packages
6468 with optional bodies), it is not necessary to specify the
6469 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6470 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6471 a correct Ada 83 program is usually also a correct program
6472 in these later versions of the language standard.
6473 For further information, please refer to @ref{Compatibility and Porting Guide}.
6475 @item -gnat95 (Ada 95 mode)
6476 @cindex @option{-gnat95} (@command{gcc})
6480 This switch directs the compiler to implement the Ada 95 version of the
6482 Since Ada 95 is almost completely upwards
6483 compatible with Ada 83, Ada 83 programs may generally be compiled using
6484 this switch (see the description of the @option{-gnat83} switch for further
6485 information about Ada 83 mode).
6486 If an Ada 2005 program is compiled in Ada 95 mode,
6487 uses of the new Ada 2005 features will cause error
6488 messages or warnings.
6490 This switch also can be used to cancel the effect of a previous
6491 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6493 @item -gnat05 (Ada 2005 mode)
6494 @cindex @option{-gnat05} (@command{gcc})
6495 @cindex Ada 2005 mode
6498 This switch directs the compiler to implement the Ada 2005 version of the
6500 Since Ada 2005 is almost completely upwards
6501 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6502 may generally be compiled using this switch (see the description of the
6503 @option{-gnat83} and @option{-gnat95} switches for further
6506 For information about the approved ``Ada Issues'' that have been incorporated
6507 into Ada 2005, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6508 Included with GNAT releases is a file @file{features-ada0y} that describes
6509 the set of implemented Ada 2005 features.
6513 @node Character Set Control
6514 @subsection Character Set Control
6516 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6517 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6520 Normally GNAT recognizes the Latin-1 character set in source program
6521 identifiers, as described in the Ada Reference Manual.
6523 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6524 single character ^^or word^ indicating the character set, as follows:
6528 ISO 8859-1 (Latin-1) identifiers
6531 ISO 8859-2 (Latin-2) letters allowed in identifiers
6534 ISO 8859-3 (Latin-3) letters allowed in identifiers
6537 ISO 8859-4 (Latin-4) letters allowed in identifiers
6540 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6543 ISO 8859-15 (Latin-9) letters allowed in identifiers
6546 IBM PC letters (code page 437) allowed in identifiers
6549 IBM PC letters (code page 850) allowed in identifiers
6551 @item ^f^FULL_UPPER^
6552 Full upper-half codes allowed in identifiers
6555 No upper-half codes allowed in identifiers
6558 Wide-character codes (that is, codes greater than 255)
6559 allowed in identifiers
6562 @xref{Foreign Language Representation}, for full details on the
6563 implementation of these character sets.
6565 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6566 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6567 Specify the method of encoding for wide characters.
6568 @var{e} is one of the following:
6573 Hex encoding (brackets coding also recognized)
6576 Upper half encoding (brackets encoding also recognized)
6579 Shift/JIS encoding (brackets encoding also recognized)
6582 EUC encoding (brackets encoding also recognized)
6585 UTF-8 encoding (brackets encoding also recognized)
6588 Brackets encoding only (default value)
6590 For full details on these encoding
6591 methods see @ref{Wide Character Encodings}.
6592 Note that brackets coding is always accepted, even if one of the other
6593 options is specified, so for example @option{-gnatW8} specifies that both
6594 brackets and UTF-8 encodings will be recognized. The units that are
6595 with'ed directly or indirectly will be scanned using the specified
6596 representation scheme, and so if one of the non-brackets scheme is
6597 used, it must be used consistently throughout the program. However,
6598 since brackets encoding is always recognized, it may be conveniently
6599 used in standard libraries, allowing these libraries to be used with
6600 any of the available coding schemes.
6603 If no @option{-gnatW?} parameter is present, then the default
6604 representation is normally Brackets encoding only. However, if the
6605 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6606 byte order mark or BOM for UTF-8), then these three characters are
6607 skipped and the default representation for the file is set to UTF-8.
6609 Note that the wide character representation that is specified (explicitly
6610 or by default) for the main program also acts as the default encoding used
6611 for Wide_Text_IO files if not specifically overridden by a WCEM form
6615 @node File Naming Control
6616 @subsection File Naming Control
6619 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6620 @cindex @option{-gnatk} (@command{gcc})
6621 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6622 1-999, indicates the maximum allowable length of a file name (not
6623 including the @file{.ads} or @file{.adb} extension). The default is not
6624 to enable file name krunching.
6626 For the source file naming rules, @xref{File Naming Rules}.
6629 @node Subprogram Inlining Control
6630 @subsection Subprogram Inlining Control
6635 @cindex @option{-gnatn} (@command{gcc})
6637 The @code{n} here is intended to suggest the first syllable of the
6640 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6641 inlining to actually occur, optimization must be enabled. To enable
6642 inlining of subprograms specified by pragma @code{Inline},
6643 you must also specify this switch.
6644 In the absence of this switch, GNAT does not attempt
6645 inlining and does not need to access the bodies of
6646 subprograms for which @code{pragma Inline} is specified if they are not
6647 in the current unit.
6649 If you specify this switch the compiler will access these bodies,
6650 creating an extra source dependency for the resulting object file, and
6651 where possible, the call will be inlined.
6652 For further details on when inlining is possible
6653 see @ref{Inlining of Subprograms}.
6656 @cindex @option{-gnatN} (@command{gcc})
6657 The front end inlining activated by this switch is generally more extensive,
6658 and quite often more effective than the standard @option{-gnatn} inlining mode.
6659 It will also generate additional dependencies.
6661 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
6662 to specify both options.
6665 @node Auxiliary Output Control
6666 @subsection Auxiliary Output Control
6670 @cindex @option{-gnatt} (@command{gcc})
6671 @cindex Writing internal trees
6672 @cindex Internal trees, writing to file
6673 Causes GNAT to write the internal tree for a unit to a file (with the
6674 extension @file{.adt}.
6675 This not normally required, but is used by separate analysis tools.
6677 these tools do the necessary compilations automatically, so you should
6678 not have to specify this switch in normal operation.
6681 @cindex @option{-gnatu} (@command{gcc})
6682 Print a list of units required by this compilation on @file{stdout}.
6683 The listing includes all units on which the unit being compiled depends
6684 either directly or indirectly.
6687 @item -pass-exit-codes
6688 @cindex @option{-pass-exit-codes} (@command{gcc})
6689 If this switch is not used, the exit code returned by @command{gcc} when
6690 compiling multiple files indicates whether all source files have
6691 been successfully used to generate object files or not.
6693 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
6694 exit status and allows an integrated development environment to better
6695 react to a compilation failure. Those exit status are:
6699 There was an error in at least one source file.
6701 At least one source file did not generate an object file.
6703 The compiler died unexpectedly (internal error for example).
6705 An object file has been generated for every source file.
6710 @node Debugging Control
6711 @subsection Debugging Control
6715 @cindex Debugging options
6718 @cindex @option{-gnatd} (@command{gcc})
6719 Activate internal debugging switches. @var{x} is a letter or digit, or
6720 string of letters or digits, which specifies the type of debugging
6721 outputs desired. Normally these are used only for internal development
6722 or system debugging purposes. You can find full documentation for these
6723 switches in the body of the @code{Debug} unit in the compiler source
6724 file @file{debug.adb}.
6728 @cindex @option{-gnatG} (@command{gcc})
6729 This switch causes the compiler to generate auxiliary output containing
6730 a pseudo-source listing of the generated expanded code. Like most Ada
6731 compilers, GNAT works by first transforming the high level Ada code into
6732 lower level constructs. For example, tasking operations are transformed
6733 into calls to the tasking run-time routines. A unique capability of GNAT
6734 is to list this expanded code in a form very close to normal Ada source.
6735 This is very useful in understanding the implications of various Ada
6736 usage on the efficiency of the generated code. There are many cases in
6737 Ada (e.g.@: the use of controlled types), where simple Ada statements can
6738 generate a lot of run-time code. By using @option{-gnatG} you can identify
6739 these cases, and consider whether it may be desirable to modify the coding
6740 approach to improve efficiency.
6742 The format of the output is very similar to standard Ada source, and is
6743 easily understood by an Ada programmer. The following special syntactic
6744 additions correspond to low level features used in the generated code that
6745 do not have any exact analogies in pure Ada source form. The following
6746 is a partial list of these special constructions. See the spec
6747 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6749 If the switch @option{-gnatL} is used in conjunction with
6750 @cindex @option{-gnatL} (@command{gcc})
6751 @option{-gnatG}, then the original source lines are interspersed
6752 in the expanded source (as comment lines with the original line number).
6755 @item new @var{xxx} [storage_pool = @var{yyy}]
6756 Shows the storage pool being used for an allocator.
6758 @item at end @var{procedure-name};
6759 Shows the finalization (cleanup) procedure for a scope.
6761 @item (if @var{expr} then @var{expr} else @var{expr})
6762 Conditional expression equivalent to the @code{x?y:z} construction in C.
6764 @item @var{target}^^^(@var{source})
6765 A conversion with floating-point truncation instead of rounding.
6767 @item @var{target}?(@var{source})
6768 A conversion that bypasses normal Ada semantic checking. In particular
6769 enumeration types and fixed-point types are treated simply as integers.
6771 @item @var{target}?^^^(@var{source})
6772 Combines the above two cases.
6774 @item @var{x} #/ @var{y}
6775 @itemx @var{x} #mod @var{y}
6776 @itemx @var{x} #* @var{y}
6777 @itemx @var{x} #rem @var{y}
6778 A division or multiplication of fixed-point values which are treated as
6779 integers without any kind of scaling.
6781 @item free @var{expr} [storage_pool = @var{xxx}]
6782 Shows the storage pool associated with a @code{free} statement.
6784 @item [subtype or type declaration]
6785 Used to list an equivalent declaration for an internally generated
6786 type that is referenced elsewhere in the listing.
6788 @item freeze @var{type-name} [@var{actions}]
6789 Shows the point at which @var{type-name} is frozen, with possible
6790 associated actions to be performed at the freeze point.
6792 @item reference @var{itype}
6793 Reference (and hence definition) to internal type @var{itype}.
6795 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6796 Intrinsic function call.
6798 @item @var{label-name} : label
6799 Declaration of label @var{labelname}.
6801 @item #$ @var{subprogram-name}
6802 An implicit call to a run-time support routine
6803 (to meet the requirement of H.3.1(9) in a
6806 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
6807 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6808 @var{expr}, but handled more efficiently).
6810 @item [constraint_error]
6811 Raise the @code{Constraint_Error} exception.
6813 @item @var{expression}'reference
6814 A pointer to the result of evaluating @var{expression}.
6816 @item @var{target-type}!(@var{source-expression})
6817 An unchecked conversion of @var{source-expression} to @var{target-type}.
6819 @item [@var{numerator}/@var{denominator}]
6820 Used to represent internal real literals (that) have no exact
6821 representation in base 2-16 (for example, the result of compile time
6822 evaluation of the expression 1.0/27.0).
6826 @cindex @option{-gnatD} (@command{gcc})
6827 When used in conjunction with @option{-gnatG}, this switch causes
6828 the expanded source, as described above for
6829 @option{-gnatG} to be written to files with names
6830 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6831 instead of to the standard output file. For
6832 example, if the source file name is @file{hello.adb}, then a file
6833 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written. The debugging
6834 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
6835 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6836 you to do source level debugging using the generated code which is
6837 sometimes useful for complex code, for example to find out exactly
6838 which part of a complex construction raised an exception. This switch
6839 also suppress generation of cross-reference information (see
6840 @option{-gnatx}) since otherwise the cross-reference information
6841 would refer to the @file{^.dg^.DG^} file, which would cause
6842 confusion since this is not the original source file.
6844 Note that @option{-gnatD} actually implies @option{-gnatG}
6845 automatically, so it is not necessary to give both options.
6846 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6848 If the switch @option{-gnatL} is used in conjunction with
6849 @cindex @option{-gnatL} (@command{gcc})
6850 @option{-gnatDG}, then the original source lines are interspersed
6851 in the expanded source (as comment lines with the original line number).
6854 @cindex @option{-gnatr} (@command{gcc})
6855 @cindex pragma Restrictions
6856 This switch causes pragma Restrictions to be treated as Restriction_Warnings
6857 so that violation of restrictions causes warnings rather than illegalities.
6858 This is useful during the development process when new restrictions are added
6859 or investigated. The switch also causes pragma Profile to be treated as
6860 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
6861 restriction warnings rather than restrictions.
6864 @item -gnatR[0|1|2|3[s]]
6865 @cindex @option{-gnatR} (@command{gcc})
6866 This switch controls output from the compiler of a listing showing
6867 representation information for declared types and objects. For
6868 @option{-gnatR0}, no information is output (equivalent to omitting
6869 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6870 so @option{-gnatR} with no parameter has the same effect), size and alignment
6871 information is listed for declared array and record types. For
6872 @option{-gnatR2}, size and alignment information is listed for all
6873 declared types and objects. Finally @option{-gnatR3} includes symbolic
6874 expressions for values that are computed at run time for
6875 variant records. These symbolic expressions have a mostly obvious
6876 format with #n being used to represent the value of the n'th
6877 discriminant. See source files @file{repinfo.ads/adb} in the
6878 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6879 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
6880 the output is to a file with the name @file{^file.rep^file_REP^} where
6881 file is the name of the corresponding source file.
6884 @item /REPRESENTATION_INFO
6885 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
6886 This qualifier controls output from the compiler of a listing showing
6887 representation information for declared types and objects. For
6888 @option{/REPRESENTATION_INFO=NONE}, no information is output
6889 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6890 @option{/REPRESENTATION_INFO} without option is equivalent to
6891 @option{/REPRESENTATION_INFO=ARRAYS}.
6892 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6893 information is listed for declared array and record types. For
6894 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6895 is listed for all expression information for values that are computed
6896 at run time for variant records. These symbolic expressions have a mostly
6897 obvious format with #n being used to represent the value of the n'th
6898 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6899 @code{GNAT} sources for full details on the format of
6900 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6901 If _FILE is added at the end of an option
6902 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6903 then the output is to a file with the name @file{file_REP} where
6904 file is the name of the corresponding source file.
6906 Note that it is possible for record components to have zero size. In
6907 this case, the component clause uses an obvious extension of permitted
6908 Ada syntax, for example @code{at 0 range 0 .. -1}.
6910 Representation information requires that code be generated (since it is the
6911 code generator that lays out complex data structures). If an attempt is made
6912 to output representation information when no code is generated, for example
6913 when a subunit is compiled on its own, then no information can be generated
6914 and the compiler outputs a message to this effect.
6917 @cindex @option{-gnatS} (@command{gcc})
6918 The use of the switch @option{-gnatS} for an
6919 Ada compilation will cause the compiler to output a
6920 representation of package Standard in a form very
6921 close to standard Ada. It is not quite possible to
6922 do this entirely in standard Ada (since new
6923 numeric base types cannot be created in standard
6924 Ada), but the output is easily
6925 readable to any Ada programmer, and is useful to
6926 determine the characteristics of target dependent
6927 types in package Standard.
6930 @cindex @option{-gnatx} (@command{gcc})
6931 Normally the compiler generates full cross-referencing information in
6932 the @file{ALI} file. This information is used by a number of tools,
6933 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
6934 suppresses this information. This saves some space and may slightly
6935 speed up compilation, but means that these tools cannot be used.
6938 @node Exception Handling Control
6939 @subsection Exception Handling Control
6942 GNAT uses two methods for handling exceptions at run-time. The
6943 @code{setjmp/longjmp} method saves the context when entering
6944 a frame with an exception handler. Then when an exception is
6945 raised, the context can be restored immediately, without the
6946 need for tracing stack frames. This method provides very fast
6947 exception propagation, but introduces significant overhead for
6948 the use of exception handlers, even if no exception is raised.
6950 The other approach is called ``zero cost'' exception handling.
6951 With this method, the compiler builds static tables to describe
6952 the exception ranges. No dynamic code is required when entering
6953 a frame containing an exception handler. When an exception is
6954 raised, the tables are used to control a back trace of the
6955 subprogram invocation stack to locate the required exception
6956 handler. This method has considerably poorer performance for
6957 the propagation of exceptions, but there is no overhead for
6958 exception handlers if no exception is raised. Note that in this
6959 mode and in the context of mixed Ada and C/C++ programming,
6960 to propagate an exception through a C/C++ code, the C/C++ code
6961 must be compiled with the @option{-funwind-tables} GCC's
6964 The following switches may be used to control which of the
6965 two exception handling methods is used.
6971 @cindex @option{--RTS=sjlj} (@command{gnatmake})
6972 This switch causes the setjmp/longjmp run-time (when available) to be used
6973 for exception handling. If the default
6974 mechanism for the target is zero cost exceptions, then
6975 this switch can be used to modify this default, and must be
6976 used for all units in the partition.
6977 This option is rarely used. One case in which it may be
6978 advantageous is if you have an application where exception
6979 raising is common and the overall performance of the
6980 application is improved by favoring exception propagation.
6983 @cindex @option{--RTS=zcx} (@command{gnatmake})
6984 @cindex Zero Cost Exceptions
6985 This switch causes the zero cost approach to be used
6986 for exception handling. If this is the default mechanism for the
6987 target (see below), then this switch is unneeded. If the default
6988 mechanism for the target is setjmp/longjmp exceptions, then
6989 this switch can be used to modify this default, and must be
6990 used for all units in the partition.
6991 This option can only be used if the zero cost approach
6992 is available for the target in use, otherwise it will generate an error.
6996 The same option @option{--RTS} must be used both for @command{gcc}
6997 and @command{gnatbind}. Passing this option to @command{gnatmake}
6998 (@pxref{Switches for gnatmake}) will ensure the required consistency
6999 through the compilation and binding steps.
7001 @node Units to Sources Mapping Files
7002 @subsection Units to Sources Mapping Files
7006 @item -gnatem^^=^@var{path}
7007 @cindex @option{-gnatem} (@command{gcc})
7008 A mapping file is a way to communicate to the compiler two mappings:
7009 from unit names to file names (without any directory information) and from
7010 file names to path names (with full directory information). These mappings
7011 are used by the compiler to short-circuit the path search.
7013 The use of mapping files is not required for correct operation of the
7014 compiler, but mapping files can improve efficiency, particularly when
7015 sources are read over a slow network connection. In normal operation,
7016 you need not be concerned with the format or use of mapping files,
7017 and the @option{-gnatem} switch is not a switch that you would use
7018 explicitly. it is intended only for use by automatic tools such as
7019 @command{gnatmake} running under the project file facility. The
7020 description here of the format of mapping files is provided
7021 for completeness and for possible use by other tools.
7023 A mapping file is a sequence of sets of three lines. In each set,
7024 the first line is the unit name, in lower case, with ``@code{%s}''
7026 specs and ``@code{%b}'' appended for bodies; the second line is the
7027 file name; and the third line is the path name.
7033 /gnat/project1/sources/main.2.ada
7036 When the switch @option{-gnatem} is specified, the compiler will create
7037 in memory the two mappings from the specified file. If there is any problem
7038 (nonexistent file, truncated file or duplicate entries), no mapping will
7041 Several @option{-gnatem} switches may be specified; however, only the last
7042 one on the command line will be taken into account.
7044 When using a project file, @command{gnatmake} create a temporary mapping file
7045 and communicates it to the compiler using this switch.
7049 @node Integrated Preprocessing
7050 @subsection Integrated Preprocessing
7053 GNAT sources may be preprocessed immediately before compilation.
7054 In this case, the actual
7055 text of the source is not the text of the source file, but is derived from it
7056 through a process called preprocessing. Integrated preprocessing is specified
7057 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7058 indicates, through a text file, the preprocessing data to be used.
7059 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7062 Note that when integrated preprocessing is used, the output from the
7063 preprocessor is not written to any external file. Instead it is passed
7064 internally to the compiler. If you need to preserve the result of
7065 preprocessing in a file, then you should use @command{gnatprep}
7066 to perform the desired preprocessing in stand-alone mode.
7069 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7070 used when Integrated Preprocessing is used. The reason is that preprocessing
7071 with another Preprocessing Data file without changing the sources will
7072 not trigger recompilation without this switch.
7075 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7076 always trigger recompilation for sources that are preprocessed,
7077 because @command{gnatmake} cannot compute the checksum of the source after
7081 The actual preprocessing function is described in details in section
7082 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7083 preprocessing is triggered and parameterized.
7087 @item -gnatep=@var{file}
7088 @cindex @option{-gnatep} (@command{gcc})
7089 This switch indicates to the compiler the file name (without directory
7090 information) of the preprocessor data file to use. The preprocessor data file
7091 should be found in the source directories.
7094 A preprocessing data file is a text file with significant lines indicating
7095 how should be preprocessed either a specific source or all sources not
7096 mentioned in other lines. A significant line is a nonempty, non-comment line.
7097 Comments are similar to Ada comments.
7100 Each significant line starts with either a literal string or the character '*'.
7101 A literal string is the file name (without directory information) of the source
7102 to preprocess. A character '*' indicates the preprocessing for all the sources
7103 that are not specified explicitly on other lines (order of the lines is not
7104 significant). It is an error to have two lines with the same file name or two
7105 lines starting with the character '*'.
7108 After the file name or the character '*', another optional literal string
7109 indicating the file name of the definition file to be used for preprocessing
7110 (@pxref{Form of Definitions File}). The definition files are found by the
7111 compiler in one of the source directories. In some cases, when compiling
7112 a source in a directory other than the current directory, if the definition
7113 file is in the current directory, it may be necessary to add the current
7114 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7115 the compiler would not find the definition file.
7118 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7119 be found. Those ^switches^switches^ are:
7124 Causes both preprocessor lines and the lines deleted by
7125 preprocessing to be replaced by blank lines, preserving the line number.
7126 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7127 it cancels the effect of @option{-c}.
7130 Causes both preprocessor lines and the lines deleted
7131 by preprocessing to be retained as comments marked
7132 with the special string ``@code{--! }''.
7134 @item -Dsymbol=value
7135 Define or redefine a symbol, associated with value. A symbol is an Ada
7136 identifier, or an Ada reserved word, with the exception of @code{if},
7137 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7138 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7139 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7140 same name defined in a definition file.
7143 Causes a sorted list of symbol names and values to be
7144 listed on the standard output file.
7147 Causes undefined symbols to be treated as having the value @code{FALSE}
7149 of a preprocessor test. In the absence of this option, an undefined symbol in
7150 a @code{#if} or @code{#elsif} test will be treated as an error.
7155 Examples of valid lines in a preprocessor data file:
7158 "toto.adb" "prep.def" -u
7159 -- preprocess "toto.adb", using definition file "prep.def",
7160 -- undefined symbol are False.
7163 -- preprocess all other sources without a definition file;
7164 -- suppressed lined are commented; symbol VERSION has the value V101.
7166 "titi.adb" "prep2.def" -s
7167 -- preprocess "titi.adb", using definition file "prep2.def";
7168 -- list all symbols with their values.
7171 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
7172 @cindex @option{-gnateD} (@command{gcc})
7173 Define or redefine a preprocessing symbol, associated with value. If no value
7174 is given on the command line, then the value of the symbol is @code{True}.
7175 A symbol is an identifier, following normal Ada (case-insensitive)
7176 rules for its syntax, and value is any sequence (including an empty sequence)
7177 of characters from the set (letters, digits, period, underline).
7178 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7179 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7182 A symbol declared with this ^switch^switch^ on the command line replaces a
7183 symbol with the same name either in a definition file or specified with a
7184 ^switch^switch^ -D in the preprocessor data file.
7187 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7191 @node Code Generation Control
7192 @subsection Code Generation Control
7196 The GCC technology provides a wide range of target dependent
7197 @option{-m} switches for controlling
7198 details of code generation with respect to different versions of
7199 architectures. This includes variations in instruction sets (e.g.@:
7200 different members of the power pc family), and different requirements
7201 for optimal arrangement of instructions (e.g.@: different members of
7202 the x86 family). The list of available @option{-m} switches may be
7203 found in the GCC documentation.
7205 Use of these @option{-m} switches may in some cases result in improved
7208 The GNAT Pro technology is tested and qualified without any
7209 @option{-m} switches,
7210 so generally the most reliable approach is to avoid the use of these
7211 switches. However, we generally expect most of these switches to work
7212 successfully with GNAT Pro, and many customers have reported successful
7213 use of these options.
7215 Our general advice is to avoid the use of @option{-m} switches unless
7216 special needs lead to requirements in this area. In particular,
7217 there is no point in using @option{-m} switches to improve performance
7218 unless you actually see a performance improvement.
7222 @subsection Return Codes
7223 @cindex Return Codes
7224 @cindex @option{/RETURN_CODES=VMS}
7227 On VMS, GNAT compiled programs return POSIX-style codes by default,
7228 e.g.@: @option{/RETURN_CODES=POSIX}.
7230 To enable VMS style return codes, use GNAT BIND and LINK with the option
7231 @option{/RETURN_CODES=VMS}. For example:
7234 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7235 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7239 Programs built with /RETURN_CODES=VMS are suitable to be called in
7240 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7241 are suitable for spawning with appropriate GNAT RTL routines.
7245 @node Search Paths and the Run-Time Library (RTL)
7246 @section Search Paths and the Run-Time Library (RTL)
7249 With the GNAT source-based library system, the compiler must be able to
7250 find source files for units that are needed by the unit being compiled.
7251 Search paths are used to guide this process.
7253 The compiler compiles one source file whose name must be given
7254 explicitly on the command line. In other words, no searching is done
7255 for this file. To find all other source files that are needed (the most
7256 common being the specs of units), the compiler examines the following
7257 directories, in the following order:
7261 The directory containing the source file of the main unit being compiled
7262 (the file name on the command line).
7265 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7266 @command{gcc} command line, in the order given.
7269 @findex ADA_PRJ_INCLUDE_FILE
7270 Each of the directories listed in the text file whose name is given
7271 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7274 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7275 driver when project files are used. It should not normally be set
7279 @findex ADA_INCLUDE_PATH
7280 Each of the directories listed in the value of the
7281 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7283 Construct this value
7284 exactly as the @env{PATH} environment variable: a list of directory
7285 names separated by colons (semicolons when working with the NT version).
7288 Normally, define this value as a logical name containing a comma separated
7289 list of directory names.
7291 This variable can also be defined by means of an environment string
7292 (an argument to the HP C exec* set of functions).
7296 DEFINE ANOTHER_PATH FOO:[BAG]
7297 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7300 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7301 first, followed by the standard Ada
7302 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7303 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7304 (Text_IO, Sequential_IO, etc)
7305 instead of the standard Ada packages. Thus, in order to get the standard Ada
7306 packages by default, ADA_INCLUDE_PATH must be redefined.
7310 The content of the @file{ada_source_path} file which is part of the GNAT
7311 installation tree and is used to store standard libraries such as the
7312 GNAT Run Time Library (RTL) source files.
7314 @ref{Installing a library}
7319 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7320 inhibits the use of the directory
7321 containing the source file named in the command line. You can still
7322 have this directory on your search path, but in this case it must be
7323 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7325 Specifying the switch @option{-nostdinc}
7326 inhibits the search of the default location for the GNAT Run Time
7327 Library (RTL) source files.
7329 The compiler outputs its object files and ALI files in the current
7332 Caution: The object file can be redirected with the @option{-o} switch;
7333 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7334 so the @file{ALI} file will not go to the right place. Therefore, you should
7335 avoid using the @option{-o} switch.
7339 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7340 children make up the GNAT RTL, together with the simple @code{System.IO}
7341 package used in the @code{"Hello World"} example. The sources for these units
7342 are needed by the compiler and are kept together in one directory. Not
7343 all of the bodies are needed, but all of the sources are kept together
7344 anyway. In a normal installation, you need not specify these directory
7345 names when compiling or binding. Either the environment variables or
7346 the built-in defaults cause these files to be found.
7348 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7349 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7350 consisting of child units of @code{GNAT}. This is a collection of generally
7351 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7352 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7354 Besides simplifying access to the RTL, a major use of search paths is
7355 in compiling sources from multiple directories. This can make
7356 development environments much more flexible.
7358 @node Order of Compilation Issues
7359 @section Order of Compilation Issues
7362 If, in our earlier example, there was a spec for the @code{hello}
7363 procedure, it would be contained in the file @file{hello.ads}; yet this
7364 file would not have to be explicitly compiled. This is the result of the
7365 model we chose to implement library management. Some of the consequences
7366 of this model are as follows:
7370 There is no point in compiling specs (except for package
7371 specs with no bodies) because these are compiled as needed by clients. If
7372 you attempt a useless compilation, you will receive an error message.
7373 It is also useless to compile subunits because they are compiled as needed
7377 There are no order of compilation requirements: performing a
7378 compilation never obsoletes anything. The only way you can obsolete
7379 something and require recompilations is to modify one of the
7380 source files on which it depends.
7383 There is no library as such, apart from the ALI files
7384 (@pxref{The Ada Library Information Files}, for information on the format
7385 of these files). For now we find it convenient to create separate ALI files,
7386 but eventually the information therein may be incorporated into the object
7390 When you compile a unit, the source files for the specs of all units
7391 that it @code{with}'s, all its subunits, and the bodies of any generics it
7392 instantiates must be available (reachable by the search-paths mechanism
7393 described above), or you will receive a fatal error message.
7400 The following are some typical Ada compilation command line examples:
7403 @item $ gcc -c xyz.adb
7404 Compile body in file @file{xyz.adb} with all default options.
7407 @item $ gcc -c -O2 -gnata xyz-def.adb
7410 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7413 Compile the child unit package in file @file{xyz-def.adb} with extensive
7414 optimizations, and pragma @code{Assert}/@code{Debug} statements
7417 @item $ gcc -c -gnatc abc-def.adb
7418 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7422 @node Binding Using gnatbind
7423 @chapter Binding Using @code{gnatbind}
7427 * Running gnatbind::
7428 * Switches for gnatbind::
7429 * Command-Line Access::
7430 * Search Paths for gnatbind::
7431 * Examples of gnatbind Usage::
7435 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7436 to bind compiled GNAT objects.
7438 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7439 driver (see @ref{The GNAT Driver and Project Files}).
7441 The @code{gnatbind} program performs four separate functions:
7445 Checks that a program is consistent, in accordance with the rules in
7446 Chapter 10 of the Ada Reference Manual. In particular, error
7447 messages are generated if a program uses inconsistent versions of a
7451 Checks that an acceptable order of elaboration exists for the program
7452 and issues an error message if it cannot find an order of elaboration
7453 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7456 Generates a main program incorporating the given elaboration order.
7457 This program is a small Ada package (body and spec) that
7458 must be subsequently compiled
7459 using the GNAT compiler. The necessary compilation step is usually
7460 performed automatically by @command{gnatlink}. The two most important
7461 functions of this program
7462 are to call the elaboration routines of units in an appropriate order
7463 and to call the main program.
7466 Determines the set of object files required by the given main program.
7467 This information is output in the forms of comments in the generated program,
7468 to be read by the @command{gnatlink} utility used to link the Ada application.
7471 @node Running gnatbind
7472 @section Running @code{gnatbind}
7475 The form of the @code{gnatbind} command is
7478 $ gnatbind [@i{switches}] @i{mainprog}[.ali] [@i{switches}]
7482 where @file{@i{mainprog}.adb} is the Ada file containing the main program
7483 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
7484 package in two files whose names are
7485 @file{b~@i{mainprog}.ads}, and @file{b~@i{mainprog}.adb}.
7486 For example, if given the
7487 parameter @file{hello.ali}, for a main program contained in file
7488 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7489 and @file{b~hello.adb}.
7491 When doing consistency checking, the binder takes into consideration
7492 any source files it can locate. For example, if the binder determines
7493 that the given main program requires the package @code{Pack}, whose
7495 file is @file{pack.ali} and whose corresponding source spec file is
7496 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7497 (using the same search path conventions as previously described for the
7498 @command{gcc} command). If it can locate this source file, it checks that
7500 or source checksums of the source and its references to in @file{ALI} files
7501 match. In other words, any @file{ALI} files that mentions this spec must have
7502 resulted from compiling this version of the source file (or in the case
7503 where the source checksums match, a version close enough that the
7504 difference does not matter).
7506 @cindex Source files, use by binder
7507 The effect of this consistency checking, which includes source files, is
7508 that the binder ensures that the program is consistent with the latest
7509 version of the source files that can be located at bind time. Editing a
7510 source file without compiling files that depend on the source file cause
7511 error messages to be generated by the binder.
7513 For example, suppose you have a main program @file{hello.adb} and a
7514 package @code{P}, from file @file{p.ads} and you perform the following
7519 Enter @code{gcc -c hello.adb} to compile the main program.
7522 Enter @code{gcc -c p.ads} to compile package @code{P}.
7525 Edit file @file{p.ads}.
7528 Enter @code{gnatbind hello}.
7532 At this point, the file @file{p.ali} contains an out-of-date time stamp
7533 because the file @file{p.ads} has been edited. The attempt at binding
7534 fails, and the binder generates the following error messages:
7537 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7538 error: "p.ads" has been modified and must be recompiled
7542 Now both files must be recompiled as indicated, and then the bind can
7543 succeed, generating a main program. You need not normally be concerned
7544 with the contents of this file, but for reference purposes a sample
7545 binder output file is given in @ref{Example of Binder Output File}.
7547 In most normal usage, the default mode of @command{gnatbind} which is to
7548 generate the main package in Ada, as described in the previous section.
7549 In particular, this means that any Ada programmer can read and understand
7550 the generated main program. It can also be debugged just like any other
7551 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7552 @command{gnatbind} and @command{gnatlink}.
7554 However for some purposes it may be convenient to generate the main
7555 program in C rather than Ada. This may for example be helpful when you
7556 are generating a mixed language program with the main program in C. The
7557 GNAT compiler itself is an example.
7558 The use of the @option{^-C^/BIND_FILE=C^} switch
7559 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7560 be generated in C (and compiled using the gnu C compiler).
7562 @node Switches for gnatbind
7563 @section Switches for @command{gnatbind}
7566 The following switches are available with @code{gnatbind}; details will
7567 be presented in subsequent sections.
7570 * Consistency-Checking Modes::
7571 * Binder Error Message Control::
7572 * Elaboration Control::
7574 * Binding with Non-Ada Main Programs::
7575 * Binding Programs with No Main Subprogram::
7582 @cindex @option{--version} @command{gnatbind}
7583 Display Copyright and version, then exit disregarding all other options.
7586 @cindex @option{--help} @command{gnatbind}
7587 If @option{--version} was not used, display usage, then exit disregarding
7591 @cindex @option{-a} @command{gnatbind}
7592 Indicates that, if supported by the platform, the adainit procedure should
7593 be treated as an initialisation routine by the linker (a constructor). This
7594 is intended to be used by the Project Manager to automatically initialize
7595 shared Stand-Alone Libraries.
7597 @item ^-aO^/OBJECT_SEARCH^
7598 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7599 Specify directory to be searched for ALI files.
7601 @item ^-aI^/SOURCE_SEARCH^
7602 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7603 Specify directory to be searched for source file.
7605 @item ^-A^/BIND_FILE=ADA^
7606 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
7607 Generate binder program in Ada (default)
7609 @item ^-b^/REPORT_ERRORS=BRIEF^
7610 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
7611 Generate brief messages to @file{stderr} even if verbose mode set.
7613 @item ^-c^/NOOUTPUT^
7614 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
7615 Check only, no generation of binder output file.
7617 @item ^-C^/BIND_FILE=C^
7618 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
7619 Generate binder program in C
7621 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}[k|m]
7622 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}[k|m]} (@command{gnatbind})
7623 This switch can be used to change the default task stack size value
7624 to a specified size @var{nn}, which is expressed in bytes by default, or
7625 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7627 In the absence of a [k|m] suffix, this switch is equivalent, in effect,
7628 to completing all task specs with
7629 @smallexample @c ada
7630 pragma Storage_Size (nn);
7632 When they do not already have such a pragma.
7634 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}[k|m]
7635 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
7636 This switch can be used to change the default secondary stack size value
7637 to a specified size @var{nn}, which is expressed in bytes by default, or
7638 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7641 The secondary stack is used to deal with functions that return a variable
7642 sized result, for example a function returning an unconstrained
7643 String. There are two ways in which this secondary stack is allocated.
7645 For most targets, the secondary stack is growing on demand and is allocated
7646 as a chain of blocks in the heap. The -D option is not very
7647 relevant. It only give some control over the size of the allocated
7648 blocks (whose size is the minimum of the default secondary stack size value,
7649 and the actual size needed for the current allocation request).
7651 For certain targets, notably VxWorks 653,
7652 the secondary stack is allocated by carving off a fixed ratio chunk of the
7653 primary task stack. The -D option is used to define the
7654 size of the environment task's secondary stack.
7656 @item ^-e^/ELABORATION_DEPENDENCIES^
7657 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
7658 Output complete list of elaboration-order dependencies.
7660 @item ^-E^/STORE_TRACEBACKS^
7661 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
7662 Store tracebacks in exception occurrences when the target supports it.
7663 This is the default with the zero cost exception mechanism.
7665 @c The following may get moved to an appendix
7666 This option is currently supported on the following targets:
7667 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
7669 See also the packages @code{GNAT.Traceback} and
7670 @code{GNAT.Traceback.Symbolic} for more information.
7672 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
7673 @command{gcc} option.
7676 @item ^-F^/FORCE_ELABS_FLAGS^
7677 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
7678 Force the checks of elaboration flags. @command{gnatbind} does not normally
7679 generate checks of elaboration flags for the main executable, except when
7680 a Stand-Alone Library is used. However, there are cases when this cannot be
7681 detected by gnatbind. An example is importing an interface of a Stand-Alone
7682 Library through a pragma Import and only specifying through a linker switch
7683 this Stand-Alone Library. This switch is used to guarantee that elaboration
7684 flag checks are generated.
7687 @cindex @option{^-h^/HELP^} (@command{gnatbind})
7688 Output usage (help) information
7691 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7692 Specify directory to be searched for source and ALI files.
7694 @item ^-I-^/NOCURRENT_DIRECTORY^
7695 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
7696 Do not look for sources in the current directory where @code{gnatbind} was
7697 invoked, and do not look for ALI files in the directory containing the
7698 ALI file named in the @code{gnatbind} command line.
7700 @item ^-l^/ORDER_OF_ELABORATION^
7701 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
7702 Output chosen elaboration order.
7704 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
7705 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
7706 Bind the units for library building. In this case the adainit and
7707 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
7708 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
7709 ^@var{xxx}final^@var{XXX}FINAL^.
7710 Implies ^-n^/NOCOMPILE^.
7712 (@xref{GNAT and Libraries}, for more details.)
7715 On OpenVMS, these init and final procedures are exported in uppercase
7716 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
7717 the init procedure will be "TOTOINIT" and the exported name of the final
7718 procedure will be "TOTOFINAL".
7721 @item ^-Mxyz^/RENAME_MAIN=xyz^
7722 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
7723 Rename generated main program from main to xyz. This option is
7724 supported on cross environments only.
7726 @item ^-m^/ERROR_LIMIT=^@var{n}
7727 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
7728 Limit number of detected errors to @var{n}, where @var{n} is
7729 in the range 1..999_999. The default value if no switch is
7730 given is 9999. Binding is terminated if the limit is exceeded.
7732 Furthermore, under Windows, the sources pointed to by the libraries path
7733 set in the registry are not searched for.
7737 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7741 @cindex @option{-nostdinc} (@command{gnatbind})
7742 Do not look for sources in the system default directory.
7745 @cindex @option{-nostdlib} (@command{gnatbind})
7746 Do not look for library files in the system default directory.
7748 @item --RTS=@var{rts-path}
7749 @cindex @option{--RTS} (@code{gnatbind})
7750 Specifies the default location of the runtime library. Same meaning as the
7751 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
7753 @item ^-o ^/OUTPUT=^@var{file}
7754 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7755 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7756 Note that if this option is used, then linking must be done manually,
7757 gnatlink cannot be used.
7759 @item ^-O^/OBJECT_LIST^
7760 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7763 @item ^-p^/PESSIMISTIC_ELABORATION^
7764 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7765 Pessimistic (worst-case) elaboration order
7768 @cindex @option{^-R^-R^} (@command{gnatbind})
7769 Output closure source list.
7771 @item ^-s^/READ_SOURCES=ALL^
7772 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7773 Require all source files to be present.
7775 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7776 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7777 Specifies the value to be used when detecting uninitialized scalar
7778 objects with pragma Initialize_Scalars.
7779 The @var{xxx} ^string specified with the switch^option^ may be either
7781 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7782 @item ``@option{^lo^LOW^}'' for the lowest possible value
7783 @item ``@option{^hi^HIGH^}'' for the highest possible value
7784 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
7785 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
7788 In addition, you can specify @option{-Sev} to indicate that the value is
7789 to be set at run time. In this case, the program will look for an environment
7790 @cindex GNAT_INIT_SCALARS
7791 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
7792 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
7793 If no environment variable is found, or if it does not have a valid value,
7794 then the default is @option{in} (invalid values).
7798 @cindex @option{-static} (@code{gnatbind})
7799 Link against a static GNAT run time.
7802 @cindex @option{-shared} (@code{gnatbind})
7803 Link against a shared GNAT run time when available.
7806 @item ^-t^/NOTIME_STAMP_CHECK^
7807 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7808 Tolerate time stamp and other consistency errors
7810 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7811 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7812 Set the time slice value to @var{n} milliseconds. If the system supports
7813 the specification of a specific time slice value, then the indicated value
7814 is used. If the system does not support specific time slice values, but
7815 does support some general notion of round-robin scheduling, then any
7816 nonzero value will activate round-robin scheduling.
7818 A value of zero is treated specially. It turns off time
7819 slicing, and in addition, indicates to the tasking run time that the
7820 semantics should match as closely as possible the Annex D
7821 requirements of the Ada RM, and in particular sets the default
7822 scheduling policy to @code{FIFO_Within_Priorities}.
7824 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
7825 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
7826 Enable dynamic stack usage, with @var{n} results stored and displayed
7827 at program termination. A result is generated when a task
7828 terminates. Results that can't be stored are displayed on the fly, at
7829 task termination. This option is currently not supported on Itanium
7830 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
7832 @item ^-v^/REPORT_ERRORS=VERBOSE^
7833 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7834 Verbose mode. Write error messages, header, summary output to
7839 @cindex @option{-w} (@code{gnatbind})
7840 Warning mode (@var{x}=s/e for suppress/treat as error)
7844 @item /WARNINGS=NORMAL
7845 @cindex @option{/WARNINGS} (@code{gnatbind})
7846 Normal warnings mode. Warnings are issued but ignored
7848 @item /WARNINGS=SUPPRESS
7849 @cindex @option{/WARNINGS} (@code{gnatbind})
7850 All warning messages are suppressed
7852 @item /WARNINGS=ERROR
7853 @cindex @option{/WARNINGS} (@code{gnatbind})
7854 Warning messages are treated as fatal errors
7857 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
7858 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
7859 Override default wide character encoding for standard Text_IO files.
7861 @item ^-x^/READ_SOURCES=NONE^
7862 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7863 Exclude source files (check object consistency only).
7866 @item /READ_SOURCES=AVAILABLE
7867 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7868 Default mode, in which sources are checked for consistency only if
7872 @item ^-y^/ENABLE_LEAP_SECONDS^
7873 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
7874 Enable leap seconds support in @code{Ada.Calendar} and its children.
7876 @item ^-z^/ZERO_MAIN^
7877 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7883 You may obtain this listing of switches by running @code{gnatbind} with
7887 @node Consistency-Checking Modes
7888 @subsection Consistency-Checking Modes
7891 As described earlier, by default @code{gnatbind} checks
7892 that object files are consistent with one another and are consistent
7893 with any source files it can locate. The following switches control binder
7898 @item ^-s^/READ_SOURCES=ALL^
7899 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
7900 Require source files to be present. In this mode, the binder must be
7901 able to locate all source files that are referenced, in order to check
7902 their consistency. In normal mode, if a source file cannot be located it
7903 is simply ignored. If you specify this switch, a missing source
7906 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
7907 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
7908 Override default wide character encoding for standard Text_IO files.
7909 Normally the default wide character encoding method used for standard
7910 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
7911 the main source input (see description of switch
7912 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
7913 use of this switch for the binder (which has the same set of
7914 possible arguments) overrides this default as specified.
7916 @item ^-x^/READ_SOURCES=NONE^
7917 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
7918 Exclude source files. In this mode, the binder only checks that ALI
7919 files are consistent with one another. Source files are not accessed.
7920 The binder runs faster in this mode, and there is still a guarantee that
7921 the resulting program is self-consistent.
7922 If a source file has been edited since it was last compiled, and you
7923 specify this switch, the binder will not detect that the object
7924 file is out of date with respect to the source file. Note that this is the
7925 mode that is automatically used by @command{gnatmake} because in this
7926 case the checking against sources has already been performed by
7927 @command{gnatmake} in the course of compilation (i.e.@: before binding).
7930 @item /READ_SOURCES=AVAILABLE
7931 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
7932 This is the default mode in which source files are checked if they are
7933 available, and ignored if they are not available.
7937 @node Binder Error Message Control
7938 @subsection Binder Error Message Control
7941 The following switches provide control over the generation of error
7942 messages from the binder:
7946 @item ^-v^/REPORT_ERRORS=VERBOSE^
7947 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7948 Verbose mode. In the normal mode, brief error messages are generated to
7949 @file{stderr}. If this switch is present, a header is written
7950 to @file{stdout} and any error messages are directed to @file{stdout}.
7951 All that is written to @file{stderr} is a brief summary message.
7953 @item ^-b^/REPORT_ERRORS=BRIEF^
7954 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
7955 Generate brief error messages to @file{stderr} even if verbose mode is
7956 specified. This is relevant only when used with the
7957 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
7961 @cindex @option{-m} (@code{gnatbind})
7962 Limits the number of error messages to @var{n}, a decimal integer in the
7963 range 1-999. The binder terminates immediately if this limit is reached.
7966 @cindex @option{-M} (@code{gnatbind})
7967 Renames the generated main program from @code{main} to @code{xxx}.
7968 This is useful in the case of some cross-building environments, where
7969 the actual main program is separate from the one generated
7973 @item ^-ws^/WARNINGS=SUPPRESS^
7974 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
7976 Suppress all warning messages.
7978 @item ^-we^/WARNINGS=ERROR^
7979 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
7980 Treat any warning messages as fatal errors.
7983 @item /WARNINGS=NORMAL
7984 Standard mode with warnings generated, but warnings do not get treated
7988 @item ^-t^/NOTIME_STAMP_CHECK^
7989 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7990 @cindex Time stamp checks, in binder
7991 @cindex Binder consistency checks
7992 @cindex Consistency checks, in binder
7993 The binder performs a number of consistency checks including:
7997 Check that time stamps of a given source unit are consistent
7999 Check that checksums of a given source unit are consistent
8001 Check that consistent versions of @code{GNAT} were used for compilation
8003 Check consistency of configuration pragmas as required
8007 Normally failure of such checks, in accordance with the consistency
8008 requirements of the Ada Reference Manual, causes error messages to be
8009 generated which abort the binder and prevent the output of a binder
8010 file and subsequent link to obtain an executable.
8012 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8013 into warnings, so that
8014 binding and linking can continue to completion even in the presence of such
8015 errors. The result may be a failed link (due to missing symbols), or a
8016 non-functional executable which has undefined semantics.
8017 @emph{This means that
8018 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8022 @node Elaboration Control
8023 @subsection Elaboration Control
8026 The following switches provide additional control over the elaboration
8027 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8030 @item ^-p^/PESSIMISTIC_ELABORATION^
8031 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8032 Normally the binder attempts to choose an elaboration order that is
8033 likely to minimize the likelihood of an elaboration order error resulting
8034 in raising a @code{Program_Error} exception. This switch reverses the
8035 action of the binder, and requests that it deliberately choose an order
8036 that is likely to maximize the likelihood of an elaboration error.
8037 This is useful in ensuring portability and avoiding dependence on
8038 accidental fortuitous elaboration ordering.
8040 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8042 elaboration checking is used (@option{-gnatE} switch used for compilation).
8043 This is because in the default static elaboration mode, all necessary
8044 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8045 These implicit pragmas are still respected by the binder in
8046 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8047 safe elaboration order is assured.
8050 @node Output Control
8051 @subsection Output Control
8054 The following switches allow additional control over the output
8055 generated by the binder.
8060 @item ^-A^/BIND_FILE=ADA^
8061 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
8062 Generate binder program in Ada (default). The binder program is named
8063 @file{b~@var{mainprog}.adb} by default. This can be changed with
8064 @option{^-o^/OUTPUT^} @code{gnatbind} option.
8066 @item ^-c^/NOOUTPUT^
8067 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8068 Check only. Do not generate the binder output file. In this mode the
8069 binder performs all error checks but does not generate an output file.
8071 @item ^-C^/BIND_FILE=C^
8072 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
8073 Generate binder program in C. The binder program is named
8074 @file{b_@var{mainprog}.c}.
8075 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
8078 @item ^-e^/ELABORATION_DEPENDENCIES^
8079 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8080 Output complete list of elaboration-order dependencies, showing the
8081 reason for each dependency. This output can be rather extensive but may
8082 be useful in diagnosing problems with elaboration order. The output is
8083 written to @file{stdout}.
8086 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8087 Output usage information. The output is written to @file{stdout}.
8089 @item ^-K^/LINKER_OPTION_LIST^
8090 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8091 Output linker options to @file{stdout}. Includes library search paths,
8092 contents of pragmas Ident and Linker_Options, and libraries added
8095 @item ^-l^/ORDER_OF_ELABORATION^
8096 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8097 Output chosen elaboration order. The output is written to @file{stdout}.
8099 @item ^-O^/OBJECT_LIST^
8100 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8101 Output full names of all the object files that must be linked to provide
8102 the Ada component of the program. The output is written to @file{stdout}.
8103 This list includes the files explicitly supplied and referenced by the user
8104 as well as implicitly referenced run-time unit files. The latter are
8105 omitted if the corresponding units reside in shared libraries. The
8106 directory names for the run-time units depend on the system configuration.
8108 @item ^-o ^/OUTPUT=^@var{file}
8109 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8110 Set name of output file to @var{file} instead of the normal
8111 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8112 binder generated body filename. In C mode you would normally give
8113 @var{file} an extension of @file{.c} because it will be a C source program.
8114 Note that if this option is used, then linking must be done manually.
8115 It is not possible to use gnatlink in this case, since it cannot locate
8118 @item ^-r^/RESTRICTION_LIST^
8119 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8120 Generate list of @code{pragma Restrictions} that could be applied to
8121 the current unit. This is useful for code audit purposes, and also may
8122 be used to improve code generation in some cases.
8126 @node Binding with Non-Ada Main Programs
8127 @subsection Binding with Non-Ada Main Programs
8130 In our description so far we have assumed that the main
8131 program is in Ada, and that the task of the binder is to generate a
8132 corresponding function @code{main} that invokes this Ada main
8133 program. GNAT also supports the building of executable programs where
8134 the main program is not in Ada, but some of the called routines are
8135 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8136 The following switch is used in this situation:
8140 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8141 No main program. The main program is not in Ada.
8145 In this case, most of the functions of the binder are still required,
8146 but instead of generating a main program, the binder generates a file
8147 containing the following callable routines:
8152 You must call this routine to initialize the Ada part of the program by
8153 calling the necessary elaboration routines. A call to @code{adainit} is
8154 required before the first call to an Ada subprogram.
8156 Note that it is assumed that the basic execution environment must be setup
8157 to be appropriate for Ada execution at the point where the first Ada
8158 subprogram is called. In particular, if the Ada code will do any
8159 floating-point operations, then the FPU must be setup in an appropriate
8160 manner. For the case of the x86, for example, full precision mode is
8161 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8162 that the FPU is in the right state.
8166 You must call this routine to perform any library-level finalization
8167 required by the Ada subprograms. A call to @code{adafinal} is required
8168 after the last call to an Ada subprogram, and before the program
8173 If the @option{^-n^/NOMAIN^} switch
8174 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8175 @cindex Binder, multiple input files
8176 is given, more than one ALI file may appear on
8177 the command line for @code{gnatbind}. The normal @dfn{closure}
8178 calculation is performed for each of the specified units. Calculating
8179 the closure means finding out the set of units involved by tracing
8180 @code{with} references. The reason it is necessary to be able to
8181 specify more than one ALI file is that a given program may invoke two or
8182 more quite separate groups of Ada units.
8184 The binder takes the name of its output file from the last specified ALI
8185 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8186 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8187 The output is an Ada unit in source form that can
8188 be compiled with GNAT unless the -C switch is used in which case the
8189 output is a C source file, which must be compiled using the C compiler.
8190 This compilation occurs automatically as part of the @command{gnatlink}
8193 Currently the GNAT run time requires a FPU using 80 bits mode
8194 precision. Under targets where this is not the default it is required to
8195 call GNAT.Float_Control.Reset before using floating point numbers (this
8196 include float computation, float input and output) in the Ada code. A
8197 side effect is that this could be the wrong mode for the foreign code
8198 where floating point computation could be broken after this call.
8200 @node Binding Programs with No Main Subprogram
8201 @subsection Binding Programs with No Main Subprogram
8204 It is possible to have an Ada program which does not have a main
8205 subprogram. This program will call the elaboration routines of all the
8206 packages, then the finalization routines.
8208 The following switch is used to bind programs organized in this manner:
8211 @item ^-z^/ZERO_MAIN^
8212 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8213 Normally the binder checks that the unit name given on the command line
8214 corresponds to a suitable main subprogram. When this switch is used,
8215 a list of ALI files can be given, and the execution of the program
8216 consists of elaboration of these units in an appropriate order. Note
8217 that the default wide character encoding method for standard Text_IO
8218 files is always set to Brackets if this switch is set (you can use
8220 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8223 @node Command-Line Access
8224 @section Command-Line Access
8227 The package @code{Ada.Command_Line} provides access to the command-line
8228 arguments and program name. In order for this interface to operate
8229 correctly, the two variables
8241 are declared in one of the GNAT library routines. These variables must
8242 be set from the actual @code{argc} and @code{argv} values passed to the
8243 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8244 generates the C main program to automatically set these variables.
8245 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8246 set these variables. If they are not set, the procedures in
8247 @code{Ada.Command_Line} will not be available, and any attempt to use
8248 them will raise @code{Constraint_Error}. If command line access is
8249 required, your main program must set @code{gnat_argc} and
8250 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8253 @node Search Paths for gnatbind
8254 @section Search Paths for @code{gnatbind}
8257 The binder takes the name of an ALI file as its argument and needs to
8258 locate source files as well as other ALI files to verify object consistency.
8260 For source files, it follows exactly the same search rules as @command{gcc}
8261 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8262 directories searched are:
8266 The directory containing the ALI file named in the command line, unless
8267 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8270 All directories specified by @option{^-I^/SEARCH^}
8271 switches on the @code{gnatbind}
8272 command line, in the order given.
8275 @findex ADA_PRJ_OBJECTS_FILE
8276 Each of the directories listed in the text file whose name is given
8277 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8280 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8281 driver when project files are used. It should not normally be set
8285 @findex ADA_OBJECTS_PATH
8286 Each of the directories listed in the value of the
8287 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8289 Construct this value
8290 exactly as the @env{PATH} environment variable: a list of directory
8291 names separated by colons (semicolons when working with the NT version
8295 Normally, define this value as a logical name containing a comma separated
8296 list of directory names.
8298 This variable can also be defined by means of an environment string
8299 (an argument to the HP C exec* set of functions).
8303 DEFINE ANOTHER_PATH FOO:[BAG]
8304 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8307 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8308 first, followed by the standard Ada
8309 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8310 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8311 (Text_IO, Sequential_IO, etc)
8312 instead of the standard Ada packages. Thus, in order to get the standard Ada
8313 packages by default, ADA_OBJECTS_PATH must be redefined.
8317 The content of the @file{ada_object_path} file which is part of the GNAT
8318 installation tree and is used to store standard libraries such as the
8319 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8322 @ref{Installing a library}
8327 In the binder the switch @option{^-I^/SEARCH^}
8328 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8329 is used to specify both source and
8330 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8331 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8332 instead if you want to specify
8333 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8334 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8335 if you want to specify library paths
8336 only. This means that for the binder
8337 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8338 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8339 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8340 The binder generates the bind file (a C language source file) in the
8341 current working directory.
8347 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8348 children make up the GNAT Run-Time Library, together with the package
8349 GNAT and its children, which contain a set of useful additional
8350 library functions provided by GNAT. The sources for these units are
8351 needed by the compiler and are kept together in one directory. The ALI
8352 files and object files generated by compiling the RTL are needed by the
8353 binder and the linker and are kept together in one directory, typically
8354 different from the directory containing the sources. In a normal
8355 installation, you need not specify these directory names when compiling
8356 or binding. Either the environment variables or the built-in defaults
8357 cause these files to be found.
8359 Besides simplifying access to the RTL, a major use of search paths is
8360 in compiling sources from multiple directories. This can make
8361 development environments much more flexible.
8363 @node Examples of gnatbind Usage
8364 @section Examples of @code{gnatbind} Usage
8367 This section contains a number of examples of using the GNAT binding
8368 utility @code{gnatbind}.
8371 @item gnatbind hello
8372 The main program @code{Hello} (source program in @file{hello.adb}) is
8373 bound using the standard switch settings. The generated main program is
8374 @file{b~hello.adb}. This is the normal, default use of the binder.
8377 @item gnatbind hello -o mainprog.adb
8380 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8382 The main program @code{Hello} (source program in @file{hello.adb}) is
8383 bound using the standard switch settings. The generated main program is
8384 @file{mainprog.adb} with the associated spec in
8385 @file{mainprog.ads}. Note that you must specify the body here not the
8386 spec, in the case where the output is in Ada. Note that if this option
8387 is used, then linking must be done manually, since gnatlink will not
8388 be able to find the generated file.
8391 @item gnatbind main -C -o mainprog.c -x
8394 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
8396 The main program @code{Main} (source program in
8397 @file{main.adb}) is bound, excluding source files from the
8398 consistency checking, generating
8399 the file @file{mainprog.c}.
8402 @item gnatbind -x main_program -C -o mainprog.c
8403 This command is exactly the same as the previous example. Switches may
8404 appear anywhere in the command line, and single letter switches may be
8405 combined into a single switch.
8409 @item gnatbind -n math dbase -C -o ada-control.c
8412 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
8414 The main program is in a language other than Ada, but calls to
8415 subprograms in packages @code{Math} and @code{Dbase} appear. This call
8416 to @code{gnatbind} generates the file @file{ada-control.c} containing
8417 the @code{adainit} and @code{adafinal} routines to be called before and
8418 after accessing the Ada units.
8421 @c ------------------------------------
8422 @node Linking Using gnatlink
8423 @chapter Linking Using @command{gnatlink}
8424 @c ------------------------------------
8428 This chapter discusses @command{gnatlink}, a tool that links
8429 an Ada program and builds an executable file. This utility
8430 invokes the system linker ^(via the @command{gcc} command)^^
8431 with a correct list of object files and library references.
8432 @command{gnatlink} automatically determines the list of files and
8433 references for the Ada part of a program. It uses the binder file
8434 generated by the @command{gnatbind} to determine this list.
8436 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8437 driver (see @ref{The GNAT Driver and Project Files}).
8440 * Running gnatlink::
8441 * Switches for gnatlink::
8444 @node Running gnatlink
8445 @section Running @command{gnatlink}
8448 The form of the @command{gnatlink} command is
8451 $ gnatlink [@var{switches}] @var{mainprog}[.ali]
8452 [@var{non-Ada objects}] [@var{linker options}]
8456 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8458 or linker options) may be in any order, provided that no non-Ada object may
8459 be mistaken for a main @file{ALI} file.
8460 Any file name @file{F} without the @file{.ali}
8461 extension will be taken as the main @file{ALI} file if a file exists
8462 whose name is the concatenation of @file{F} and @file{.ali}.
8465 @file{@var{mainprog}.ali} references the ALI file of the main program.
8466 The @file{.ali} extension of this file can be omitted. From this
8467 reference, @command{gnatlink} locates the corresponding binder file
8468 @file{b~@var{mainprog}.adb} and, using the information in this file along
8469 with the list of non-Ada objects and linker options, constructs a
8470 linker command file to create the executable.
8472 The arguments other than the @command{gnatlink} switches and the main
8473 @file{ALI} file are passed to the linker uninterpreted.
8474 They typically include the names of
8475 object files for units written in other languages than Ada and any library
8476 references required to resolve references in any of these foreign language
8477 units, or in @code{Import} pragmas in any Ada units.
8479 @var{linker options} is an optional list of linker specific
8481 The default linker called by gnatlink is @command{gcc} which in
8482 turn calls the appropriate system linker.
8483 Standard options for the linker such as @option{-lmy_lib} or
8484 @option{-Ldir} can be added as is.
8485 For options that are not recognized by
8486 @command{gcc} as linker options, use the @command{gcc} switches
8487 @option{-Xlinker} or @option{-Wl,}.
8488 Refer to the GCC documentation for
8489 details. Here is an example showing how to generate a linker map:
8492 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8495 Using @var{linker options} it is possible to set the program stack and
8498 See @ref{Setting Stack Size from gnatlink} and
8499 @ref{Setting Heap Size from gnatlink}.
8502 @command{gnatlink} determines the list of objects required by the Ada
8503 program and prepends them to the list of objects passed to the linker.
8504 @command{gnatlink} also gathers any arguments set by the use of
8505 @code{pragma Linker_Options} and adds them to the list of arguments
8506 presented to the linker.
8509 @command{gnatlink} accepts the following types of extra files on the command
8510 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8511 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8512 handled according to their extension.
8515 @node Switches for gnatlink
8516 @section Switches for @command{gnatlink}
8519 The following switches are available with the @command{gnatlink} utility:
8525 @cindex @option{--version} @command{gnatlink}
8526 Display Copyright and version, then exit disregarding all other options.
8529 @cindex @option{--help} @command{gnatlink}
8530 If @option{--version} was not used, display usage, then exit disregarding
8533 @item ^-A^/BIND_FILE=ADA^
8534 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
8535 The binder has generated code in Ada. This is the default.
8537 @item ^-C^/BIND_FILE=C^
8538 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
8539 If instead of generating a file in Ada, the binder has generated one in
8540 C, then the linker needs to know about it. Use this switch to signal
8541 to @command{gnatlink} that the binder has generated C code rather than
8544 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8545 @cindex Command line length
8546 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8547 On some targets, the command line length is limited, and @command{gnatlink}
8548 will generate a separate file for the linker if the list of object files
8550 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8551 to be generated even if
8552 the limit is not exceeded. This is useful in some cases to deal with
8553 special situations where the command line length is exceeded.
8556 @cindex Debugging information, including
8557 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8558 The option to include debugging information causes the Ada bind file (in
8559 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8560 @option{^-g^/DEBUG^}.
8561 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8562 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8563 Without @option{^-g^/DEBUG^}, the binder removes these files by
8564 default. The same procedure apply if a C bind file was generated using
8565 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8566 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8568 @item ^-n^/NOCOMPILE^
8569 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8570 Do not compile the file generated by the binder. This may be used when
8571 a link is rerun with different options, but there is no need to recompile
8575 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8576 Causes additional information to be output, including a full list of the
8577 included object files. This switch option is most useful when you want
8578 to see what set of object files are being used in the link step.
8580 @item ^-v -v^/VERBOSE/VERBOSE^
8581 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8582 Very verbose mode. Requests that the compiler operate in verbose mode when
8583 it compiles the binder file, and that the system linker run in verbose mode.
8585 @item ^-o ^/EXECUTABLE=^@var{exec-name}
8586 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
8587 @var{exec-name} specifies an alternate name for the generated
8588 executable program. If this switch is omitted, the executable has the same
8589 name as the main unit. For example, @code{gnatlink try.ali} creates
8590 an executable called @file{^try^TRY.EXE^}.
8593 @item -b @var{target}
8594 @cindex @option{-b} (@command{gnatlink})
8595 Compile your program to run on @var{target}, which is the name of a
8596 system configuration. You must have a GNAT cross-compiler built if
8597 @var{target} is not the same as your host system.
8600 @cindex @option{-B} (@command{gnatlink})
8601 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8602 from @var{dir} instead of the default location. Only use this switch
8603 when multiple versions of the GNAT compiler are available.
8604 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
8605 for further details. You would normally use the @option{-b} or
8606 @option{-V} switch instead.
8608 @item --GCC=@var{compiler_name}
8609 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8610 Program used for compiling the binder file. The default is
8611 @command{gcc}. You need to use quotes around @var{compiler_name} if
8612 @code{compiler_name} contains spaces or other separator characters.
8613 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8614 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8615 inserted after your command name. Thus in the above example the compiler
8616 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8617 A limitation of this syntax is that the name and path name of the executable
8618 itself must not include any embedded spaces. If the compiler executable is
8619 different from the default one (gcc or <prefix>-gcc), then the back-end
8620 switches in the ALI file are not used to compile the binder generated source.
8621 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
8622 switches will be used for @option{--GCC="gcc -gnatv"}. If several
8623 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
8624 is taken into account. However, all the additional switches are also taken
8626 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8627 @option{--GCC="bar -x -y -z -t"}.
8629 @item --LINK=@var{name}
8630 @cindex @option{--LINK=} (@command{gnatlink})
8631 @var{name} is the name of the linker to be invoked. This is especially
8632 useful in mixed language programs since languages such as C++ require
8633 their own linker to be used. When this switch is omitted, the default
8634 name for the linker is @command{gcc}. When this switch is used, the
8635 specified linker is called instead of @command{gcc} with exactly the same
8636 parameters that would have been passed to @command{gcc} so if the desired
8637 linker requires different parameters it is necessary to use a wrapper
8638 script that massages the parameters before invoking the real linker. It
8639 may be useful to control the exact invocation by using the verbose
8645 @item /DEBUG=TRACEBACK
8646 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
8647 This qualifier causes sufficient information to be included in the
8648 executable file to allow a traceback, but does not include the full
8649 symbol information needed by the debugger.
8651 @item /IDENTIFICATION="<string>"
8652 @code{"<string>"} specifies the string to be stored in the image file
8653 identification field in the image header.
8654 It overrides any pragma @code{Ident} specified string.
8656 @item /NOINHIBIT-EXEC
8657 Generate the executable file even if there are linker warnings.
8659 @item /NOSTART_FILES
8660 Don't link in the object file containing the ``main'' transfer address.
8661 Used when linking with a foreign language main program compiled with an
8665 Prefer linking with object libraries over sharable images, even without
8671 @node The GNAT Make Program gnatmake
8672 @chapter The GNAT Make Program @command{gnatmake}
8676 * Running gnatmake::
8677 * Switches for gnatmake::
8678 * Mode Switches for gnatmake::
8679 * Notes on the Command Line::
8680 * How gnatmake Works::
8681 * Examples of gnatmake Usage::
8684 A typical development cycle when working on an Ada program consists of
8685 the following steps:
8689 Edit some sources to fix bugs.
8695 Compile all sources affected.
8705 The third step can be tricky, because not only do the modified files
8706 @cindex Dependency rules
8707 have to be compiled, but any files depending on these files must also be
8708 recompiled. The dependency rules in Ada can be quite complex, especially
8709 in the presence of overloading, @code{use} clauses, generics and inlined
8712 @command{gnatmake} automatically takes care of the third and fourth steps
8713 of this process. It determines which sources need to be compiled,
8714 compiles them, and binds and links the resulting object files.
8716 Unlike some other Ada make programs, the dependencies are always
8717 accurately recomputed from the new sources. The source based approach of
8718 the GNAT compilation model makes this possible. This means that if
8719 changes to the source program cause corresponding changes in
8720 dependencies, they will always be tracked exactly correctly by
8723 @node Running gnatmake
8724 @section Running @command{gnatmake}
8727 The usual form of the @command{gnatmake} command is
8730 $ gnatmake [@var{switches}] @var{file_name}
8731 [@var{file_names}] [@var{mode_switches}]
8735 The only required argument is one @var{file_name}, which specifies
8736 a compilation unit that is a main program. Several @var{file_names} can be
8737 specified: this will result in several executables being built.
8738 If @code{switches} are present, they can be placed before the first
8739 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8740 If @var{mode_switches} are present, they must always be placed after
8741 the last @var{file_name} and all @code{switches}.
8743 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
8744 extension may be omitted from the @var{file_name} arguments. However, if
8745 you are using non-standard extensions, then it is required that the
8746 extension be given. A relative or absolute directory path can be
8747 specified in a @var{file_name}, in which case, the input source file will
8748 be searched for in the specified directory only. Otherwise, the input
8749 source file will first be searched in the directory where
8750 @command{gnatmake} was invoked and if it is not found, it will be search on
8751 the source path of the compiler as described in
8752 @ref{Search Paths and the Run-Time Library (RTL)}.
8754 All @command{gnatmake} output (except when you specify
8755 @option{^-M^/DEPENDENCIES_LIST^}) is to
8756 @file{stderr}. The output produced by the
8757 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8760 @node Switches for gnatmake
8761 @section Switches for @command{gnatmake}
8764 You may specify any of the following switches to @command{gnatmake}:
8770 @cindex @option{--version} @command{gnatmake}
8771 Display Copyright and version, then exit disregarding all other options.
8774 @cindex @option{--help} @command{gnatmake}
8775 If @option{--version} was not used, display usage, then exit disregarding
8779 @item --GCC=@var{compiler_name}
8780 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
8781 Program used for compiling. The default is `@command{gcc}'. You need to use
8782 quotes around @var{compiler_name} if @code{compiler_name} contains
8783 spaces or other separator characters. As an example @option{--GCC="foo -x
8784 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
8785 compiler. A limitation of this syntax is that the name and path name of
8786 the executable itself must not include any embedded spaces. Note that
8787 switch @option{-c} is always inserted after your command name. Thus in the
8788 above example the compiler command that will be used by @command{gnatmake}
8789 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
8790 used, only the last @var{compiler_name} is taken into account. However,
8791 all the additional switches are also taken into account. Thus,
8792 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8793 @option{--GCC="bar -x -y -z -t"}.
8795 @item --GNATBIND=@var{binder_name}
8796 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
8797 Program used for binding. The default is `@code{gnatbind}'. You need to
8798 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8799 or other separator characters. As an example @option{--GNATBIND="bar -x
8800 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
8801 binder. Binder switches that are normally appended by @command{gnatmake}
8802 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8803 A limitation of this syntax is that the name and path name of the executable
8804 itself must not include any embedded spaces.
8806 @item --GNATLINK=@var{linker_name}
8807 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
8808 Program used for linking. The default is `@command{gnatlink}'. You need to
8809 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8810 or other separator characters. As an example @option{--GNATLINK="lan -x
8811 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
8812 linker. Linker switches that are normally appended by @command{gnatmake} to
8813 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
8814 A limitation of this syntax is that the name and path name of the executable
8815 itself must not include any embedded spaces.
8819 @item ^-a^/ALL_FILES^
8820 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
8821 Consider all files in the make process, even the GNAT internal system
8822 files (for example, the predefined Ada library files), as well as any
8823 locked files. Locked files are files whose ALI file is write-protected.
8825 @command{gnatmake} does not check these files,
8826 because the assumption is that the GNAT internal files are properly up
8827 to date, and also that any write protected ALI files have been properly
8828 installed. Note that if there is an installation problem, such that one
8829 of these files is not up to date, it will be properly caught by the
8831 You may have to specify this switch if you are working on GNAT
8832 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8833 in conjunction with @option{^-f^/FORCE_COMPILE^}
8834 if you need to recompile an entire application,
8835 including run-time files, using special configuration pragmas,
8836 such as a @code{Normalize_Scalars} pragma.
8839 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8842 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8845 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8848 @item ^-b^/ACTIONS=BIND^
8849 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
8850 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8851 compilation and binding, but no link.
8852 Can be combined with @option{^-l^/ACTIONS=LINK^}
8853 to do binding and linking. When not combined with
8854 @option{^-c^/ACTIONS=COMPILE^}
8855 all the units in the closure of the main program must have been previously
8856 compiled and must be up to date. The root unit specified by @var{file_name}
8857 may be given without extension, with the source extension or, if no GNAT
8858 Project File is specified, with the ALI file extension.
8860 @item ^-c^/ACTIONS=COMPILE^
8861 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
8862 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8863 is also specified. Do not perform linking, except if both
8864 @option{^-b^/ACTIONS=BIND^} and
8865 @option{^-l^/ACTIONS=LINK^} are also specified.
8866 If the root unit specified by @var{file_name} is not a main unit, this is the
8867 default. Otherwise @command{gnatmake} will attempt binding and linking
8868 unless all objects are up to date and the executable is more recent than
8872 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
8873 Use a temporary mapping file. A mapping file is a way to communicate to the
8874 compiler two mappings: from unit names to file names (without any directory
8875 information) and from file names to path names (with full directory
8876 information). These mappings are used by the compiler to short-circuit the path
8877 search. When @command{gnatmake} is invoked with this switch, it will create
8878 a temporary mapping file, initially populated by the project manager,
8879 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8880 Each invocation of the compiler will add the newly accessed sources to the
8881 mapping file. This will improve the source search during the next invocation
8884 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8885 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
8886 Use a specific mapping file. The file, specified as a path name (absolute or
8887 relative) by this switch, should already exist, otherwise the switch is
8888 ineffective. The specified mapping file will be communicated to the compiler.
8889 This switch is not compatible with a project file
8890 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8891 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8893 @item ^-d^/DISPLAY_PROGRESS^
8894 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
8895 Display progress for each source, up to date or not, as a single line
8897 completed x out of y (zz%)
8899 If the file needs to be compiled this is displayed after the invocation of
8900 the compiler. These lines are displayed even in quiet output mode.
8902 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
8903 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
8904 Put all object files and ALI file in directory @var{dir}.
8905 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
8906 and ALI files go in the current working directory.
8908 This switch cannot be used when using a project file.
8912 @cindex @option{-eL} (@command{gnatmake})
8913 Follow all symbolic links when processing project files.
8916 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
8917 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
8918 Output the commands for the compiler, the binder and the linker
8919 on ^standard output^SYS$OUTPUT^,
8920 instead of ^standard error^SYS$ERROR^.
8922 @item ^-f^/FORCE_COMPILE^
8923 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
8924 Force recompilations. Recompile all sources, even though some object
8925 files may be up to date, but don't recompile predefined or GNAT internal
8926 files or locked files (files with a write-protected ALI file),
8927 unless the @option{^-a^/ALL_FILES^} switch is also specified.
8929 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
8930 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
8931 When using project files, if some errors or warnings are detected during
8932 parsing and verbose mode is not in effect (no use of switch
8933 ^-v^/VERBOSE^), then error lines start with the full path name of the project
8934 file, rather than its simple file name.
8937 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
8938 Enable debugging. This switch is simply passed to the compiler and to the
8941 @item ^-i^/IN_PLACE^
8942 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
8943 In normal mode, @command{gnatmake} compiles all object files and ALI files
8944 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
8945 then instead object files and ALI files that already exist are overwritten
8946 in place. This means that once a large project is organized into separate
8947 directories in the desired manner, then @command{gnatmake} will automatically
8948 maintain and update this organization. If no ALI files are found on the
8949 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
8950 the new object and ALI files are created in the
8951 directory containing the source being compiled. If another organization
8952 is desired, where objects and sources are kept in different directories,
8953 a useful technique is to create dummy ALI files in the desired directories.
8954 When detecting such a dummy file, @command{gnatmake} will be forced to
8955 recompile the corresponding source file, and it will be put the resulting
8956 object and ALI files in the directory where it found the dummy file.
8958 @item ^-j^/PROCESSES=^@var{n}
8959 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
8960 @cindex Parallel make
8961 Use @var{n} processes to carry out the (re)compilations. On a
8962 multiprocessor machine compilations will occur in parallel. In the
8963 event of compilation errors, messages from various compilations might
8964 get interspersed (but @command{gnatmake} will give you the full ordered
8965 list of failing compiles at the end). If this is problematic, rerun
8966 the make process with n set to 1 to get a clean list of messages.
8968 @item ^-k^/CONTINUE_ON_ERROR^
8969 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
8970 Keep going. Continue as much as possible after a compilation error. To
8971 ease the programmer's task in case of compilation errors, the list of
8972 sources for which the compile fails is given when @command{gnatmake}
8975 If @command{gnatmake} is invoked with several @file{file_names} and with this
8976 switch, if there are compilation errors when building an executable,
8977 @command{gnatmake} will not attempt to build the following executables.
8979 @item ^-l^/ACTIONS=LINK^
8980 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
8981 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
8982 and linking. Linking will not be performed if combined with
8983 @option{^-c^/ACTIONS=COMPILE^}
8984 but not with @option{^-b^/ACTIONS=BIND^}.
8985 When not combined with @option{^-b^/ACTIONS=BIND^}
8986 all the units in the closure of the main program must have been previously
8987 compiled and must be up to date, and the main program needs to have been bound.
8988 The root unit specified by @var{file_name}
8989 may be given without extension, with the source extension or, if no GNAT
8990 Project File is specified, with the ALI file extension.
8992 @item ^-m^/MINIMAL_RECOMPILATION^
8993 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
8994 Specify that the minimum necessary amount of recompilations
8995 be performed. In this mode @command{gnatmake} ignores time
8996 stamp differences when the only
8997 modifications to a source file consist in adding/removing comments,
8998 empty lines, spaces or tabs. This means that if you have changed the
8999 comments in a source file or have simply reformatted it, using this
9000 switch will tell @command{gnatmake} not to recompile files that depend on it
9001 (provided other sources on which these files depend have undergone no
9002 semantic modifications). Note that the debugging information may be
9003 out of date with respect to the sources if the @option{-m} switch causes
9004 a compilation to be switched, so the use of this switch represents a
9005 trade-off between compilation time and accurate debugging information.
9007 @item ^-M^/DEPENDENCIES_LIST^
9008 @cindex Dependencies, producing list
9009 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9010 Check if all objects are up to date. If they are, output the object
9011 dependences to @file{stdout} in a form that can be directly exploited in
9012 a @file{Makefile}. By default, each source file is prefixed with its
9013 (relative or absolute) directory name. This name is whatever you
9014 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9015 and @option{^-I^/SEARCH^} switches. If you use
9016 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9017 @option{^-q^/QUIET^}
9018 (see below), only the source file names,
9019 without relative paths, are output. If you just specify the
9020 @option{^-M^/DEPENDENCIES_LIST^}
9021 switch, dependencies of the GNAT internal system files are omitted. This
9022 is typically what you want. If you also specify
9023 the @option{^-a^/ALL_FILES^} switch,
9024 dependencies of the GNAT internal files are also listed. Note that
9025 dependencies of the objects in external Ada libraries (see switch
9026 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9029 @item ^-n^/DO_OBJECT_CHECK^
9030 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9031 Don't compile, bind, or link. Checks if all objects are up to date.
9032 If they are not, the full name of the first file that needs to be
9033 recompiled is printed.
9034 Repeated use of this option, followed by compiling the indicated source
9035 file, will eventually result in recompiling all required units.
9037 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9038 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9039 Output executable name. The name of the final executable program will be
9040 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9041 name for the executable will be the name of the input file in appropriate form
9042 for an executable file on the host system.
9044 This switch cannot be used when invoking @command{gnatmake} with several
9047 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9048 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9049 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9050 automatically missing object directories, library directories and exec
9053 @item ^-P^/PROJECT_FILE=^@var{project}
9054 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9055 Use project file @var{project}. Only one such switch can be used.
9056 @xref{gnatmake and Project Files}.
9059 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9060 Quiet. When this flag is not set, the commands carried out by
9061 @command{gnatmake} are displayed.
9063 @item ^-s^/SWITCH_CHECK/^
9064 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9065 Recompile if compiler switches have changed since last compilation.
9066 All compiler switches but -I and -o are taken into account in the
9068 orders between different ``first letter'' switches are ignored, but
9069 orders between same switches are taken into account. For example,
9070 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9071 is equivalent to @option{-O -g}.
9073 This switch is recommended when Integrated Preprocessing is used.
9076 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9077 Unique. Recompile at most the main files. It implies -c. Combined with
9078 -f, it is equivalent to calling the compiler directly. Note that using
9079 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9080 (@pxref{Project Files and Main Subprograms}).
9082 @item ^-U^/ALL_PROJECTS^
9083 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9084 When used without a project file or with one or several mains on the command
9085 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9086 on the command line, all sources of all project files are checked and compiled
9087 if not up to date, and libraries are rebuilt, if necessary.
9090 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9091 Verbose. Display the reason for all recompilations @command{gnatmake}
9092 decides are necessary, with the highest verbosity level.
9094 @item ^-vl^/LOW_VERBOSITY^
9095 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9096 Verbosity level Low. Display fewer lines than in verbosity Medium.
9098 @item ^-vm^/MEDIUM_VERBOSITY^
9099 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9100 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9102 @item ^-vh^/HIGH_VERBOSITY^
9103 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9104 Verbosity level High. Equivalent to ^-v^/REASONS^.
9106 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9107 Indicate the verbosity of the parsing of GNAT project files.
9108 @xref{Switches Related to Project Files}.
9110 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9111 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9112 Indicate that sources that are not part of any Project File may be compiled.
9113 Normally, when using Project Files, only sources that are part of a Project
9114 File may be compile. When this switch is used, a source outside of all Project
9115 Files may be compiled. The ALI file and the object file will be put in the
9116 object directory of the main Project. The compilation switches used will only
9117 be those specified on the command line. Even when
9118 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9119 command line need to be sources of a project file.
9121 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9122 Indicate that external variable @var{name} has the value @var{value}.
9123 The Project Manager will use this value for occurrences of
9124 @code{external(name)} when parsing the project file.
9125 @xref{Switches Related to Project Files}.
9128 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9129 No main subprogram. Bind and link the program even if the unit name
9130 given on the command line is a package name. The resulting executable
9131 will execute the elaboration routines of the package and its closure,
9132 then the finalization routines.
9137 @item @command{gcc} @asis{switches}
9139 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9140 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9143 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9144 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9145 automatically treated as a compiler switch, and passed on to all
9146 compilations that are carried out.
9151 Source and library search path switches:
9155 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9156 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9157 When looking for source files also look in directory @var{dir}.
9158 The order in which source files search is undertaken is
9159 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9161 @item ^-aL^/SKIP_MISSING=^@var{dir}
9162 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9163 Consider @var{dir} as being an externally provided Ada library.
9164 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9165 files have been located in directory @var{dir}. This allows you to have
9166 missing bodies for the units in @var{dir} and to ignore out of date bodies
9167 for the same units. You still need to specify
9168 the location of the specs for these units by using the switches
9169 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9170 or @option{^-I^/SEARCH=^@var{dir}}.
9171 Note: this switch is provided for compatibility with previous versions
9172 of @command{gnatmake}. The easier method of causing standard libraries
9173 to be excluded from consideration is to write-protect the corresponding
9176 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9177 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9178 When searching for library and object files, look in directory
9179 @var{dir}. The order in which library files are searched is described in
9180 @ref{Search Paths for gnatbind}.
9182 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9183 @cindex Search paths, for @command{gnatmake}
9184 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9185 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9186 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9188 @item ^-I^/SEARCH=^@var{dir}
9189 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9190 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9191 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9193 @item ^-I-^/NOCURRENT_DIRECTORY^
9194 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9195 @cindex Source files, suppressing search
9196 Do not look for source files in the directory containing the source
9197 file named in the command line.
9198 Do not look for ALI or object files in the directory
9199 where @command{gnatmake} was invoked.
9201 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9202 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9203 @cindex Linker libraries
9204 Add directory @var{dir} to the list of directories in which the linker
9205 will search for libraries. This is equivalent to
9206 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9208 Furthermore, under Windows, the sources pointed to by the libraries path
9209 set in the registry are not searched for.
9213 @cindex @option{-nostdinc} (@command{gnatmake})
9214 Do not look for source files in the system default directory.
9217 @cindex @option{-nostdlib} (@command{gnatmake})
9218 Do not look for library files in the system default directory.
9220 @item --RTS=@var{rts-path}
9221 @cindex @option{--RTS} (@command{gnatmake})
9222 Specifies the default location of the runtime library. GNAT looks for the
9224 in the following directories, and stops as soon as a valid runtime is found
9225 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9226 @file{ada_object_path} present):
9229 @item <current directory>/$rts_path
9231 @item <default-search-dir>/$rts_path
9233 @item <default-search-dir>/rts-$rts_path
9237 The selected path is handled like a normal RTS path.
9241 @node Mode Switches for gnatmake
9242 @section Mode Switches for @command{gnatmake}
9245 The mode switches (referred to as @code{mode_switches}) allow the
9246 inclusion of switches that are to be passed to the compiler itself, the
9247 binder or the linker. The effect of a mode switch is to cause all
9248 subsequent switches up to the end of the switch list, or up to the next
9249 mode switch, to be interpreted as switches to be passed on to the
9250 designated component of GNAT.
9254 @item -cargs @var{switches}
9255 @cindex @option{-cargs} (@command{gnatmake})
9256 Compiler switches. Here @var{switches} is a list of switches
9257 that are valid switches for @command{gcc}. They will be passed on to
9258 all compile steps performed by @command{gnatmake}.
9260 @item -bargs @var{switches}
9261 @cindex @option{-bargs} (@command{gnatmake})
9262 Binder switches. Here @var{switches} is a list of switches
9263 that are valid switches for @code{gnatbind}. They will be passed on to
9264 all bind steps performed by @command{gnatmake}.
9266 @item -largs @var{switches}
9267 @cindex @option{-largs} (@command{gnatmake})
9268 Linker switches. Here @var{switches} is a list of switches
9269 that are valid switches for @command{gnatlink}. They will be passed on to
9270 all link steps performed by @command{gnatmake}.
9272 @item -margs @var{switches}
9273 @cindex @option{-margs} (@command{gnatmake})
9274 Make switches. The switches are directly interpreted by @command{gnatmake},
9275 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9279 @node Notes on the Command Line
9280 @section Notes on the Command Line
9283 This section contains some additional useful notes on the operation
9284 of the @command{gnatmake} command.
9288 @cindex Recompilation, by @command{gnatmake}
9289 If @command{gnatmake} finds no ALI files, it recompiles the main program
9290 and all other units required by the main program.
9291 This means that @command{gnatmake}
9292 can be used for the initial compile, as well as during subsequent steps of
9293 the development cycle.
9296 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9297 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9298 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9302 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9303 is used to specify both source and
9304 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9305 instead if you just want to specify
9306 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9307 if you want to specify library paths
9311 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9312 This may conveniently be used to exclude standard libraries from
9313 consideration and in particular it means that the use of the
9314 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9315 unless @option{^-a^/ALL_FILES^} is also specified.
9318 @command{gnatmake} has been designed to make the use of Ada libraries
9319 particularly convenient. Assume you have an Ada library organized
9320 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9321 of your Ada compilation units,
9322 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9323 specs of these units, but no bodies. Then to compile a unit
9324 stored in @code{main.adb}, which uses this Ada library you would just type
9328 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
9331 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9332 /SKIP_MISSING=@i{[OBJ_DIR]} main
9337 Using @command{gnatmake} along with the
9338 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9339 switch provides a mechanism for avoiding unnecessary recompilations. Using
9341 you can update the comments/format of your
9342 source files without having to recompile everything. Note, however, that
9343 adding or deleting lines in a source files may render its debugging
9344 info obsolete. If the file in question is a spec, the impact is rather
9345 limited, as that debugging info will only be useful during the
9346 elaboration phase of your program. For bodies the impact can be more
9347 significant. In all events, your debugger will warn you if a source file
9348 is more recent than the corresponding object, and alert you to the fact
9349 that the debugging information may be out of date.
9352 @node How gnatmake Works
9353 @section How @command{gnatmake} Works
9356 Generally @command{gnatmake} automatically performs all necessary
9357 recompilations and you don't need to worry about how it works. However,
9358 it may be useful to have some basic understanding of the @command{gnatmake}
9359 approach and in particular to understand how it uses the results of
9360 previous compilations without incorrectly depending on them.
9362 First a definition: an object file is considered @dfn{up to date} if the
9363 corresponding ALI file exists and if all the source files listed in the
9364 dependency section of this ALI file have time stamps matching those in
9365 the ALI file. This means that neither the source file itself nor any
9366 files that it depends on have been modified, and hence there is no need
9367 to recompile this file.
9369 @command{gnatmake} works by first checking if the specified main unit is up
9370 to date. If so, no compilations are required for the main unit. If not,
9371 @command{gnatmake} compiles the main program to build a new ALI file that
9372 reflects the latest sources. Then the ALI file of the main unit is
9373 examined to find all the source files on which the main program depends,
9374 and @command{gnatmake} recursively applies the above procedure on all these
9377 This process ensures that @command{gnatmake} only trusts the dependencies
9378 in an existing ALI file if they are known to be correct. Otherwise it
9379 always recompiles to determine a new, guaranteed accurate set of
9380 dependencies. As a result the program is compiled ``upside down'' from what may
9381 be more familiar as the required order of compilation in some other Ada
9382 systems. In particular, clients are compiled before the units on which
9383 they depend. The ability of GNAT to compile in any order is critical in
9384 allowing an order of compilation to be chosen that guarantees that
9385 @command{gnatmake} will recompute a correct set of new dependencies if
9388 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9389 imported by several of the executables, it will be recompiled at most once.
9391 Note: when using non-standard naming conventions
9392 (@pxref{Using Other File Names}), changing through a configuration pragmas
9393 file the version of a source and invoking @command{gnatmake} to recompile may
9394 have no effect, if the previous version of the source is still accessible
9395 by @command{gnatmake}. It may be necessary to use the switch
9396 ^-f^/FORCE_COMPILE^.
9398 @node Examples of gnatmake Usage
9399 @section Examples of @command{gnatmake} Usage
9402 @item gnatmake hello.adb
9403 Compile all files necessary to bind and link the main program
9404 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9405 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9407 @item gnatmake main1 main2 main3
9408 Compile all files necessary to bind and link the main programs
9409 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9410 (containing unit @code{Main2}) and @file{main3.adb}
9411 (containing unit @code{Main3}) and bind and link the resulting object files
9412 to generate three executable files @file{^main1^MAIN1.EXE^},
9413 @file{^main2^MAIN2.EXE^}
9414 and @file{^main3^MAIN3.EXE^}.
9417 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9421 @item gnatmake Main_Unit /QUIET
9422 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9423 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9425 Compile all files necessary to bind and link the main program unit
9426 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9427 be done with optimization level 2 and the order of elaboration will be
9428 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9429 displaying commands it is executing.
9432 @c *************************
9433 @node Improving Performance
9434 @chapter Improving Performance
9435 @cindex Improving performance
9438 This chapter presents several topics related to program performance.
9439 It first describes some of the tradeoffs that need to be considered
9440 and some of the techniques for making your program run faster.
9441 It then documents the @command{gnatelim} tool and unused subprogram/data
9442 elimination feature, which can reduce the size of program executables.
9444 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9445 driver (see @ref{The GNAT Driver and Project Files}).
9449 * Performance Considerations::
9450 * Text_IO Suggestions::
9451 * Reducing Size of Ada Executables with gnatelim::
9452 * Reducing Size of Executables with unused subprogram/data elimination::
9456 @c *****************************
9457 @node Performance Considerations
9458 @section Performance Considerations
9461 The GNAT system provides a number of options that allow a trade-off
9466 performance of the generated code
9469 speed of compilation
9472 minimization of dependences and recompilation
9475 the degree of run-time checking.
9479 The defaults (if no options are selected) aim at improving the speed
9480 of compilation and minimizing dependences, at the expense of performance
9481 of the generated code:
9488 no inlining of subprogram calls
9491 all run-time checks enabled except overflow and elaboration checks
9495 These options are suitable for most program development purposes. This
9496 chapter describes how you can modify these choices, and also provides
9497 some guidelines on debugging optimized code.
9500 * Controlling Run-Time Checks::
9501 * Use of Restrictions::
9502 * Optimization Levels::
9503 * Debugging Optimized Code::
9504 * Inlining of Subprograms::
9505 * Other Optimization Switches::
9506 * Optimization and Strict Aliasing::
9509 * Coverage Analysis::
9513 @node Controlling Run-Time Checks
9514 @subsection Controlling Run-Time Checks
9517 By default, GNAT generates all run-time checks, except arithmetic overflow
9518 checking for integer operations and checks for access before elaboration on
9519 subprogram calls. The latter are not required in default mode, because all
9520 necessary checking is done at compile time.
9521 @cindex @option{-gnatp} (@command{gcc})
9522 @cindex @option{-gnato} (@command{gcc})
9523 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9524 be modified. @xref{Run-Time Checks}.
9526 Our experience is that the default is suitable for most development
9529 We treat integer overflow specially because these
9530 are quite expensive and in our experience are not as important as other
9531 run-time checks in the development process. Note that division by zero
9532 is not considered an overflow check, and divide by zero checks are
9533 generated where required by default.
9535 Elaboration checks are off by default, and also not needed by default, since
9536 GNAT uses a static elaboration analysis approach that avoids the need for
9537 run-time checking. This manual contains a full chapter discussing the issue
9538 of elaboration checks, and if the default is not satisfactory for your use,
9539 you should read this chapter.
9541 For validity checks, the minimal checks required by the Ada Reference
9542 Manual (for case statements and assignments to array elements) are on
9543 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9544 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9545 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9546 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9547 are also suppressed entirely if @option{-gnatp} is used.
9549 @cindex Overflow checks
9550 @cindex Checks, overflow
9553 @cindex pragma Suppress
9554 @cindex pragma Unsuppress
9555 Note that the setting of the switches controls the default setting of
9556 the checks. They may be modified using either @code{pragma Suppress} (to
9557 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9558 checks) in the program source.
9560 @node Use of Restrictions
9561 @subsection Use of Restrictions
9564 The use of pragma Restrictions allows you to control which features are
9565 permitted in your program. Apart from the obvious point that if you avoid
9566 relatively expensive features like finalization (enforceable by the use
9567 of pragma Restrictions (No_Finalization), the use of this pragma does not
9568 affect the generated code in most cases.
9570 One notable exception to this rule is that the possibility of task abort
9571 results in some distributed overhead, particularly if finalization or
9572 exception handlers are used. The reason is that certain sections of code
9573 have to be marked as non-abortable.
9575 If you use neither the @code{abort} statement, nor asynchronous transfer
9576 of control (@code{select @dots{} then abort}), then this distributed overhead
9577 is removed, which may have a general positive effect in improving
9578 overall performance. Especially code involving frequent use of tasking
9579 constructs and controlled types will show much improved performance.
9580 The relevant restrictions pragmas are
9582 @smallexample @c ada
9583 pragma Restrictions (No_Abort_Statements);
9584 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
9588 It is recommended that these restriction pragmas be used if possible. Note
9589 that this also means that you can write code without worrying about the
9590 possibility of an immediate abort at any point.
9592 @node Optimization Levels
9593 @subsection Optimization Levels
9594 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
9597 Without any optimization ^option,^qualifier,^
9598 the compiler's goal is to reduce the cost of
9599 compilation and to make debugging produce the expected results.
9600 Statements are independent: if you stop the program with a breakpoint between
9601 statements, you can then assign a new value to any variable or change
9602 the program counter to any other statement in the subprogram and get exactly
9603 the results you would expect from the source code.
9605 Turning on optimization makes the compiler attempt to improve the
9606 performance and/or code size at the expense of compilation time and
9607 possibly the ability to debug the program.
9610 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
9611 the last such option is the one that is effective.
9614 The default is optimization off. This results in the fastest compile
9615 times, but GNAT makes absolutely no attempt to optimize, and the
9616 generated programs are considerably larger and slower than when
9617 optimization is enabled. You can use the
9619 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
9620 @option{-O2}, @option{-O3}, and @option{-Os})
9623 @code{OPTIMIZE} qualifier
9625 to @command{gcc} to control the optimization level:
9628 @item ^-O0^/OPTIMIZE=NONE^
9629 No optimization (the default);
9630 generates unoptimized code but has
9631 the fastest compilation time.
9633 Note that many other compilers do fairly extensive optimization
9634 even if ``no optimization'' is specified. With gcc, it is
9635 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
9636 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
9637 really does mean no optimization at all. This difference between
9638 gcc and other compilers should be kept in mind when doing
9639 performance comparisons.
9641 @item ^-O1^/OPTIMIZE=SOME^
9642 Moderate optimization;
9643 optimizes reasonably well but does not
9644 degrade compilation time significantly.
9646 @item ^-O2^/OPTIMIZE=ALL^
9648 @itemx /OPTIMIZE=DEVELOPMENT
9651 generates highly optimized code and has
9652 the slowest compilation time.
9654 @item ^-O3^/OPTIMIZE=INLINING^
9655 Full optimization as in @option{-O2},
9656 and also attempts automatic inlining of small
9657 subprograms within a unit (@pxref{Inlining of Subprograms}).
9659 @item ^-Os^/OPTIMIZE=SPACE^
9660 Optimize space usage of resulting program.
9664 Higher optimization levels perform more global transformations on the
9665 program and apply more expensive analysis algorithms in order to generate
9666 faster and more compact code. The price in compilation time, and the
9667 resulting improvement in execution time,
9668 both depend on the particular application and the hardware environment.
9669 You should experiment to find the best level for your application.
9671 Since the precise set of optimizations done at each level will vary from
9672 release to release (and sometime from target to target), it is best to think
9673 of the optimization settings in general terms.
9674 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
9675 the GNU Compiler Collection (GCC)}, for details about
9676 ^the @option{-O} settings and a number of @option{-f} options that^how to^
9677 individually enable or disable specific optimizations.
9679 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
9680 been tested extensively at all optimization levels. There are some bugs
9681 which appear only with optimization turned on, but there have also been
9682 bugs which show up only in @emph{unoptimized} code. Selecting a lower
9683 level of optimization does not improve the reliability of the code
9684 generator, which in practice is highly reliable at all optimization
9687 Note regarding the use of @option{-O3}: The use of this optimization level
9688 is generally discouraged with GNAT, since it often results in larger
9689 executables which run more slowly. See further discussion of this point
9690 in @ref{Inlining of Subprograms}.
9692 @node Debugging Optimized Code
9693 @subsection Debugging Optimized Code
9694 @cindex Debugging optimized code
9695 @cindex Optimization and debugging
9698 Although it is possible to do a reasonable amount of debugging at
9700 nonzero optimization levels,
9701 the higher the level the more likely that
9704 @option{/OPTIMIZE} settings other than @code{NONE},
9705 such settings will make it more likely that
9707 source-level constructs will have been eliminated by optimization.
9708 For example, if a loop is strength-reduced, the loop
9709 control variable may be completely eliminated and thus cannot be
9710 displayed in the debugger.
9711 This can only happen at @option{-O2} or @option{-O3}.
9712 Explicit temporary variables that you code might be eliminated at
9713 ^level^setting^ @option{-O1} or higher.
9715 The use of the @option{^-g^/DEBUG^} switch,
9716 @cindex @option{^-g^/DEBUG^} (@command{gcc})
9717 which is needed for source-level debugging,
9718 affects the size of the program executable on disk,
9719 and indeed the debugging information can be quite large.
9720 However, it has no effect on the generated code (and thus does not
9721 degrade performance)
9723 Since the compiler generates debugging tables for a compilation unit before
9724 it performs optimizations, the optimizing transformations may invalidate some
9725 of the debugging data. You therefore need to anticipate certain
9726 anomalous situations that may arise while debugging optimized code.
9727 These are the most common cases:
9731 @i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next}
9733 the PC bouncing back and forth in the code. This may result from any of
9734 the following optimizations:
9738 @i{Common subexpression elimination:} using a single instance of code for a
9739 quantity that the source computes several times. As a result you
9740 may not be able to stop on what looks like a statement.
9743 @i{Invariant code motion:} moving an expression that does not change within a
9744 loop, to the beginning of the loop.
9747 @i{Instruction scheduling:} moving instructions so as to
9748 overlap loads and stores (typically) with other code, or in
9749 general to move computations of values closer to their uses. Often
9750 this causes you to pass an assignment statement without the assignment
9751 happening and then later bounce back to the statement when the
9752 value is actually needed. Placing a breakpoint on a line of code
9753 and then stepping over it may, therefore, not always cause all the
9754 expected side-effects.
9758 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
9759 two identical pieces of code are merged and the program counter suddenly
9760 jumps to a statement that is not supposed to be executed, simply because
9761 it (and the code following) translates to the same thing as the code
9762 that @emph{was} supposed to be executed. This effect is typically seen in
9763 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
9764 a @code{break} in a C @code{^switch^switch^} statement.
9767 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
9768 There are various reasons for this effect:
9772 In a subprogram prologue, a parameter may not yet have been moved to its
9776 A variable may be dead, and its register re-used. This is
9777 probably the most common cause.
9780 As mentioned above, the assignment of a value to a variable may
9784 A variable may be eliminated entirely by value propagation or
9785 other means. In this case, GCC may incorrectly generate debugging
9786 information for the variable
9790 In general, when an unexpected value appears for a local variable or parameter
9791 you should first ascertain if that value was actually computed by
9792 your program, as opposed to being incorrectly reported by the debugger.
9794 array elements in an object designated by an access value
9795 are generally less of a problem, once you have ascertained that the access
9797 Typically, this means checking variables in the preceding code and in the
9798 calling subprogram to verify that the value observed is explainable from other
9799 values (one must apply the procedure recursively to those
9800 other values); or re-running the code and stopping a little earlier
9801 (perhaps before the call) and stepping to better see how the variable obtained
9802 the value in question; or continuing to step @emph{from} the point of the
9803 strange value to see if code motion had simply moved the variable's
9808 In light of such anomalies, a recommended technique is to use @option{-O0}
9809 early in the software development cycle, when extensive debugging capabilities
9810 are most needed, and then move to @option{-O1} and later @option{-O2} as
9811 the debugger becomes less critical.
9812 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
9813 a release management issue.
9815 Note that if you use @option{-g} you can then use the @command{strip} program
9816 on the resulting executable,
9817 which removes both debugging information and global symbols.
9820 @node Inlining of Subprograms
9821 @subsection Inlining of Subprograms
9824 A call to a subprogram in the current unit is inlined if all the
9825 following conditions are met:
9829 The optimization level is at least @option{-O1}.
9832 The called subprogram is suitable for inlining: It must be small enough
9833 and not contain something that @command{gcc} cannot support in inlined
9837 @cindex pragma Inline
9839 Either @code{pragma Inline} applies to the subprogram, or it is local
9840 to the unit and called once from within it, or it is small and automatic
9841 inlining (optimization level @option{-O3}) is specified.
9845 Calls to subprograms in @code{with}'ed units are normally not inlined.
9846 To achieve actual inlining (that is, replacement of the call by the code
9847 in the body of the subprogram), the following conditions must all be true.
9851 The optimization level is at least @option{-O1}.
9854 The called subprogram is suitable for inlining: It must be small enough
9855 and not contain something that @command{gcc} cannot support in inlined
9859 The call appears in a body (not in a package spec).
9862 There is a @code{pragma Inline} for the subprogram.
9865 @cindex @option{-gnatn} (@command{gcc})
9866 The @option{^-gnatn^/INLINE^} switch
9867 is used in the @command{gcc} command line
9870 Even if all these conditions are met, it may not be possible for
9871 the compiler to inline the call, due to the length of the body,
9872 or features in the body that make it impossible for the compiler
9875 Note that specifying the @option{-gnatn} switch causes additional
9876 compilation dependencies. Consider the following:
9878 @smallexample @c ada
9898 With the default behavior (no @option{-gnatn} switch specified), the
9899 compilation of the @code{Main} procedure depends only on its own source,
9900 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
9901 means that editing the body of @code{R} does not require recompiling
9904 On the other hand, the call @code{R.Q} is not inlined under these
9905 circumstances. If the @option{-gnatn} switch is present when @code{Main}
9906 is compiled, the call will be inlined if the body of @code{Q} is small
9907 enough, but now @code{Main} depends on the body of @code{R} in
9908 @file{r.adb} as well as on the spec. This means that if this body is edited,
9909 the main program must be recompiled. Note that this extra dependency
9910 occurs whether or not the call is in fact inlined by @command{gcc}.
9912 The use of front end inlining with @option{-gnatN} generates similar
9913 additional dependencies.
9915 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
9916 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
9917 can be used to prevent
9918 all inlining. This switch overrides all other conditions and ensures
9919 that no inlining occurs. The extra dependences resulting from
9920 @option{-gnatn} will still be active, even if
9921 this switch is used to suppress the resulting inlining actions.
9923 @cindex @option{-fno-inline-functions} (@command{gcc})
9924 Note: The @option{-fno-inline-functions} switch can be used to prevent
9925 automatic inlining of small subprograms if @option{-O3} is used.
9927 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
9928 Note: The @option{-fno-inline-functions-called-once} switch
9929 can be used to prevent inlining of subprograms local to the unit
9930 and called once from within it if @option{-O1} is used.
9932 Note regarding the use of @option{-O3}: There is no difference in inlining
9933 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
9934 pragma @code{Inline} assuming the use of @option{-gnatn}
9935 or @option{-gnatN} (the switches that activate inlining). If you have used
9936 pragma @code{Inline} in appropriate cases, then it is usually much better
9937 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
9938 in this case only has the effect of inlining subprograms you did not
9939 think should be inlined. We often find that the use of @option{-O3} slows
9940 down code by performing excessive inlining, leading to increased instruction
9941 cache pressure from the increased code size. So the bottom line here is
9942 that you should not automatically assume that @option{-O3} is better than
9943 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
9944 it actually improves performance.
9946 @node Other Optimization Switches
9947 @subsection Other Optimization Switches
9948 @cindex Optimization Switches
9950 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
9951 @command{gcc} optimization switches are potentially usable. These switches
9952 have not been extensively tested with GNAT but can generally be expected
9953 to work. Examples of switches in this category are
9954 @option{-funroll-loops} and
9955 the various target-specific @option{-m} options (in particular, it has been
9956 observed that @option{-march=pentium4} can significantly improve performance
9957 on appropriate machines). For full details of these switches, see
9958 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
9959 the GNU Compiler Collection (GCC)}.
9961 @node Optimization and Strict Aliasing
9962 @subsection Optimization and Strict Aliasing
9964 @cindex Strict Aliasing
9965 @cindex No_Strict_Aliasing
9968 The strong typing capabilities of Ada allow an optimizer to generate
9969 efficient code in situations where other languages would be forced to
9970 make worst case assumptions preventing such optimizations. Consider
9971 the following example:
9973 @smallexample @c ada
9976 type Int1 is new Integer;
9977 type Int2 is new Integer;
9978 type Int1A is access Int1;
9979 type Int2A is access Int2;
9986 for J in Data'Range loop
9987 if Data (J) = Int1V.all then
9988 Int2V.all := Int2V.all + 1;
9997 In this example, since the variable @code{Int1V} can only access objects
9998 of type @code{Int1}, and @code{Int2V} can only access objects of type
9999 @code{Int2}, there is no possibility that the assignment to
10000 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10001 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10002 for all iterations of the loop and avoid the extra memory reference
10003 required to dereference it each time through the loop.
10005 This kind of optimization, called strict aliasing analysis, is
10006 triggered by specifying an optimization level of @option{-O2} or
10007 higher and allows @code{GNAT} to generate more efficient code
10008 when access values are involved.
10010 However, although this optimization is always correct in terms of
10011 the formal semantics of the Ada Reference Manual, difficulties can
10012 arise if features like @code{Unchecked_Conversion} are used to break
10013 the typing system. Consider the following complete program example:
10015 @smallexample @c ada
10018 type int1 is new integer;
10019 type int2 is new integer;
10020 type a1 is access int1;
10021 type a2 is access int2;
10026 function to_a2 (Input : a1) return a2;
10029 with Unchecked_Conversion;
10031 function to_a2 (Input : a1) return a2 is
10033 new Unchecked_Conversion (a1, a2);
10035 return to_a2u (Input);
10041 with Text_IO; use Text_IO;
10043 v1 : a1 := new int1;
10044 v2 : a2 := to_a2 (v1);
10048 put_line (int1'image (v1.all));
10054 This program prints out 0 in @option{-O0} or @option{-O1}
10055 mode, but it prints out 1 in @option{-O2} mode. That's
10056 because in strict aliasing mode, the compiler can and
10057 does assume that the assignment to @code{v2.all} could not
10058 affect the value of @code{v1.all}, since different types
10061 This behavior is not a case of non-conformance with the standard, since
10062 the Ada RM specifies that an unchecked conversion where the resulting
10063 bit pattern is not a correct value of the target type can result in an
10064 abnormal value and attempting to reference an abnormal value makes the
10065 execution of a program erroneous. That's the case here since the result
10066 does not point to an object of type @code{int2}. This means that the
10067 effect is entirely unpredictable.
10069 However, although that explanation may satisfy a language
10070 lawyer, in practice an applications programmer expects an
10071 unchecked conversion involving pointers to create true
10072 aliases and the behavior of printing 1 seems plain wrong.
10073 In this case, the strict aliasing optimization is unwelcome.
10075 Indeed the compiler recognizes this possibility, and the
10076 unchecked conversion generates a warning:
10079 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10080 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10081 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
10085 Unfortunately the problem is recognized when compiling the body of
10086 package @code{p2}, but the actual "bad" code is generated while
10087 compiling the body of @code{m} and this latter compilation does not see
10088 the suspicious @code{Unchecked_Conversion}.
10090 As implied by the warning message, there are approaches you can use to
10091 avoid the unwanted strict aliasing optimization in a case like this.
10093 One possibility is to simply avoid the use of @option{-O2}, but
10094 that is a bit drastic, since it throws away a number of useful
10095 optimizations that do not involve strict aliasing assumptions.
10097 A less drastic approach is to compile the program using the
10098 option @option{-fno-strict-aliasing}. Actually it is only the
10099 unit containing the dereferencing of the suspicious pointer
10100 that needs to be compiled. So in this case, if we compile
10101 unit @code{m} with this switch, then we get the expected
10102 value of zero printed. Analyzing which units might need
10103 the switch can be painful, so a more reasonable approach
10104 is to compile the entire program with options @option{-O2}
10105 and @option{-fno-strict-aliasing}. If the performance is
10106 satisfactory with this combination of options, then the
10107 advantage is that the entire issue of possible "wrong"
10108 optimization due to strict aliasing is avoided.
10110 To avoid the use of compiler switches, the configuration
10111 pragma @code{No_Strict_Aliasing} with no parameters may be
10112 used to specify that for all access types, the strict
10113 aliasing optimization should be suppressed.
10115 However, these approaches are still overkill, in that they causes
10116 all manipulations of all access values to be deoptimized. A more
10117 refined approach is to concentrate attention on the specific
10118 access type identified as problematic.
10120 First, if a careful analysis of uses of the pointer shows
10121 that there are no possible problematic references, then
10122 the warning can be suppressed by bracketing the
10123 instantiation of @code{Unchecked_Conversion} to turn
10126 @smallexample @c ada
10127 pragma Warnings (Off);
10129 new Unchecked_Conversion (a1, a2);
10130 pragma Warnings (On);
10134 Of course that approach is not appropriate for this particular
10135 example, since indeed there is a problematic reference. In this
10136 case we can take one of two other approaches.
10138 The first possibility is to move the instantiation of unchecked
10139 conversion to the unit in which the type is declared. In
10140 this example, we would move the instantiation of
10141 @code{Unchecked_Conversion} from the body of package
10142 @code{p2} to the spec of package @code{p1}. Now the
10143 warning disappears. That's because any use of the
10144 access type knows there is a suspicious unchecked
10145 conversion, and the strict aliasing optimization
10146 is automatically suppressed for the type.
10148 If it is not practical to move the unchecked conversion to the same unit
10149 in which the destination access type is declared (perhaps because the
10150 source type is not visible in that unit), you may use pragma
10151 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10152 same declarative sequence as the declaration of the access type:
10154 @smallexample @c ada
10155 type a2 is access int2;
10156 pragma No_Strict_Aliasing (a2);
10160 Here again, the compiler now knows that the strict aliasing optimization
10161 should be suppressed for any reference to type @code{a2} and the
10162 expected behavior is obtained.
10164 Finally, note that although the compiler can generate warnings for
10165 simple cases of unchecked conversions, there are tricker and more
10166 indirect ways of creating type incorrect aliases which the compiler
10167 cannot detect. Examples are the use of address overlays and unchecked
10168 conversions involving composite types containing access types as
10169 components. In such cases, no warnings are generated, but there can
10170 still be aliasing problems. One safe coding practice is to forbid the
10171 use of address clauses for type overlaying, and to allow unchecked
10172 conversion only for primitive types. This is not really a significant
10173 restriction since any possible desired effect can be achieved by
10174 unchecked conversion of access values.
10177 @node Coverage Analysis
10178 @subsection Coverage Analysis
10181 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10182 the user to determine the distribution of execution time across a program,
10183 @pxref{Profiling} for details of usage.
10187 @node Text_IO Suggestions
10188 @section @code{Text_IO} Suggestions
10189 @cindex @code{Text_IO} and performance
10192 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10193 the requirement of maintaining page and line counts. If performance
10194 is critical, a recommendation is to use @code{Stream_IO} instead of
10195 @code{Text_IO} for volume output, since this package has less overhead.
10197 If @code{Text_IO} must be used, note that by default output to the standard
10198 output and standard error files is unbuffered (this provides better
10199 behavior when output statements are used for debugging, or if the
10200 progress of a program is observed by tracking the output, e.g. by
10201 using the Unix @command{tail -f} command to watch redirected output.
10203 If you are generating large volumes of output with @code{Text_IO} and
10204 performance is an important factor, use a designated file instead
10205 of the standard output file, or change the standard output file to
10206 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10210 @node Reducing Size of Ada Executables with gnatelim
10211 @section Reducing Size of Ada Executables with @code{gnatelim}
10215 This section describes @command{gnatelim}, a tool which detects unused
10216 subprograms and helps the compiler to create a smaller executable for your
10221 * Running gnatelim::
10222 * Correcting the List of Eliminate Pragmas::
10223 * Making Your Executables Smaller::
10224 * Summary of the gnatelim Usage Cycle::
10227 @node About gnatelim
10228 @subsection About @code{gnatelim}
10231 When a program shares a set of Ada
10232 packages with other programs, it may happen that this program uses
10233 only a fraction of the subprograms defined in these packages. The code
10234 created for these unused subprograms increases the size of the executable.
10236 @code{gnatelim} tracks unused subprograms in an Ada program and
10237 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10238 subprograms that are declared but never called. By placing the list of
10239 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10240 recompiling your program, you may decrease the size of its executable,
10241 because the compiler will not generate the code for 'eliminated' subprograms.
10242 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10243 information about this pragma.
10245 @code{gnatelim} needs as its input data the name of the main subprogram
10246 and a bind file for a main subprogram.
10248 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
10249 the main subprogram. @code{gnatelim} can work with both Ada and C
10250 bind files; when both are present, it uses the Ada bind file.
10251 The following commands will build the program and create the bind file:
10254 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10255 $ gnatbind main_prog
10258 Note that @code{gnatelim} needs neither object nor ALI files.
10260 @node Running gnatelim
10261 @subsection Running @code{gnatelim}
10264 @code{gnatelim} has the following command-line interface:
10267 $ gnatelim [options] name
10271 @code{name} should be a name of a source file that contains the main subprogram
10272 of a program (partition).
10274 @code{gnatelim} has the following switches:
10279 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10280 Quiet mode: by default @code{gnatelim} outputs to the standard error
10281 stream the number of program units left to be processed. This option turns
10284 @item ^-v^/VERBOSE^
10285 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10286 Verbose mode: @code{gnatelim} version information is printed as Ada
10287 comments to the standard output stream. Also, in addition to the number of
10288 program units left @code{gnatelim} will output the name of the current unit
10292 @cindex @option{^-a^/ALL^} (@command{gnatelim})
10293 Also look for subprograms from the GNAT run time that can be eliminated. Note
10294 that when @file{gnat.adc} is produced using this switch, the entire program
10295 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
10297 @item ^-I^/INCLUDE_DIRS=^@var{dir}
10298 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
10299 When looking for source files also look in directory @var{dir}. Specifying
10300 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
10301 sources in the current directory.
10303 @item ^-b^/BIND_FILE=^@var{bind_file}
10304 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
10305 Specifies @var{bind_file} as the bind file to process. If not set, the name
10306 of the bind file is computed from the full expanded Ada name
10307 of a main subprogram.
10309 @item ^-C^/CONFIG_FILE=^@var{config_file}
10310 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
10311 Specifies a file @var{config_file} that contains configuration pragmas. The
10312 file must be specified with full path.
10314 @item ^--GCC^/COMPILER^=@var{compiler_name}
10315 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
10316 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
10317 available on the path.
10319 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
10320 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
10321 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
10322 available on the path.
10326 @code{gnatelim} sends its output to the standard output stream, and all the
10327 tracing and debug information is sent to the standard error stream.
10328 In order to produce a proper GNAT configuration file
10329 @file{gnat.adc}, redirection must be used:
10333 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
10336 $ gnatelim main_prog.adb > gnat.adc
10345 $ gnatelim main_prog.adb >> gnat.adc
10349 in order to append the @code{gnatelim} output to the existing contents of
10353 @node Correcting the List of Eliminate Pragmas
10354 @subsection Correcting the List of Eliminate Pragmas
10357 In some rare cases @code{gnatelim} may try to eliminate
10358 subprograms that are actually called in the program. In this case, the
10359 compiler will generate an error message of the form:
10362 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
10366 You will need to manually remove the wrong @code{Eliminate} pragmas from
10367 the @file{gnat.adc} file. You should recompile your program
10368 from scratch after that, because you need a consistent @file{gnat.adc} file
10369 during the entire compilation.
10371 @node Making Your Executables Smaller
10372 @subsection Making Your Executables Smaller
10375 In order to get a smaller executable for your program you now have to
10376 recompile the program completely with the new @file{gnat.adc} file
10377 created by @code{gnatelim} in your current directory:
10380 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10384 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10385 recompile everything
10386 with the set of pragmas @code{Eliminate} that you have obtained with
10387 @command{gnatelim}).
10389 Be aware that the set of @code{Eliminate} pragmas is specific to each
10390 program. It is not recommended to merge sets of @code{Eliminate}
10391 pragmas created for different programs in one @file{gnat.adc} file.
10393 @node Summary of the gnatelim Usage Cycle
10394 @subsection Summary of the gnatelim Usage Cycle
10397 Here is a quick summary of the steps to be taken in order to reduce
10398 the size of your executables with @code{gnatelim}. You may use
10399 other GNAT options to control the optimization level,
10400 to produce the debugging information, to set search path, etc.
10404 Produce a bind file
10407 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10408 $ gnatbind main_prog
10412 Generate a list of @code{Eliminate} pragmas
10415 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10418 $ gnatelim main_prog >[>] gnat.adc
10423 Recompile the application
10426 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10431 @node Reducing Size of Executables with unused subprogram/data elimination
10432 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10433 @findex unused subprogram/data elimination
10436 This section describes how you can eliminate unused subprograms and data from
10437 your executable just by setting options at compilation time.
10440 * About unused subprogram/data elimination::
10441 * Compilation options::
10442 * Example of unused subprogram/data elimination::
10445 @node About unused subprogram/data elimination
10446 @subsection About unused subprogram/data elimination
10449 By default, an executable contains all code and data of its composing objects
10450 (directly linked or coming from statically linked libraries), even data or code
10451 never used by this executable.
10453 This feature will allow you to eliminate such unused code from your
10454 executable, making it smaller (in disk and in memory).
10456 This functionality is available on all Linux platforms except for the IA-64
10457 architecture and on all cross platforms using the ELF binary file format.
10458 In both cases GNU binutils version 2.16 or later are required to enable it.
10460 @node Compilation options
10461 @subsection Compilation options
10464 The operation of eliminating the unused code and data from the final executable
10465 is directly performed by the linker.
10467 In order to do this, it has to work with objects compiled with the
10469 @option{-ffunction-sections} @option{-fdata-sections}.
10470 @cindex @option{-ffunction-sections} (@command{gcc})
10471 @cindex @option{-fdata-sections} (@command{gcc})
10472 These options are usable with C and Ada files.
10473 They will place respectively each
10474 function or data in a separate section in the resulting object file.
10476 Once the objects and static libraries are created with these options, the
10477 linker can perform the dead code elimination. You can do this by setting
10478 the @option{-Wl,--gc-sections} option to gcc command or in the
10479 @option{-largs} section of @command{gnatmake}. This will perform a
10480 garbage collection of code and data never referenced.
10482 If the linker performs a partial link (@option{-r} ld linker option), then you
10483 will need to provide one or several entry point using the
10484 @option{-e} / @option{--entry} ld option.
10486 Note that objects compiled without the @option{-ffunction-sections} and
10487 @option{-fdata-sections} options can still be linked with the executable.
10488 However, no dead code elimination will be performed on those objects (they will
10491 The GNAT static library is now compiled with -ffunction-sections and
10492 -fdata-sections on some platforms. This allows you to eliminate the unused code
10493 and data of the GNAT library from your executable.
10495 @node Example of unused subprogram/data elimination
10496 @subsection Example of unused subprogram/data elimination
10499 Here is a simple example:
10501 @smallexample @c ada
10510 Used_Data : Integer;
10511 Unused_Data : Integer;
10513 procedure Used (Data : Integer);
10514 procedure Unused (Data : Integer);
10517 package body Aux is
10518 procedure Used (Data : Integer) is
10523 procedure Unused (Data : Integer) is
10525 Unused_Data := Data;
10531 @code{Unused} and @code{Unused_Data} are never referenced in this code
10532 excerpt, and hence they may be safely removed from the final executable.
10537 $ nm test | grep used
10538 020015f0 T aux__unused
10539 02005d88 B aux__unused_data
10540 020015cc T aux__used
10541 02005d84 B aux__used_data
10543 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10544 -largs -Wl,--gc-sections
10546 $ nm test | grep used
10547 02005350 T aux__used
10548 0201ffe0 B aux__used_data
10552 It can be observed that the procedure @code{Unused} and the object
10553 @code{Unused_Data} are removed by the linker when using the
10554 appropriate options.
10556 @c ********************************
10557 @node Renaming Files Using gnatchop
10558 @chapter Renaming Files Using @code{gnatchop}
10562 This chapter discusses how to handle files with multiple units by using
10563 the @code{gnatchop} utility. This utility is also useful in renaming
10564 files to meet the standard GNAT default file naming conventions.
10567 * Handling Files with Multiple Units::
10568 * Operating gnatchop in Compilation Mode::
10569 * Command Line for gnatchop::
10570 * Switches for gnatchop::
10571 * Examples of gnatchop Usage::
10574 @node Handling Files with Multiple Units
10575 @section Handling Files with Multiple Units
10578 The basic compilation model of GNAT requires that a file submitted to the
10579 compiler have only one unit and there be a strict correspondence
10580 between the file name and the unit name.
10582 The @code{gnatchop} utility allows both of these rules to be relaxed,
10583 allowing GNAT to process files which contain multiple compilation units
10584 and files with arbitrary file names. @code{gnatchop}
10585 reads the specified file and generates one or more output files,
10586 containing one unit per file. The unit and the file name correspond,
10587 as required by GNAT.
10589 If you want to permanently restructure a set of ``foreign'' files so that
10590 they match the GNAT rules, and do the remaining development using the
10591 GNAT structure, you can simply use @command{gnatchop} once, generate the
10592 new set of files and work with them from that point on.
10594 Alternatively, if you want to keep your files in the ``foreign'' format,
10595 perhaps to maintain compatibility with some other Ada compilation
10596 system, you can set up a procedure where you use @command{gnatchop} each
10597 time you compile, regarding the source files that it writes as temporary
10598 files that you throw away.
10600 @node Operating gnatchop in Compilation Mode
10601 @section Operating gnatchop in Compilation Mode
10604 The basic function of @code{gnatchop} is to take a file with multiple units
10605 and split it into separate files. The boundary between files is reasonably
10606 clear, except for the issue of comments and pragmas. In default mode, the
10607 rule is that any pragmas between units belong to the previous unit, except
10608 that configuration pragmas always belong to the following unit. Any comments
10609 belong to the following unit. These rules
10610 almost always result in the right choice of
10611 the split point without needing to mark it explicitly and most users will
10612 find this default to be what they want. In this default mode it is incorrect to
10613 submit a file containing only configuration pragmas, or one that ends in
10614 configuration pragmas, to @code{gnatchop}.
10616 However, using a special option to activate ``compilation mode'',
10618 can perform another function, which is to provide exactly the semantics
10619 required by the RM for handling of configuration pragmas in a compilation.
10620 In the absence of configuration pragmas (at the main file level), this
10621 option has no effect, but it causes such configuration pragmas to be handled
10622 in a quite different manner.
10624 First, in compilation mode, if @code{gnatchop} is given a file that consists of
10625 only configuration pragmas, then this file is appended to the
10626 @file{gnat.adc} file in the current directory. This behavior provides
10627 the required behavior described in the RM for the actions to be taken
10628 on submitting such a file to the compiler, namely that these pragmas
10629 should apply to all subsequent compilations in the same compilation
10630 environment. Using GNAT, the current directory, possibly containing a
10631 @file{gnat.adc} file is the representation
10632 of a compilation environment. For more information on the
10633 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
10635 Second, in compilation mode, if @code{gnatchop}
10636 is given a file that starts with
10637 configuration pragmas, and contains one or more units, then these
10638 configuration pragmas are prepended to each of the chopped files. This
10639 behavior provides the required behavior described in the RM for the
10640 actions to be taken on compiling such a file, namely that the pragmas
10641 apply to all units in the compilation, but not to subsequently compiled
10644 Finally, if configuration pragmas appear between units, they are appended
10645 to the previous unit. This results in the previous unit being illegal,
10646 since the compiler does not accept configuration pragmas that follow
10647 a unit. This provides the required RM behavior that forbids configuration
10648 pragmas other than those preceding the first compilation unit of a
10651 For most purposes, @code{gnatchop} will be used in default mode. The
10652 compilation mode described above is used only if you need exactly
10653 accurate behavior with respect to compilations, and you have files
10654 that contain multiple units and configuration pragmas. In this
10655 circumstance the use of @code{gnatchop} with the compilation mode
10656 switch provides the required behavior, and is for example the mode
10657 in which GNAT processes the ACVC tests.
10659 @node Command Line for gnatchop
10660 @section Command Line for @code{gnatchop}
10663 The @code{gnatchop} command has the form:
10666 $ gnatchop switches @var{file name} [@var{file name} @var{file name} @dots{}]
10671 The only required argument is the file name of the file to be chopped.
10672 There are no restrictions on the form of this file name. The file itself
10673 contains one or more Ada units, in normal GNAT format, concatenated
10674 together. As shown, more than one file may be presented to be chopped.
10676 When run in default mode, @code{gnatchop} generates one output file in
10677 the current directory for each unit in each of the files.
10679 @var{directory}, if specified, gives the name of the directory to which
10680 the output files will be written. If it is not specified, all files are
10681 written to the current directory.
10683 For example, given a
10684 file called @file{hellofiles} containing
10686 @smallexample @c ada
10691 with Text_IO; use Text_IO;
10694 Put_Line ("Hello");
10704 $ gnatchop ^hellofiles^HELLOFILES.^
10708 generates two files in the current directory, one called
10709 @file{hello.ads} containing the single line that is the procedure spec,
10710 and the other called @file{hello.adb} containing the remaining text. The
10711 original file is not affected. The generated files can be compiled in
10715 When gnatchop is invoked on a file that is empty or that contains only empty
10716 lines and/or comments, gnatchop will not fail, but will not produce any
10719 For example, given a
10720 file called @file{toto.txt} containing
10722 @smallexample @c ada
10734 $ gnatchop ^toto.txt^TOT.TXT^
10738 will not produce any new file and will result in the following warnings:
10741 toto.txt:1:01: warning: empty file, contains no compilation units
10742 no compilation units found
10743 no source files written
10746 @node Switches for gnatchop
10747 @section Switches for @code{gnatchop}
10750 @command{gnatchop} recognizes the following switches:
10756 @cindex @option{--version} @command{gnatchop}
10757 Display Copyright and version, then exit disregarding all other options.
10760 @cindex @option{--help} @command{gnatchop}
10761 If @option{--version} was not used, display usage, then exit disregarding
10764 @item ^-c^/COMPILATION^
10765 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
10766 Causes @code{gnatchop} to operate in compilation mode, in which
10767 configuration pragmas are handled according to strict RM rules. See
10768 previous section for a full description of this mode.
10771 @item -gnat@var{xxx}
10772 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
10773 used to parse the given file. Not all @var{xxx} options make sense,
10774 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
10775 process a source file that uses Latin-2 coding for identifiers.
10779 Causes @code{gnatchop} to generate a brief help summary to the standard
10780 output file showing usage information.
10782 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
10783 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
10784 Limit generated file names to the specified number @code{mm}
10786 This is useful if the
10787 resulting set of files is required to be interoperable with systems
10788 which limit the length of file names.
10790 If no value is given, or
10791 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
10792 a default of 39, suitable for OpenVMS Alpha
10793 Systems, is assumed
10796 No space is allowed between the @option{-k} and the numeric value. The numeric
10797 value may be omitted in which case a default of @option{-k8},
10799 with DOS-like file systems, is used. If no @option{-k} switch
10801 there is no limit on the length of file names.
10804 @item ^-p^/PRESERVE^
10805 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
10806 Causes the file ^modification^creation^ time stamp of the input file to be
10807 preserved and used for the time stamp of the output file(s). This may be
10808 useful for preserving coherency of time stamps in an environment where
10809 @code{gnatchop} is used as part of a standard build process.
10812 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
10813 Causes output of informational messages indicating the set of generated
10814 files to be suppressed. Warnings and error messages are unaffected.
10816 @item ^-r^/REFERENCE^
10817 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
10818 @findex Source_Reference
10819 Generate @code{Source_Reference} pragmas. Use this switch if the output
10820 files are regarded as temporary and development is to be done in terms
10821 of the original unchopped file. This switch causes
10822 @code{Source_Reference} pragmas to be inserted into each of the
10823 generated files to refers back to the original file name and line number.
10824 The result is that all error messages refer back to the original
10826 In addition, the debugging information placed into the object file (when
10827 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
10829 also refers back to this original file so that tools like profilers and
10830 debuggers will give information in terms of the original unchopped file.
10832 If the original file to be chopped itself contains
10833 a @code{Source_Reference}
10834 pragma referencing a third file, then gnatchop respects
10835 this pragma, and the generated @code{Source_Reference} pragmas
10836 in the chopped file refer to the original file, with appropriate
10837 line numbers. This is particularly useful when @code{gnatchop}
10838 is used in conjunction with @code{gnatprep} to compile files that
10839 contain preprocessing statements and multiple units.
10841 @item ^-v^/VERBOSE^
10842 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
10843 Causes @code{gnatchop} to operate in verbose mode. The version
10844 number and copyright notice are output, as well as exact copies of
10845 the gnat1 commands spawned to obtain the chop control information.
10847 @item ^-w^/OVERWRITE^
10848 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
10849 Overwrite existing file names. Normally @code{gnatchop} regards it as a
10850 fatal error if there is already a file with the same name as a
10851 file it would otherwise output, in other words if the files to be
10852 chopped contain duplicated units. This switch bypasses this
10853 check, and causes all but the last instance of such duplicated
10854 units to be skipped.
10857 @item --GCC=@var{xxxx}
10858 @cindex @option{--GCC=} (@code{gnatchop})
10859 Specify the path of the GNAT parser to be used. When this switch is used,
10860 no attempt is made to add the prefix to the GNAT parser executable.
10864 @node Examples of gnatchop Usage
10865 @section Examples of @code{gnatchop} Usage
10869 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
10872 @item gnatchop -w hello_s.ada prerelease/files
10875 Chops the source file @file{hello_s.ada}. The output files will be
10876 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
10878 files with matching names in that directory (no files in the current
10879 directory are modified).
10881 @item gnatchop ^archive^ARCHIVE.^
10882 Chops the source file @file{^archive^ARCHIVE.^}
10883 into the current directory. One
10884 useful application of @code{gnatchop} is in sending sets of sources
10885 around, for example in email messages. The required sources are simply
10886 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
10888 @command{gnatchop} is used at the other end to reconstitute the original
10891 @item gnatchop file1 file2 file3 direc
10892 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
10893 the resulting files in the directory @file{direc}. Note that if any units
10894 occur more than once anywhere within this set of files, an error message
10895 is generated, and no files are written. To override this check, use the
10896 @option{^-w^/OVERWRITE^} switch,
10897 in which case the last occurrence in the last file will
10898 be the one that is output, and earlier duplicate occurrences for a given
10899 unit will be skipped.
10902 @node Configuration Pragmas
10903 @chapter Configuration Pragmas
10904 @cindex Configuration pragmas
10905 @cindex Pragmas, configuration
10908 Configuration pragmas include those pragmas described as
10909 such in the Ada Reference Manual, as well as
10910 implementation-dependent pragmas that are configuration pragmas.
10911 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
10912 for details on these additional GNAT-specific configuration pragmas.
10913 Most notably, the pragma @code{Source_File_Name}, which allows
10914 specifying non-default names for source files, is a configuration
10915 pragma. The following is a complete list of configuration pragmas
10916 recognized by GNAT:
10928 Compile_Time_Warning
10930 Component_Alignment
10937 External_Name_Casing
10940 Float_Representation
10953 Priority_Specific_Dispatching
10956 Propagate_Exceptions
10959 Restricted_Run_Time
10961 Restrictions_Warnings
10964 Source_File_Name_Project
10967 Suppress_Exception_Locations
10968 Task_Dispatching_Policy
10974 Wide_Character_Encoding
10979 * Handling of Configuration Pragmas::
10980 * The Configuration Pragmas Files::
10983 @node Handling of Configuration Pragmas
10984 @section Handling of Configuration Pragmas
10986 Configuration pragmas may either appear at the start of a compilation
10987 unit, in which case they apply only to that unit, or they may apply to
10988 all compilations performed in a given compilation environment.
10990 GNAT also provides the @code{gnatchop} utility to provide an automatic
10991 way to handle configuration pragmas following the semantics for
10992 compilations (that is, files with multiple units), described in the RM.
10993 See @ref{Operating gnatchop in Compilation Mode} for details.
10994 However, for most purposes, it will be more convenient to edit the
10995 @file{gnat.adc} file that contains configuration pragmas directly,
10996 as described in the following section.
10998 @node The Configuration Pragmas Files
10999 @section The Configuration Pragmas Files
11000 @cindex @file{gnat.adc}
11003 In GNAT a compilation environment is defined by the current
11004 directory at the time that a compile command is given. This current
11005 directory is searched for a file whose name is @file{gnat.adc}. If
11006 this file is present, it is expected to contain one or more
11007 configuration pragmas that will be applied to the current compilation.
11008 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11011 Configuration pragmas may be entered into the @file{gnat.adc} file
11012 either by running @code{gnatchop} on a source file that consists only of
11013 configuration pragmas, or more conveniently by
11014 direct editing of the @file{gnat.adc} file, which is a standard format
11017 In addition to @file{gnat.adc}, additional files containing configuration
11018 pragmas may be applied to the current compilation using the switch
11019 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11020 contains only configuration pragmas. These configuration pragmas are
11021 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11022 is present and switch @option{-gnatA} is not used).
11024 It is allowed to specify several switches @option{-gnatec}, all of which
11025 will be taken into account.
11027 If you are using project file, a separate mechanism is provided using
11028 project attributes, see @ref{Specifying Configuration Pragmas} for more
11032 Of special interest to GNAT OpenVMS Alpha is the following
11033 configuration pragma:
11035 @smallexample @c ada
11037 pragma Extend_System (Aux_DEC);
11042 In the presence of this pragma, GNAT adds to the definition of the
11043 predefined package SYSTEM all the additional types and subprograms that are
11044 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11047 @node Handling Arbitrary File Naming Conventions Using gnatname
11048 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11049 @cindex Arbitrary File Naming Conventions
11052 * Arbitrary File Naming Conventions::
11053 * Running gnatname::
11054 * Switches for gnatname::
11055 * Examples of gnatname Usage::
11058 @node Arbitrary File Naming Conventions
11059 @section Arbitrary File Naming Conventions
11062 The GNAT compiler must be able to know the source file name of a compilation
11063 unit. When using the standard GNAT default file naming conventions
11064 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11065 does not need additional information.
11068 When the source file names do not follow the standard GNAT default file naming
11069 conventions, the GNAT compiler must be given additional information through
11070 a configuration pragmas file (@pxref{Configuration Pragmas})
11072 When the non-standard file naming conventions are well-defined,
11073 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11074 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11075 if the file naming conventions are irregular or arbitrary, a number
11076 of pragma @code{Source_File_Name} for individual compilation units
11078 To help maintain the correspondence between compilation unit names and
11079 source file names within the compiler,
11080 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11083 @node Running gnatname
11084 @section Running @code{gnatname}
11087 The usual form of the @code{gnatname} command is
11090 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}] \
11091 [--and @var{switches}] @var{naming_pattern} [@var{naming_patterns}]]
11095 All of the arguments are optional. If invoked without any argument,
11096 @code{gnatname} will display its usage.
11099 When used with at least one naming pattern, @code{gnatname} will attempt to
11100 find all the compilation units in files that follow at least one of the
11101 naming patterns. To find these compilation units,
11102 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11106 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11107 Each Naming Pattern is enclosed between double quotes.
11108 A Naming Pattern is a regular expression similar to the wildcard patterns
11109 used in file names by the Unix shells or the DOS prompt.
11112 @code{gnatname} may be called with several sections of directories/patterns.
11113 Sections are separated by switch @code{--and}. In each section, there must be
11114 at least one pattern. If no directory is specified in a section, the current
11115 directory (or the project directory is @code{-P} is used) is implied.
11116 The options other that the directory switches and the patterns apply globally
11117 even if they are in different sections.
11120 Examples of Naming Patterns are
11129 For a more complete description of the syntax of Naming Patterns,
11130 see the second kind of regular expressions described in @file{g-regexp.ads}
11131 (the ``Glob'' regular expressions).
11134 When invoked with no switch @code{-P}, @code{gnatname} will create a
11135 configuration pragmas file @file{gnat.adc} in the current working directory,
11136 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11139 @node Switches for gnatname
11140 @section Switches for @code{gnatname}
11143 Switches for @code{gnatname} must precede any specified Naming Pattern.
11146 You may specify any of the following switches to @code{gnatname}:
11152 @cindex @option{--version} @command{gnatname}
11153 Display Copyright and version, then exit disregarding all other options.
11156 @cindex @option{--help} @command{gnatname}
11157 If @option{--version} was not used, display usage, then exit disregarding
11161 Start another section of directories/patterns.
11163 @item ^-c^/CONFIG_FILE=^@file{file}
11164 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11165 Create a configuration pragmas file @file{file} (instead of the default
11168 There may be zero, one or more space between @option{-c} and
11171 @file{file} may include directory information. @file{file} must be
11172 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11173 When a switch @option{^-c^/CONFIG_FILE^} is
11174 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11176 @item ^-d^/SOURCE_DIRS=^@file{dir}
11177 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11178 Look for source files in directory @file{dir}. There may be zero, one or more
11179 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11180 When a switch @option{^-d^/SOURCE_DIRS^}
11181 is specified, the current working directory will not be searched for source
11182 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11183 or @option{^-D^/DIR_FILES^} switch.
11184 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11185 If @file{dir} is a relative path, it is relative to the directory of
11186 the configuration pragmas file specified with switch
11187 @option{^-c^/CONFIG_FILE^},
11188 or to the directory of the project file specified with switch
11189 @option{^-P^/PROJECT_FILE^} or,
11190 if neither switch @option{^-c^/CONFIG_FILE^}
11191 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11192 current working directory. The directory
11193 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11195 @item ^-D^/DIRS_FILE=^@file{file}
11196 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11197 Look for source files in all directories listed in text file @file{file}.
11198 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11200 @file{file} must be an existing, readable text file.
11201 Each nonempty line in @file{file} must be a directory.
11202 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11203 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11206 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11207 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11208 Foreign patterns. Using this switch, it is possible to add sources of languages
11209 other than Ada to the list of sources of a project file.
11210 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11213 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11216 will look for Ada units in all files with the @file{.ada} extension,
11217 and will add to the list of file for project @file{prj.gpr} the C files
11218 with extension @file{.^c^C^}.
11221 @cindex @option{^-h^/HELP^} (@code{gnatname})
11222 Output usage (help) information. The output is written to @file{stdout}.
11224 @item ^-P^/PROJECT_FILE=^@file{proj}
11225 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11226 Create or update project file @file{proj}. There may be zero, one or more space
11227 between @option{-P} and @file{proj}. @file{proj} may include directory
11228 information. @file{proj} must be writable.
11229 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11230 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11231 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11233 @item ^-v^/VERBOSE^
11234 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11235 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11236 This includes name of the file written, the name of the directories to search
11237 and, for each file in those directories whose name matches at least one of
11238 the Naming Patterns, an indication of whether the file contains a unit,
11239 and if so the name of the unit.
11241 @item ^-v -v^/VERBOSE /VERBOSE^
11242 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11243 Very Verbose mode. In addition to the output produced in verbose mode,
11244 for each file in the searched directories whose name matches none of
11245 the Naming Patterns, an indication is given that there is no match.
11247 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11248 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11249 Excluded patterns. Using this switch, it is possible to exclude some files
11250 that would match the name patterns. For example,
11252 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11255 will look for Ada units in all files with the @file{.ada} extension,
11256 except those whose names end with @file{_nt.ada}.
11260 @node Examples of gnatname Usage
11261 @section Examples of @code{gnatname} Usage
11265 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11271 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11276 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11277 and be writable. In addition, the directory
11278 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11279 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11282 Note the optional spaces after @option{-c} and @option{-d}.
11287 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11288 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11291 $ gnatname /PROJECT_FILE=[HOME.ME]PROJ
11292 /EXCLUDED_PATTERN=*_nt_body.ada
11293 /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11294 /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11298 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11299 even in conjunction with one or several switches
11300 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11301 are used in this example.
11303 @c *****************************************
11304 @c * G N A T P r o j e c t M a n a g e r *
11305 @c *****************************************
11306 @node GNAT Project Manager
11307 @chapter GNAT Project Manager
11311 * Examples of Project Files::
11312 * Project File Syntax::
11313 * Objects and Sources in Project Files::
11314 * Importing Projects::
11315 * Project Extension::
11316 * Project Hierarchy Extension::
11317 * External References in Project Files::
11318 * Packages in Project Files::
11319 * Variables from Imported Projects::
11321 * Library Projects::
11322 * Stand-alone Library Projects::
11323 * Switches Related to Project Files::
11324 * Tools Supporting Project Files::
11325 * An Extended Example::
11326 * Project File Complete Syntax::
11329 @c ****************
11330 @c * Introduction *
11331 @c ****************
11334 @section Introduction
11337 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
11338 you to manage complex builds involving a number of source files, directories,
11339 and compilation options for different system configurations. In particular,
11340 project files allow you to specify:
11343 The directory or set of directories containing the source files, and/or the
11344 names of the specific source files themselves
11346 The directory in which the compiler's output
11347 (@file{ALI} files, object files, tree files) is to be placed
11349 The directory in which the executable programs is to be placed
11351 ^Switch^Switch^ settings for any of the project-enabled tools
11352 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
11353 @code{gnatfind}); you can apply these settings either globally or to individual
11356 The source files containing the main subprogram(s) to be built
11358 The source programming language(s) (currently Ada and/or C)
11360 Source file naming conventions; you can specify these either globally or for
11361 individual compilation units
11368 @node Project Files
11369 @subsection Project Files
11372 Project files are written in a syntax close to that of Ada, using familiar
11373 notions such as packages, context clauses, declarations, default values,
11374 assignments, and inheritance. Finally, project files can be built
11375 hierarchically from other project files, simplifying complex system
11376 integration and project reuse.
11378 A @dfn{project} is a specific set of values for various compilation properties.
11379 The settings for a given project are described by means of
11380 a @dfn{project file}, which is a text file written in an Ada-like syntax.
11381 Property values in project files are either strings or lists of strings.
11382 Properties that are not explicitly set receive default values. A project
11383 file may interrogate the values of @dfn{external variables} (user-defined
11384 command-line switches or environment variables), and it may specify property
11385 settings conditionally, based on the value of such variables.
11387 In simple cases, a project's source files depend only on other source files
11388 in the same project, or on the predefined libraries. (@emph{Dependence} is
11390 the Ada technical sense; as in one Ada unit @code{with}ing another.) However,
11391 the Project Manager also allows more sophisticated arrangements,
11392 where the source files in one project depend on source files in other
11396 One project can @emph{import} other projects containing needed source files.
11398 You can organize GNAT projects in a hierarchy: a @emph{child} project
11399 can extend a @emph{parent} project, inheriting the parent's source files and
11400 optionally overriding any of them with alternative versions
11404 More generally, the Project Manager lets you structure large development
11405 efforts into hierarchical subsystems, where build decisions are delegated
11406 to the subsystem level, and thus different compilation environments
11407 (^switch^switch^ settings) used for different subsystems.
11409 The Project Manager is invoked through the
11410 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
11411 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
11413 There may be zero, one or more spaces between @option{-P} and
11414 @option{@emph{projectfile}}.
11416 If you want to define (on the command line) an external variable that is
11417 queried by the project file, you must use the
11418 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
11419 The Project Manager parses and interprets the project file, and drives the
11420 invoked tool based on the project settings.
11422 The Project Manager supports a wide range of development strategies,
11423 for systems of all sizes. Here are some typical practices that are
11427 Using a common set of source files, but generating object files in different
11428 directories via different ^switch^switch^ settings
11430 Using a mostly-shared set of source files, but with different versions of
11435 The destination of an executable can be controlled inside a project file
11436 using the @option{^-o^-o^}
11438 In the absence of such a ^switch^switch^ either inside
11439 the project file or on the command line, any executable files generated by
11440 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
11441 in the project file. If no @code{Exec_Dir} is specified, they will be placed
11442 in the object directory of the project.
11444 You can use project files to achieve some of the effects of a source
11445 versioning system (for example, defining separate projects for
11446 the different sets of sources that comprise different releases) but the
11447 Project Manager is independent of any source configuration management tools
11448 that might be used by the developers.
11450 The next section introduces the main features of GNAT's project facility
11451 through a sequence of examples; subsequent sections will present the syntax
11452 and semantics in more detail. A more formal description of the project
11453 facility appears in @ref{Project File Reference,,, gnat_rm, GNAT
11456 @c *****************************
11457 @c * Examples of Project Files *
11458 @c *****************************
11460 @node Examples of Project Files
11461 @section Examples of Project Files
11463 This section illustrates some of the typical uses of project files and
11464 explains their basic structure and behavior.
11467 * Common Sources with Different ^Switches^Switches^ and Directories::
11468 * Using External Variables::
11469 * Importing Other Projects::
11470 * Extending a Project::
11473 @node Common Sources with Different ^Switches^Switches^ and Directories
11474 @subsection Common Sources with Different ^Switches^Switches^ and Directories
11478 * Specifying the Object Directory::
11479 * Specifying the Exec Directory::
11480 * Project File Packages::
11481 * Specifying ^Switch^Switch^ Settings::
11482 * Main Subprograms::
11483 * Executable File Names::
11484 * Source File Naming Conventions::
11485 * Source Language(s)::
11489 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
11490 @file{proc.adb} are in the @file{/common} directory. The file
11491 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
11492 package @code{Pack}. We want to compile these source files under two sets
11493 of ^switches^switches^:
11496 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
11497 and the @option{^-gnata^-gnata^},
11498 @option{^-gnato^-gnato^},
11499 and @option{^-gnatE^-gnatE^} switches to the
11500 compiler; the compiler's output is to appear in @file{/common/debug}
11502 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
11503 to the compiler; the compiler's output is to appear in @file{/common/release}
11507 The GNAT project files shown below, respectively @file{debug.gpr} and
11508 @file{release.gpr} in the @file{/common} directory, achieve these effects.
11521 ^/common/debug^[COMMON.DEBUG]^
11526 ^/common/release^[COMMON.RELEASE]^
11531 Here are the corresponding project files:
11533 @smallexample @c projectfile
11536 for Object_Dir use "debug";
11537 for Main use ("proc");
11540 for ^Default_Switches^Default_Switches^ ("Ada")
11542 for Executable ("proc.adb") use "proc1";
11547 package Compiler is
11548 for ^Default_Switches^Default_Switches^ ("Ada")
11549 use ("-fstack-check",
11552 "^-gnatE^-gnatE^");
11558 @smallexample @c projectfile
11561 for Object_Dir use "release";
11562 for Exec_Dir use ".";
11563 for Main use ("proc");
11565 package Compiler is
11566 for ^Default_Switches^Default_Switches^ ("Ada")
11574 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
11575 insensitive), and analogously the project defined by @file{release.gpr} is
11576 @code{"Release"}. For consistency the file should have the same name as the
11577 project, and the project file's extension should be @code{"gpr"}. These
11578 conventions are not required, but a warning is issued if they are not followed.
11580 If the current directory is @file{^/temp^[TEMP]^}, then the command
11582 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
11586 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
11587 as well as the @code{^proc1^PROC1.EXE^} executable,
11588 using the ^switch^switch^ settings defined in the project file.
11590 Likewise, the command
11592 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
11596 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
11597 and the @code{^proc^PROC.EXE^}
11598 executable in @file{^/common^[COMMON]^},
11599 using the ^switch^switch^ settings from the project file.
11602 @unnumberedsubsubsec Source Files
11605 If a project file does not explicitly specify a set of source directories or
11606 a set of source files, then by default the project's source files are the
11607 Ada source files in the project file directory. Thus @file{pack.ads},
11608 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
11610 @node Specifying the Object Directory
11611 @unnumberedsubsubsec Specifying the Object Directory
11614 Several project properties are modeled by Ada-style @emph{attributes};
11615 a property is defined by supplying the equivalent of an Ada attribute
11616 definition clause in the project file.
11617 A project's object directory is another such a property; the corresponding
11618 attribute is @code{Object_Dir}, and its value is also a string expression,
11619 specified either as absolute or relative. In the later case,
11620 it is relative to the project file directory. Thus the compiler's
11621 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
11622 (for the @code{Debug} project)
11623 and to @file{^/common/release^[COMMON.RELEASE]^}
11624 (for the @code{Release} project).
11625 If @code{Object_Dir} is not specified, then the default is the project file
11628 @node Specifying the Exec Directory
11629 @unnumberedsubsubsec Specifying the Exec Directory
11632 A project's exec directory is another property; the corresponding
11633 attribute is @code{Exec_Dir}, and its value is also a string expression,
11634 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
11635 then the default is the object directory (which may also be the project file
11636 directory if attribute @code{Object_Dir} is not specified). Thus the executable
11637 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
11638 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
11639 and in @file{^/common^[COMMON]^} for the @code{Release} project.
11641 @node Project File Packages
11642 @unnumberedsubsubsec Project File Packages
11645 A GNAT tool that is integrated with the Project Manager is modeled by a
11646 corresponding package in the project file. In the example above,
11647 The @code{Debug} project defines the packages @code{Builder}
11648 (for @command{gnatmake}) and @code{Compiler};
11649 the @code{Release} project defines only the @code{Compiler} package.
11651 The Ada-like package syntax is not to be taken literally. Although packages in
11652 project files bear a surface resemblance to packages in Ada source code, the
11653 notation is simply a way to convey a grouping of properties for a named
11654 entity. Indeed, the package names permitted in project files are restricted
11655 to a predefined set, corresponding to the project-aware tools, and the contents
11656 of packages are limited to a small set of constructs.
11657 The packages in the example above contain attribute definitions.
11659 @node Specifying ^Switch^Switch^ Settings
11660 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
11663 ^Switch^Switch^ settings for a project-aware tool can be specified through
11664 attributes in the package that corresponds to the tool.
11665 The example above illustrates one of the relevant attributes,
11666 @code{^Default_Switches^Default_Switches^}, which is defined in packages
11667 in both project files.
11668 Unlike simple attributes like @code{Source_Dirs},
11669 @code{^Default_Switches^Default_Switches^} is
11670 known as an @emph{associative array}. When you define this attribute, you must
11671 supply an ``index'' (a literal string), and the effect of the attribute
11672 definition is to set the value of the array at the specified index.
11673 For the @code{^Default_Switches^Default_Switches^} attribute,
11674 the index is a programming language (in our case, Ada),
11675 and the value specified (after @code{use}) must be a list
11676 of string expressions.
11678 The attributes permitted in project files are restricted to a predefined set.
11679 Some may appear at project level, others in packages.
11680 For any attribute that is an associative array, the index must always be a
11681 literal string, but the restrictions on this string (e.g., a file name or a
11682 language name) depend on the individual attribute.
11683 Also depending on the attribute, its specified value will need to be either a
11684 string or a string list.
11686 In the @code{Debug} project, we set the switches for two tools,
11687 @command{gnatmake} and the compiler, and thus we include the two corresponding
11688 packages; each package defines the @code{^Default_Switches^Default_Switches^}
11689 attribute with index @code{"Ada"}.
11690 Note that the package corresponding to
11691 @command{gnatmake} is named @code{Builder}. The @code{Release} project is
11692 similar, but only includes the @code{Compiler} package.
11694 In project @code{Debug} above, the ^switches^switches^ starting with
11695 @option{-gnat} that are specified in package @code{Compiler}
11696 could have been placed in package @code{Builder}, since @command{gnatmake}
11697 transmits all such ^switches^switches^ to the compiler.
11699 @node Main Subprograms
11700 @unnumberedsubsubsec Main Subprograms
11703 One of the specifiable properties of a project is a list of files that contain
11704 main subprograms. This property is captured in the @code{Main} attribute,
11705 whose value is a list of strings. If a project defines the @code{Main}
11706 attribute, it is not necessary to identify the main subprogram(s) when
11707 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
11709 @node Executable File Names
11710 @unnumberedsubsubsec Executable File Names
11713 By default, the executable file name corresponding to a main source is
11714 deduced from the main source file name. Through the attributes
11715 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
11716 it is possible to change this default.
11717 In project @code{Debug} above, the executable file name
11718 for main source @file{^proc.adb^PROC.ADB^} is
11719 @file{^proc1^PROC1.EXE^}.
11720 Attribute @code{Executable_Suffix}, when specified, may change the suffix
11721 of the executable files, when no attribute @code{Executable} applies:
11722 its value replace the platform-specific executable suffix.
11723 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
11724 specify a non-default executable file name when several mains are built at once
11725 in a single @command{gnatmake} command.
11727 @node Source File Naming Conventions
11728 @unnumberedsubsubsec Source File Naming Conventions
11731 Since the project files above do not specify any source file naming
11732 conventions, the GNAT defaults are used. The mechanism for defining source
11733 file naming conventions -- a package named @code{Naming} --
11734 is described below (@pxref{Naming Schemes}).
11736 @node Source Language(s)
11737 @unnumberedsubsubsec Source Language(s)
11740 Since the project files do not specify a @code{Languages} attribute, by
11741 default the GNAT tools assume that the language of the project file is Ada.
11742 More generally, a project can comprise source files
11743 in Ada, C, and/or other languages.
11745 @node Using External Variables
11746 @subsection Using External Variables
11749 Instead of supplying different project files for debug and release, we can
11750 define a single project file that queries an external variable (set either
11751 on the command line or via an ^environment variable^logical name^) in order to
11752 conditionally define the appropriate settings. Again, assume that the
11753 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
11754 located in directory @file{^/common^[COMMON]^}. The following project file,
11755 @file{build.gpr}, queries the external variable named @code{STYLE} and
11756 defines an object directory and ^switch^switch^ settings based on whether
11757 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
11758 the default is @code{"deb"}.
11760 @smallexample @c projectfile
11763 for Main use ("proc");
11765 type Style_Type is ("deb", "rel");
11766 Style : Style_Type := external ("STYLE", "deb");
11770 for Object_Dir use "debug";
11773 for Object_Dir use "release";
11774 for Exec_Dir use ".";
11783 for ^Default_Switches^Default_Switches^ ("Ada")
11785 for Executable ("proc") use "proc1";
11794 package Compiler is
11798 for ^Default_Switches^Default_Switches^ ("Ada")
11799 use ("^-gnata^-gnata^",
11801 "^-gnatE^-gnatE^");
11804 for ^Default_Switches^Default_Switches^ ("Ada")
11815 @code{Style_Type} is an example of a @emph{string type}, which is the project
11816 file analog of an Ada enumeration type but whose components are string literals
11817 rather than identifiers. @code{Style} is declared as a variable of this type.
11819 The form @code{external("STYLE", "deb")} is known as an
11820 @emph{external reference}; its first argument is the name of an
11821 @emph{external variable}, and the second argument is a default value to be
11822 used if the external variable doesn't exist. You can define an external
11823 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
11824 or you can use ^an environment variable^a logical name^
11825 as an external variable.
11827 Each @code{case} construct is expanded by the Project Manager based on the
11828 value of @code{Style}. Thus the command
11831 gnatmake -P/common/build.gpr -XSTYLE=deb
11837 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
11842 is equivalent to the @command{gnatmake} invocation using the project file
11843 @file{debug.gpr} in the earlier example. So is the command
11845 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
11849 since @code{"deb"} is the default for @code{STYLE}.
11855 gnatmake -P/common/build.gpr -XSTYLE=rel
11861 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
11866 is equivalent to the @command{gnatmake} invocation using the project file
11867 @file{release.gpr} in the earlier example.
11869 @node Importing Other Projects
11870 @subsection Importing Other Projects
11871 @cindex @code{ADA_PROJECT_PATH}
11874 A compilation unit in a source file in one project may depend on compilation
11875 units in source files in other projects. To compile this unit under
11876 control of a project file, the
11877 dependent project must @emph{import} the projects containing the needed source
11879 This effect is obtained using syntax similar to an Ada @code{with} clause,
11880 but where @code{with}ed entities are strings that denote project files.
11882 As an example, suppose that the two projects @code{GUI_Proj} and
11883 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
11884 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
11885 and @file{^/comm^[COMM]^}, respectively.
11886 Suppose that the source files for @code{GUI_Proj} are
11887 @file{gui.ads} and @file{gui.adb}, and that the source files for
11888 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
11889 files is located in its respective project file directory. Schematically:
11908 We want to develop an application in directory @file{^/app^[APP]^} that
11909 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
11910 the corresponding project files (e.g.@: the ^switch^switch^ settings
11911 and object directory).
11912 Skeletal code for a main procedure might be something like the following:
11914 @smallexample @c ada
11917 procedure App_Main is
11926 Here is a project file, @file{app_proj.gpr}, that achieves the desired
11929 @smallexample @c projectfile
11931 with "/gui/gui_proj", "/comm/comm_proj";
11932 project App_Proj is
11933 for Main use ("app_main");
11939 Building an executable is achieved through the command:
11941 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
11944 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
11945 in the directory where @file{app_proj.gpr} resides.
11947 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
11948 (as illustrated above) the @code{with} clause can omit the extension.
11950 Our example specified an absolute path for each imported project file.
11951 Alternatively, the directory name of an imported object can be omitted
11955 The imported project file is in the same directory as the importing project
11958 You have defined ^an environment variable^a logical name^
11959 that includes the directory containing
11960 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
11961 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
11962 directory names separated by colons (semicolons on Windows).
11966 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
11967 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
11970 @smallexample @c projectfile
11972 with "gui_proj", "comm_proj";
11973 project App_Proj is
11974 for Main use ("app_main");
11980 Importing other projects can create ambiguities.
11981 For example, the same unit might be present in different imported projects, or
11982 it might be present in both the importing project and in an imported project.
11983 Both of these conditions are errors. Note that in the current version of
11984 the Project Manager, it is illegal to have an ambiguous unit even if the
11985 unit is never referenced by the importing project. This restriction may be
11986 relaxed in a future release.
11988 @node Extending a Project
11989 @subsection Extending a Project
11992 In large software systems it is common to have multiple
11993 implementations of a common interface; in Ada terms, multiple versions of a
11994 package body for the same spec. For example, one implementation
11995 might be safe for use in tasking programs, while another might only be used
11996 in sequential applications. This can be modeled in GNAT using the concept
11997 of @emph{project extension}. If one project (the ``child'') @emph{extends}
11998 another project (the ``parent'') then by default all source files of the
11999 parent project are inherited by the child, but the child project can
12000 override any of the parent's source files with new versions, and can also
12001 add new files. This facility is the project analog of a type extension in
12002 Object-Oriented Programming. Project hierarchies are permitted (a child
12003 project may be the parent of yet another project), and a project that
12004 inherits one project can also import other projects.
12006 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
12007 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
12008 @file{pack.adb}, and @file{proc.adb}:
12021 Note that the project file can simply be empty (that is, no attribute or
12022 package is defined):
12024 @smallexample @c projectfile
12026 project Seq_Proj is
12032 implying that its source files are all the Ada source files in the project
12035 Suppose we want to supply an alternate version of @file{pack.adb}, in
12036 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
12037 @file{pack.ads} and @file{proc.adb}. We can define a project
12038 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
12042 ^/tasking^[TASKING]^
12048 project Tasking_Proj extends "/seq/seq_proj" is
12054 The version of @file{pack.adb} used in a build depends on which project file
12057 Note that we could have obtained the desired behavior using project import
12058 rather than project inheritance; a @code{base} project would contain the
12059 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
12060 import @code{base} and add @file{pack.adb}, and likewise a tasking project
12061 would import @code{base} and add a different version of @file{pack.adb}. The
12062 choice depends on whether other sources in the original project need to be
12063 overridden. If they do, then project extension is necessary, otherwise,
12064 importing is sufficient.
12067 In a project file that extends another project file, it is possible to
12068 indicate that an inherited source is not part of the sources of the extending
12069 project. This is necessary sometimes when a package spec has been overloaded
12070 and no longer requires a body: in this case, it is necessary to indicate that
12071 the inherited body is not part of the sources of the project, otherwise there
12072 will be a compilation error when compiling the spec.
12074 For that purpose, the attribute @code{Excluded_Source_Files} is used.
12075 Its value is a string list: a list of file names. It is also possible to use
12076 attribute @code{Excluded_Source_List_File}. Its value is a single string:
12077 the file name of a text file containing a list of file names, one per line.
12079 @smallexample @c @projectfile
12080 project B extends "a" is
12081 for Source_Files use ("pkg.ads");
12082 -- New spec of Pkg does not need a completion
12083 for Excluded_Source_Files use ("pkg.adb");
12087 Attribute @code{Excluded_Source_Files} may also be used to check if a source
12088 is still needed: if it is possible to build using @command{gnatmake} when such
12089 a source is put in attribute @code{Excluded_Source_Files} of a project P, then
12090 it is possible to remove the source completely from a system that includes
12093 @c ***********************
12094 @c * Project File Syntax *
12095 @c ***********************
12097 @node Project File Syntax
12098 @section Project File Syntax
12102 * Qualified Projects::
12108 * Associative Array Attributes::
12109 * case Constructions::
12113 This section describes the structure of project files.
12115 A project may be an @emph{independent project}, entirely defined by a single
12116 project file. Any Ada source file in an independent project depends only
12117 on the predefined library and other Ada source files in the same project.
12120 A project may also @dfn{depend on} other projects, in either or both of
12121 the following ways:
12123 @item It may import any number of projects
12124 @item It may extend at most one other project
12128 The dependence relation is a directed acyclic graph (the subgraph reflecting
12129 the ``extends'' relation is a tree).
12131 A project's @dfn{immediate sources} are the source files directly defined by
12132 that project, either implicitly by residing in the project file's directory,
12133 or explicitly through any of the source-related attributes described below.
12134 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
12135 of @var{proj} together with the immediate sources (unless overridden) of any
12136 project on which @var{proj} depends (either directly or indirectly).
12139 @subsection Basic Syntax
12142 As seen in the earlier examples, project files have an Ada-like syntax.
12143 The minimal project file is:
12144 @smallexample @c projectfile
12153 The identifier @code{Empty} is the name of the project.
12154 This project name must be present after the reserved
12155 word @code{end} at the end of the project file, followed by a semi-colon.
12157 Any name in a project file, such as the project name or a variable name,
12158 has the same syntax as an Ada identifier.
12160 The reserved words of project files are the Ada 95 reserved words plus
12161 @code{extends}, @code{external}, and @code{project}. Note that the only Ada
12162 reserved words currently used in project file syntax are:
12198 Comments in project files have the same syntax as in Ada, two consecutive
12199 hyphens through the end of the line.
12201 @node Qualified Projects
12202 @subsection Qualified Projects
12205 Before the reserved @code{project}, there may be one or two "qualifiers", that
12206 is identifiers or other reserved words, to qualify the project.
12208 The current list of qualifiers is:
12212 @code{abstract}: qualify a project with no sources. An abstract project must
12213 have a declaration specifying that there are no sources in the project, and,
12214 if it extends another project, the project it extends must also be a qualified
12218 @code{standard}: a standard project is a non library project with sources.
12221 @code{aggregate}: for future extension
12224 @code{aggregate library}: for future extension
12227 @code{library}: a library project must declare both attributes
12228 @code{Library_Name} and @code{Library_Dir}.
12231 @code{configuration}: a configuration project cannot be in a project tree.
12235 @subsection Packages
12238 A project file may contain @emph{packages}. The name of a package must be one
12239 of the identifiers from the following list. A package
12240 with a given name may only appear once in a project file. Package names are
12241 case insensitive. The following package names are legal:
12257 @code{Cross_Reference}
12261 @code{Pretty_Printer}
12271 @code{Language_Processing}
12275 In its simplest form, a package may be empty:
12277 @smallexample @c projectfile
12287 A package may contain @emph{attribute declarations},
12288 @emph{variable declarations} and @emph{case constructions}, as will be
12291 When there is ambiguity between a project name and a package name,
12292 the name always designates the project. To avoid possible confusion, it is
12293 always a good idea to avoid naming a project with one of the
12294 names allowed for packages or any name that starts with @code{gnat}.
12297 @subsection Expressions
12300 An @emph{expression} is either a @emph{string expression} or a
12301 @emph{string list expression}.
12303 A @emph{string expression} is either a @emph{simple string expression} or a
12304 @emph{compound string expression}.
12306 A @emph{simple string expression} is one of the following:
12308 @item A literal string; e.g.@: @code{"comm/my_proj.gpr"}
12309 @item A string-valued variable reference (@pxref{Variables})
12310 @item A string-valued attribute reference (@pxref{Attributes})
12311 @item An external reference (@pxref{External References in Project Files})
12315 A @emph{compound string expression} is a concatenation of string expressions,
12316 using the operator @code{"&"}
12318 Path & "/" & File_Name & ".ads"
12322 A @emph{string list expression} is either a
12323 @emph{simple string list expression} or a
12324 @emph{compound string list expression}.
12326 A @emph{simple string list expression} is one of the following:
12328 @item A parenthesized list of zero or more string expressions,
12329 separated by commas
12331 File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
12334 @item A string list-valued variable reference
12335 @item A string list-valued attribute reference
12339 A @emph{compound string list expression} is the concatenation (using
12340 @code{"&"}) of a simple string list expression and an expression. Note that
12341 each term in a compound string list expression, except the first, may be
12342 either a string expression or a string list expression.
12344 @smallexample @c projectfile
12346 File_Name_List := () & File_Name; -- One string in this list
12347 Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
12349 Big_List := File_Name_List & Extended_File_Name_List;
12350 -- Concatenation of two string lists: three strings
12351 Illegal_List := "gnat.adc" & Extended_File_Name_List;
12352 -- Illegal: must start with a string list
12357 @subsection String Types
12360 A @emph{string type declaration} introduces a discrete set of string literals.
12361 If a string variable is declared to have this type, its value
12362 is restricted to the given set of literals.
12364 Here is an example of a string type declaration:
12366 @smallexample @c projectfile
12367 type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
12371 Variables of a string type are called @emph{typed variables}; all other
12372 variables are called @emph{untyped variables}. Typed variables are
12373 particularly useful in @code{case} constructions, to support conditional
12374 attribute declarations.
12375 (@pxref{case Constructions}).
12377 The string literals in the list are case sensitive and must all be different.
12378 They may include any graphic characters allowed in Ada, including spaces.
12380 A string type may only be declared at the project level, not inside a package.
12382 A string type may be referenced by its name if it has been declared in the same
12383 project file, or by an expanded name whose prefix is the name of the project
12384 in which it is declared.
12387 @subsection Variables
12390 A variable may be declared at the project file level, or within a package.
12391 Here are some examples of variable declarations:
12393 @smallexample @c projectfile
12395 This_OS : OS := external ("OS"); -- a typed variable declaration
12396 That_OS := "GNU/Linux"; -- an untyped variable declaration
12401 The syntax of a @emph{typed variable declaration} is identical to the Ada
12402 syntax for an object declaration. By contrast, the syntax of an untyped
12403 variable declaration is identical to an Ada assignment statement. In fact,
12404 variable declarations in project files have some of the characteristics of
12405 an assignment, in that successive declarations for the same variable are
12406 allowed. Untyped variable declarations do establish the expected kind of the
12407 variable (string or string list), and successive declarations for it must
12408 respect the initial kind.
12411 A string variable declaration (typed or untyped) declares a variable
12412 whose value is a string. This variable may be used as a string expression.
12413 @smallexample @c projectfile
12414 File_Name := "readme.txt";
12415 Saved_File_Name := File_Name & ".saved";
12419 A string list variable declaration declares a variable whose value is a list
12420 of strings. The list may contain any number (zero or more) of strings.
12422 @smallexample @c projectfile
12424 List_With_One_Element := ("^-gnaty^-gnaty^");
12425 List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
12426 Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
12427 "pack2.ada", "util_.ada", "util.ada");
12431 The same typed variable may not be declared more than once at project level,
12432 and it may not be declared more than once in any package; it is in effect
12435 The same untyped variable may be declared several times. Declarations are
12436 elaborated in the order in which they appear, so the new value replaces
12437 the old one, and any subsequent reference to the variable uses the new value.
12438 However, as noted above, if a variable has been declared as a string, all
12440 declarations must give it a string value. Similarly, if a variable has
12441 been declared as a string list, all subsequent declarations
12442 must give it a string list value.
12444 A @emph{variable reference} may take several forms:
12447 @item The simple variable name, for a variable in the current package (if any)
12448 or in the current project
12449 @item An expanded name, whose prefix is a context name.
12453 A @emph{context} may be one of the following:
12456 @item The name of an existing package in the current project
12457 @item The name of an imported project of the current project
12458 @item The name of an ancestor project (i.e., a project extended by the current
12459 project, either directly or indirectly)
12460 @item An expanded name whose prefix is an imported/parent project name, and
12461 whose selector is a package name in that project.
12465 A variable reference may be used in an expression.
12468 @subsection Attributes
12471 A project (and its packages) may have @emph{attributes} that define
12472 the project's properties. Some attributes have values that are strings;
12473 others have values that are string lists.
12475 There are two categories of attributes: @emph{simple attributes}
12476 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
12478 Legal project attribute names, and attribute names for each legal package are
12479 listed below. Attributes names are case-insensitive.
12481 The following attributes are defined on projects (all are simple attributes):
12483 @multitable @columnfractions .4 .3
12484 @item @emph{Attribute Name}
12486 @item @code{Source_Files}
12488 @item @code{Source_Dirs}
12490 @item @code{Source_List_File}
12492 @item @code{Object_Dir}
12494 @item @code{Exec_Dir}
12496 @item @code{Excluded_Source_Dirs}
12498 @item @code{Excluded_Source_Files}
12500 @item @code{Excluded_Source_List_File}
12502 @item @code{Languages}
12506 @item @code{Library_Dir}
12508 @item @code{Library_Name}
12510 @item @code{Library_Kind}
12512 @item @code{Library_Version}
12514 @item @code{Library_Interface}
12516 @item @code{Library_Auto_Init}
12518 @item @code{Library_Options}
12520 @item @code{Library_Src_Dir}
12522 @item @code{Library_ALI_Dir}
12524 @item @code{Library_GCC}
12526 @item @code{Library_Symbol_File}
12528 @item @code{Library_Symbol_Policy}
12530 @item @code{Library_Reference_Symbol_File}
12532 @item @code{Externally_Built}
12537 The following attributes are defined for package @code{Naming}
12538 (@pxref{Naming Schemes}):
12540 @multitable @columnfractions .4 .2 .2 .2
12541 @item Attribute Name @tab Category @tab Index @tab Value
12542 @item @code{Spec_Suffix}
12543 @tab associative array
12546 @item @code{Body_Suffix}
12547 @tab associative array
12550 @item @code{Separate_Suffix}
12551 @tab simple attribute
12554 @item @code{Casing}
12555 @tab simple attribute
12558 @item @code{Dot_Replacement}
12559 @tab simple attribute
12563 @tab associative array
12567 @tab associative array
12570 @item @code{Specification_Exceptions}
12571 @tab associative array
12574 @item @code{Implementation_Exceptions}
12575 @tab associative array
12581 The following attributes are defined for packages @code{Builder},
12582 @code{Compiler}, @code{Binder},
12583 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
12584 (@pxref{^Switches^Switches^ and Project Files}).
12586 @multitable @columnfractions .4 .2 .2 .2
12587 @item Attribute Name @tab Category @tab Index @tab Value
12588 @item @code{^Default_Switches^Default_Switches^}
12589 @tab associative array
12592 @item @code{^Switches^Switches^}
12593 @tab associative array
12599 In addition, package @code{Compiler} has a single string attribute
12600 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
12601 string attribute @code{Global_Configuration_Pragmas}.
12604 Each simple attribute has a default value: the empty string (for string-valued
12605 attributes) and the empty list (for string list-valued attributes).
12607 An attribute declaration defines a new value for an attribute.
12609 Examples of simple attribute declarations:
12611 @smallexample @c projectfile
12612 for Object_Dir use "objects";
12613 for Source_Dirs use ("units", "test/drivers");
12617 The syntax of a @dfn{simple attribute declaration} is similar to that of an
12618 attribute definition clause in Ada.
12620 Attributes references may be appear in expressions.
12621 The general form for such a reference is @code{<entity>'<attribute>}:
12622 Associative array attributes are functions. Associative
12623 array attribute references must have an argument that is a string literal.
12627 @smallexample @c projectfile
12629 Naming'Dot_Replacement
12630 Imported_Project'Source_Dirs
12631 Imported_Project.Naming'Casing
12632 Builder'^Default_Switches^Default_Switches^("Ada")
12636 The prefix of an attribute may be:
12638 @item @code{project} for an attribute of the current project
12639 @item The name of an existing package of the current project
12640 @item The name of an imported project
12641 @item The name of a parent project that is extended by the current project
12642 @item An expanded name whose prefix is imported/parent project name,
12643 and whose selector is a package name
12648 @smallexample @c projectfile
12651 for Source_Dirs use project'Source_Dirs & "units";
12652 for Source_Dirs use project'Source_Dirs & "test/drivers"
12658 In the first attribute declaration, initially the attribute @code{Source_Dirs}
12659 has the default value: an empty string list. After this declaration,
12660 @code{Source_Dirs} is a string list of one element: @code{"units"}.
12661 After the second attribute declaration @code{Source_Dirs} is a string list of
12662 two elements: @code{"units"} and @code{"test/drivers"}.
12664 Note: this example is for illustration only. In practice,
12665 the project file would contain only one attribute declaration:
12667 @smallexample @c projectfile
12668 for Source_Dirs use ("units", "test/drivers");
12671 @node Associative Array Attributes
12672 @subsection Associative Array Attributes
12675 Some attributes are defined as @emph{associative arrays}. An associative
12676 array may be regarded as a function that takes a string as a parameter
12677 and delivers a string or string list value as its result.
12679 Here are some examples of single associative array attribute associations:
12681 @smallexample @c projectfile
12682 for Body ("main") use "Main.ada";
12683 for ^Switches^Switches^ ("main.ada")
12685 "^-gnatv^-gnatv^");
12686 for ^Switches^Switches^ ("main.ada")
12687 use Builder'^Switches^Switches^ ("main.ada")
12692 Like untyped variables and simple attributes, associative array attributes
12693 may be declared several times. Each declaration supplies a new value for the
12694 attribute, and replaces the previous setting.
12697 An associative array attribute may be declared as a full associative array
12698 declaration, with the value of the same attribute in an imported or extended
12701 @smallexample @c projectfile
12703 for Default_Switches use Default.Builder'Default_Switches;
12708 In this example, @code{Default} must be either a project imported by the
12709 current project, or the project that the current project extends. If the
12710 attribute is in a package (in this case, in package @code{Builder}), the same
12711 package needs to be specified.
12714 A full associative array declaration replaces any other declaration for the
12715 attribute, including other full associative array declaration. Single
12716 associative array associations may be declare after a full associative
12717 declaration, modifying the value for a single association of the attribute.
12719 @node case Constructions
12720 @subsection @code{case} Constructions
12723 A @code{case} construction is used in a project file to effect conditional
12725 Here is a typical example:
12727 @smallexample @c projectfile
12730 type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
12732 OS : OS_Type := external ("OS", "GNU/Linux");
12736 package Compiler is
12738 when "GNU/Linux" | "Unix" =>
12739 for ^Default_Switches^Default_Switches^ ("Ada")
12740 use ("^-gnath^-gnath^");
12742 for ^Default_Switches^Default_Switches^ ("Ada")
12743 use ("^-gnatP^-gnatP^");
12752 The syntax of a @code{case} construction is based on the Ada case statement
12753 (although there is no @code{null} construction for empty alternatives).
12755 The case expression must be a typed string variable.
12756 Each alternative comprises the reserved word @code{when}, either a list of
12757 literal strings separated by the @code{"|"} character or the reserved word
12758 @code{others}, and the @code{"=>"} token.
12759 Each literal string must belong to the string type that is the type of the
12761 An @code{others} alternative, if present, must occur last.
12763 After each @code{=>}, there are zero or more constructions. The only
12764 constructions allowed in a case construction are other case constructions,
12765 attribute declarations and variable declarations. String type declarations and
12766 package declarations are not allowed. Variable declarations are restricted to
12767 variables that have already been declared before the case construction.
12769 The value of the case variable is often given by an external reference
12770 (@pxref{External References in Project Files}).
12772 @c ****************************************
12773 @c * Objects and Sources in Project Files *
12774 @c ****************************************
12776 @node Objects and Sources in Project Files
12777 @section Objects and Sources in Project Files
12780 * Object Directory::
12782 * Source Directories::
12783 * Source File Names::
12787 Each project has exactly one object directory and one or more source
12788 directories. The source directories must contain at least one source file,
12789 unless the project file explicitly specifies that no source files are present
12790 (@pxref{Source File Names}).
12792 @node Object Directory
12793 @subsection Object Directory
12796 The object directory for a project is the directory containing the compiler's
12797 output (such as @file{ALI} files and object files) for the project's immediate
12800 The object directory is given by the value of the attribute @code{Object_Dir}
12801 in the project file.
12803 @smallexample @c projectfile
12804 for Object_Dir use "objects";
12808 The attribute @code{Object_Dir} has a string value, the path name of the object
12809 directory. The path name may be absolute or relative to the directory of the
12810 project file. This directory must already exist, and be readable and writable.
12812 By default, when the attribute @code{Object_Dir} is not given an explicit value
12813 or when its value is the empty string, the object directory is the same as the
12814 directory containing the project file.
12816 @node Exec Directory
12817 @subsection Exec Directory
12820 The exec directory for a project is the directory containing the executables
12821 for the project's main subprograms.
12823 The exec directory is given by the value of the attribute @code{Exec_Dir}
12824 in the project file.
12826 @smallexample @c projectfile
12827 for Exec_Dir use "executables";
12831 The attribute @code{Exec_Dir} has a string value, the path name of the exec
12832 directory. The path name may be absolute or relative to the directory of the
12833 project file. This directory must already exist, and be writable.
12835 By default, when the attribute @code{Exec_Dir} is not given an explicit value
12836 or when its value is the empty string, the exec directory is the same as the
12837 object directory of the project file.
12839 @node Source Directories
12840 @subsection Source Directories
12843 The source directories of a project are specified by the project file
12844 attribute @code{Source_Dirs}.
12846 This attribute's value is a string list. If the attribute is not given an
12847 explicit value, then there is only one source directory, the one where the
12848 project file resides.
12850 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
12853 @smallexample @c projectfile
12854 for Source_Dirs use ();
12858 indicates that the project contains no source files.
12860 Otherwise, each string in the string list designates one or more
12861 source directories.
12863 @smallexample @c projectfile
12864 for Source_Dirs use ("sources", "test/drivers");
12868 If a string in the list ends with @code{"/**"}, then the directory whose path
12869 name precedes the two asterisks, as well as all its subdirectories
12870 (recursively), are source directories.
12872 @smallexample @c projectfile
12873 for Source_Dirs use ("/system/sources/**");
12877 Here the directory @code{/system/sources} and all of its subdirectories
12878 (recursively) are source directories.
12880 To specify that the source directories are the directory of the project file
12881 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
12882 @smallexample @c projectfile
12883 for Source_Dirs use ("./**");
12887 Each of the source directories must exist and be readable.
12889 @node Source File Names
12890 @subsection Source File Names
12893 In a project that contains source files, their names may be specified by the
12894 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
12895 (a string). Source file names never include any directory information.
12897 If the attribute @code{Source_Files} is given an explicit value, then each
12898 element of the list is a source file name.
12900 @smallexample @c projectfile
12901 for Source_Files use ("main.adb");
12902 for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
12906 If the attribute @code{Source_Files} is not given an explicit value,
12907 but the attribute @code{Source_List_File} is given a string value,
12908 then the source file names are contained in the text file whose path name
12909 (absolute or relative to the directory of the project file) is the
12910 value of the attribute @code{Source_List_File}.
12912 Each line in the file that is not empty or is not a comment
12913 contains a source file name.
12915 @smallexample @c projectfile
12916 for Source_List_File use "source_list.txt";
12920 By default, if neither the attribute @code{Source_Files} nor the attribute
12921 @code{Source_List_File} is given an explicit value, then each file in the
12922 source directories that conforms to the project's naming scheme
12923 (@pxref{Naming Schemes}) is an immediate source of the project.
12925 A warning is issued if both attributes @code{Source_Files} and
12926 @code{Source_List_File} are given explicit values. In this case, the attribute
12927 @code{Source_Files} prevails.
12929 Each source file name must be the name of one existing source file
12930 in one of the source directories.
12932 A @code{Source_Files} attribute whose value is an empty list
12933 indicates that there are no source files in the project.
12935 If the order of the source directories is known statically, that is if
12936 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
12937 be several files with the same source file name. In this case, only the file
12938 in the first directory is considered as an immediate source of the project
12939 file. If the order of the source directories is not known statically, it is
12940 an error to have several files with the same source file name.
12942 Projects can be specified to have no Ada source
12943 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
12944 list, or the @code{"Ada"} may be absent from @code{Languages}:
12946 @smallexample @c projectfile
12947 for Source_Dirs use ();
12948 for Source_Files use ();
12949 for Languages use ("C", "C++");
12953 Otherwise, a project must contain at least one immediate source.
12955 Projects with no source files are useful as template packages
12956 (@pxref{Packages in Project Files}) for other projects; in particular to
12957 define a package @code{Naming} (@pxref{Naming Schemes}).
12959 @c ****************************
12960 @c * Importing Projects *
12961 @c ****************************
12963 @node Importing Projects
12964 @section Importing Projects
12965 @cindex @code{ADA_PROJECT_PATH}
12968 An immediate source of a project P may depend on source files that
12969 are neither immediate sources of P nor in the predefined library.
12970 To get this effect, P must @emph{import} the projects that contain the needed
12973 @smallexample @c projectfile
12975 with "project1", "utilities.gpr";
12976 with "/namings/apex.gpr";
12983 As can be seen in this example, the syntax for importing projects is similar
12984 to the syntax for importing compilation units in Ada. However, project files
12985 use literal strings instead of names, and the @code{with} clause identifies
12986 project files rather than packages.
12988 Each literal string is the file name or path name (absolute or relative) of a
12989 project file. If a string corresponds to a file name, with no path or a
12990 relative path, then its location is determined by the @emph{project path}. The
12991 latter can be queried using @code{gnatls -v}. It contains:
12995 In first position, the directory containing the current project file.
12997 In last position, the default project directory. This default project directory
12998 is part of the GNAT installation and is the standard place to install project
12999 files giving access to standard support libraries.
13001 @ref{Installing a library}
13005 In between, all the directories referenced in the
13006 ^environment variable^logical name^ @env{ADA_PROJECT_PATH} if it exists.
13010 If a relative pathname is used, as in
13012 @smallexample @c projectfile
13017 then the full path for the project is constructed by concatenating this
13018 relative path to those in the project path, in order, until a matching file is
13019 found. Any symbolic link will be fully resolved in the directory of the
13020 importing project file before the imported project file is examined.
13022 If the @code{with}'ed project file name does not have an extension,
13023 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
13024 then the file name as specified in the @code{with} clause (no extension) will
13025 be used. In the above example, if a file @code{project1.gpr} is found, then it
13026 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
13027 then it will be used; if neither file exists, this is an error.
13029 A warning is issued if the name of the project file does not match the
13030 name of the project; this check is case insensitive.
13032 Any source file that is an immediate source of the imported project can be
13033 used by the immediate sources of the importing project, transitively. Thus
13034 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
13035 sources of @code{A} may depend on the immediate sources of @code{C}, even if
13036 @code{A} does not import @code{C} explicitly. However, this is not recommended,
13037 because if and when @code{B} ceases to import @code{C}, some sources in
13038 @code{A} will no longer compile.
13040 A side effect of this capability is that normally cyclic dependencies are not
13041 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
13042 is not allowed to import @code{A}. However, there are cases when cyclic
13043 dependencies would be beneficial. For these cases, another form of import
13044 between projects exists, the @code{limited with}: a project @code{A} that
13045 imports a project @code{B} with a straight @code{with} may also be imported,
13046 directly or indirectly, by @code{B} on the condition that imports from @code{B}
13047 to @code{A} include at least one @code{limited with}.
13049 @smallexample @c 0projectfile
13055 limited with "../a/a.gpr";
13063 limited with "../a/a.gpr";
13069 In the above legal example, there are two project cycles:
13072 @item A -> C -> D -> A
13076 In each of these cycle there is one @code{limited with}: import of @code{A}
13077 from @code{B} and import of @code{A} from @code{D}.
13079 The difference between straight @code{with} and @code{limited with} is that
13080 the name of a project imported with a @code{limited with} cannot be used in the
13081 project that imports it. In particular, its packages cannot be renamed and
13082 its variables cannot be referred to.
13084 An exception to the above rules for @code{limited with} is that for the main
13085 project specified to @command{gnatmake} or to the @command{GNAT} driver a
13086 @code{limited with} is equivalent to a straight @code{with}. For example,
13087 in the example above, projects @code{B} and @code{D} could not be main
13088 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
13089 each have a @code{limited with} that is the only one in a cycle of importing
13092 @c *********************
13093 @c * Project Extension *
13094 @c *********************
13096 @node Project Extension
13097 @section Project Extension
13100 During development of a large system, it is sometimes necessary to use
13101 modified versions of some of the source files, without changing the original
13102 sources. This can be achieved through the @emph{project extension} facility.
13104 @smallexample @c projectfile
13105 project Modified_Utilities extends "/baseline/utilities.gpr" is @dots{}
13109 A project extension declaration introduces an extending project
13110 (the @emph{child}) and a project being extended (the @emph{parent}).
13112 By default, a child project inherits all the sources of its parent.
13113 However, inherited sources can be overridden: a unit in a parent is hidden
13114 by a unit of the same name in the child.
13116 Inherited sources are considered to be sources (but not immediate sources)
13117 of the child project; see @ref{Project File Syntax}.
13119 An inherited source file retains any switches specified in the parent project.
13121 For example if the project @code{Utilities} contains the spec and the
13122 body of an Ada package @code{Util_IO}, then the project
13123 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
13124 The original body of @code{Util_IO} will not be considered in program builds.
13125 However, the package spec will still be found in the project
13128 A child project can have only one parent, except when it is qualified as
13129 abstract. But it may import any number of other projects.
13131 A project is not allowed to import directly or indirectly at the same time a
13132 child project and any of its ancestors.
13134 @c *******************************
13135 @c * Project Hierarchy Extension *
13136 @c *******************************
13138 @node Project Hierarchy Extension
13139 @section Project Hierarchy Extension
13142 When extending a large system spanning multiple projects, it is often
13143 inconvenient to extend every project in the hierarchy that is impacted by a
13144 small change introduced. In such cases, it is possible to create a virtual
13145 extension of entire hierarchy using @code{extends all} relationship.
13147 When the project is extended using @code{extends all} inheritance, all projects
13148 that are imported by it, both directly and indirectly, are considered virtually
13149 extended. That is, the Project Manager creates "virtual projects"
13150 that extend every project in the hierarchy; all these virtual projects have
13151 no sources of their own and have as object directory the object directory of
13152 the root of "extending all" project.
13154 It is possible to explicitly extend one or more projects in the hierarchy
13155 in order to modify the sources. These extending projects must be imported by
13156 the "extending all" project, which will replace the corresponding virtual
13157 projects with the explicit ones.
13159 When building such a project hierarchy extension, the Project Manager will
13160 ensure that both modified sources and sources in virtual extending projects
13161 that depend on them, are recompiled.
13163 By means of example, consider the following hierarchy of projects.
13167 project A, containing package P1
13169 project B importing A and containing package P2 which depends on P1
13171 project C importing B and containing package P3 which depends on P2
13175 We want to modify packages P1 and P3.
13177 This project hierarchy will need to be extended as follows:
13181 Create project A1 that extends A, placing modified P1 there:
13183 @smallexample @c 0projectfile
13184 project A1 extends "(@dots{})/A" is
13189 Create project C1 that "extends all" C and imports A1, placing modified
13192 @smallexample @c 0projectfile
13193 with "(@dots{})/A1";
13194 project C1 extends all "(@dots{})/C" is
13199 When you build project C1, your entire modified project space will be
13200 recompiled, including the virtual project B1 that has been impacted by the
13201 "extending all" inheritance of project C.
13203 Note that if a Library Project in the hierarchy is virtually extended,
13204 the virtual project that extends the Library Project is not a Library Project.
13206 @c ****************************************
13207 @c * External References in Project Files *
13208 @c ****************************************
13210 @node External References in Project Files
13211 @section External References in Project Files
13214 A project file may contain references to external variables; such references
13215 are called @emph{external references}.
13217 An external variable is either defined as part of the environment (an
13218 environment variable in Unix, for example) or else specified on the command
13219 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
13220 If both, then the command line value is used.
13222 The value of an external reference is obtained by means of the built-in
13223 function @code{external}, which returns a string value.
13224 This function has two forms:
13226 @item @code{external (external_variable_name)}
13227 @item @code{external (external_variable_name, default_value)}
13231 Each parameter must be a string literal. For example:
13233 @smallexample @c projectfile
13235 external ("OS", "GNU/Linux")
13239 In the form with one parameter, the function returns the value of
13240 the external variable given as parameter. If this name is not present in the
13241 environment, the function returns an empty string.
13243 In the form with two string parameters, the second argument is
13244 the value returned when the variable given as the first argument is not
13245 present in the environment. In the example above, if @code{"OS"} is not
13246 the name of ^an environment variable^a logical name^ and is not passed on
13247 the command line, then the returned value is @code{"GNU/Linux"}.
13249 An external reference may be part of a string expression or of a string
13250 list expression, and can therefore appear in a variable declaration or
13251 an attribute declaration.
13253 @smallexample @c projectfile
13255 type Mode_Type is ("Debug", "Release");
13256 Mode : Mode_Type := external ("MODE");
13263 @c *****************************
13264 @c * Packages in Project Files *
13265 @c *****************************
13267 @node Packages in Project Files
13268 @section Packages in Project Files
13271 A @emph{package} defines the settings for project-aware tools within a
13273 For each such tool one can declare a package; the names for these
13274 packages are preset (@pxref{Packages}).
13275 A package may contain variable declarations, attribute declarations, and case
13278 @smallexample @c projectfile
13281 package Builder is -- used by gnatmake
13282 for ^Default_Switches^Default_Switches^ ("Ada")
13291 The syntax of package declarations mimics that of package in Ada.
13293 Most of the packages have an attribute
13294 @code{^Default_Switches^Default_Switches^}.
13295 This attribute is an associative array, and its value is a string list.
13296 The index of the associative array is the name of a programming language (case
13297 insensitive). This attribute indicates the ^switch^switch^
13298 or ^switches^switches^ to be used
13299 with the corresponding tool.
13301 Some packages also have another attribute, @code{^Switches^Switches^},
13302 an associative array whose value is a string list.
13303 The index is the name of a source file.
13304 This attribute indicates the ^switch^switch^
13305 or ^switches^switches^ to be used by the corresponding
13306 tool when dealing with this specific file.
13308 Further information on these ^switch^switch^-related attributes is found in
13309 @ref{^Switches^Switches^ and Project Files}.
13311 A package may be declared as a @emph{renaming} of another package; e.g., from
13312 the project file for an imported project.
13314 @smallexample @c projectfile
13316 with "/global/apex.gpr";
13318 package Naming renames Apex.Naming;
13325 Packages that are renamed in other project files often come from project files
13326 that have no sources: they are just used as templates. Any modification in the
13327 template will be reflected automatically in all the project files that rename
13328 a package from the template.
13330 In addition to the tool-oriented packages, you can also declare a package
13331 named @code{Naming} to establish specialized source file naming conventions
13332 (@pxref{Naming Schemes}).
13334 @c ************************************
13335 @c * Variables from Imported Projects *
13336 @c ************************************
13338 @node Variables from Imported Projects
13339 @section Variables from Imported Projects
13342 An attribute or variable defined in an imported or parent project can
13343 be used in expressions in the importing / extending project.
13344 Such an attribute or variable is denoted by an expanded name whose prefix
13345 is either the name of the project or the expanded name of a package within
13348 @smallexample @c projectfile
13351 project Main extends "base" is
13352 Var1 := Imported.Var;
13353 Var2 := Base.Var & ".new";
13358 for ^Default_Switches^Default_Switches^ ("Ada")
13359 use Imported.Builder'Ada_^Switches^Switches^ &
13360 "^-gnatg^-gnatg^" &
13366 package Compiler is
13367 for ^Default_Switches^Default_Switches^ ("Ada")
13368 use Base.Compiler'Ada_^Switches^Switches^;
13379 The value of @code{Var1} is a copy of the variable @code{Var} defined
13380 in the project file @file{"imported.gpr"}
13382 the value of @code{Var2} is a copy of the value of variable @code{Var}
13383 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
13385 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13386 @code{Builder} is a string list that includes in its value a copy of the value
13387 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
13388 in project file @file{imported.gpr} plus two new elements:
13389 @option{"^-gnatg^-gnatg^"}
13390 and @option{"^-v^-v^"};
13392 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13393 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
13394 defined in the @code{Compiler} package in project file @file{base.gpr},
13395 the project being extended.
13398 @c ******************
13399 @c * Naming Schemes *
13400 @c ******************
13402 @node Naming Schemes
13403 @section Naming Schemes
13406 Sometimes an Ada software system is ported from a foreign compilation
13407 environment to GNAT, and the file names do not use the default GNAT
13408 conventions. Instead of changing all the file names (which for a variety
13409 of reasons might not be possible), you can define the relevant file
13410 naming scheme in the @code{Naming} package in your project file.
13413 Note that the use of pragmas described in
13414 @ref{Alternative File Naming Schemes} by mean of a configuration
13415 pragmas file is not supported when using project files. You must use
13416 the features described in this paragraph. You can however use specify
13417 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
13420 For example, the following
13421 package models the Apex file naming rules:
13423 @smallexample @c projectfile
13426 for Casing use "lowercase";
13427 for Dot_Replacement use ".";
13428 for Spec_Suffix ("Ada") use ".1.ada";
13429 for Body_Suffix ("Ada") use ".2.ada";
13436 For example, the following package models the HP Ada file naming rules:
13438 @smallexample @c projectfile
13441 for Casing use "lowercase";
13442 for Dot_Replacement use "__";
13443 for Spec_Suffix ("Ada") use "_.^ada^ada^";
13444 for Body_Suffix ("Ada") use ".^ada^ada^";
13450 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
13451 names in lower case)
13455 You can define the following attributes in package @code{Naming}:
13459 @item @code{Casing}
13460 This must be a string with one of the three values @code{"lowercase"},
13461 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
13464 If @code{Casing} is not specified, then the default is @code{"lowercase"}.
13466 @item @code{Dot_Replacement}
13467 This must be a string whose value satisfies the following conditions:
13470 @item It must not be empty
13471 @item It cannot start or end with an alphanumeric character
13472 @item It cannot be a single underscore
13473 @item It cannot start with an underscore followed by an alphanumeric
13474 @item It cannot contain a dot @code{'.'} except if the entire string
13479 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
13481 @item @code{Spec_Suffix}
13482 This is an associative array (indexed by the programming language name, case
13483 insensitive) whose value is a string that must satisfy the following
13487 @item It must not be empty
13488 @item It must include at least one dot
13491 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
13492 @code{"^.ads^.ADS^"}.
13494 @item @code{Body_Suffix}
13495 This is an associative array (indexed by the programming language name, case
13496 insensitive) whose value is a string that must satisfy the following
13500 @item It must not be empty
13501 @item It must include at least one dot
13502 @item It cannot be the same as @code{Spec_Suffix ("Ada")}
13505 If @code{Body_Suffix ("Ada")} and @code{Spec_Suffix ("Ada")} end with the
13506 same string, then a file name that ends with the longest of these two suffixes
13507 will be a body if the longest suffix is @code{Body_Suffix ("Ada")} or a spec
13508 if the longest suffix is @code{Spec_Suffix ("Ada")}.
13510 If @code{Body_Suffix ("Ada")} is not specified, then the default is
13511 @code{"^.adb^.ADB^"}.
13513 @item @code{Separate_Suffix}
13514 This must be a string whose value satisfies the same conditions as
13515 @code{Body_Suffix}. The same "longest suffix" rules apply.
13518 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
13519 value as @code{Body_Suffix ("Ada")}.
13523 You can use the associative array attribute @code{Spec} to define
13524 the source file name for an individual Ada compilation unit's spec. The array
13525 index must be a string literal that identifies the Ada unit (case insensitive).
13526 The value of this attribute must be a string that identifies the file that
13527 contains this unit's spec (case sensitive or insensitive depending on the
13530 @smallexample @c projectfile
13531 for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
13536 You can use the associative array attribute @code{Body} to
13537 define the source file name for an individual Ada compilation unit's body
13538 (possibly a subunit). The array index must be a string literal that identifies
13539 the Ada unit (case insensitive). The value of this attribute must be a string
13540 that identifies the file that contains this unit's body or subunit (case
13541 sensitive or insensitive depending on the operating system).
13543 @smallexample @c projectfile
13544 for Body ("MyPack.MyChild") use "mypack.mychild.body";
13548 @c ********************
13549 @c * Library Projects *
13550 @c ********************
13552 @node Library Projects
13553 @section Library Projects
13556 @emph{Library projects} are projects whose object code is placed in a library.
13557 (Note that this facility is not yet supported on all platforms)
13559 To create a library project, you need to define in its project file
13560 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
13561 Additionally, you may define other library-related attributes such as
13562 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
13563 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
13565 The @code{Library_Name} attribute has a string value. There is no restriction
13566 on the name of a library. It is the responsibility of the developer to
13567 choose a name that will be accepted by the platform. It is recommended to
13568 choose names that could be Ada identifiers; such names are almost guaranteed
13569 to be acceptable on all platforms.
13571 The @code{Library_Dir} attribute has a string value that designates the path
13572 (absolute or relative) of the directory where the library will reside.
13573 It must designate an existing directory, and this directory must be writable,
13574 different from the project's object directory and from any source directory
13575 in the project tree.
13577 If both @code{Library_Name} and @code{Library_Dir} are specified and
13578 are legal, then the project file defines a library project. The optional
13579 library-related attributes are checked only for such project files.
13581 The @code{Library_Kind} attribute has a string value that must be one of the
13582 following (case insensitive): @code{"static"}, @code{"dynamic"} or
13583 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
13584 attribute is not specified, the library is a static library, that is
13585 an archive of object files that can be potentially linked into a
13586 static executable. Otherwise, the library may be dynamic or
13587 relocatable, that is a library that is loaded only at the start of execution.
13589 If you need to build both a static and a dynamic library, you should use two
13590 different object directories, since in some cases some extra code needs to
13591 be generated for the latter. For such cases, it is recommended to either use
13592 two different project files, or a single one which uses external variables
13593 to indicate what kind of library should be build.
13595 The @code{Library_ALI_Dir} attribute may be specified to indicate the
13596 directory where the ALI files of the library will be copied. When it is
13597 not specified, the ALI files are copied to the directory specified in
13598 attribute @code{Library_Dir}. The directory specified by @code{Library_ALI_Dir}
13599 must be writable and different from the project's object directory and from
13600 any source directory in the project tree.
13602 The @code{Library_Version} attribute has a string value whose interpretation
13603 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
13604 used only for dynamic/relocatable libraries as the internal name of the
13605 library (the @code{"soname"}). If the library file name (built from the
13606 @code{Library_Name}) is different from the @code{Library_Version}, then the
13607 library file will be a symbolic link to the actual file whose name will be
13608 @code{Library_Version}.
13612 @smallexample @c projectfile
13618 for Library_Dir use "lib_dir";
13619 for Library_Name use "dummy";
13620 for Library_Kind use "relocatable";
13621 for Library_Version use "libdummy.so." & Version;
13628 Directory @file{lib_dir} will contain the internal library file whose name
13629 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
13630 @file{libdummy.so.1}.
13632 When @command{gnatmake} detects that a project file
13633 is a library project file, it will check all immediate sources of the project
13634 and rebuild the library if any of the sources have been recompiled.
13636 Standard project files can import library project files. In such cases,
13637 the libraries will only be rebuilt if some of its sources are recompiled
13638 because they are in the closure of some other source in an importing project.
13639 Sources of the library project files that are not in such a closure will
13640 not be checked, unless the full library is checked, because one of its sources
13641 needs to be recompiled.
13643 For instance, assume the project file @code{A} imports the library project file
13644 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
13645 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
13646 @file{l2.ads}, @file{l2.adb}.
13648 If @file{l1.adb} has been modified, then the library associated with @code{L}
13649 will be rebuilt when compiling all the immediate sources of @code{A} only
13650 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
13653 To be sure that all the sources in the library associated with @code{L} are
13654 up to date, and that all the sources of project @code{A} are also up to date,
13655 the following two commands needs to be used:
13662 When a library is built or rebuilt, an attempt is made first to delete all
13663 files in the library directory.
13664 All @file{ALI} files will also be copied from the object directory to the
13665 library directory. To build executables, @command{gnatmake} will use the
13666 library rather than the individual object files.
13669 It is also possible to create library project files for third-party libraries
13670 that are precompiled and cannot be compiled locally thanks to the
13671 @code{externally_built} attribute. (See @ref{Installing a library}).
13674 @c *******************************
13675 @c * Stand-alone Library Projects *
13676 @c *******************************
13678 @node Stand-alone Library Projects
13679 @section Stand-alone Library Projects
13682 A Stand-alone Library is a library that contains the necessary code to
13683 elaborate the Ada units that are included in the library. A Stand-alone
13684 Library is suitable to be used in an executable when the main is not
13685 in Ada. However, Stand-alone Libraries may also be used with an Ada main
13688 A Stand-alone Library Project is a Library Project where the library is
13689 a Stand-alone Library.
13691 To be a Stand-alone Library Project, in addition to the two attributes
13692 that make a project a Library Project (@code{Library_Name} and
13693 @code{Library_Dir}, see @ref{Library Projects}), the attribute
13694 @code{Library_Interface} must be defined.
13696 @smallexample @c projectfile
13698 for Library_Dir use "lib_dir";
13699 for Library_Name use "dummy";
13700 for Library_Interface use ("int1", "int1.child");
13704 Attribute @code{Library_Interface} has a nonempty string list value,
13705 each string in the list designating a unit contained in an immediate source
13706 of the project file.
13708 When a Stand-alone Library is built, first the binder is invoked to build
13709 a package whose name depends on the library name
13710 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
13711 This binder-generated package includes initialization and
13712 finalization procedures whose
13713 names depend on the library name (dummyinit and dummyfinal in the example
13714 above). The object corresponding to this package is included in the library.
13716 A dynamic or relocatable Stand-alone Library is automatically initialized
13717 if automatic initialization of Stand-alone Libraries is supported on the
13718 platform and if attribute @code{Library_Auto_Init} is not specified or
13719 is specified with the value "true". A static Stand-alone Library is never
13720 automatically initialized.
13722 Single string attribute @code{Library_Auto_Init} may be specified with only
13723 two possible values: "false" or "true" (case-insensitive). Specifying
13724 "false" for attribute @code{Library_Auto_Init} will prevent automatic
13725 initialization of dynamic or relocatable libraries.
13727 When a non-automatically initialized Stand-alone Library is used
13728 in an executable, its initialization procedure must be called before
13729 any service of the library is used.
13730 When the main subprogram is in Ada, it may mean that the initialization
13731 procedure has to be called during elaboration of another package.
13733 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
13734 (those that are listed in attribute @code{Library_Interface}) are copied to
13735 the Library Directory. As a consequence, only the Interface Units may be
13736 imported from Ada units outside of the library. If other units are imported,
13737 the binding phase will fail.
13739 When a Stand-Alone Library is bound, the switches that are specified in
13740 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
13741 used in the call to @command{gnatbind}.
13743 The string list attribute @code{Library_Options} may be used to specified
13744 additional switches to the call to @command{gcc} to link the library.
13746 The attribute @code{Library_Src_Dir}, may be specified for a
13747 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
13748 single string value. Its value must be the path (absolute or relative to the
13749 project directory) of an existing directory. This directory cannot be the
13750 object directory or one of the source directories, but it can be the same as
13751 the library directory. The sources of the Interface
13752 Units of the library, necessary to an Ada client of the library, will be
13753 copied to the designated directory, called Interface Copy directory.
13754 These sources includes the specs of the Interface Units, but they may also
13755 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
13756 are used, or when there is a generic units in the spec. Before the sources
13757 are copied to the Interface Copy directory, an attempt is made to delete all
13758 files in the Interface Copy directory.
13760 @c *************************************
13761 @c * Switches Related to Project Files *
13762 @c *************************************
13763 @node Switches Related to Project Files
13764 @section Switches Related to Project Files
13767 The following switches are used by GNAT tools that support project files:
13771 @item ^-P^/PROJECT_FILE=^@var{project}
13772 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
13773 Indicates the name of a project file. This project file will be parsed with
13774 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
13775 if any, and using the external references indicated
13776 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
13778 There may zero, one or more spaces between @option{-P} and @var{project}.
13782 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
13785 Since the Project Manager parses the project file only after all the switches
13786 on the command line are checked, the order of the switches
13787 @option{^-P^/PROJECT_FILE^},
13788 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
13789 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
13791 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
13792 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
13793 Indicates that external variable @var{name} has the value @var{value}.
13794 The Project Manager will use this value for occurrences of
13795 @code{external(name)} when parsing the project file.
13799 If @var{name} or @var{value} includes a space, then @var{name=value} should be
13800 put between quotes.
13808 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
13809 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
13810 @var{name}, only the last one is used.
13813 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
13814 takes precedence over the value of the same name in the environment.
13816 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
13817 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
13818 Indicates the verbosity of the parsing of GNAT project files.
13821 @option{-vP0} means Default;
13822 @option{-vP1} means Medium;
13823 @option{-vP2} means High.
13827 There are three possible options for this qualifier: DEFAULT, MEDIUM and
13832 The default is ^Default^DEFAULT^: no output for syntactically correct
13835 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
13836 only the last one is used.
13838 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
13839 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
13840 Add directory <dir> at the beginning of the project search path, in order,
13841 after the current working directory.
13845 @cindex @option{-eL} (any project-aware tool)
13846 Follow all symbolic links when processing project files.
13849 @item ^--subdirs^/SUBDIRS^=<subdir>
13850 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
13851 This switch is recognized by gnatmake and gnatclean. It indicate that the real
13852 directories (except the source directories) are the subdirectories <subdir>
13853 of the directories specified in the project files. This applies in particular
13854 to object directories, library directories and exec directories. If the
13855 subdirectories do not exist, they are created automatically.
13859 @c **********************************
13860 @c * Tools Supporting Project Files *
13861 @c **********************************
13863 @node Tools Supporting Project Files
13864 @section Tools Supporting Project Files
13867 * gnatmake and Project Files::
13868 * The GNAT Driver and Project Files::
13871 @node gnatmake and Project Files
13872 @subsection gnatmake and Project Files
13875 This section covers several topics related to @command{gnatmake} and
13876 project files: defining ^switches^switches^ for @command{gnatmake}
13877 and for the tools that it invokes; specifying configuration pragmas;
13878 the use of the @code{Main} attribute; building and rebuilding library project
13882 * ^Switches^Switches^ and Project Files::
13883 * Specifying Configuration Pragmas::
13884 * Project Files and Main Subprograms::
13885 * Library Project Files::
13888 @node ^Switches^Switches^ and Project Files
13889 @subsubsection ^Switches^Switches^ and Project Files
13892 It is not currently possible to specify VMS style qualifiers in the project
13893 files; only Unix style ^switches^switches^ may be specified.
13897 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
13898 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
13899 attribute, a @code{^Switches^Switches^} attribute, or both;
13900 as their names imply, these ^switch^switch^-related
13901 attributes affect the ^switches^switches^ that are used for each of these GNAT
13903 @command{gnatmake} is invoked. As will be explained below, these
13904 component-specific ^switches^switches^ precede
13905 the ^switches^switches^ provided on the @command{gnatmake} command line.
13907 The @code{^Default_Switches^Default_Switches^} attribute is an associative
13908 array indexed by language name (case insensitive) whose value is a string list.
13911 @smallexample @c projectfile
13913 package Compiler is
13914 for ^Default_Switches^Default_Switches^ ("Ada")
13915 use ("^-gnaty^-gnaty^",
13922 The @code{^Switches^Switches^} attribute is also an associative array,
13923 indexed by a file name (which may or may not be case sensitive, depending
13924 on the operating system) whose value is a string list. For example:
13926 @smallexample @c projectfile
13929 for ^Switches^Switches^ ("main1.adb")
13931 for ^Switches^Switches^ ("main2.adb")
13938 For the @code{Builder} package, the file names must designate source files
13939 for main subprograms. For the @code{Binder} and @code{Linker} packages, the
13940 file names must designate @file{ALI} or source files for main subprograms.
13941 In each case just the file name without an explicit extension is acceptable.
13943 For each tool used in a program build (@command{gnatmake}, the compiler, the
13944 binder, and the linker), the corresponding package @dfn{contributes} a set of
13945 ^switches^switches^ for each file on which the tool is invoked, based on the
13946 ^switch^switch^-related attributes defined in the package.
13947 In particular, the ^switches^switches^
13948 that each of these packages contributes for a given file @var{f} comprise:
13952 the value of attribute @code{^Switches^Switches^ (@var{f})},
13953 if it is specified in the package for the given file,
13955 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
13956 if it is specified in the package.
13960 If neither of these attributes is defined in the package, then the package does
13961 not contribute any ^switches^switches^ for the given file.
13963 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
13964 two sets, in the following order: those contributed for the file
13965 by the @code{Builder} package;
13966 and the switches passed on the command line.
13968 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
13969 the ^switches^switches^ passed to the tool comprise three sets,
13970 in the following order:
13974 the applicable ^switches^switches^ contributed for the file
13975 by the @code{Builder} package in the project file supplied on the command line;
13978 those contributed for the file by the package (in the relevant project file --
13979 see below) corresponding to the tool; and
13982 the applicable switches passed on the command line.
13986 The term @emph{applicable ^switches^switches^} reflects the fact that
13987 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
13988 tools, depending on the individual ^switch^switch^.
13990 @command{gnatmake} may invoke the compiler on source files from different
13991 projects. The Project Manager will use the appropriate project file to
13992 determine the @code{Compiler} package for each source file being compiled.
13993 Likewise for the @code{Binder} and @code{Linker} packages.
13995 As an example, consider the following package in a project file:
13997 @smallexample @c projectfile
14000 package Compiler is
14001 for ^Default_Switches^Default_Switches^ ("Ada")
14003 for ^Switches^Switches^ ("a.adb")
14005 for ^Switches^Switches^ ("b.adb")
14007 "^-gnaty^-gnaty^");
14014 If @command{gnatmake} is invoked with this project file, and it needs to
14015 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
14016 @file{a.adb} will be compiled with the ^switch^switch^
14017 @option{^-O1^-O1^},
14018 @file{b.adb} with ^switches^switches^
14020 and @option{^-gnaty^-gnaty^},
14021 and @file{c.adb} with @option{^-g^-g^}.
14023 The following example illustrates the ordering of the ^switches^switches^
14024 contributed by different packages:
14026 @smallexample @c projectfile
14030 for ^Switches^Switches^ ("main.adb")
14038 package Compiler is
14039 for ^Switches^Switches^ ("main.adb")
14047 If you issue the command:
14050 gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
14054 then the compiler will be invoked on @file{main.adb} with the following
14055 sequence of ^switches^switches^
14058 ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
14061 with the last @option{^-O^-O^}
14062 ^switch^switch^ having precedence over the earlier ones;
14063 several other ^switches^switches^
14064 (such as @option{^-c^-c^}) are added implicitly.
14066 The ^switches^switches^
14068 and @option{^-O1^-O1^} are contributed by package
14069 @code{Builder}, @option{^-O2^-O2^} is contributed
14070 by the package @code{Compiler}
14071 and @option{^-O0^-O0^} comes from the command line.
14073 The @option{^-g^-g^}
14074 ^switch^switch^ will also be passed in the invocation of
14075 @command{Gnatlink.}
14077 A final example illustrates switch contributions from packages in different
14080 @smallexample @c projectfile
14083 for Source_Files use ("pack.ads", "pack.adb");
14084 package Compiler is
14085 for ^Default_Switches^Default_Switches^ ("Ada")
14086 use ("^-gnata^-gnata^");
14094 for Source_Files use ("foo_main.adb", "bar_main.adb");
14096 for ^Switches^Switches^ ("foo_main.adb")
14104 -- Ada source file:
14106 procedure Foo_Main is
14114 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
14118 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
14119 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
14120 @option{^-gnato^-gnato^} (passed on the command line).
14121 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
14122 are @option{^-g^-g^} from @code{Proj4.Builder},
14123 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
14124 and @option{^-gnato^-gnato^} from the command line.
14127 When using @command{gnatmake} with project files, some ^switches^switches^ or
14128 arguments may be expressed as relative paths. As the working directory where
14129 compilation occurs may change, these relative paths are converted to absolute
14130 paths. For the ^switches^switches^ found in a project file, the relative paths
14131 are relative to the project file directory, for the switches on the command
14132 line, they are relative to the directory where @command{gnatmake} is invoked.
14133 The ^switches^switches^ for which this occurs are:
14139 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
14141 ^-o^-o^, object files specified in package @code{Linker} or after
14142 -largs on the command line). The exception to this rule is the ^switch^switch^
14143 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
14145 @node Specifying Configuration Pragmas
14146 @subsubsection Specifying Configuration Pragmas
14148 When using @command{gnatmake} with project files, if there exists a file
14149 @file{gnat.adc} that contains configuration pragmas, this file will be
14152 Configuration pragmas can be defined by means of the following attributes in
14153 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
14154 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
14156 Both these attributes are single string attributes. Their values is the path
14157 name of a file containing configuration pragmas. If a path name is relative,
14158 then it is relative to the project directory of the project file where the
14159 attribute is defined.
14161 When compiling a source, the configuration pragmas used are, in order,
14162 those listed in the file designated by attribute
14163 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
14164 project file, if it is specified, and those listed in the file designated by
14165 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
14166 the project file of the source, if it exists.
14168 @node Project Files and Main Subprograms
14169 @subsubsection Project Files and Main Subprograms
14172 When using a project file, you can invoke @command{gnatmake}
14173 with one or several main subprograms, by specifying their source files on the
14177 gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
14181 Each of these needs to be a source file of the same project, except
14182 when the switch ^-u^/UNIQUE^ is used.
14185 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
14186 same project, one of the project in the tree rooted at the project specified
14187 on the command line. The package @code{Builder} of this common project, the
14188 "main project" is the one that is considered by @command{gnatmake}.
14191 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
14192 imported directly or indirectly by the project specified on the command line.
14193 Note that if such a source file is not part of the project specified on the
14194 command line, the ^switches^switches^ found in package @code{Builder} of the
14195 project specified on the command line, if any, that are transmitted
14196 to the compiler will still be used, not those found in the project file of
14200 When using a project file, you can also invoke @command{gnatmake} without
14201 explicitly specifying any main, and the effect depends on whether you have
14202 defined the @code{Main} attribute. This attribute has a string list value,
14203 where each element in the list is the name of a source file (the file
14204 extension is optional) that contains a unit that can be a main subprogram.
14206 If the @code{Main} attribute is defined in a project file as a non-empty
14207 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
14208 line, then invoking @command{gnatmake} with this project file but without any
14209 main on the command line is equivalent to invoking @command{gnatmake} with all
14210 the file names in the @code{Main} attribute on the command line.
14213 @smallexample @c projectfile
14216 for Main use ("main1", "main2", "main3");
14222 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
14224 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
14226 When the project attribute @code{Main} is not specified, or is specified
14227 as an empty string list, or when the switch @option{-u} is used on the command
14228 line, then invoking @command{gnatmake} with no main on the command line will
14229 result in all immediate sources of the project file being checked, and
14230 potentially recompiled. Depending on the presence of the switch @option{-u},
14231 sources from other project files on which the immediate sources of the main
14232 project file depend are also checked and potentially recompiled. In other
14233 words, the @option{-u} switch is applied to all of the immediate sources of the
14236 When no main is specified on the command line and attribute @code{Main} exists
14237 and includes several mains, or when several mains are specified on the
14238 command line, the default ^switches^switches^ in package @code{Builder} will
14239 be used for all mains, even if there are specific ^switches^switches^
14240 specified for one or several mains.
14242 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
14243 the specific ^switches^switches^ for each main, if they are specified.
14245 @node Library Project Files
14246 @subsubsection Library Project Files
14249 When @command{gnatmake} is invoked with a main project file that is a library
14250 project file, it is not allowed to specify one or more mains on the command
14254 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
14255 ^-l^/ACTION=LINK^ have special meanings.
14258 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
14259 to @command{gnatmake} that @command{gnatbind} should be invoked for the
14262 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
14263 to @command{gnatmake} that the binder generated file should be compiled
14264 (in the case of a stand-alone library) and that the library should be built.
14268 @node The GNAT Driver and Project Files
14269 @subsection The GNAT Driver and Project Files
14272 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
14273 can benefit from project files:
14274 @command{^gnatbind^gnatbind^},
14275 @command{^gnatcheck^gnatcheck^}),
14276 @command{^gnatclean^gnatclean^}),
14277 @command{^gnatelim^gnatelim^},
14278 @command{^gnatfind^gnatfind^},
14279 @command{^gnatlink^gnatlink^},
14280 @command{^gnatls^gnatls^},
14281 @command{^gnatmetric^gnatmetric^},
14282 @command{^gnatpp^gnatpp^},
14283 @command{^gnatstub^gnatstub^},
14284 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
14285 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
14286 They must be invoked through the @command{gnat} driver.
14288 The @command{gnat} driver is a wrapper that accepts a number of commands and
14289 calls the corresponding tool. It was designed initially for VMS platforms (to
14290 convert VMS qualifiers to Unix-style switches), but it is now available on all
14293 On non-VMS platforms, the @command{gnat} driver accepts the following commands
14294 (case insensitive):
14298 BIND to invoke @command{^gnatbind^gnatbind^}
14300 CHOP to invoke @command{^gnatchop^gnatchop^}
14302 CLEAN to invoke @command{^gnatclean^gnatclean^}
14304 COMP or COMPILE to invoke the compiler
14306 ELIM to invoke @command{^gnatelim^gnatelim^}
14308 FIND to invoke @command{^gnatfind^gnatfind^}
14310 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
14312 LINK to invoke @command{^gnatlink^gnatlink^}
14314 LS or LIST to invoke @command{^gnatls^gnatls^}
14316 MAKE to invoke @command{^gnatmake^gnatmake^}
14318 NAME to invoke @command{^gnatname^gnatname^}
14320 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
14322 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
14324 METRIC to invoke @command{^gnatmetric^gnatmetric^}
14326 STUB to invoke @command{^gnatstub^gnatstub^}
14328 XREF to invoke @command{^gnatxref^gnatxref^}
14332 (note that the compiler is invoked using the command
14333 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
14336 On non-VMS platforms, between @command{gnat} and the command, two
14337 special switches may be used:
14341 @command{-v} to display the invocation of the tool.
14343 @command{-dn} to prevent the @command{gnat} driver from removing
14344 the temporary files it has created. These temporary files are
14345 configuration files and temporary file list files.
14349 The command may be followed by switches and arguments for the invoked
14353 gnat bind -C main.ali
14359 Switches may also be put in text files, one switch per line, and the text
14360 files may be specified with their path name preceded by '@@'.
14363 gnat bind @@args.txt main.ali
14367 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
14368 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
14369 (@option{^-P^/PROJECT_FILE^},
14370 @option{^-X^/EXTERNAL_REFERENCE^} and
14371 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
14372 the switches of the invoking tool.
14375 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
14376 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
14377 the immediate sources of the specified project file.
14380 When GNAT METRIC is used with a project file, but with no source
14381 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
14382 with all the immediate sources of the specified project file and with
14383 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
14387 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
14388 a project file, no source is specified on the command line and
14389 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
14390 the underlying tool (^gnatpp^gnatpp^ or
14391 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
14392 not only for the immediate sources of the main project.
14394 (-U stands for Universal or Union of the project files of the project tree)
14398 For each of the following commands, there is optionally a corresponding
14399 package in the main project.
14403 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
14406 package @code{Check} for command CHECK (invoking
14407 @code{^gnatcheck^gnatcheck^})
14410 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
14413 package @code{Cross_Reference} for command XREF (invoking
14414 @code{^gnatxref^gnatxref^})
14417 package @code{Eliminate} for command ELIM (invoking
14418 @code{^gnatelim^gnatelim^})
14421 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
14424 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
14427 package @code{Gnatstub} for command STUB
14428 (invoking @code{^gnatstub^gnatstub^})
14431 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
14434 package @code{Metrics} for command METRIC
14435 (invoking @code{^gnatmetric^gnatmetric^})
14438 package @code{Pretty_Printer} for command PP or PRETTY
14439 (invoking @code{^gnatpp^gnatpp^})
14444 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
14445 a simple variable with a string list value. It contains ^switches^switches^
14446 for the invocation of @code{^gnatls^gnatls^}.
14448 @smallexample @c projectfile
14452 for ^Switches^Switches^
14461 All other packages have two attribute @code{^Switches^Switches^} and
14462 @code{^Default_Switches^Default_Switches^}.
14465 @code{^Switches^Switches^} is an associative array attribute, indexed by the
14466 source file name, that has a string list value: the ^switches^switches^ to be
14467 used when the tool corresponding to the package is invoked for the specific
14471 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
14472 indexed by the programming language that has a string list value.
14473 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
14474 ^switches^switches^ for the invocation of the tool corresponding
14475 to the package, except if a specific @code{^Switches^Switches^} attribute
14476 is specified for the source file.
14478 @smallexample @c projectfile
14482 for Source_Dirs use ("./**");
14485 for ^Switches^Switches^ use
14492 package Compiler is
14493 for ^Default_Switches^Default_Switches^ ("Ada")
14494 use ("^-gnatv^-gnatv^",
14495 "^-gnatwa^-gnatwa^");
14501 for ^Default_Switches^Default_Switches^ ("Ada")
14509 for ^Default_Switches^Default_Switches^ ("Ada")
14511 for ^Switches^Switches^ ("main.adb")
14520 for ^Default_Switches^Default_Switches^ ("Ada")
14527 package Cross_Reference is
14528 for ^Default_Switches^Default_Switches^ ("Ada")
14533 end Cross_Reference;
14539 With the above project file, commands such as
14542 ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
14543 ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
14544 ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
14545 ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
14546 ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
14550 will set up the environment properly and invoke the tool with the switches
14551 found in the package corresponding to the tool:
14552 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
14553 except @code{^Switches^Switches^ ("main.adb")}
14554 for @code{^gnatlink^gnatlink^}.
14555 It is also possible to invoke some of the tools,
14556 @code{^gnatcheck^gnatcheck^}),
14557 @code{^gnatmetric^gnatmetric^}),
14558 and @code{^gnatpp^gnatpp^})
14559 on a set of project units thanks to the combination of the switches
14560 @option{-P}, @option{-U} and possibly the main unit when one is interested
14561 in its closure. For instance,
14565 will compute the metrics for all the immediate units of project
14568 gnat metric -Pproj -U
14570 will compute the metrics for all the units of the closure of projects
14571 rooted at @code{proj}.
14573 gnat metric -Pproj -U main_unit
14575 will compute the metrics for the closure of units rooted at
14576 @code{main_unit}. This last possibility relies implicitly
14577 on @command{gnatbind}'s option @option{-R}.
14579 @c **********************
14580 @node An Extended Example
14581 @section An Extended Example
14584 Suppose that we have two programs, @var{prog1} and @var{prog2},
14585 whose sources are in corresponding directories. We would like
14586 to build them with a single @command{gnatmake} command, and we want to place
14587 their object files into @file{build} subdirectories of the source directories.
14588 Furthermore, we want to have to have two separate subdirectories
14589 in @file{build} -- @file{release} and @file{debug} -- which will contain
14590 the object files compiled with different set of compilation flags.
14592 In other words, we have the following structure:
14609 Here are the project files that we must place in a directory @file{main}
14610 to maintain this structure:
14614 @item We create a @code{Common} project with a package @code{Compiler} that
14615 specifies the compilation ^switches^switches^:
14620 @b{project} Common @b{is}
14622 @b{for} Source_Dirs @b{use} (); -- No source files
14626 @b{type} Build_Type @b{is} ("release", "debug");
14627 Build : Build_Type := External ("BUILD", "debug");
14630 @b{package} Compiler @b{is}
14631 @b{case} Build @b{is}
14632 @b{when} "release" =>
14633 @b{for} ^Default_Switches^Default_Switches^ ("Ada")
14634 @b{use} ("^-O2^-O2^");
14635 @b{when} "debug" =>
14636 @b{for} ^Default_Switches^Default_Switches^ ("Ada")
14637 @b{use} ("^-g^-g^");
14645 @item We create separate projects for the two programs:
14652 @b{project} Prog1 @b{is}
14654 @b{for} Source_Dirs @b{use} ("prog1");
14655 @b{for} Object_Dir @b{use} "prog1/build/" & Common.Build;
14657 @b{package} Compiler @b{renames} Common.Compiler;
14668 @b{project} Prog2 @b{is}
14670 @b{for} Source_Dirs @b{use} ("prog2");
14671 @b{for} Object_Dir @b{use} "prog2/build/" & Common.Build;
14673 @b{package} Compiler @b{renames} Common.Compiler;
14679 @item We create a wrapping project @code{Main}:
14688 @b{project} Main @b{is}
14690 @b{package} Compiler @b{renames} Common.Compiler;
14696 @item Finally we need to create a dummy procedure that @code{with}s (either
14697 explicitly or implicitly) all the sources of our two programs.
14702 Now we can build the programs using the command
14705 gnatmake ^-P^/PROJECT_FILE=^main dummy
14709 for the Debug mode, or
14713 gnatmake -Pmain -XBUILD=release
14719 GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
14724 for the Release mode.
14726 @c ********************************
14727 @c * Project File Complete Syntax *
14728 @c ********************************
14730 @node Project File Complete Syntax
14731 @section Project File Complete Syntax
14735 context_clause project_declaration
14741 @b{with} path_name @{ , path_name @} ;
14746 project_declaration ::=
14747 simple_project_declaration | project_extension
14749 simple_project_declaration ::=
14750 @b{project} <project_>simple_name @b{is}
14751 @{declarative_item@}
14752 @b{end} <project_>simple_name;
14754 project_extension ::=
14755 @b{project} <project_>simple_name @b{extends} path_name @b{is}
14756 @{declarative_item@}
14757 @b{end} <project_>simple_name;
14759 declarative_item ::=
14760 package_declaration |
14761 typed_string_declaration |
14762 other_declarative_item
14764 package_declaration ::=
14765 package_spec | package_renaming
14768 @b{package} package_identifier @b{is}
14769 @{simple_declarative_item@}
14770 @b{end} package_identifier ;
14772 package_identifier ::=
14773 @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
14774 @code{Linker} | @code{Finder} | @code{Cross_Reference} |
14775 @code{^gnatls^gnatls^} | @code{IDE} | @code{Pretty_Printer}
14777 package_renaming ::==
14778 @b{package} package_identifier @b{renames}
14779 <project_>simple_name.package_identifier ;
14781 typed_string_declaration ::=
14782 @b{type} <typed_string_>_simple_name @b{is}
14783 ( string_literal @{, string_literal@} );
14785 other_declarative_item ::=
14786 attribute_declaration |
14787 typed_variable_declaration |
14788 variable_declaration |
14791 attribute_declaration ::=
14792 full_associative_array_declaration |
14793 @b{for} attribute_designator @b{use} expression ;
14795 full_associative_array_declaration ::=
14796 @b{for} <associative_array_attribute_>simple_name @b{use}
14797 <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
14799 attribute_designator ::=
14800 <simple_attribute_>simple_name |
14801 <associative_array_attribute_>simple_name ( string_literal )
14803 typed_variable_declaration ::=
14804 <typed_variable_>simple_name : <typed_string_>name := string_expression ;
14806 variable_declaration ::=
14807 <variable_>simple_name := expression;
14817 attribute_reference
14823 ( <string_>expression @{ , <string_>expression @} )
14826 @b{external} ( string_literal [, string_literal] )
14828 attribute_reference ::=
14829 attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
14831 attribute_prefix ::=
14833 <project_>simple_name | package_identifier |
14834 <project_>simple_name . package_identifier
14836 case_construction ::=
14837 @b{case} <typed_variable_>name @b{is}
14842 @b{when} discrete_choice_list =>
14843 @{case_construction | attribute_declaration@}
14845 discrete_choice_list ::=
14846 string_literal @{| string_literal@} |
14850 simple_name @{. simple_name@}
14853 identifier (same as Ada)
14857 @node The Cross-Referencing Tools gnatxref and gnatfind
14858 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
14863 The compiler generates cross-referencing information (unless
14864 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
14865 This information indicates where in the source each entity is declared and
14866 referenced. Note that entities in package Standard are not included, but
14867 entities in all other predefined units are included in the output.
14869 Before using any of these two tools, you need to compile successfully your
14870 application, so that GNAT gets a chance to generate the cross-referencing
14873 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
14874 information to provide the user with the capability to easily locate the
14875 declaration and references to an entity. These tools are quite similar,
14876 the difference being that @code{gnatfind} is intended for locating
14877 definitions and/or references to a specified entity or entities, whereas
14878 @code{gnatxref} is oriented to generating a full report of all
14881 To use these tools, you must not compile your application using the
14882 @option{-gnatx} switch on the @command{gnatmake} command line
14883 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
14884 information will not be generated.
14886 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
14887 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
14890 * gnatxref Switches::
14891 * gnatfind Switches::
14892 * Project Files for gnatxref and gnatfind::
14893 * Regular Expressions in gnatfind and gnatxref::
14894 * Examples of gnatxref Usage::
14895 * Examples of gnatfind Usage::
14898 @node gnatxref Switches
14899 @section @code{gnatxref} Switches
14902 The command invocation for @code{gnatxref} is:
14904 $ gnatxref [switches] sourcefile1 [sourcefile2 @dots{}]
14911 @item sourcefile1, sourcefile2
14912 identifies the source files for which a report is to be generated. The
14913 ``with''ed units will be processed too. You must provide at least one file.
14915 These file names are considered to be regular expressions, so for instance
14916 specifying @file{source*.adb} is the same as giving every file in the current
14917 directory whose name starts with @file{source} and whose extension is
14920 You shouldn't specify any directory name, just base names. @command{gnatxref}
14921 and @command{gnatfind} will be able to locate these files by themselves using
14922 the source path. If you specify directories, no result is produced.
14927 The switches can be:
14931 @cindex @option{--version} @command{gnatxref}
14932 Display Copyright and version, then exit disregarding all other options.
14935 @cindex @option{--help} @command{gnatxref}
14936 If @option{--version} was not used, display usage, then exit disregarding
14939 @item ^-a^/ALL_FILES^
14940 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
14941 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
14942 the read-only files found in the library search path. Otherwise, these files
14943 will be ignored. This option can be used to protect Gnat sources or your own
14944 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
14945 much faster, and their output much smaller. Read-only here refers to access
14946 or permissions status in the file system for the current user.
14949 @cindex @option{-aIDIR} (@command{gnatxref})
14950 When looking for source files also look in directory DIR. The order in which
14951 source file search is undertaken is the same as for @command{gnatmake}.
14954 @cindex @option{-aODIR} (@command{gnatxref})
14955 When searching for library and object files, look in directory
14956 DIR. The order in which library files are searched is the same as for
14957 @command{gnatmake}.
14960 @cindex @option{-nostdinc} (@command{gnatxref})
14961 Do not look for sources in the system default directory.
14964 @cindex @option{-nostdlib} (@command{gnatxref})
14965 Do not look for library files in the system default directory.
14967 @item --RTS=@var{rts-path}
14968 @cindex @option{--RTS} (@command{gnatxref})
14969 Specifies the default location of the runtime library. Same meaning as the
14970 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14972 @item ^-d^/DERIVED_TYPES^
14973 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
14974 If this switch is set @code{gnatxref} will output the parent type
14975 reference for each matching derived types.
14977 @item ^-f^/FULL_PATHNAME^
14978 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
14979 If this switch is set, the output file names will be preceded by their
14980 directory (if the file was found in the search path). If this switch is
14981 not set, the directory will not be printed.
14983 @item ^-g^/IGNORE_LOCALS^
14984 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
14985 If this switch is set, information is output only for library-level
14986 entities, ignoring local entities. The use of this switch may accelerate
14987 @code{gnatfind} and @code{gnatxref}.
14990 @cindex @option{-IDIR} (@command{gnatxref})
14991 Equivalent to @samp{-aODIR -aIDIR}.
14994 @cindex @option{-pFILE} (@command{gnatxref})
14995 Specify a project file to use @xref{Project Files}.
14996 If you need to use the @file{.gpr}
14997 project files, you should use gnatxref through the GNAT driver
14998 (@command{gnat xref -Pproject}).
15000 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15001 project file in the current directory.
15003 If a project file is either specified or found by the tools, then the content
15004 of the source directory and object directory lines are added as if they
15005 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
15006 and @samp{^-aO^OBJECT_SEARCH^}.
15008 Output only unused symbols. This may be really useful if you give your
15009 main compilation unit on the command line, as @code{gnatxref} will then
15010 display every unused entity and 'with'ed package.
15014 Instead of producing the default output, @code{gnatxref} will generate a
15015 @file{tags} file that can be used by vi. For examples how to use this
15016 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
15017 to the standard output, thus you will have to redirect it to a file.
15023 All these switches may be in any order on the command line, and may even
15024 appear after the file names. They need not be separated by spaces, thus
15025 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15026 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15028 @node gnatfind Switches
15029 @section @code{gnatfind} Switches
15032 The command line for @code{gnatfind} is:
15035 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
15036 [file1 file2 @dots{}]
15044 An entity will be output only if it matches the regular expression found
15045 in @samp{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
15047 Omitting the pattern is equivalent to specifying @samp{*}, which
15048 will match any entity. Note that if you do not provide a pattern, you
15049 have to provide both a sourcefile and a line.
15051 Entity names are given in Latin-1, with uppercase/lowercase equivalence
15052 for matching purposes. At the current time there is no support for
15053 8-bit codes other than Latin-1, or for wide characters in identifiers.
15056 @code{gnatfind} will look for references, bodies or declarations
15057 of symbols referenced in @file{sourcefile}, at line @samp{line}
15058 and column @samp{column}. See @ref{Examples of gnatfind Usage}
15059 for syntax examples.
15062 is a decimal integer identifying the line number containing
15063 the reference to the entity (or entities) to be located.
15066 is a decimal integer identifying the exact location on the
15067 line of the first character of the identifier for the
15068 entity reference. Columns are numbered from 1.
15070 @item file1 file2 @dots{}
15071 The search will be restricted to these source files. If none are given, then
15072 the search will be done for every library file in the search path.
15073 These file must appear only after the pattern or sourcefile.
15075 These file names are considered to be regular expressions, so for instance
15076 specifying @file{source*.adb} is the same as giving every file in the current
15077 directory whose name starts with @file{source} and whose extension is
15080 The location of the spec of the entity will always be displayed, even if it
15081 isn't in one of @file{file1}, @file{file2},@enddots{} The occurrences
15082 of the entity in the separate units of the ones given on the command
15083 line will also be displayed.
15085 Note that if you specify at least one file in this part, @code{gnatfind} may
15086 sometimes not be able to find the body of the subprograms.
15091 At least one of 'sourcefile' or 'pattern' has to be present on
15094 The following switches are available:
15098 @cindex @option{--version} @command{gnatfind}
15099 Display Copyright and version, then exit disregarding all other options.
15102 @cindex @option{--help} @command{gnatfind}
15103 If @option{--version} was not used, display usage, then exit disregarding
15106 @item ^-a^/ALL_FILES^
15107 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
15108 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15109 the read-only files found in the library search path. Otherwise, these files
15110 will be ignored. This option can be used to protect Gnat sources or your own
15111 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15112 much faster, and their output much smaller. Read-only here refers to access
15113 or permission status in the file system for the current user.
15116 @cindex @option{-aIDIR} (@command{gnatfind})
15117 When looking for source files also look in directory DIR. The order in which
15118 source file search is undertaken is the same as for @command{gnatmake}.
15121 @cindex @option{-aODIR} (@command{gnatfind})
15122 When searching for library and object files, look in directory
15123 DIR. The order in which library files are searched is the same as for
15124 @command{gnatmake}.
15127 @cindex @option{-nostdinc} (@command{gnatfind})
15128 Do not look for sources in the system default directory.
15131 @cindex @option{-nostdlib} (@command{gnatfind})
15132 Do not look for library files in the system default directory.
15134 @item --RTS=@var{rts-path}
15135 @cindex @option{--RTS} (@command{gnatfind})
15136 Specifies the default location of the runtime library. Same meaning as the
15137 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15139 @item ^-d^/DERIVED_TYPE_INFORMATION^
15140 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
15141 If this switch is set, then @code{gnatfind} will output the parent type
15142 reference for each matching derived types.
15144 @item ^-e^/EXPRESSIONS^
15145 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
15146 By default, @code{gnatfind} accept the simple regular expression set for
15147 @samp{pattern}. If this switch is set, then the pattern will be
15148 considered as full Unix-style regular expression.
15150 @item ^-f^/FULL_PATHNAME^
15151 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
15152 If this switch is set, the output file names will be preceded by their
15153 directory (if the file was found in the search path). If this switch is
15154 not set, the directory will not be printed.
15156 @item ^-g^/IGNORE_LOCALS^
15157 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
15158 If this switch is set, information is output only for library-level
15159 entities, ignoring local entities. The use of this switch may accelerate
15160 @code{gnatfind} and @code{gnatxref}.
15163 @cindex @option{-IDIR} (@command{gnatfind})
15164 Equivalent to @samp{-aODIR -aIDIR}.
15167 @cindex @option{-pFILE} (@command{gnatfind})
15168 Specify a project file (@pxref{Project Files}) to use.
15169 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15170 project file in the current directory.
15172 If a project file is either specified or found by the tools, then the content
15173 of the source directory and object directory lines are added as if they
15174 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
15175 @samp{^-aO^/OBJECT_SEARCH^}.
15177 @item ^-r^/REFERENCES^
15178 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
15179 By default, @code{gnatfind} will output only the information about the
15180 declaration, body or type completion of the entities. If this switch is
15181 set, the @code{gnatfind} will locate every reference to the entities in
15182 the files specified on the command line (or in every file in the search
15183 path if no file is given on the command line).
15185 @item ^-s^/PRINT_LINES^
15186 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
15187 If this switch is set, then @code{gnatfind} will output the content
15188 of the Ada source file lines were the entity was found.
15190 @item ^-t^/TYPE_HIERARCHY^
15191 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
15192 If this switch is set, then @code{gnatfind} will output the type hierarchy for
15193 the specified type. It act like -d option but recursively from parent
15194 type to parent type. When this switch is set it is not possible to
15195 specify more than one file.
15200 All these switches may be in any order on the command line, and may even
15201 appear after the file names. They need not be separated by spaces, thus
15202 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15203 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15205 As stated previously, gnatfind will search in every directory in the
15206 search path. You can force it to look only in the current directory if
15207 you specify @code{*} at the end of the command line.
15209 @node Project Files for gnatxref and gnatfind
15210 @section Project Files for @command{gnatxref} and @command{gnatfind}
15213 Project files allow a programmer to specify how to compile its
15214 application, where to find sources, etc. These files are used
15216 primarily by GPS, but they can also be used
15219 @code{gnatxref} and @code{gnatfind}.
15221 A project file name must end with @file{.gpr}. If a single one is
15222 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
15223 extract the information from it. If multiple project files are found, none of
15224 them is read, and you have to use the @samp{-p} switch to specify the one
15227 The following lines can be included, even though most of them have default
15228 values which can be used in most cases.
15229 The lines can be entered in any order in the file.
15230 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
15231 each line. If you have multiple instances, only the last one is taken into
15236 [default: @code{"^./^[]^"}]
15237 specifies a directory where to look for source files. Multiple @code{src_dir}
15238 lines can be specified and they will be searched in the order they
15242 [default: @code{"^./^[]^"}]
15243 specifies a directory where to look for object and library files. Multiple
15244 @code{obj_dir} lines can be specified, and they will be searched in the order
15247 @item comp_opt=SWITCHES
15248 [default: @code{""}]
15249 creates a variable which can be referred to subsequently by using
15250 the @code{$@{comp_opt@}} notation. This is intended to store the default
15251 switches given to @command{gnatmake} and @command{gcc}.
15253 @item bind_opt=SWITCHES
15254 [default: @code{""}]
15255 creates a variable which can be referred to subsequently by using
15256 the @samp{$@{bind_opt@}} notation. This is intended to store the default
15257 switches given to @command{gnatbind}.
15259 @item link_opt=SWITCHES
15260 [default: @code{""}]
15261 creates a variable which can be referred to subsequently by using
15262 the @samp{$@{link_opt@}} notation. This is intended to store the default
15263 switches given to @command{gnatlink}.
15265 @item main=EXECUTABLE
15266 [default: @code{""}]
15267 specifies the name of the executable for the application. This variable can
15268 be referred to in the following lines by using the @samp{$@{main@}} notation.
15271 @item comp_cmd=COMMAND
15272 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
15275 @item comp_cmd=COMMAND
15276 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
15278 specifies the command used to compile a single file in the application.
15281 @item make_cmd=COMMAND
15282 [default: @code{"GNAT MAKE $@{main@}
15283 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
15284 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
15285 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
15288 @item make_cmd=COMMAND
15289 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
15290 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
15291 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
15293 specifies the command used to recompile the whole application.
15295 @item run_cmd=COMMAND
15296 [default: @code{"$@{main@}"}]
15297 specifies the command used to run the application.
15299 @item debug_cmd=COMMAND
15300 [default: @code{"gdb $@{main@}"}]
15301 specifies the command used to debug the application
15306 @command{gnatxref} and @command{gnatfind} only take into account the
15307 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
15309 @node Regular Expressions in gnatfind and gnatxref
15310 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
15313 As specified in the section about @command{gnatfind}, the pattern can be a
15314 regular expression. Actually, there are to set of regular expressions
15315 which are recognized by the program:
15318 @item globbing patterns
15319 These are the most usual regular expression. They are the same that you
15320 generally used in a Unix shell command line, or in a DOS session.
15322 Here is a more formal grammar:
15329 term ::= elmt -- matches elmt
15330 term ::= elmt elmt -- concatenation (elmt then elmt)
15331 term ::= * -- any string of 0 or more characters
15332 term ::= ? -- matches any character
15333 term ::= [char @{char@}] -- matches any character listed
15334 term ::= [char - char] -- matches any character in range
15338 @item full regular expression
15339 The second set of regular expressions is much more powerful. This is the
15340 type of regular expressions recognized by utilities such a @file{grep}.
15342 The following is the form of a regular expression, expressed in Ada
15343 reference manual style BNF is as follows
15350 regexp ::= term @{| term@} -- alternation (term or term @dots{})
15352 term ::= item @{item@} -- concatenation (item then item)
15354 item ::= elmt -- match elmt
15355 item ::= elmt * -- zero or more elmt's
15356 item ::= elmt + -- one or more elmt's
15357 item ::= elmt ? -- matches elmt or nothing
15360 elmt ::= nschar -- matches given character
15361 elmt ::= [nschar @{nschar@}] -- matches any character listed
15362 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
15363 elmt ::= [char - char] -- matches chars in given range
15364 elmt ::= \ char -- matches given character
15365 elmt ::= . -- matches any single character
15366 elmt ::= ( regexp ) -- parens used for grouping
15368 char ::= any character, including special characters
15369 nschar ::= any character except ()[].*+?^^^
15373 Following are a few examples:
15377 will match any of the two strings @samp{abcde} and @samp{fghi},
15380 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
15381 @samp{abcccd}, and so on,
15384 will match any string which has only lowercase characters in it (and at
15385 least one character.
15390 @node Examples of gnatxref Usage
15391 @section Examples of @code{gnatxref} Usage
15393 @subsection General Usage
15396 For the following examples, we will consider the following units:
15398 @smallexample @c ada
15404 3: procedure Foo (B : in Integer);
15411 1: package body Main is
15412 2: procedure Foo (B : in Integer) is
15423 2: procedure Print (B : Integer);
15432 The first thing to do is to recompile your application (for instance, in
15433 that case just by doing a @samp{gnatmake main}, so that GNAT generates
15434 the cross-referencing information.
15435 You can then issue any of the following commands:
15437 @item gnatxref main.adb
15438 @code{gnatxref} generates cross-reference information for main.adb
15439 and every unit 'with'ed by main.adb.
15441 The output would be:
15449 Decl: main.ads 3:20
15450 Body: main.adb 2:20
15451 Ref: main.adb 4:13 5:13 6:19
15454 Ref: main.adb 6:8 7:8
15464 Decl: main.ads 3:15
15465 Body: main.adb 2:15
15468 Body: main.adb 1:14
15471 Ref: main.adb 6:12 7:12
15475 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
15476 its body is in main.adb, line 1, column 14 and is not referenced any where.
15478 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
15479 it referenced in main.adb, line 6 column 12 and line 7 column 12.
15481 @item gnatxref package1.adb package2.ads
15482 @code{gnatxref} will generates cross-reference information for
15483 package1.adb, package2.ads and any other package 'with'ed by any
15489 @subsection Using gnatxref with vi
15491 @code{gnatxref} can generate a tags file output, which can be used
15492 directly from @command{vi}. Note that the standard version of @command{vi}
15493 will not work properly with overloaded symbols. Consider using another
15494 free implementation of @command{vi}, such as @command{vim}.
15497 $ gnatxref -v gnatfind.adb > tags
15501 will generate the tags file for @code{gnatfind} itself (if the sources
15502 are in the search path!).
15504 From @command{vi}, you can then use the command @samp{:tag @i{entity}}
15505 (replacing @i{entity} by whatever you are looking for), and vi will
15506 display a new file with the corresponding declaration of entity.
15509 @node Examples of gnatfind Usage
15510 @section Examples of @code{gnatfind} Usage
15514 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
15515 Find declarations for all entities xyz referenced at least once in
15516 main.adb. The references are search in every library file in the search
15519 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
15522 The output will look like:
15524 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15525 ^directory/^[directory]^main.adb:24:10: xyz <= body
15526 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15530 that is to say, one of the entities xyz found in main.adb is declared at
15531 line 12 of main.ads (and its body is in main.adb), and another one is
15532 declared at line 45 of foo.ads
15534 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
15535 This is the same command as the previous one, instead @code{gnatfind} will
15536 display the content of the Ada source file lines.
15538 The output will look like:
15541 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15543 ^directory/^[directory]^main.adb:24:10: xyz <= body
15545 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15550 This can make it easier to find exactly the location your are looking
15553 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
15554 Find references to all entities containing an x that are
15555 referenced on line 123 of main.ads.
15556 The references will be searched only in main.ads and foo.adb.
15558 @item gnatfind main.ads:123
15559 Find declarations and bodies for all entities that are referenced on
15560 line 123 of main.ads.
15562 This is the same as @code{gnatfind "*":main.adb:123}.
15564 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
15565 Find the declaration for the entity referenced at column 45 in
15566 line 123 of file main.adb in directory mydir. Note that it
15567 is usual to omit the identifier name when the column is given,
15568 since the column position identifies a unique reference.
15570 The column has to be the beginning of the identifier, and should not
15571 point to any character in the middle of the identifier.
15575 @c *********************************
15576 @node The GNAT Pretty-Printer gnatpp
15577 @chapter The GNAT Pretty-Printer @command{gnatpp}
15579 @cindex Pretty-Printer
15582 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
15583 for source reformatting / pretty-printing.
15584 It takes an Ada source file as input and generates a reformatted
15586 You can specify various style directives via switches; e.g.,
15587 identifier case conventions, rules of indentation, and comment layout.
15589 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
15590 tree for the input source and thus requires the input to be syntactically and
15591 semantically legal.
15592 If this condition is not met, @command{gnatpp} will terminate with an
15593 error message; no output file will be generated.
15595 If the source files presented to @command{gnatpp} contain
15596 preprocessing directives, then the output file will
15597 correspond to the generated source after all
15598 preprocessing is carried out. There is no way
15599 using @command{gnatpp} to obtain pretty printed files that
15600 include the preprocessing directives.
15602 If the compilation unit
15603 contained in the input source depends semantically upon units located
15604 outside the current directory, you have to provide the source search path
15605 when invoking @command{gnatpp}, if these units are contained in files with
15606 names that do not follow the GNAT file naming rules, you have to provide
15607 the configuration file describing the corresponding naming scheme;
15608 see the description of the @command{gnatpp}
15609 switches below. Another possibility is to use a project file and to
15610 call @command{gnatpp} through the @command{gnat} driver
15612 The @command{gnatpp} command has the form
15615 $ gnatpp [@var{switches}] @var{filename}
15622 @var{switches} is an optional sequence of switches defining such properties as
15623 the formatting rules, the source search path, and the destination for the
15627 @var{filename} is the name (including the extension) of the source file to
15628 reformat; ``wildcards'' or several file names on the same gnatpp command are
15629 allowed. The file name may contain path information; it does not have to
15630 follow the GNAT file naming rules
15634 * Switches for gnatpp::
15635 * Formatting Rules::
15638 @node Switches for gnatpp
15639 @section Switches for @command{gnatpp}
15642 The following subsections describe the various switches accepted by
15643 @command{gnatpp}, organized by category.
15646 You specify a switch by supplying a name and generally also a value.
15647 In many cases the values for a switch with a given name are incompatible with
15649 (for example the switch that controls the casing of a reserved word may have
15650 exactly one value: upper case, lower case, or
15651 mixed case) and thus exactly one such switch can be in effect for an
15652 invocation of @command{gnatpp}.
15653 If more than one is supplied, the last one is used.
15654 However, some values for the same switch are mutually compatible.
15655 You may supply several such switches to @command{gnatpp}, but then
15656 each must be specified in full, with both the name and the value.
15657 Abbreviated forms (the name appearing once, followed by each value) are
15659 For example, to set
15660 the alignment of the assignment delimiter both in declarations and in
15661 assignment statements, you must write @option{-A2A3}
15662 (or @option{-A2 -A3}), but not @option{-A23}.
15666 In many cases the set of options for a given qualifier are incompatible with
15667 each other (for example the qualifier that controls the casing of a reserved
15668 word may have exactly one option, which specifies either upper case, lower
15669 case, or mixed case), and thus exactly one such option can be in effect for
15670 an invocation of @command{gnatpp}.
15671 If more than one is supplied, the last one is used.
15672 However, some qualifiers have options that are mutually compatible,
15673 and then you may then supply several such options when invoking
15677 In most cases, it is obvious whether or not the
15678 ^values for a switch with a given name^options for a given qualifier^
15679 are compatible with each other.
15680 When the semantics might not be evident, the summaries below explicitly
15681 indicate the effect.
15684 * Alignment Control::
15686 * Construct Layout Control::
15687 * General Text Layout Control::
15688 * Other Formatting Options::
15689 * Setting the Source Search Path::
15690 * Output File Control::
15691 * Other gnatpp Switches::
15694 @node Alignment Control
15695 @subsection Alignment Control
15696 @cindex Alignment control in @command{gnatpp}
15699 Programs can be easier to read if certain constructs are vertically aligned.
15700 By default all alignments are set ON.
15701 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
15702 OFF, and then use one or more of the other
15703 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
15704 to activate alignment for specific constructs.
15707 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
15711 Set all alignments to ON
15714 @item ^-A0^/ALIGN=OFF^
15715 Set all alignments to OFF
15717 @item ^-A1^/ALIGN=COLONS^
15718 Align @code{:} in declarations
15720 @item ^-A2^/ALIGN=DECLARATIONS^
15721 Align @code{:=} in initializations in declarations
15723 @item ^-A3^/ALIGN=STATEMENTS^
15724 Align @code{:=} in assignment statements
15726 @item ^-A4^/ALIGN=ARROWS^
15727 Align @code{=>} in associations
15729 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
15730 Align @code{at} keywords in the component clauses in record
15731 representation clauses
15735 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
15738 @node Casing Control
15739 @subsection Casing Control
15740 @cindex Casing control in @command{gnatpp}
15743 @command{gnatpp} allows you to specify the casing for reserved words,
15744 pragma names, attribute designators and identifiers.
15745 For identifiers you may define a
15746 general rule for name casing but also override this rule
15747 via a set of dictionary files.
15749 Three types of casing are supported: lower case, upper case, and mixed case.
15750 Lower and upper case are self-explanatory (but since some letters in
15751 Latin1 and other GNAT-supported character sets
15752 exist only in lower-case form, an upper case conversion will have no
15754 ``Mixed case'' means that the first letter, and also each letter immediately
15755 following an underscore, are converted to their uppercase forms;
15756 all the other letters are converted to their lowercase forms.
15759 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
15760 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
15761 Attribute designators are lower case
15763 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
15764 Attribute designators are upper case
15766 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
15767 Attribute designators are mixed case (this is the default)
15769 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
15770 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
15771 Keywords (technically, these are known in Ada as @emph{reserved words}) are
15772 lower case (this is the default)
15774 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
15775 Keywords are upper case
15777 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
15778 @item ^-nD^/NAME_CASING=AS_DECLARED^
15779 Name casing for defining occurrences are as they appear in the source file
15780 (this is the default)
15782 @item ^-nU^/NAME_CASING=UPPER_CASE^
15783 Names are in upper case
15785 @item ^-nL^/NAME_CASING=LOWER_CASE^
15786 Names are in lower case
15788 @item ^-nM^/NAME_CASING=MIXED_CASE^
15789 Names are in mixed case
15791 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
15792 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
15793 Pragma names are lower case
15795 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
15796 Pragma names are upper case
15798 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
15799 Pragma names are mixed case (this is the default)
15801 @item ^-D@var{file}^/DICTIONARY=@var{file}^
15802 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
15803 Use @var{file} as a @emph{dictionary file} that defines
15804 the casing for a set of specified names,
15805 thereby overriding the effect on these names by
15806 any explicit or implicit
15807 ^-n^/NAME_CASING^ switch.
15808 To supply more than one dictionary file,
15809 use ^several @option{-D} switches^a list of files as options^.
15812 @option{gnatpp} implicitly uses a @emph{default dictionary file}
15813 to define the casing for the Ada predefined names and
15814 the names declared in the GNAT libraries.
15816 @item ^-D-^/SPECIFIC_CASING^
15817 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
15818 Do not use the default dictionary file;
15819 instead, use the casing
15820 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
15825 The structure of a dictionary file, and details on the conventions
15826 used in the default dictionary file, are defined in @ref{Name Casing}.
15828 The @option{^-D-^/SPECIFIC_CASING^} and
15829 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
15832 @node Construct Layout Control
15833 @subsection Construct Layout Control
15834 @cindex Layout control in @command{gnatpp}
15837 This group of @command{gnatpp} switches controls the layout of comments and
15838 complex syntactic constructs. See @ref{Formatting Comments} for details
15842 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
15843 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
15844 All the comments remain unchanged
15846 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
15847 GNAT-style comment line indentation (this is the default).
15849 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
15850 Reference-manual comment line indentation.
15852 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
15853 GNAT-style comment beginning
15855 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
15856 Reformat comment blocks
15858 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
15859 Keep unchanged special form comments
15861 Reformat comment blocks
15863 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
15864 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
15865 GNAT-style layout (this is the default)
15867 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
15870 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
15873 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
15875 All the VT characters are removed from the comment text. All the HT characters
15876 are expanded with the sequences of space characters to get to the next tab
15879 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
15880 @item ^--no-separate-is^/NO_SEPARATE_IS^
15881 Do not place the keyword @code{is} on a separate line in a subprogram body in
15882 case if the spec occupies more then one line.
15884 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
15885 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
15886 Place the keyword @code{loop} in FOR and WHILE loop statements and the
15887 keyword @code{then} in IF statements on a separate line.
15889 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
15890 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
15891 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
15892 keyword @code{then} in IF statements on a separate line. This option is
15893 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
15895 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
15896 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
15897 Start each USE clause in a context clause from a separate line.
15899 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
15900 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
15901 Use a separate line for a loop or block statement name, but do not use an extra
15902 indentation level for the statement itself.
15908 The @option{-c1} and @option{-c2} switches are incompatible.
15909 The @option{-c3} and @option{-c4} switches are compatible with each other and
15910 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
15911 the other comment formatting switches.
15913 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
15918 For the @option{/COMMENTS_LAYOUT} qualifier:
15921 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
15923 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
15924 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
15928 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
15929 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
15932 @node General Text Layout Control
15933 @subsection General Text Layout Control
15936 These switches allow control over line length and indentation.
15939 @item ^-M@i{nnn}^/LINE_LENGTH_MAX=@i{nnn}^
15940 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
15941 Maximum line length, @i{nnn} from 32@dots{}256, the default value is 79
15943 @item ^-i@i{nnn}^/INDENTATION_LEVEL=@i{nnn}^
15944 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
15945 Indentation level, @i{nnn} from 1@dots{}9, the default value is 3
15947 @item ^-cl@i{nnn}^/CONTINUATION_INDENT=@i{nnn}^
15948 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
15949 Indentation level for continuation lines (relative to the line being
15950 continued), @i{nnn} from 1@dots{}9.
15952 value is one less then the (normal) indentation level, unless the
15953 indentation is set to 1 (in which case the default value for continuation
15954 line indentation is also 1)
15957 @node Other Formatting Options
15958 @subsection Other Formatting Options
15961 These switches control the inclusion of missing end/exit labels, and
15962 the indentation level in @b{case} statements.
15965 @item ^-e^/NO_MISSED_LABELS^
15966 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
15967 Do not insert missing end/exit labels. An end label is the name of
15968 a construct that may optionally be repeated at the end of the
15969 construct's declaration;
15970 e.g., the names of packages, subprograms, and tasks.
15971 An exit label is the name of a loop that may appear as target
15972 of an exit statement within the loop.
15973 By default, @command{gnatpp} inserts these end/exit labels when
15974 they are absent from the original source. This option suppresses such
15975 insertion, so that the formatted source reflects the original.
15977 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
15978 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
15979 Insert a Form Feed character after a pragma Page.
15981 @item ^-T@i{nnn}^/MAX_INDENT=@i{nnn}^
15982 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
15983 Do not use an additional indentation level for @b{case} alternatives
15984 and variants if there are @i{nnn} or more (the default
15986 If @i{nnn} is 0, an additional indentation level is
15987 used for @b{case} alternatives and variants regardless of their number.
15990 @node Setting the Source Search Path
15991 @subsection Setting the Source Search Path
15994 To define the search path for the input source file, @command{gnatpp}
15995 uses the same switches as the GNAT compiler, with the same effects.
15998 @item ^-I^/SEARCH=^@var{dir}
15999 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
16000 The same as the corresponding gcc switch
16002 @item ^-I-^/NOCURRENT_DIRECTORY^
16003 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
16004 The same as the corresponding gcc switch
16006 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
16007 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
16008 The same as the corresponding gcc switch
16010 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
16011 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
16012 The same as the corresponding gcc switch
16016 @node Output File Control
16017 @subsection Output File Control
16020 By default the output is sent to the file whose name is obtained by appending
16021 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
16022 (if the file with this name already exists, it is unconditionally overwritten).
16023 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
16024 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
16026 The output may be redirected by the following switches:
16029 @item ^-pipe^/STANDARD_OUTPUT^
16030 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
16031 Send the output to @code{Standard_Output}
16033 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
16034 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
16035 Write the output into @var{output_file}.
16036 If @var{output_file} already exists, @command{gnatpp} terminates without
16037 reading or processing the input file.
16039 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
16040 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
16041 Write the output into @var{output_file}, overwriting the existing file
16042 (if one is present).
16044 @item ^-r^/REPLACE^
16045 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
16046 Replace the input source file with the reformatted output, and copy the
16047 original input source into the file whose name is obtained by appending the
16048 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
16049 If a file with this name already exists, @command{gnatpp} terminates without
16050 reading or processing the input file.
16052 @item ^-rf^/OVERRIDING_REPLACE^
16053 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
16054 Like @option{^-r^/REPLACE^} except that if the file with the specified name
16055 already exists, it is overwritten.
16057 @item ^-rnb^/REPLACE_NO_BACKUP^
16058 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
16059 Replace the input source file with the reformatted output without
16060 creating any backup copy of the input source.
16062 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
16063 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
16064 Specifies the format of the reformatted output file. The @var{xxx}
16065 ^string specified with the switch^option^ may be either
16067 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
16068 @item ``@option{^crlf^CRLF^}''
16069 the same as @option{^crlf^CRLF^}
16070 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
16071 @item ``@option{^lf^LF^}''
16072 the same as @option{^unix^UNIX^}
16075 @item ^-W^/RESULT_ENCODING=^@var{e}
16076 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
16077 Specify the wide character encoding method used to write the code in the
16079 @var{e} is one of the following:
16087 Upper half encoding
16089 @item ^s^SHIFT_JIS^
16099 Brackets encoding (default value)
16105 Options @option{^-pipe^/STANDARD_OUTPUT^},
16106 @option{^-o^/OUTPUT^} and
16107 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
16108 contains only one file to reformat.
16110 @option{^--eol^/END_OF_LINE^}
16112 @option{^-W^/RESULT_ENCODING^}
16113 cannot be used together
16114 with @option{^-pipe^/STANDARD_OUTPUT^} option.
16116 @node Other gnatpp Switches
16117 @subsection Other @code{gnatpp} Switches
16120 The additional @command{gnatpp} switches are defined in this subsection.
16123 @item ^-files @var{filename}^/FILES=@var{output_file}^
16124 @cindex @option{^-files^/FILES^} (@code{gnatpp})
16125 Take the argument source files from the specified file. This file should be an
16126 ordinary textual file containing file names separated by spaces or
16127 line breaks. You can use this switch more then once in the same call to
16128 @command{gnatpp}. You also can combine this switch with explicit list of
16131 @item ^-v^/VERBOSE^
16132 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
16134 @command{gnatpp} generates version information and then
16135 a trace of the actions it takes to produce or obtain the ASIS tree.
16137 @item ^-w^/WARNINGS^
16138 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
16140 @command{gnatpp} generates a warning whenever it cannot provide
16141 a required layout in the result source.
16144 @node Formatting Rules
16145 @section Formatting Rules
16148 The following subsections show how @command{gnatpp} treats ``white space'',
16149 comments, program layout, and name casing.
16150 They provide the detailed descriptions of the switches shown above.
16153 * White Space and Empty Lines::
16154 * Formatting Comments::
16155 * Construct Layout::
16159 @node White Space and Empty Lines
16160 @subsection White Space and Empty Lines
16163 @command{gnatpp} does not have an option to control space characters.
16164 It will add or remove spaces according to the style illustrated by the
16165 examples in the @cite{Ada Reference Manual}.
16167 The only format effectors
16168 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
16169 that will appear in the output file are platform-specific line breaks,
16170 and also format effectors within (but not at the end of) comments.
16171 In particular, each horizontal tab character that is not inside
16172 a comment will be treated as a space and thus will appear in the
16173 output file as zero or more spaces depending on
16174 the reformatting of the line in which it appears.
16175 The only exception is a Form Feed character, which is inserted after a
16176 pragma @code{Page} when @option{-ff} is set.
16178 The output file will contain no lines with trailing ``white space'' (spaces,
16181 Empty lines in the original source are preserved
16182 only if they separate declarations or statements.
16183 In such contexts, a
16184 sequence of two or more empty lines is replaced by exactly one empty line.
16185 Note that a blank line will be removed if it separates two ``comment blocks''
16186 (a comment block is a sequence of whole-line comments).
16187 In order to preserve a visual separation between comment blocks, use an
16188 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
16189 Likewise, if for some reason you wish to have a sequence of empty lines,
16190 use a sequence of empty comments instead.
16192 @node Formatting Comments
16193 @subsection Formatting Comments
16196 Comments in Ada code are of two kinds:
16199 a @emph{whole-line comment}, which appears by itself (possibly preceded by
16200 ``white space'') on a line
16203 an @emph{end-of-line comment}, which follows some other Ada lexical element
16208 The indentation of a whole-line comment is that of either
16209 the preceding or following line in
16210 the formatted source, depending on switch settings as will be described below.
16212 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
16213 between the end of the preceding Ada lexical element and the beginning
16214 of the comment as appear in the original source,
16215 unless either the comment has to be split to
16216 satisfy the line length limitation, or else the next line contains a
16217 whole line comment that is considered a continuation of this end-of-line
16218 comment (because it starts at the same position).
16220 cases, the start of the end-of-line comment is moved right to the nearest
16221 multiple of the indentation level.
16222 This may result in a ``line overflow'' (the right-shifted comment extending
16223 beyond the maximum line length), in which case the comment is split as
16226 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
16227 (GNAT-style comment line indentation)
16228 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
16229 (reference-manual comment line indentation).
16230 With reference-manual style, a whole-line comment is indented as if it
16231 were a declaration or statement at the same place
16232 (i.e., according to the indentation of the preceding line(s)).
16233 With GNAT style, a whole-line comment that is immediately followed by an
16234 @b{if} or @b{case} statement alternative, a record variant, or the reserved
16235 word @b{begin}, is indented based on the construct that follows it.
16238 @smallexample @c ada
16250 Reference-manual indentation produces:
16252 @smallexample @c ada
16264 while GNAT-style indentation produces:
16266 @smallexample @c ada
16278 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
16279 (GNAT style comment beginning) has the following
16284 For each whole-line comment that does not end with two hyphens,
16285 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
16286 to ensure that there are at least two spaces between these hyphens and the
16287 first non-blank character of the comment.
16291 For an end-of-line comment, if in the original source the next line is a
16292 whole-line comment that starts at the same position
16293 as the end-of-line comment,
16294 then the whole-line comment (and all whole-line comments
16295 that follow it and that start at the same position)
16296 will start at this position in the output file.
16299 That is, if in the original source we have:
16301 @smallexample @c ada
16304 A := B + C; -- B must be in the range Low1..High1
16305 -- C must be in the range Low2..High2
16306 --B+C will be in the range Low1+Low2..High1+High2
16312 Then in the formatted source we get
16314 @smallexample @c ada
16317 A := B + C; -- B must be in the range Low1..High1
16318 -- C must be in the range Low2..High2
16319 -- B+C will be in the range Low1+Low2..High1+High2
16325 A comment that exceeds the line length limit will be split.
16327 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
16328 the line belongs to a reformattable block, splitting the line generates a
16329 @command{gnatpp} warning.
16330 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
16331 comments may be reformatted in typical
16332 word processor style (that is, moving words between lines and putting as
16333 many words in a line as possible).
16336 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
16337 that has a special format (that is, a character that is neither a letter nor digit
16338 not white space nor line break immediately following the leading @code{--} of
16339 the comment) should be without any change moved from the argument source
16340 into reformatted source. This switch allows to preserve comments that are used
16341 as a special marks in the code (e.g.@: SPARK annotation).
16343 @node Construct Layout
16344 @subsection Construct Layout
16347 In several cases the suggested layout in the Ada Reference Manual includes
16348 an extra level of indentation that many programmers prefer to avoid. The
16349 affected cases include:
16353 @item Record type declaration (RM 3.8)
16355 @item Record representation clause (RM 13.5.1)
16357 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
16359 @item Block statement in case if a block has a statement identifier (RM 5.6)
16363 In compact mode (when GNAT style layout or compact layout is set),
16364 the pretty printer uses one level of indentation instead
16365 of two. This is achieved in the record definition and record representation
16366 clause cases by putting the @code{record} keyword on the same line as the
16367 start of the declaration or representation clause, and in the block and loop
16368 case by putting the block or loop header on the same line as the statement
16372 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
16373 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
16374 layout on the one hand, and uncompact layout
16375 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
16376 can be illustrated by the following examples:
16380 @multitable @columnfractions .5 .5
16381 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
16384 @smallexample @c ada
16391 @smallexample @c ada
16400 @smallexample @c ada
16402 a at 0 range 0 .. 31;
16403 b at 4 range 0 .. 31;
16407 @smallexample @c ada
16410 a at 0 range 0 .. 31;
16411 b at 4 range 0 .. 31;
16416 @smallexample @c ada
16424 @smallexample @c ada
16434 @smallexample @c ada
16435 Clear : for J in 1 .. 10 loop
16440 @smallexample @c ada
16442 for J in 1 .. 10 loop
16453 GNAT style, compact layout Uncompact layout
16455 type q is record type q is
16456 a : integer; record
16457 b : integer; a : integer;
16458 end record; b : integer;
16461 for q use record for q use
16462 a at 0 range 0 .. 31; record
16463 b at 4 range 0 .. 31; a at 0 range 0 .. 31;
16464 end record; b at 4 range 0 .. 31;
16467 Block : declare Block :
16468 A : Integer := 3; declare
16469 begin A : Integer := 3;
16471 end Block; Proc (A, A);
16474 Clear : for J in 1 .. 10 loop Clear :
16475 A (J) := 0; for J in 1 .. 10 loop
16476 end loop Clear; A (J) := 0;
16483 A further difference between GNAT style layout and compact layout is that
16484 GNAT style layout inserts empty lines as separation for
16485 compound statements, return statements and bodies.
16487 Note that the layout specified by
16488 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
16489 for named block and loop statements overrides the layout defined by these
16490 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
16491 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
16492 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
16495 @subsection Name Casing
16498 @command{gnatpp} always converts the usage occurrence of a (simple) name to
16499 the same casing as the corresponding defining identifier.
16501 You control the casing for defining occurrences via the
16502 @option{^-n^/NAME_CASING^} switch.
16504 With @option{-nD} (``as declared'', which is the default),
16507 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
16509 defining occurrences appear exactly as in the source file
16510 where they are declared.
16511 The other ^values for this switch^options for this qualifier^ ---
16512 @option{^-nU^UPPER_CASE^},
16513 @option{^-nL^LOWER_CASE^},
16514 @option{^-nM^MIXED_CASE^} ---
16516 ^upper, lower, or mixed case, respectively^the corresponding casing^.
16517 If @command{gnatpp} changes the casing of a defining
16518 occurrence, it analogously changes the casing of all the
16519 usage occurrences of this name.
16521 If the defining occurrence of a name is not in the source compilation unit
16522 currently being processed by @command{gnatpp}, the casing of each reference to
16523 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
16524 switch (subject to the dictionary file mechanism described below).
16525 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
16527 casing for the defining occurrence of the name.
16529 Some names may need to be spelled with casing conventions that are not
16530 covered by the upper-, lower-, and mixed-case transformations.
16531 You can arrange correct casing by placing such names in a
16532 @emph{dictionary file},
16533 and then supplying a @option{^-D^/DICTIONARY^} switch.
16534 The casing of names from dictionary files overrides
16535 any @option{^-n^/NAME_CASING^} switch.
16537 To handle the casing of Ada predefined names and the names from GNAT libraries,
16538 @command{gnatpp} assumes a default dictionary file.
16539 The name of each predefined entity is spelled with the same casing as is used
16540 for the entity in the @cite{Ada Reference Manual}.
16541 The name of each entity in the GNAT libraries is spelled with the same casing
16542 as is used in the declaration of that entity.
16544 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
16545 default dictionary file.
16546 Instead, the casing for predefined and GNAT-defined names will be established
16547 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
16548 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
16549 will appear as just shown,
16550 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
16551 To ensure that even such names are rendered in uppercase,
16552 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
16553 (or else, less conveniently, place these names in upper case in a dictionary
16556 A dictionary file is
16557 a plain text file; each line in this file can be either a blank line
16558 (containing only space characters and ASCII.HT characters), an Ada comment
16559 line, or the specification of exactly one @emph{casing schema}.
16561 A casing schema is a string that has the following syntax:
16565 @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
16567 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
16572 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
16573 @var{identifier} lexical element and the @var{letter_or_digit} category.)
16575 The casing schema string can be followed by white space and/or an Ada-style
16576 comment; any amount of white space is allowed before the string.
16578 If a dictionary file is passed as
16580 the value of a @option{-D@var{file}} switch
16583 an option to the @option{/DICTIONARY} qualifier
16586 simple name and every identifier, @command{gnatpp} checks if the dictionary
16587 defines the casing for the name or for some of its parts (the term ``subword''
16588 is used below to denote the part of a name which is delimited by ``_'' or by
16589 the beginning or end of the word and which does not contain any ``_'' inside):
16593 if the whole name is in the dictionary, @command{gnatpp} uses for this name
16594 the casing defined by the dictionary; no subwords are checked for this word
16597 for every subword @command{gnatpp} checks if the dictionary contains the
16598 corresponding string of the form @code{*@var{simple_identifier}*},
16599 and if it does, the casing of this @var{simple_identifier} is used
16603 if the whole name does not contain any ``_'' inside, and if for this name
16604 the dictionary contains two entries - one of the form @var{identifier},
16605 and another - of the form *@var{simple_identifier}*, then the first one
16606 is applied to define the casing of this name
16609 if more than one dictionary file is passed as @command{gnatpp} switches, each
16610 dictionary adds new casing exceptions and overrides all the existing casing
16611 exceptions set by the previous dictionaries
16614 when @command{gnatpp} checks if the word or subword is in the dictionary,
16615 this check is not case sensitive
16619 For example, suppose we have the following source to reformat:
16621 @smallexample @c ada
16624 name1 : integer := 1;
16625 name4_name3_name2 : integer := 2;
16626 name2_name3_name4 : Boolean;
16629 name2_name3_name4 := name4_name3_name2 > name1;
16635 And suppose we have two dictionaries:
16652 If @command{gnatpp} is called with the following switches:
16656 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
16659 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
16664 then we will get the following name casing in the @command{gnatpp} output:
16666 @smallexample @c ada
16669 NAME1 : Integer := 1;
16670 Name4_NAME3_Name2 : Integer := 2;
16671 Name2_NAME3_Name4 : Boolean;
16674 Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
16679 @c *********************************
16680 @node The GNAT Metric Tool gnatmetric
16681 @chapter The GNAT Metric Tool @command{gnatmetric}
16683 @cindex Metric tool
16686 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
16687 for computing various program metrics.
16688 It takes an Ada source file as input and generates a file containing the
16689 metrics data as output. Various switches control which
16690 metrics are computed and output.
16692 @command{gnatmetric} generates and uses the ASIS
16693 tree for the input source and thus requires the input to be syntactically and
16694 semantically legal.
16695 If this condition is not met, @command{gnatmetric} will generate
16696 an error message; no metric information for this file will be
16697 computed and reported.
16699 If the compilation unit contained in the input source depends semantically
16700 upon units in files located outside the current directory, you have to provide
16701 the source search path when invoking @command{gnatmetric}.
16702 If it depends semantically upon units that are contained
16703 in files with names that do not follow the GNAT file naming rules, you have to
16704 provide the configuration file describing the corresponding naming scheme (see
16705 the description of the @command{gnatmetric} switches below.)
16706 Alternatively, you may use a project file and invoke @command{gnatmetric}
16707 through the @command{gnat} driver.
16709 The @command{gnatmetric} command has the form
16712 $ gnatmetric [@i{switches}] @{@i{filename}@} [@i{-cargs gcc_switches}]
16719 @i{switches} specify the metrics to compute and define the destination for
16723 Each @i{filename} is the name (including the extension) of a source
16724 file to process. ``Wildcards'' are allowed, and
16725 the file name may contain path information.
16726 If no @i{filename} is supplied, then the @i{switches} list must contain
16728 @option{-files} switch (@pxref{Other gnatmetric Switches}).
16729 Including both a @option{-files} switch and one or more
16730 @i{filename} arguments is permitted.
16733 @i{-cargs gcc_switches} is a list of switches for
16734 @command{gcc}. They will be passed on to all compiler invocations made by
16735 @command{gnatmetric} to generate the ASIS trees. Here you can provide
16736 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
16737 and use the @option{-gnatec} switch to set the configuration file.
16741 * Switches for gnatmetric::
16744 @node Switches for gnatmetric
16745 @section Switches for @command{gnatmetric}
16748 The following subsections describe the various switches accepted by
16749 @command{gnatmetric}, organized by category.
16752 * Output Files Control::
16753 * Disable Metrics For Local Units::
16754 * Specifying a set of metrics to compute::
16755 * Other gnatmetric Switches::
16756 * Generate project-wide metrics::
16759 @node Output Files Control
16760 @subsection Output File Control
16761 @cindex Output file control in @command{gnatmetric}
16764 @command{gnatmetric} has two output formats. It can generate a
16765 textual (human-readable) form, and also XML. By default only textual
16766 output is generated.
16768 When generating the output in textual form, @command{gnatmetric} creates
16769 for each Ada source file a corresponding text file
16770 containing the computed metrics, except for the case when the set of metrics
16771 specified by gnatmetric parameters consists only of metrics that are computed
16772 for the whole set of analyzed sources, but not for each Ada source.
16773 By default, this file is placed in the same directory as where the source
16774 file is located, and its name is obtained
16775 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
16778 All the output information generated in XML format is placed in a single
16779 file. By default this file is placed in the current directory and has the
16780 name ^@file{metrix.xml}^@file{METRIX$XML}^.
16782 Some of the computed metrics are summed over the units passed to
16783 @command{gnatmetric}; for example, the total number of lines of code.
16784 By default this information is sent to @file{stdout}, but a file
16785 can be specified with the @option{-og} switch.
16787 The following switches control the @command{gnatmetric} output:
16790 @cindex @option{^-x^/XML^} (@command{gnatmetric})
16792 Generate the XML output
16794 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
16795 @item ^-nt^/NO_TEXT^
16796 Do not generate the output in text form (implies @option{^-x^/XML^})
16798 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
16799 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
16800 Put textual files with detailed metrics into @var{output_dir}
16802 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
16803 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
16804 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
16805 in the name of the output file.
16807 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
16808 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
16809 Put global metrics into @var{file_name}
16811 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
16812 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
16813 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
16815 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
16816 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
16817 Use ``short'' source file names in the output. (The @command{gnatmetric}
16818 output includes the name(s) of the Ada source file(s) from which the metrics
16819 are computed. By default each name includes the absolute path. The
16820 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
16821 to exclude all directory information from the file names that are output.)
16825 @node Disable Metrics For Local Units
16826 @subsection Disable Metrics For Local Units
16827 @cindex Disable Metrics For Local Units in @command{gnatmetric}
16830 @command{gnatmetric} relies on the GNAT compilation model @minus{}
16832 unit per one source file. It computes line metrics for the whole source
16833 file, and it also computes syntax
16834 and complexity metrics for the file's outermost unit.
16836 By default, @command{gnatmetric} will also compute all metrics for certain
16837 kinds of locally declared program units:
16841 subprogram (and generic subprogram) bodies;
16844 package (and generic package) specs and bodies;
16847 task object and type specifications and bodies;
16850 protected object and type specifications and bodies.
16854 These kinds of entities will be referred to as
16855 @emph{eligible local program units}, or simply @emph{eligible local units},
16856 @cindex Eligible local unit (for @command{gnatmetric})
16857 in the discussion below.
16859 Note that a subprogram declaration, generic instantiation,
16860 or renaming declaration only receives metrics
16861 computation when it appear as the outermost entity
16864 Suppression of metrics computation for eligible local units can be
16865 obtained via the following switch:
16868 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
16869 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
16870 Do not compute detailed metrics for eligible local program units
16874 @node Specifying a set of metrics to compute
16875 @subsection Specifying a set of metrics to compute
16878 By default all the metrics are computed and reported. The switches
16879 described in this subsection allow you to control, on an individual
16880 basis, whether metrics are computed and
16881 reported. If at least one positive metric
16882 switch is specified (that is, a switch that defines that a given
16883 metric or set of metrics is to be computed), then only
16884 explicitly specified metrics are reported.
16887 * Line Metrics Control::
16888 * Syntax Metrics Control::
16889 * Complexity Metrics Control::
16890 * Object-Oriented Metrics Control::
16893 @node Line Metrics Control
16894 @subsubsection Line Metrics Control
16895 @cindex Line metrics control in @command{gnatmetric}
16898 For any (legal) source file, and for each of its
16899 eligible local program units, @command{gnatmetric} computes the following
16904 the total number of lines;
16907 the total number of code lines (i.e., non-blank lines that are not comments)
16910 the number of comment lines
16913 the number of code lines containing end-of-line comments;
16916 the comment percentage: the ratio between the number of lines that contain
16917 comments and the number of all non-blank lines, expressed as a percentage;
16920 the number of empty lines and lines containing only space characters and/or
16921 format effectors (blank lines)
16924 the average number of code lines in subprogram bodies, task bodies, entry
16925 bodies and statement sequences in package bodies (this metric is only computed
16926 across the whole set of the analyzed units)
16931 @command{gnatmetric} sums the values of the line metrics for all the
16932 files being processed and then generates the cumulative results. The tool
16933 also computes for all the files being processed the average number of code
16936 You can use the following switches to select the specific line metrics
16937 to be computed and reported.
16940 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
16943 @cindex @option{--no-lines@var{x}}
16946 @item ^--lines-all^/LINE_COUNT_METRICS=ALL_ON^
16947 Report all the line metrics
16949 @item ^--no-lines-all^/LINE_COUNT_METRICS=ALL_OFF^
16950 Do not report any of line metrics
16952 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES_ON^
16953 Report the number of all lines
16955 @item ^--no-lines^/LINE_COUNT_METRICS=ALL_LINES_OFF^
16956 Do not report the number of all lines
16958 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES_ON^
16959 Report the number of code lines
16961 @item ^--no-lines-code^/LINE_COUNT_METRICS=CODE_LINES_OFF^
16962 Do not report the number of code lines
16964 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES_ON^
16965 Report the number of comment lines
16967 @item ^--no-lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES_OFF^
16968 Do not report the number of comment lines
16970 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES_ON^
16971 Report the number of code lines containing
16972 end-of-line comments
16974 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES_OFF^
16975 Do not report the number of code lines containing
16976 end-of-line comments
16978 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE_ON^
16979 Report the comment percentage in the program text
16981 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE_OFF^
16982 Do not report the comment percentage in the program text
16984 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES_ON^
16985 Report the number of blank lines
16987 @item ^--no-lines-blank^/LINE_COUNT_METRICS=BLANK_LINES_OFF^
16988 Do not report the number of blank lines
16990 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES_ON^
16991 Report the average number of code lines in subprogram bodies, task bodies,
16992 entry bodies and statement sequences in package bodies. The metric is computed
16993 and reported for the whole set of processed Ada sources only.
16995 @item ^--no-lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES_OFF^
16996 Do not report the average number of code lines in subprogram bodies,
16997 task bodies, entry bodies and statement sequences in package bodies.
17001 @node Syntax Metrics Control
17002 @subsubsection Syntax Metrics Control
17003 @cindex Syntax metrics control in @command{gnatmetric}
17006 @command{gnatmetric} computes various syntactic metrics for the
17007 outermost unit and for each eligible local unit:
17010 @item LSLOC (``Logical Source Lines Of Code'')
17011 The total number of declarations and the total number of statements
17013 @item Maximal static nesting level of inner program units
17015 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
17016 package, a task unit, a protected unit, a
17017 protected entry, a generic unit, or an explicitly declared subprogram other
17018 than an enumeration literal.''
17020 @item Maximal nesting level of composite syntactic constructs
17021 This corresponds to the notion of the
17022 maximum nesting level in the GNAT built-in style checks
17023 (@pxref{Style Checking})
17027 For the outermost unit in the file, @command{gnatmetric} additionally computes
17028 the following metrics:
17031 @item Public subprograms
17032 This metric is computed for package specs. It is the
17033 number of subprograms and generic subprograms declared in the visible
17034 part (including the visible part of nested packages, protected objects, and
17037 @item All subprograms
17038 This metric is computed for bodies and subunits. The
17039 metric is equal to a total number of subprogram bodies in the compilation
17041 Neither generic instantiations nor renamings-as-a-body nor body stubs
17042 are counted. Any subprogram body is counted, independently of its nesting
17043 level and enclosing constructs. Generic bodies and bodies of protected
17044 subprograms are counted in the same way as ``usual'' subprogram bodies.
17047 This metric is computed for package specs and
17048 generic package declarations. It is the total number of types
17049 that can be referenced from outside this compilation unit, plus the
17050 number of types from all the visible parts of all the visible generic
17051 packages. Generic formal types are not counted. Only types, not subtypes,
17055 Along with the total number of public types, the following
17056 types are counted and reported separately:
17063 Root tagged types (abstract, non-abstract, private, non-private). Type
17064 extensions are @emph{not} counted
17067 Private types (including private extensions)
17078 This metric is computed for any compilation unit. It is equal to the total
17079 number of the declarations of different types given in the compilation unit.
17080 The private and the corresponding full type declaration are counted as one
17081 type declaration. Incomplete type declarations and generic formal types
17083 No distinction is made among different kinds of types (abstract,
17084 private etc.); the total number of types is computed and reported.
17089 By default, all the syntax metrics are computed and reported. You can use the
17090 following switches to select specific syntax metrics.
17094 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
17097 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
17100 @item ^--syntax-all^/SYNTAX_METRICS=ALL_ON^
17101 Report all the syntax metrics
17103 @item ^--no-syntax-all^/ALL_OFF^
17104 Do not report any of syntax metrics
17106 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS_ON^
17107 Report the total number of declarations
17109 @item ^--no-declarations^/SYNTAX_METRICS=DECLARATIONS_OFF^
17110 Do not report the total number of declarations
17112 @item ^--statements^/SYNTAX_METRICS=STATEMENTS_ON^
17113 Report the total number of statements
17115 @item ^--no-statements^/SYNTAX_METRICS=STATEMENTS_OFF^
17116 Do not report the total number of statements
17118 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS_ON^
17119 Report the number of public subprograms in a compilation unit
17121 @item ^--no-public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS_OFF^
17122 Do not report the number of public subprograms in a compilation unit
17124 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS_ON^
17125 Report the number of all the subprograms in a compilation unit
17127 @item ^--no-all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS_OFF^
17128 Do not report the number of all the subprograms in a compilation unit
17130 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES_ON^
17131 Report the number of public types in a compilation unit
17133 @item ^--no-public-types^/SYNTAX_METRICS=PUBLIC_TYPES_OFF^
17134 Do not report the number of public types in a compilation unit
17136 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES_ON^
17137 Report the number of all the types in a compilation unit
17139 @item ^--no-all-types^/SYNTAX_METRICS=ALL_TYPES_OFF^
17140 Do not report the number of all the types in a compilation unit
17142 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_ON^
17143 Report the maximal program unit nesting level
17145 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
17146 Do not report the maximal program unit nesting level
17148 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING_ON^
17149 Report the maximal construct nesting level
17151 @item ^--no-construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING_OFF^
17152 Do not report the maximal construct nesting level
17156 @node Complexity Metrics Control
17157 @subsubsection Complexity Metrics Control
17158 @cindex Complexity metrics control in @command{gnatmetric}
17161 For a program unit that is an executable body (a subprogram body (including
17162 generic bodies), task body, entry body or a package body containing
17163 its own statement sequence) @command{gnatmetric} computes the following
17164 complexity metrics:
17168 McCabe cyclomatic complexity;
17171 McCabe essential complexity;
17174 maximal loop nesting level
17179 The McCabe complexity metrics are defined
17180 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
17182 According to McCabe, both control statements and short-circuit control forms
17183 should be taken into account when computing cyclomatic complexity. For each
17184 body, we compute three metric values:
17188 the complexity introduced by control
17189 statements only, without taking into account short-circuit forms,
17192 the complexity introduced by short-circuit control forms only, and
17196 cyclomatic complexity, which is the sum of these two values.
17200 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
17201 the code in the exception handlers and in all the nested program units.
17203 By default, all the complexity metrics are computed and reported.
17204 For more fine-grained control you can use
17205 the following switches:
17208 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
17211 @cindex @option{--no-complexity@var{x}}
17214 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL_ON^
17215 Report all the complexity metrics
17217 @item ^--no-complexity-all^/COMPLEXITY_METRICS=ALL_OFF^
17218 Do not report any of complexity metrics
17220 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC_ON^
17221 Report the McCabe Cyclomatic Complexity
17223 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC_OFF^
17224 Do not report the McCabe Cyclomatic Complexity
17226 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL_ON^
17227 Report the Essential Complexity
17229 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL_OFF^
17230 Do not report the Essential Complexity
17232 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
17233 Report maximal loop nesting level
17235 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_OFF^
17236 Do not report maximal loop nesting level
17238 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY_ON^
17239 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
17240 task bodies, entry bodies and statement sequences in package bodies.
17241 The metric is computed and reported for whole set of processed Ada sources
17244 @item ^--no-complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY_OFF^
17245 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
17246 bodies, task bodies, entry bodies and statement sequences in package bodies
17248 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
17249 @item ^-ne^/NO_EXITS_AS_GOTOS^
17250 Do not consider @code{exit} statements as @code{goto}s when
17251 computing Essential Complexity
17256 @node Object-Oriented Metrics Control
17257 @subsubsection Object-Oriented Metrics Control
17258 @cindex Object-Oriented metrics control in @command{gnatmetric}
17261 @cindex Coupling metrics (in in @command{gnatmetric})
17262 Coupling metrics are object-oriented metrics that measure the
17263 dependencies between a given class (or a group of classes) and the
17264 ``external world'' (that is, the other classes in the program). In this
17265 subsection the term ``class'' is used in its
17266 traditional object-oriented programming sense
17267 (an instantiable module that contains data and/or method members).
17268 A @emph{category} (of classes)
17269 is a group of closely related classes that are reused and/or
17272 A class @code{K}'s @emph{efferent coupling} is the number of classes
17273 that @code{K} depends upon.
17274 A category's efferent coupling is the number of classes outside the
17275 category that the classes inside the category depend upon.
17277 A class @code{K}'s @emph{afferent coupling} is the number of classes
17278 that depend upon @code{K}.
17279 A category's afferent coupling is the number of classes outside the
17280 category that depend on classes belonging to the category.
17282 Ada's implementation of the object-oriented paradigm does not use the
17283 traditional class notion, so the definition of the coupling
17284 metrics for Ada maps the class and class category notions
17285 onto Ada constructs.
17287 For the coupling metrics, several kinds of modules -- a library package,
17288 a library generic package, and a library generic package instantiation --
17289 that define a tagged type or an interface type are
17290 considered to be a class. A category consists of a library package (or
17291 a library generic package) that defines a tagged or an interface type,
17292 together with all its descendant (generic) packages that define tagged
17293 or interface types. For any package counted as a class,
17294 its body (if any) is considered
17295 together with its spec when counting the dependencies. For dependencies
17296 between classes, the Ada semantic dependencies are considered.
17297 For coupling metrics, only dependencies on units that are considered as
17298 classes, are considered.
17300 When computing coupling metrics, @command{gnatmetric} counts only
17301 dependencies between units that are arguments of the gnatmetric call.
17302 Coupling metrics are program-wide (or project-wide) metrics, so to
17303 get a valid result, you should call @command{gnatmetric} for
17304 the whole set of sources that make up your program. It can be done
17305 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
17306 option (see See @ref{The GNAT Driver and Project Files} for details.
17308 By default, all the coupling metrics are disabled. You can use the following
17309 switches to specify the coupling metrics to be computed and reported:
17314 @cindex @option{--package@var{x}} (@command{gnatmetric})
17315 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
17316 @cindex @option{--category@var{x}} (@command{gnatmetric})
17317 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
17321 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
17324 @item ^--coupling-all^/COUPLING_METRICS=ALL_ON^
17325 Report all the coupling metrics
17327 @item ^--no-coupling-all^/COUPLING_METRICS=ALL_OFF^
17328 Do not report any of metrics
17330 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT_ON^
17331 Report package efferent coupling
17333 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT_OFF^
17334 Do not report package efferent coupling
17336 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT_ON^
17337 Report package afferent coupling
17339 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT_OFF^
17340 Do not report package afferent coupling
17342 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT_ON^
17343 Report category efferent coupling
17345 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT_OFF^
17346 Do not report category efferent coupling
17348 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT_ON^
17349 Report category afferent coupling
17351 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT_OFF^
17352 Do not report category afferent coupling
17356 @node Other gnatmetric Switches
17357 @subsection Other @code{gnatmetric} Switches
17360 Additional @command{gnatmetric} switches are as follows:
17363 @item ^-files @var{filename}^/FILES=@var{filename}^
17364 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
17365 Take the argument source files from the specified file. This file should be an
17366 ordinary text file containing file names separated by spaces or
17367 line breaks. You can use this switch more then once in the same call to
17368 @command{gnatmetric}. You also can combine this switch with
17369 an explicit list of files.
17371 @item ^-v^/VERBOSE^
17372 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
17374 @command{gnatmetric} generates version information and then
17375 a trace of sources being processed.
17377 @item ^-dv^/DEBUG_OUTPUT^
17378 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
17380 @command{gnatmetric} generates various messages useful to understand what
17381 happens during the metrics computation
17384 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
17388 @node Generate project-wide metrics
17389 @subsection Generate project-wide metrics
17391 In order to compute metrics on all units of a given project, you can use
17392 the @command{gnat} driver along with the @option{-P} option:
17398 If the project @code{proj} depends upon other projects, you can compute
17399 the metrics on the project closure using the @option{-U} option:
17401 gnat metric -Pproj -U
17405 Finally, if not all the units are relevant to a particular main
17406 program in the project closure, you can generate metrics for the set
17407 of units needed to create a given main program (unit closure) using
17408 the @option{-U} option followed by the name of the main unit:
17410 gnat metric -Pproj -U main
17414 @c ***********************************
17415 @node File Name Krunching Using gnatkr
17416 @chapter File Name Krunching Using @code{gnatkr}
17420 This chapter discusses the method used by the compiler to shorten
17421 the default file names chosen for Ada units so that they do not
17422 exceed the maximum length permitted. It also describes the
17423 @code{gnatkr} utility that can be used to determine the result of
17424 applying this shortening.
17428 * Krunching Method::
17429 * Examples of gnatkr Usage::
17433 @section About @code{gnatkr}
17436 The default file naming rule in GNAT
17437 is that the file name must be derived from
17438 the unit name. The exact default rule is as follows:
17441 Take the unit name and replace all dots by hyphens.
17443 If such a replacement occurs in the
17444 second character position of a name, and the first character is
17445 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
17446 then replace the dot by the character
17447 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
17448 instead of a minus.
17450 The reason for this exception is to avoid clashes
17451 with the standard names for children of System, Ada, Interfaces,
17452 and GNAT, which use the prefixes
17453 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
17456 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
17457 switch of the compiler activates a ``krunching''
17458 circuit that limits file names to nn characters (where nn is a decimal
17459 integer). For example, using OpenVMS,
17460 where the maximum file name length is
17461 39, the value of nn is usually set to 39, but if you want to generate
17462 a set of files that would be usable if ported to a system with some
17463 different maximum file length, then a different value can be specified.
17464 The default value of 39 for OpenVMS need not be specified.
17466 The @code{gnatkr} utility can be used to determine the krunched name for
17467 a given file, when krunched to a specified maximum length.
17470 @section Using @code{gnatkr}
17473 The @code{gnatkr} command has the form
17477 $ gnatkr @var{name} [@var{length}]
17483 $ gnatkr @var{name} /COUNT=nn
17488 @var{name} is the uncrunched file name, derived from the name of the unit
17489 in the standard manner described in the previous section (i.e., in particular
17490 all dots are replaced by hyphens). The file name may or may not have an
17491 extension (defined as a suffix of the form period followed by arbitrary
17492 characters other than period). If an extension is present then it will
17493 be preserved in the output. For example, when krunching @file{hellofile.ads}
17494 to eight characters, the result will be hellofil.ads.
17496 Note: for compatibility with previous versions of @code{gnatkr} dots may
17497 appear in the name instead of hyphens, but the last dot will always be
17498 taken as the start of an extension. So if @code{gnatkr} is given an argument
17499 such as @file{Hello.World.adb} it will be treated exactly as if the first
17500 period had been a hyphen, and for example krunching to eight characters
17501 gives the result @file{hellworl.adb}.
17503 Note that the result is always all lower case (except on OpenVMS where it is
17504 all upper case). Characters of the other case are folded as required.
17506 @var{length} represents the length of the krunched name. The default
17507 when no argument is given is ^8^39^ characters. A length of zero stands for
17508 unlimited, in other words do not chop except for system files where the
17509 implied crunching length is always eight characters.
17512 The output is the krunched name. The output has an extension only if the
17513 original argument was a file name with an extension.
17515 @node Krunching Method
17516 @section Krunching Method
17519 The initial file name is determined by the name of the unit that the file
17520 contains. The name is formed by taking the full expanded name of the
17521 unit and replacing the separating dots with hyphens and
17522 using ^lowercase^uppercase^
17523 for all letters, except that a hyphen in the second character position is
17524 replaced by a ^tilde^dollar sign^ if the first character is
17525 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
17526 The extension is @code{.ads} for a
17527 spec and @code{.adb} for a body.
17528 Krunching does not affect the extension, but the file name is shortened to
17529 the specified length by following these rules:
17533 The name is divided into segments separated by hyphens, tildes or
17534 underscores and all hyphens, tildes, and underscores are
17535 eliminated. If this leaves the name short enough, we are done.
17538 If the name is too long, the longest segment is located (left-most
17539 if there are two of equal length), and shortened by dropping
17540 its last character. This is repeated until the name is short enough.
17542 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
17543 to fit the name into 8 characters as required by some operating systems.
17546 our-strings-wide_fixed 22
17547 our strings wide fixed 19
17548 our string wide fixed 18
17549 our strin wide fixed 17
17550 our stri wide fixed 16
17551 our stri wide fixe 15
17552 our str wide fixe 14
17553 our str wid fixe 13
17559 Final file name: oustwifi.adb
17563 The file names for all predefined units are always krunched to eight
17564 characters. The krunching of these predefined units uses the following
17565 special prefix replacements:
17569 replaced by @file{^a^A^-}
17572 replaced by @file{^g^G^-}
17575 replaced by @file{^i^I^-}
17578 replaced by @file{^s^S^-}
17581 These system files have a hyphen in the second character position. That
17582 is why normal user files replace such a character with a
17583 ^tilde^dollar sign^, to
17584 avoid confusion with system file names.
17586 As an example of this special rule, consider
17587 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
17590 ada-strings-wide_fixed 22
17591 a- strings wide fixed 18
17592 a- string wide fixed 17
17593 a- strin wide fixed 16
17594 a- stri wide fixed 15
17595 a- stri wide fixe 14
17596 a- str wide fixe 13
17602 Final file name: a-stwifi.adb
17606 Of course no file shortening algorithm can guarantee uniqueness over all
17607 possible unit names, and if file name krunching is used then it is your
17608 responsibility to ensure that no name clashes occur. The utility
17609 program @code{gnatkr} is supplied for conveniently determining the
17610 krunched name of a file.
17612 @node Examples of gnatkr Usage
17613 @section Examples of @code{gnatkr} Usage
17620 $ gnatkr very_long_unit_name.ads --> velounna.ads
17621 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
17622 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
17623 $ gnatkr grandparent-parent-child --> grparchi
17625 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
17626 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
17629 @node Preprocessing Using gnatprep
17630 @chapter Preprocessing Using @code{gnatprep}
17634 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
17636 Although designed for use with GNAT, @code{gnatprep} does not depend on any
17637 special GNAT features.
17638 For further discussion of conditional compilation in general, see
17639 @ref{Conditional Compilation}.
17642 * Preprocessing Symbols::
17644 * Switches for gnatprep::
17645 * Form of Definitions File::
17646 * Form of Input Text for gnatprep::
17649 @node Preprocessing Symbols
17650 @section Preprocessing Symbols
17653 Preprocessing symbols are defined in definition files and referred to in
17654 sources to be preprocessed. A Preprocessing symbol is an identifier, following
17655 normal Ada (case-insensitive) rules for its syntax, with the restriction that
17656 all characters need to be in the ASCII set (no accented letters).
17658 @node Using gnatprep
17659 @section Using @code{gnatprep}
17662 To call @code{gnatprep} use
17665 $ gnatprep [switches] infile outfile [deffile]
17672 is an optional sequence of switches as described in the next section.
17675 is the full name of the input file, which is an Ada source
17676 file containing preprocessor directives.
17679 is the full name of the output file, which is an Ada source
17680 in standard Ada form. When used with GNAT, this file name will
17681 normally have an ads or adb suffix.
17684 is the full name of a text file containing definitions of
17685 preprocessing symbols to be referenced by the preprocessor. This argument is
17686 optional, and can be replaced by the use of the @option{-D} switch.
17690 @node Switches for gnatprep
17691 @section Switches for @code{gnatprep}
17696 @item ^-b^/BLANK_LINES^
17697 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
17698 Causes both preprocessor lines and the lines deleted by
17699 preprocessing to be replaced by blank lines in the output source file,
17700 preserving line numbers in the output file.
17702 @item ^-c^/COMMENTS^
17703 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
17704 Causes both preprocessor lines and the lines deleted
17705 by preprocessing to be retained in the output source as comments marked
17706 with the special string @code{"--! "}. This option will result in line numbers
17707 being preserved in the output file.
17709 @item ^-C^/REPLACE_IN_COMMENTS^
17710 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
17711 Causes comments to be scanned. Normally comments are ignored by gnatprep.
17712 If this option is specified, then comments are scanned and any $symbol
17713 substitutions performed as in program text. This is particularly useful
17714 when structured comments are used (e.g., when writing programs in the
17715 SPARK dialect of Ada). Note that this switch is not available when
17716 doing integrated preprocessing (it would be useless in this context
17717 since comments are ignored by the compiler in any case).
17719 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
17720 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
17721 Defines a new preprocessing symbol, associated with value. If no value is given
17722 on the command line, then symbol is considered to be @code{True}. This switch
17723 can be used in place of a definition file.
17727 @cindex @option{/REMOVE} (@command{gnatprep})
17728 This is the default setting which causes lines deleted by preprocessing
17729 to be entirely removed from the output file.
17732 @item ^-r^/REFERENCE^
17733 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
17734 Causes a @code{Source_Reference} pragma to be generated that
17735 references the original input file, so that error messages will use
17736 the file name of this original file. The use of this switch implies
17737 that preprocessor lines are not to be removed from the file, so its
17738 use will force @option{^-b^/BLANK_LINES^} mode if
17739 @option{^-c^/COMMENTS^}
17740 has not been specified explicitly.
17742 Note that if the file to be preprocessed contains multiple units, then
17743 it will be necessary to @code{gnatchop} the output file from
17744 @code{gnatprep}. If a @code{Source_Reference} pragma is present
17745 in the preprocessed file, it will be respected by
17746 @code{gnatchop ^-r^/REFERENCE^}
17747 so that the final chopped files will correctly refer to the original
17748 input source file for @code{gnatprep}.
17750 @item ^-s^/SYMBOLS^
17751 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
17752 Causes a sorted list of symbol names and values to be
17753 listed on the standard output file.
17755 @item ^-u^/UNDEFINED^
17756 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
17757 Causes undefined symbols to be treated as having the value FALSE in the context
17758 of a preprocessor test. In the absence of this option, an undefined symbol in
17759 a @code{#if} or @code{#elsif} test will be treated as an error.
17765 Note: if neither @option{-b} nor @option{-c} is present,
17766 then preprocessor lines and
17767 deleted lines are completely removed from the output, unless -r is
17768 specified, in which case -b is assumed.
17771 @node Form of Definitions File
17772 @section Form of Definitions File
17775 The definitions file contains lines of the form
17782 where symbol is a preprocessing symbol, and value is one of the following:
17786 Empty, corresponding to a null substitution
17788 A string literal using normal Ada syntax
17790 Any sequence of characters from the set
17791 (letters, digits, period, underline).
17795 Comment lines may also appear in the definitions file, starting with
17796 the usual @code{--},
17797 and comments may be added to the definitions lines.
17799 @node Form of Input Text for gnatprep
17800 @section Form of Input Text for @code{gnatprep}
17803 The input text may contain preprocessor conditional inclusion lines,
17804 as well as general symbol substitution sequences.
17806 The preprocessor conditional inclusion commands have the form
17811 #if @i{expression} [then]
17813 #elsif @i{expression} [then]
17815 #elsif @i{expression} [then]
17826 In this example, @i{expression} is defined by the following grammar:
17828 @i{expression} ::= <symbol>
17829 @i{expression} ::= <symbol> = "<value>"
17830 @i{expression} ::= <symbol> = <symbol>
17831 @i{expression} ::= <symbol> 'Defined
17832 @i{expression} ::= not @i{expression}
17833 @i{expression} ::= @i{expression} and @i{expression}
17834 @i{expression} ::= @i{expression} or @i{expression}
17835 @i{expression} ::= @i{expression} and then @i{expression}
17836 @i{expression} ::= @i{expression} or else @i{expression}
17837 @i{expression} ::= ( @i{expression} )
17840 The following restriction exists: it is not allowed to have "and" or "or"
17841 following "not" in the same expression without parentheses. For example, this
17848 This should be one of the following:
17856 For the first test (@i{expression} ::= <symbol>) the symbol must have
17857 either the value true or false, that is to say the right-hand of the
17858 symbol definition must be one of the (case-insensitive) literals
17859 @code{True} or @code{False}. If the value is true, then the
17860 corresponding lines are included, and if the value is false, they are
17863 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
17864 the symbol has been defined in the definition file or by a @option{-D}
17865 switch on the command line. Otherwise, the test is false.
17867 The equality tests are case insensitive, as are all the preprocessor lines.
17869 If the symbol referenced is not defined in the symbol definitions file,
17870 then the effect depends on whether or not switch @option{-u}
17871 is specified. If so, then the symbol is treated as if it had the value
17872 false and the test fails. If this switch is not specified, then
17873 it is an error to reference an undefined symbol. It is also an error to
17874 reference a symbol that is defined with a value other than @code{True}
17877 The use of the @code{not} operator inverts the sense of this logical test.
17878 The @code{not} operator cannot be combined with the @code{or} or @code{and}
17879 operators, without parentheses. For example, "if not X or Y then" is not
17880 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
17882 The @code{then} keyword is optional as shown
17884 The @code{#} must be the first non-blank character on a line, but
17885 otherwise the format is free form. Spaces or tabs may appear between
17886 the @code{#} and the keyword. The keywords and the symbols are case
17887 insensitive as in normal Ada code. Comments may be used on a
17888 preprocessor line, but other than that, no other tokens may appear on a
17889 preprocessor line. Any number of @code{elsif} clauses can be present,
17890 including none at all. The @code{else} is optional, as in Ada.
17892 The @code{#} marking the start of a preprocessor line must be the first
17893 non-blank character on the line, i.e., it must be preceded only by
17894 spaces or horizontal tabs.
17896 Symbol substitution outside of preprocessor lines is obtained by using
17904 anywhere within a source line, except in a comment or within a
17905 string literal. The identifier
17906 following the @code{$} must match one of the symbols defined in the symbol
17907 definition file, and the result is to substitute the value of the
17908 symbol in place of @code{$symbol} in the output file.
17910 Note that although the substitution of strings within a string literal
17911 is not possible, it is possible to have a symbol whose defined value is
17912 a string literal. So instead of setting XYZ to @code{hello} and writing:
17915 Header : String := "$XYZ";
17919 you should set XYZ to @code{"hello"} and write:
17922 Header : String := $XYZ;
17926 and then the substitution will occur as desired.
17929 @node The GNAT Run-Time Library Builder gnatlbr
17930 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
17932 @cindex Library builder
17935 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
17936 supplied configuration pragmas.
17939 * Running gnatlbr::
17940 * Switches for gnatlbr::
17941 * Examples of gnatlbr Usage::
17944 @node Running gnatlbr
17945 @section Running @code{gnatlbr}
17948 The @code{gnatlbr} command has the form
17951 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
17954 @node Switches for gnatlbr
17955 @section Switches for @code{gnatlbr}
17958 @code{gnatlbr} recognizes the following switches:
17962 @item /CREATE=directory
17963 @cindex @code{/CREATE} (@code{gnatlbr})
17964 Create the new run-time library in the specified directory.
17966 @item /SET=directory
17967 @cindex @code{/SET} (@code{gnatlbr})
17968 Make the library in the specified directory the current run-time
17971 @item /DELETE=directory
17972 @cindex @code{/DELETE} (@code{gnatlbr})
17973 Delete the run-time library in the specified directory.
17976 @cindex @code{/CONFIG} (@code{gnatlbr})
17978 Use the configuration pragmas in the specified file when building
17982 Use the configuration pragmas in the specified file when compiling.
17986 @node Examples of gnatlbr Usage
17987 @section Example of @code{gnatlbr} Usage
17990 Contents of VAXFLOAT.ADC:
17991 pragma Float_Representation (VAX_Float);
17993 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
17995 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
18000 @node The GNAT Library Browser gnatls
18001 @chapter The GNAT Library Browser @code{gnatls}
18003 @cindex Library browser
18006 @code{gnatls} is a tool that outputs information about compiled
18007 units. It gives the relationship between objects, unit names and source
18008 files. It can also be used to check the source dependencies of a unit
18009 as well as various characteristics.
18011 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
18012 driver (see @ref{The GNAT Driver and Project Files}).
18016 * Switches for gnatls::
18017 * Examples of gnatls Usage::
18020 @node Running gnatls
18021 @section Running @code{gnatls}
18024 The @code{gnatls} command has the form
18027 $ gnatls switches @var{object_or_ali_file}
18031 The main argument is the list of object or @file{ali} files
18032 (@pxref{The Ada Library Information Files})
18033 for which information is requested.
18035 In normal mode, without additional option, @code{gnatls} produces a
18036 four-column listing. Each line represents information for a specific
18037 object. The first column gives the full path of the object, the second
18038 column gives the name of the principal unit in this object, the third
18039 column gives the status of the source and the fourth column gives the
18040 full path of the source representing this unit.
18041 Here is a simple example of use:
18045 ^./^[]^demo1.o demo1 DIF demo1.adb
18046 ^./^[]^demo2.o demo2 OK demo2.adb
18047 ^./^[]^hello.o h1 OK hello.adb
18048 ^./^[]^instr-child.o instr.child MOK instr-child.adb
18049 ^./^[]^instr.o instr OK instr.adb
18050 ^./^[]^tef.o tef DIF tef.adb
18051 ^./^[]^text_io_example.o text_io_example OK text_io_example.adb
18052 ^./^[]^tgef.o tgef DIF tgef.adb
18056 The first line can be interpreted as follows: the main unit which is
18058 object file @file{demo1.o} is demo1, whose main source is in
18059 @file{demo1.adb}. Furthermore, the version of the source used for the
18060 compilation of demo1 has been modified (DIF). Each source file has a status
18061 qualifier which can be:
18064 @item OK (unchanged)
18065 The version of the source file used for the compilation of the
18066 specified unit corresponds exactly to the actual source file.
18068 @item MOK (slightly modified)
18069 The version of the source file used for the compilation of the
18070 specified unit differs from the actual source file but not enough to
18071 require recompilation. If you use gnatmake with the qualifier
18072 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
18073 MOK will not be recompiled.
18075 @item DIF (modified)
18076 No version of the source found on the path corresponds to the source
18077 used to build this object.
18079 @item ??? (file not found)
18080 No source file was found for this unit.
18082 @item HID (hidden, unchanged version not first on PATH)
18083 The version of the source that corresponds exactly to the source used
18084 for compilation has been found on the path but it is hidden by another
18085 version of the same source that has been modified.
18089 @node Switches for gnatls
18090 @section Switches for @code{gnatls}
18093 @code{gnatls} recognizes the following switches:
18097 @cindex @option{--version} @command{gnatls}
18098 Display Copyright and version, then exit disregarding all other options.
18101 @cindex @option{--help} @command{gnatls}
18102 If @option{--version} was not used, display usage, then exit disregarding
18105 @item ^-a^/ALL_UNITS^
18106 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
18107 Consider all units, including those of the predefined Ada library.
18108 Especially useful with @option{^-d^/DEPENDENCIES^}.
18110 @item ^-d^/DEPENDENCIES^
18111 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
18112 List sources from which specified units depend on.
18114 @item ^-h^/OUTPUT=OPTIONS^
18115 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
18116 Output the list of options.
18118 @item ^-o^/OUTPUT=OBJECTS^
18119 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
18120 Only output information about object files.
18122 @item ^-s^/OUTPUT=SOURCES^
18123 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
18124 Only output information about source files.
18126 @item ^-u^/OUTPUT=UNITS^
18127 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
18128 Only output information about compilation units.
18130 @item ^-files^/FILES^=@var{file}
18131 @cindex @option{^-files^/FILES^} (@code{gnatls})
18132 Take as arguments the files listed in text file @var{file}.
18133 Text file @var{file} may contain empty lines that are ignored.
18134 Each nonempty line should contain the name of an existing file.
18135 Several such switches may be specified simultaneously.
18137 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18138 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
18139 @itemx ^-I^/SEARCH=^@var{dir}
18140 @itemx ^-I-^/NOCURRENT_DIRECTORY^
18142 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
18143 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
18144 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
18145 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
18146 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
18147 flags (@pxref{Switches for gnatmake}).
18149 @item --RTS=@var{rts-path}
18150 @cindex @option{--RTS} (@code{gnatls})
18151 Specifies the default location of the runtime library. Same meaning as the
18152 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
18154 @item ^-v^/OUTPUT=VERBOSE^
18155 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
18156 Verbose mode. Output the complete source, object and project paths. Do not use
18157 the default column layout but instead use long format giving as much as
18158 information possible on each requested units, including special
18159 characteristics such as:
18162 @item Preelaborable
18163 The unit is preelaborable in the Ada sense.
18166 No elaboration code has been produced by the compiler for this unit.
18169 The unit is pure in the Ada sense.
18171 @item Elaborate_Body
18172 The unit contains a pragma Elaborate_Body.
18175 The unit contains a pragma Remote_Types.
18177 @item Shared_Passive
18178 The unit contains a pragma Shared_Passive.
18181 This unit is part of the predefined environment and cannot be modified
18184 @item Remote_Call_Interface
18185 The unit contains a pragma Remote_Call_Interface.
18191 @node Examples of gnatls Usage
18192 @section Example of @code{gnatls} Usage
18196 Example of using the verbose switch. Note how the source and
18197 object paths are affected by the -I switch.
18200 $ gnatls -v -I.. demo1.o
18202 GNATLS 5.03w (20041123-34)
18203 Copyright 1997-2004 Free Software Foundation, Inc.
18205 Source Search Path:
18206 <Current_Directory>
18208 /home/comar/local/adainclude/
18210 Object Search Path:
18211 <Current_Directory>
18213 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
18215 Project Search Path:
18216 <Current_Directory>
18217 /home/comar/local/lib/gnat/
18222 Kind => subprogram body
18223 Flags => No_Elab_Code
18224 Source => demo1.adb modified
18228 The following is an example of use of the dependency list.
18229 Note the use of the -s switch
18230 which gives a straight list of source files. This can be useful for
18231 building specialized scripts.
18234 $ gnatls -d demo2.o
18235 ./demo2.o demo2 OK demo2.adb
18241 $ gnatls -d -s -a demo1.o
18243 /home/comar/local/adainclude/ada.ads
18244 /home/comar/local/adainclude/a-finali.ads
18245 /home/comar/local/adainclude/a-filico.ads
18246 /home/comar/local/adainclude/a-stream.ads
18247 /home/comar/local/adainclude/a-tags.ads
18250 /home/comar/local/adainclude/gnat.ads
18251 /home/comar/local/adainclude/g-io.ads
18253 /home/comar/local/adainclude/system.ads
18254 /home/comar/local/adainclude/s-exctab.ads
18255 /home/comar/local/adainclude/s-finimp.ads
18256 /home/comar/local/adainclude/s-finroo.ads
18257 /home/comar/local/adainclude/s-secsta.ads
18258 /home/comar/local/adainclude/s-stalib.ads
18259 /home/comar/local/adainclude/s-stoele.ads
18260 /home/comar/local/adainclude/s-stratt.ads
18261 /home/comar/local/adainclude/s-tasoli.ads
18262 /home/comar/local/adainclude/s-unstyp.ads
18263 /home/comar/local/adainclude/unchconv.ads
18269 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
18271 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
18272 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
18273 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
18274 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
18275 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
18279 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
18280 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
18282 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
18283 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
18284 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
18285 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
18286 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
18287 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
18288 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
18289 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
18290 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
18291 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
18292 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
18296 @node Cleaning Up Using gnatclean
18297 @chapter Cleaning Up Using @code{gnatclean}
18299 @cindex Cleaning tool
18302 @code{gnatclean} is a tool that allows the deletion of files produced by the
18303 compiler, binder and linker, including ALI files, object files, tree files,
18304 expanded source files, library files, interface copy source files, binder
18305 generated files and executable files.
18308 * Running gnatclean::
18309 * Switches for gnatclean::
18310 @c * Examples of gnatclean Usage::
18313 @node Running gnatclean
18314 @section Running @code{gnatclean}
18317 The @code{gnatclean} command has the form:
18320 $ gnatclean switches @var{names}
18324 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
18325 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
18326 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
18329 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
18330 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
18331 the linker. In informative-only mode, specified by switch
18332 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
18333 normal mode is listed, but no file is actually deleted.
18335 @node Switches for gnatclean
18336 @section Switches for @code{gnatclean}
18339 @code{gnatclean} recognizes the following switches:
18343 @cindex @option{--version} @command{gnatclean}
18344 Display Copyright and version, then exit disregarding all other options.
18347 @cindex @option{--help} @command{gnatclean}
18348 If @option{--version} was not used, display usage, then exit disregarding
18351 @item ^-c^/COMPILER_FILES_ONLY^
18352 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
18353 Only attempt to delete the files produced by the compiler, not those produced
18354 by the binder or the linker. The files that are not to be deleted are library
18355 files, interface copy files, binder generated files and executable files.
18357 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
18358 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
18359 Indicate that ALI and object files should normally be found in directory
18362 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
18363 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
18364 When using project files, if some errors or warnings are detected during
18365 parsing and verbose mode is not in effect (no use of switch
18366 ^-v^/VERBOSE^), then error lines start with the full path name of the project
18367 file, rather than its simple file name.
18370 @cindex @option{^-h^/HELP^} (@code{gnatclean})
18371 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
18373 @item ^-n^/NODELETE^
18374 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
18375 Informative-only mode. Do not delete any files. Output the list of the files
18376 that would have been deleted if this switch was not specified.
18378 @item ^-P^/PROJECT_FILE=^@var{project}
18379 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
18380 Use project file @var{project}. Only one such switch can be used.
18381 When cleaning a project file, the files produced by the compilation of the
18382 immediate sources or inherited sources of the project files are to be
18383 deleted. This is not depending on the presence or not of executable names
18384 on the command line.
18387 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
18388 Quiet output. If there are no errors, do not output anything, except in
18389 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
18390 (switch ^-n^/NODELETE^).
18392 @item ^-r^/RECURSIVE^
18393 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
18394 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
18395 clean all imported and extended project files, recursively. If this switch
18396 is not specified, only the files related to the main project file are to be
18397 deleted. This switch has no effect if no project file is specified.
18399 @item ^-v^/VERBOSE^
18400 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
18403 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
18404 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
18405 Indicates the verbosity of the parsing of GNAT project files.
18406 @xref{Switches Related to Project Files}.
18408 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
18409 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
18410 Indicates that external variable @var{name} has the value @var{value}.
18411 The Project Manager will use this value for occurrences of
18412 @code{external(name)} when parsing the project file.
18413 @xref{Switches Related to Project Files}.
18415 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18416 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
18417 When searching for ALI and object files, look in directory
18420 @item ^-I^/SEARCH=^@var{dir}
18421 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
18422 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
18424 @item ^-I-^/NOCURRENT_DIRECTORY^
18425 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
18426 @cindex Source files, suppressing search
18427 Do not look for ALI or object files in the directory
18428 where @code{gnatclean} was invoked.
18432 @c @node Examples of gnatclean Usage
18433 @c @section Examples of @code{gnatclean} Usage
18436 @node GNAT and Libraries
18437 @chapter GNAT and Libraries
18438 @cindex Library, building, installing, using
18441 This chapter describes how to build and use libraries with GNAT, and also shows
18442 how to recompile the GNAT run-time library. You should be familiar with the
18443 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
18447 * Introduction to Libraries in GNAT::
18448 * General Ada Libraries::
18449 * Stand-alone Ada Libraries::
18450 * Rebuilding the GNAT Run-Time Library::
18453 @node Introduction to Libraries in GNAT
18454 @section Introduction to Libraries in GNAT
18457 A library is, conceptually, a collection of objects which does not have its
18458 own main thread of execution, but rather provides certain services to the
18459 applications that use it. A library can be either statically linked with the
18460 application, in which case its code is directly included in the application,
18461 or, on platforms that support it, be dynamically linked, in which case
18462 its code is shared by all applications making use of this library.
18464 GNAT supports both types of libraries.
18465 In the static case, the compiled code can be provided in different ways. The
18466 simplest approach is to provide directly the set of objects resulting from
18467 compilation of the library source files. Alternatively, you can group the
18468 objects into an archive using whatever commands are provided by the operating
18469 system. For the latter case, the objects are grouped into a shared library.
18471 In the GNAT environment, a library has three types of components:
18477 @xref{The Ada Library Information Files}.
18479 Object files, an archive or a shared library.
18483 A GNAT library may expose all its source files, which is useful for
18484 documentation purposes. Alternatively, it may expose only the units needed by
18485 an external user to make use of the library. That is to say, the specs
18486 reflecting the library services along with all the units needed to compile
18487 those specs, which can include generic bodies or any body implementing an
18488 inlined routine. In the case of @emph{stand-alone libraries} those exposed
18489 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
18491 All compilation units comprising an application, including those in a library,
18492 need to be elaborated in an order partially defined by Ada's semantics. GNAT
18493 computes the elaboration order from the @file{ALI} files and this is why they
18494 constitute a mandatory part of GNAT libraries. Except in the case of
18495 @emph{stand-alone libraries}, where a specific library elaboration routine is
18496 produced independently of the application(s) using the library.
18498 @node General Ada Libraries
18499 @section General Ada Libraries
18502 * Building a library::
18503 * Installing a library::
18504 * Using a library::
18507 @node Building a library
18508 @subsection Building a library
18511 The easiest way to build a library is to use the Project Manager,
18512 which supports a special type of project called a @emph{Library Project}
18513 (@pxref{Library Projects}).
18515 A project is considered a library project, when two project-level attributes
18516 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
18517 control different aspects of library configuration, additional optional
18518 project-level attributes can be specified:
18521 This attribute controls whether the library is to be static or dynamic
18523 @item Library_Version
18524 This attribute specifies the library version; this value is used
18525 during dynamic linking of shared libraries to determine if the currently
18526 installed versions of the binaries are compatible.
18528 @item Library_Options
18530 These attributes specify additional low-level options to be used during
18531 library generation, and redefine the actual application used to generate
18536 The GNAT Project Manager takes full care of the library maintenance task,
18537 including recompilation of the source files for which objects do not exist
18538 or are not up to date, assembly of the library archive, and installation of
18539 the library (i.e., copying associated source, object and @file{ALI} files
18540 to the specified location).
18542 Here is a simple library project file:
18543 @smallexample @c ada
18545 for Source_Dirs use ("src1", "src2");
18546 for Object_Dir use "obj";
18547 for Library_Name use "mylib";
18548 for Library_Dir use "lib";
18549 for Library_Kind use "dynamic";
18554 and the compilation command to build and install the library:
18556 @smallexample @c ada
18557 $ gnatmake -Pmy_lib
18561 It is not entirely trivial to perform manually all the steps required to
18562 produce a library. We recommend that you use the GNAT Project Manager
18563 for this task. In special cases where this is not desired, the necessary
18564 steps are discussed below.
18566 There are various possibilities for compiling the units that make up the
18567 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
18568 with a conventional script. For simple libraries, it is also possible to create
18569 a dummy main program which depends upon all the packages that comprise the
18570 interface of the library. This dummy main program can then be given to
18571 @command{gnatmake}, which will ensure that all necessary objects are built.
18573 After this task is accomplished, you should follow the standard procedure
18574 of the underlying operating system to produce the static or shared library.
18576 Here is an example of such a dummy program:
18577 @smallexample @c ada
18579 with My_Lib.Service1;
18580 with My_Lib.Service2;
18581 with My_Lib.Service3;
18582 procedure My_Lib_Dummy is
18590 Here are the generic commands that will build an archive or a shared library.
18593 # compiling the library
18594 $ gnatmake -c my_lib_dummy.adb
18596 # we don't need the dummy object itself
18597 $ rm my_lib_dummy.o my_lib_dummy.ali
18599 # create an archive with the remaining objects
18600 $ ar rc libmy_lib.a *.o
18601 # some systems may require "ranlib" to be run as well
18603 # or create a shared library
18604 $ gcc -shared -o libmy_lib.so *.o
18605 # some systems may require the code to have been compiled with -fPIC
18607 # remove the object files that are now in the library
18610 # Make the ALI files read-only so that gnatmake will not try to
18611 # regenerate the objects that are in the library
18616 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
18617 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
18618 be accessed by the directive @option{-l@var{xxx}} at link time.
18620 @node Installing a library
18621 @subsection Installing a library
18622 @cindex @code{ADA_PROJECT_PATH}
18625 If you use project files, library installation is part of the library build
18626 process. Thus no further action is needed in order to make use of the
18627 libraries that are built as part of the general application build. A usable
18628 version of the library is installed in the directory specified by the
18629 @code{Library_Dir} attribute of the library project file.
18631 You may want to install a library in a context different from where the library
18632 is built. This situation arises with third party suppliers, who may want
18633 to distribute a library in binary form where the user is not expected to be
18634 able to recompile the library. The simplest option in this case is to provide
18635 a project file slightly different from the one used to build the library, by
18636 using the @code{externally_built} attribute. For instance, the project
18637 file used to build the library in the previous section can be changed into the
18638 following one when the library is installed:
18640 @smallexample @c projectfile
18642 for Source_Dirs use ("src1", "src2");
18643 for Library_Name use "mylib";
18644 for Library_Dir use "lib";
18645 for Library_Kind use "dynamic";
18646 for Externally_Built use "true";
18651 This project file assumes that the directories @file{src1},
18652 @file{src2}, and @file{lib} exist in
18653 the directory containing the project file. The @code{externally_built}
18654 attribute makes it clear to the GNAT builder that it should not attempt to
18655 recompile any of the units from this library. It allows the library provider to
18656 restrict the source set to the minimum necessary for clients to make use of the
18657 library as described in the first section of this chapter. It is the
18658 responsibility of the library provider to install the necessary sources, ALI
18659 files and libraries in the directories mentioned in the project file. For
18660 convenience, the user's library project file should be installed in a location
18661 that will be searched automatically by the GNAT
18662 builder. These are the directories referenced in the @env{ADA_PROJECT_PATH}
18663 environment variable (@pxref{Importing Projects}), and also the default GNAT
18664 library location that can be queried with @command{gnatls -v} and is usually of
18665 the form $gnat_install_root/lib/gnat.
18667 When project files are not an option, it is also possible, but not recommended,
18668 to install the library so that the sources needed to use the library are on the
18669 Ada source path and the ALI files & libraries be on the Ada Object path (see
18670 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
18671 administrator can place general-purpose libraries in the default compiler
18672 paths, by specifying the libraries' location in the configuration files
18673 @file{ada_source_path} and @file{ada_object_path}. These configuration files
18674 must be located in the GNAT installation tree at the same place as the gcc spec
18675 file. The location of the gcc spec file can be determined as follows:
18681 The configuration files mentioned above have a simple format: each line
18682 must contain one unique directory name.
18683 Those names are added to the corresponding path
18684 in their order of appearance in the file. The names can be either absolute
18685 or relative; in the latter case, they are relative to where theses files
18688 The files @file{ada_source_path} and @file{ada_object_path} might not be
18690 GNAT installation, in which case, GNAT will look for its run-time library in
18691 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
18692 objects and @file{ALI} files). When the files exist, the compiler does not
18693 look in @file{adainclude} and @file{adalib}, and thus the
18694 @file{ada_source_path} file
18695 must contain the location for the GNAT run-time sources (which can simply
18696 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
18697 contain the location for the GNAT run-time objects (which can simply
18700 You can also specify a new default path to the run-time library at compilation
18701 time with the switch @option{--RTS=rts-path}. You can thus choose / change
18702 the run-time library you want your program to be compiled with. This switch is
18703 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
18704 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
18706 It is possible to install a library before or after the standard GNAT
18707 library, by reordering the lines in the configuration files. In general, a
18708 library must be installed before the GNAT library if it redefines
18711 @node Using a library
18712 @subsection Using a library
18714 @noindent Once again, the project facility greatly simplifies the use of
18715 libraries. In this context, using a library is just a matter of adding a
18716 @code{with} clause in the user project. For instance, to make use of the
18717 library @code{My_Lib} shown in examples in earlier sections, you can
18720 @smallexample @c projectfile
18727 Even if you have a third-party, non-Ada library, you can still use GNAT's
18728 Project Manager facility to provide a wrapper for it. For example, the
18729 following project, when @code{with}ed by your main project, will link with the
18730 third-party library @file{liba.a}:
18732 @smallexample @c projectfile
18735 for Externally_Built use "true";
18736 for Source_Files use ();
18737 for Library_Dir use "lib";
18738 for Library_Name use "a";
18739 for Library_Kind use "static";
18743 This is an alternative to the use of @code{pragma Linker_Options}. It is
18744 especially interesting in the context of systems with several interdependent
18745 static libraries where finding a proper linker order is not easy and best be
18746 left to the tools having visibility over project dependence information.
18749 In order to use an Ada library manually, you need to make sure that this
18750 library is on both your source and object path
18751 (see @ref{Search Paths and the Run-Time Library (RTL)}
18752 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
18753 in an archive or a shared library, you need to specify the desired
18754 library at link time.
18756 For example, you can use the library @file{mylib} installed in
18757 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
18760 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
18765 This can be expressed more simply:
18770 when the following conditions are met:
18773 @file{/dir/my_lib_src} has been added by the user to the environment
18774 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
18775 @file{ada_source_path}
18777 @file{/dir/my_lib_obj} has been added by the user to the environment
18778 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
18779 @file{ada_object_path}
18781 a pragma @code{Linker_Options} has been added to one of the sources.
18784 @smallexample @c ada
18785 pragma Linker_Options ("-lmy_lib");
18789 @node Stand-alone Ada Libraries
18790 @section Stand-alone Ada Libraries
18791 @cindex Stand-alone library, building, using
18794 * Introduction to Stand-alone Libraries::
18795 * Building a Stand-alone Library::
18796 * Creating a Stand-alone Library to be used in a non-Ada context::
18797 * Restrictions in Stand-alone Libraries::
18800 @node Introduction to Stand-alone Libraries
18801 @subsection Introduction to Stand-alone Libraries
18804 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
18806 elaborate the Ada units that are included in the library. In contrast with
18807 an ordinary library, which consists of all sources, objects and @file{ALI}
18809 library, a SAL may specify a restricted subset of compilation units
18810 to serve as a library interface. In this case, the fully
18811 self-sufficient set of files will normally consist of an objects
18812 archive, the sources of interface units' specs, and the @file{ALI}
18813 files of interface units.
18814 If an interface spec contains a generic unit or an inlined subprogram,
18816 source must also be provided; if the units that must be provided in the source
18817 form depend on other units, the source and @file{ALI} files of those must
18820 The main purpose of a SAL is to minimize the recompilation overhead of client
18821 applications when a new version of the library is installed. Specifically,
18822 if the interface sources have not changed, client applications do not need to
18823 be recompiled. If, furthermore, a SAL is provided in the shared form and its
18824 version, controlled by @code{Library_Version} attribute, is not changed,
18825 then the clients do not need to be relinked.
18827 SALs also allow the library providers to minimize the amount of library source
18828 text exposed to the clients. Such ``information hiding'' might be useful or
18829 necessary for various reasons.
18831 Stand-alone libraries are also well suited to be used in an executable whose
18832 main routine is not written in Ada.
18834 @node Building a Stand-alone Library
18835 @subsection Building a Stand-alone Library
18838 GNAT's Project facility provides a simple way of building and installing
18839 stand-alone libraries; see @ref{Stand-alone Library Projects}.
18840 To be a Stand-alone Library Project, in addition to the two attributes
18841 that make a project a Library Project (@code{Library_Name} and
18842 @code{Library_Dir}; see @ref{Library Projects}), the attribute
18843 @code{Library_Interface} must be defined. For example:
18845 @smallexample @c projectfile
18847 for Library_Dir use "lib_dir";
18848 for Library_Name use "dummy";
18849 for Library_Interface use ("int1", "int1.child");
18854 Attribute @code{Library_Interface} has a non-empty string list value,
18855 each string in the list designating a unit contained in an immediate source
18856 of the project file.
18858 When a Stand-alone Library is built, first the binder is invoked to build
18859 a package whose name depends on the library name
18860 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
18861 This binder-generated package includes initialization and
18862 finalization procedures whose
18863 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
18865 above). The object corresponding to this package is included in the library.
18867 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
18868 calling of these procedures if a static SAL is built, or if a shared SAL
18870 with the project-level attribute @code{Library_Auto_Init} set to
18873 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
18874 (those that are listed in attribute @code{Library_Interface}) are copied to
18875 the Library Directory. As a consequence, only the Interface Units may be
18876 imported from Ada units outside of the library. If other units are imported,
18877 the binding phase will fail.
18879 The attribute @code{Library_Src_Dir} may be specified for a
18880 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
18881 single string value. Its value must be the path (absolute or relative to the
18882 project directory) of an existing directory. This directory cannot be the
18883 object directory or one of the source directories, but it can be the same as
18884 the library directory. The sources of the Interface
18885 Units of the library that are needed by an Ada client of the library will be
18886 copied to the designated directory, called the Interface Copy directory.
18887 These sources include the specs of the Interface Units, but they may also
18888 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
18889 are used, or when there is a generic unit in the spec. Before the sources
18890 are copied to the Interface Copy directory, an attempt is made to delete all
18891 files in the Interface Copy directory.
18893 Building stand-alone libraries by hand is somewhat tedious, but for those
18894 occasions when it is necessary here are the steps that you need to perform:
18897 Compile all library sources.
18900 Invoke the binder with the switch @option{-n} (No Ada main program),
18901 with all the @file{ALI} files of the interfaces, and
18902 with the switch @option{-L} to give specific names to the @code{init}
18903 and @code{final} procedures. For example:
18905 gnatbind -n int1.ali int2.ali -Lsal1
18909 Compile the binder generated file:
18915 Link the dynamic library with all the necessary object files,
18916 indicating to the linker the names of the @code{init} (and possibly
18917 @code{final}) procedures for automatic initialization (and finalization).
18918 The built library should be placed in a directory different from
18919 the object directory.
18922 Copy the @code{ALI} files of the interface to the library directory,
18923 add in this copy an indication that it is an interface to a SAL
18924 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
18925 with letter ``P'') and make the modified copy of the @file{ALI} file
18930 Using SALs is not different from using other libraries
18931 (see @ref{Using a library}).
18933 @node Creating a Stand-alone Library to be used in a non-Ada context
18934 @subsection Creating a Stand-alone Library to be used in a non-Ada context
18937 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
18940 The only extra step required is to ensure that library interface subprograms
18941 are compatible with the main program, by means of @code{pragma Export}
18942 or @code{pragma Convention}.
18944 Here is an example of simple library interface for use with C main program:
18946 @smallexample @c ada
18947 package Interface is
18949 procedure Do_Something;
18950 pragma Export (C, Do_Something, "do_something");
18952 procedure Do_Something_Else;
18953 pragma Export (C, Do_Something_Else, "do_something_else");
18959 On the foreign language side, you must provide a ``foreign'' view of the
18960 library interface; remember that it should contain elaboration routines in
18961 addition to interface subprograms.
18963 The example below shows the content of @code{mylib_interface.h} (note
18964 that there is no rule for the naming of this file, any name can be used)
18966 /* the library elaboration procedure */
18967 extern void mylibinit (void);
18969 /* the library finalization procedure */
18970 extern void mylibfinal (void);
18972 /* the interface exported by the library */
18973 extern void do_something (void);
18974 extern void do_something_else (void);
18978 Libraries built as explained above can be used from any program, provided
18979 that the elaboration procedures (named @code{mylibinit} in the previous
18980 example) are called before the library services are used. Any number of
18981 libraries can be used simultaneously, as long as the elaboration
18982 procedure of each library is called.
18984 Below is an example of a C program that uses the @code{mylib} library.
18987 #include "mylib_interface.h"
18992 /* First, elaborate the library before using it */
18995 /* Main program, using the library exported entities */
18997 do_something_else ();
18999 /* Library finalization at the end of the program */
19006 Note that invoking any library finalization procedure generated by
19007 @code{gnatbind} shuts down the Ada run-time environment.
19009 finalization of all Ada libraries must be performed at the end of the program.
19010 No call to these libraries or to the Ada run-time library should be made
19011 after the finalization phase.
19013 @node Restrictions in Stand-alone Libraries
19014 @subsection Restrictions in Stand-alone Libraries
19017 The pragmas listed below should be used with caution inside libraries,
19018 as they can create incompatibilities with other Ada libraries:
19020 @item pragma @code{Locking_Policy}
19021 @item pragma @code{Queuing_Policy}
19022 @item pragma @code{Task_Dispatching_Policy}
19023 @item pragma @code{Unreserve_All_Interrupts}
19027 When using a library that contains such pragmas, the user must make sure
19028 that all libraries use the same pragmas with the same values. Otherwise,
19029 @code{Program_Error} will
19030 be raised during the elaboration of the conflicting
19031 libraries. The usage of these pragmas and its consequences for the user
19032 should therefore be well documented.
19034 Similarly, the traceback in the exception occurrence mechanism should be
19035 enabled or disabled in a consistent manner across all libraries.
19036 Otherwise, Program_Error will be raised during the elaboration of the
19037 conflicting libraries.
19039 If the @code{Version} or @code{Body_Version}
19040 attributes are used inside a library, then you need to
19041 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
19042 libraries, so that version identifiers can be properly computed.
19043 In practice these attributes are rarely used, so this is unlikely
19044 to be a consideration.
19046 @node Rebuilding the GNAT Run-Time Library
19047 @section Rebuilding the GNAT Run-Time Library
19048 @cindex GNAT Run-Time Library, rebuilding
19049 @cindex Building the GNAT Run-Time Library
19050 @cindex Rebuilding the GNAT Run-Time Library
19051 @cindex Run-Time Library, rebuilding
19054 It may be useful to recompile the GNAT library in various contexts, the
19055 most important one being the use of partition-wide configuration pragmas
19056 such as @code{Normalize_Scalars}. A special Makefile called
19057 @code{Makefile.adalib} is provided to that effect and can be found in
19058 the directory containing the GNAT library. The location of this
19059 directory depends on the way the GNAT environment has been installed and can
19060 be determined by means of the command:
19067 The last entry in the object search path usually contains the
19068 gnat library. This Makefile contains its own documentation and in
19069 particular the set of instructions needed to rebuild a new library and
19072 @node Using the GNU make Utility
19073 @chapter Using the GNU @code{make} Utility
19077 This chapter offers some examples of makefiles that solve specific
19078 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
19079 make, make, GNU @code{make}}), nor does it try to replace the
19080 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
19082 All the examples in this section are specific to the GNU version of
19083 make. Although @command{make} is a standard utility, and the basic language
19084 is the same, these examples use some advanced features found only in
19088 * Using gnatmake in a Makefile::
19089 * Automatically Creating a List of Directories::
19090 * Generating the Command Line Switches::
19091 * Overcoming Command Line Length Limits::
19094 @node Using gnatmake in a Makefile
19095 @section Using gnatmake in a Makefile
19100 Complex project organizations can be handled in a very powerful way by
19101 using GNU make combined with gnatmake. For instance, here is a Makefile
19102 which allows you to build each subsystem of a big project into a separate
19103 shared library. Such a makefile allows you to significantly reduce the link
19104 time of very big applications while maintaining full coherence at
19105 each step of the build process.
19107 The list of dependencies are handled automatically by
19108 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
19109 the appropriate directories.
19111 Note that you should also read the example on how to automatically
19112 create the list of directories
19113 (@pxref{Automatically Creating a List of Directories})
19114 which might help you in case your project has a lot of subdirectories.
19119 @font@heightrm=cmr8
19122 ## This Makefile is intended to be used with the following directory
19124 ## - The sources are split into a series of csc (computer software components)
19125 ## Each of these csc is put in its own directory.
19126 ## Their name are referenced by the directory names.
19127 ## They will be compiled into shared library (although this would also work
19128 ## with static libraries
19129 ## - The main program (and possibly other packages that do not belong to any
19130 ## csc is put in the top level directory (where the Makefile is).
19131 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
19132 ## \_ second_csc (sources) __ lib (will contain the library)
19134 ## Although this Makefile is build for shared library, it is easy to modify
19135 ## to build partial link objects instead (modify the lines with -shared and
19138 ## With this makefile, you can change any file in the system or add any new
19139 ## file, and everything will be recompiled correctly (only the relevant shared
19140 ## objects will be recompiled, and the main program will be re-linked).
19142 # The list of computer software component for your project. This might be
19143 # generated automatically.
19146 # Name of the main program (no extension)
19149 # If we need to build objects with -fPIC, uncomment the following line
19152 # The following variable should give the directory containing libgnat.so
19153 # You can get this directory through 'gnatls -v'. This is usually the last
19154 # directory in the Object_Path.
19157 # The directories for the libraries
19158 # (This macro expands the list of CSC to the list of shared libraries, you
19159 # could simply use the expanded form:
19160 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
19161 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
19163 $@{MAIN@}: objects $@{LIB_DIR@}
19164 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
19165 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
19168 # recompile the sources
19169 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
19171 # Note: In a future version of GNAT, the following commands will be simplified
19172 # by a new tool, gnatmlib
19174 mkdir -p $@{dir $@@ @}
19175 cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
19176 cd $@{dir $@@ @} && cp -f ../*.ali .
19178 # The dependencies for the modules
19179 # Note that we have to force the expansion of *.o, since in some cases
19180 # make won't be able to do it itself.
19181 aa/lib/libaa.so: $@{wildcard aa/*.o@}
19182 bb/lib/libbb.so: $@{wildcard bb/*.o@}
19183 cc/lib/libcc.so: $@{wildcard cc/*.o@}
19185 # Make sure all of the shared libraries are in the path before starting the
19188 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
19191 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
19192 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
19193 $@{RM@} $@{CSC_LIST:%=%/*.o@}
19194 $@{RM@} *.o *.ali $@{MAIN@}
19197 @node Automatically Creating a List of Directories
19198 @section Automatically Creating a List of Directories
19201 In most makefiles, you will have to specify a list of directories, and
19202 store it in a variable. For small projects, it is often easier to
19203 specify each of them by hand, since you then have full control over what
19204 is the proper order for these directories, which ones should be
19207 However, in larger projects, which might involve hundreds of
19208 subdirectories, it might be more convenient to generate this list
19211 The example below presents two methods. The first one, although less
19212 general, gives you more control over the list. It involves wildcard
19213 characters, that are automatically expanded by @command{make}. Its
19214 shortcoming is that you need to explicitly specify some of the
19215 organization of your project, such as for instance the directory tree
19216 depth, whether some directories are found in a separate tree, @enddots{}
19218 The second method is the most general one. It requires an external
19219 program, called @command{find}, which is standard on all Unix systems. All
19220 the directories found under a given root directory will be added to the
19226 @font@heightrm=cmr8
19229 # The examples below are based on the following directory hierarchy:
19230 # All the directories can contain any number of files
19231 # ROOT_DIRECTORY -> a -> aa -> aaa
19234 # -> b -> ba -> baa
19237 # This Makefile creates a variable called DIRS, that can be reused any time
19238 # you need this list (see the other examples in this section)
19240 # The root of your project's directory hierarchy
19244 # First method: specify explicitly the list of directories
19245 # This allows you to specify any subset of all the directories you need.
19248 DIRS := a/aa/ a/ab/ b/ba/
19251 # Second method: use wildcards
19252 # Note that the argument(s) to wildcard below should end with a '/'.
19253 # Since wildcards also return file names, we have to filter them out
19254 # to avoid duplicate directory names.
19255 # We thus use make's @code{dir} and @code{sort} functions.
19256 # It sets DIRs to the following value (note that the directories aaa and baa
19257 # are not given, unless you change the arguments to wildcard).
19258 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
19261 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
19262 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
19265 # Third method: use an external program
19266 # This command is much faster if run on local disks, avoiding NFS slowdowns.
19267 # This is the most complete command: it sets DIRs to the following value:
19268 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
19271 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
19275 @node Generating the Command Line Switches
19276 @section Generating the Command Line Switches
19279 Once you have created the list of directories as explained in the
19280 previous section (@pxref{Automatically Creating a List of Directories}),
19281 you can easily generate the command line arguments to pass to gnatmake.
19283 For the sake of completeness, this example assumes that the source path
19284 is not the same as the object path, and that you have two separate lists
19288 # see "Automatically creating a list of directories" to create
19293 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
19294 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
19297 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
19300 @node Overcoming Command Line Length Limits
19301 @section Overcoming Command Line Length Limits
19304 One problem that might be encountered on big projects is that many
19305 operating systems limit the length of the command line. It is thus hard to give
19306 gnatmake the list of source and object directories.
19308 This example shows how you can set up environment variables, which will
19309 make @command{gnatmake} behave exactly as if the directories had been
19310 specified on the command line, but have a much higher length limit (or
19311 even none on most systems).
19313 It assumes that you have created a list of directories in your Makefile,
19314 using one of the methods presented in
19315 @ref{Automatically Creating a List of Directories}.
19316 For the sake of completeness, we assume that the object
19317 path (where the ALI files are found) is different from the sources patch.
19319 Note a small trick in the Makefile below: for efficiency reasons, we
19320 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
19321 expanded immediately by @code{make}. This way we overcome the standard
19322 make behavior which is to expand the variables only when they are
19325 On Windows, if you are using the standard Windows command shell, you must
19326 replace colons with semicolons in the assignments to these variables.
19331 @font@heightrm=cmr8
19334 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
19335 # This is the same thing as putting the -I arguments on the command line.
19336 # (the equivalent of using -aI on the command line would be to define
19337 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
19338 # You can of course have different values for these variables.
19340 # Note also that we need to keep the previous values of these variables, since
19341 # they might have been set before running 'make' to specify where the GNAT
19342 # library is installed.
19344 # see "Automatically creating a list of directories" to create these
19350 space:=$@{empty@} $@{empty@}
19351 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
19352 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
19353 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
19354 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
19355 export ADA_INCLUDE_PATH
19356 export ADA_OBJECT_PATH
19363 @node Memory Management Issues
19364 @chapter Memory Management Issues
19367 This chapter describes some useful memory pools provided in the GNAT library
19368 and in particular the GNAT Debug Pool facility, which can be used to detect
19369 incorrect uses of access values (including ``dangling references'').
19371 It also describes the @command{gnatmem} tool, which can be used to track down
19376 * Some Useful Memory Pools::
19377 * The GNAT Debug Pool Facility::
19379 * The gnatmem Tool::
19383 @node Some Useful Memory Pools
19384 @section Some Useful Memory Pools
19385 @findex Memory Pool
19386 @cindex storage, pool
19389 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
19390 storage pool. Allocations use the standard system call @code{malloc} while
19391 deallocations use the standard system call @code{free}. No reclamation is
19392 performed when the pool goes out of scope. For performance reasons, the
19393 standard default Ada allocators/deallocators do not use any explicit storage
19394 pools but if they did, they could use this storage pool without any change in
19395 behavior. That is why this storage pool is used when the user
19396 manages to make the default implicit allocator explicit as in this example:
19397 @smallexample @c ada
19398 type T1 is access Something;
19399 -- no Storage pool is defined for T2
19400 type T2 is access Something_Else;
19401 for T2'Storage_Pool use T1'Storage_Pool;
19402 -- the above is equivalent to
19403 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
19407 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
19408 pool. The allocation strategy is similar to @code{Pool_Local}'s
19409 except that the all
19410 storage allocated with this pool is reclaimed when the pool object goes out of
19411 scope. This pool provides a explicit mechanism similar to the implicit one
19412 provided by several Ada 83 compilers for allocations performed through a local
19413 access type and whose purpose was to reclaim memory when exiting the
19414 scope of a given local access. As an example, the following program does not
19415 leak memory even though it does not perform explicit deallocation:
19417 @smallexample @c ada
19418 with System.Pool_Local;
19419 procedure Pooloc1 is
19420 procedure Internal is
19421 type A is access Integer;
19422 X : System.Pool_Local.Unbounded_Reclaim_Pool;
19423 for A'Storage_Pool use X;
19426 for I in 1 .. 50 loop
19431 for I in 1 .. 100 loop
19438 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
19439 @code{Storage_Size} is specified for an access type.
19440 The whole storage for the pool is
19441 allocated at once, usually on the stack at the point where the access type is
19442 elaborated. It is automatically reclaimed when exiting the scope where the
19443 access type is defined. This package is not intended to be used directly by the
19444 user and it is implicitly used for each such declaration:
19446 @smallexample @c ada
19447 type T1 is access Something;
19448 for T1'Storage_Size use 10_000;
19451 @node The GNAT Debug Pool Facility
19452 @section The GNAT Debug Pool Facility
19454 @cindex storage, pool, memory corruption
19457 The use of unchecked deallocation and unchecked conversion can easily
19458 lead to incorrect memory references. The problems generated by such
19459 references are usually difficult to tackle because the symptoms can be
19460 very remote from the origin of the problem. In such cases, it is
19461 very helpful to detect the problem as early as possible. This is the
19462 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
19464 In order to use the GNAT specific debugging pool, the user must
19465 associate a debug pool object with each of the access types that may be
19466 related to suspected memory problems. See Ada Reference Manual 13.11.
19467 @smallexample @c ada
19468 type Ptr is access Some_Type;
19469 Pool : GNAT.Debug_Pools.Debug_Pool;
19470 for Ptr'Storage_Pool use Pool;
19474 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
19475 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
19476 allow the user to redefine allocation and deallocation strategies. They
19477 also provide a checkpoint for each dereference, through the use of
19478 the primitive operation @code{Dereference} which is implicitly called at
19479 each dereference of an access value.
19481 Once an access type has been associated with a debug pool, operations on
19482 values of the type may raise four distinct exceptions,
19483 which correspond to four potential kinds of memory corruption:
19486 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
19488 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
19490 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
19492 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
19496 For types associated with a Debug_Pool, dynamic allocation is performed using
19497 the standard GNAT allocation routine. References to all allocated chunks of
19498 memory are kept in an internal dictionary. Several deallocation strategies are
19499 provided, whereupon the user can choose to release the memory to the system,
19500 keep it allocated for further invalid access checks, or fill it with an easily
19501 recognizable pattern for debug sessions. The memory pattern is the old IBM
19502 hexadecimal convention: @code{16#DEADBEEF#}.
19504 See the documentation in the file g-debpoo.ads for more information on the
19505 various strategies.
19507 Upon each dereference, a check is made that the access value denotes a
19508 properly allocated memory location. Here is a complete example of use of
19509 @code{Debug_Pools}, that includes typical instances of memory corruption:
19510 @smallexample @c ada
19514 with Gnat.Io; use Gnat.Io;
19515 with Unchecked_Deallocation;
19516 with Unchecked_Conversion;
19517 with GNAT.Debug_Pools;
19518 with System.Storage_Elements;
19519 with Ada.Exceptions; use Ada.Exceptions;
19520 procedure Debug_Pool_Test is
19522 type T is access Integer;
19523 type U is access all T;
19525 P : GNAT.Debug_Pools.Debug_Pool;
19526 for T'Storage_Pool use P;
19528 procedure Free is new Unchecked_Deallocation (Integer, T);
19529 function UC is new Unchecked_Conversion (U, T);
19532 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
19542 Put_Line (Integer'Image(B.all));
19544 when E : others => Put_Line ("raised: " & Exception_Name (E));
19549 when E : others => Put_Line ("raised: " & Exception_Name (E));
19553 Put_Line (Integer'Image(B.all));
19555 when E : others => Put_Line ("raised: " & Exception_Name (E));
19560 when E : others => Put_Line ("raised: " & Exception_Name (E));
19563 end Debug_Pool_Test;
19567 The debug pool mechanism provides the following precise diagnostics on the
19568 execution of this erroneous program:
19571 Total allocated bytes : 0
19572 Total deallocated bytes : 0
19573 Current Water Mark: 0
19577 Total allocated bytes : 8
19578 Total deallocated bytes : 0
19579 Current Water Mark: 8
19582 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
19583 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
19584 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
19585 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
19587 Total allocated bytes : 8
19588 Total deallocated bytes : 4
19589 Current Water Mark: 4
19594 @node The gnatmem Tool
19595 @section The @command{gnatmem} Tool
19599 The @code{gnatmem} utility monitors dynamic allocation and
19600 deallocation activity in a program, and displays information about
19601 incorrect deallocations and possible sources of memory leaks.
19602 It provides three type of information:
19605 General information concerning memory management, such as the total
19606 number of allocations and deallocations, the amount of allocated
19607 memory and the high water mark, i.e.@: the largest amount of allocated
19608 memory in the course of program execution.
19611 Backtraces for all incorrect deallocations, that is to say deallocations
19612 which do not correspond to a valid allocation.
19615 Information on each allocation that is potentially the origin of a memory
19620 * Running gnatmem::
19621 * Switches for gnatmem::
19622 * Example of gnatmem Usage::
19625 @node Running gnatmem
19626 @subsection Running @code{gnatmem}
19629 @code{gnatmem} makes use of the output created by the special version of
19630 allocation and deallocation routines that record call information. This
19631 allows to obtain accurate dynamic memory usage history at a minimal cost to
19632 the execution speed. Note however, that @code{gnatmem} is not supported on
19633 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
19634 Solaris and Windows NT/2000/XP (x86).
19637 The @code{gnatmem} command has the form
19640 $ gnatmem [switches] user_program
19644 The program must have been linked with the instrumented version of the
19645 allocation and deallocation routines. This is done by linking with the
19646 @file{libgmem.a} library. For correct symbolic backtrace information,
19647 the user program should be compiled with debugging options
19648 (see @ref{Switches for gcc}). For example to build @file{my_program}:
19651 $ gnatmake -g my_program -largs -lgmem
19655 As library @file{libgmem.a} contains an alternate body for package
19656 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
19657 when an executable is linked with library @file{libgmem.a}. It is then not
19658 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
19661 When @file{my_program} is executed, the file @file{gmem.out} is produced.
19662 This file contains information about all allocations and deallocations
19663 performed by the program. It is produced by the instrumented allocations and
19664 deallocations routines and will be used by @code{gnatmem}.
19666 In order to produce symbolic backtrace information for allocations and
19667 deallocations performed by the GNAT run-time library, you need to use a
19668 version of that library that has been compiled with the @option{-g} switch
19669 (see @ref{Rebuilding the GNAT Run-Time Library}).
19671 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
19672 examine. If the location of @file{gmem.out} file was not explicitly supplied by
19673 @option{-i} switch, gnatmem will assume that this file can be found in the
19674 current directory. For example, after you have executed @file{my_program},
19675 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
19678 $ gnatmem my_program
19682 This will produce the output with the following format:
19684 *************** debut cc
19686 $ gnatmem my_program
19690 Total number of allocations : 45
19691 Total number of deallocations : 6
19692 Final Water Mark (non freed mem) : 11.29 Kilobytes
19693 High Water Mark : 11.40 Kilobytes
19698 Allocation Root # 2
19699 -------------------
19700 Number of non freed allocations : 11
19701 Final Water Mark (non freed mem) : 1.16 Kilobytes
19702 High Water Mark : 1.27 Kilobytes
19704 my_program.adb:23 my_program.alloc
19710 The first block of output gives general information. In this case, the
19711 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
19712 Unchecked_Deallocation routine occurred.
19715 Subsequent paragraphs display information on all allocation roots.
19716 An allocation root is a specific point in the execution of the program
19717 that generates some dynamic allocation, such as a ``@code{@b{new}}''
19718 construct. This root is represented by an execution backtrace (or subprogram
19719 call stack). By default the backtrace depth for allocations roots is 1, so
19720 that a root corresponds exactly to a source location. The backtrace can
19721 be made deeper, to make the root more specific.
19723 @node Switches for gnatmem
19724 @subsection Switches for @code{gnatmem}
19727 @code{gnatmem} recognizes the following switches:
19732 @cindex @option{-q} (@code{gnatmem})
19733 Quiet. Gives the minimum output needed to identify the origin of the
19734 memory leaks. Omits statistical information.
19737 @cindex @var{N} (@code{gnatmem})
19738 N is an integer literal (usually between 1 and 10) which controls the
19739 depth of the backtraces defining allocation root. The default value for
19740 N is 1. The deeper the backtrace, the more precise the localization of
19741 the root. Note that the total number of roots can depend on this
19742 parameter. This parameter must be specified @emph{before} the name of the
19743 executable to be analyzed, to avoid ambiguity.
19746 @cindex @option{-b} (@code{gnatmem})
19747 This switch has the same effect as just depth parameter.
19749 @item -i @var{file}
19750 @cindex @option{-i} (@code{gnatmem})
19751 Do the @code{gnatmem} processing starting from @file{file}, rather than
19752 @file{gmem.out} in the current directory.
19755 @cindex @option{-m} (@code{gnatmem})
19756 This switch causes @code{gnatmem} to mask the allocation roots that have less
19757 than n leaks. The default value is 1. Specifying the value of 0 will allow to
19758 examine even the roots that didn't result in leaks.
19761 @cindex @option{-s} (@code{gnatmem})
19762 This switch causes @code{gnatmem} to sort the allocation roots according to the
19763 specified order of sort criteria, each identified by a single letter. The
19764 currently supported criteria are @code{n, h, w} standing respectively for
19765 number of unfreed allocations, high watermark, and final watermark
19766 corresponding to a specific root. The default order is @code{nwh}.
19770 @node Example of gnatmem Usage
19771 @subsection Example of @code{gnatmem} Usage
19774 The following example shows the use of @code{gnatmem}
19775 on a simple memory-leaking program.
19776 Suppose that we have the following Ada program:
19778 @smallexample @c ada
19781 with Unchecked_Deallocation;
19782 procedure Test_Gm is
19784 type T is array (1..1000) of Integer;
19785 type Ptr is access T;
19786 procedure Free is new Unchecked_Deallocation (T, Ptr);
19789 procedure My_Alloc is
19794 procedure My_DeAlloc is
19802 for I in 1 .. 5 loop
19803 for J in I .. 5 loop
19814 The program needs to be compiled with debugging option and linked with
19815 @code{gmem} library:
19818 $ gnatmake -g test_gm -largs -lgmem
19822 Then we execute the program as usual:
19829 Then @code{gnatmem} is invoked simply with
19835 which produces the following output (result may vary on different platforms):
19840 Total number of allocations : 18
19841 Total number of deallocations : 5
19842 Final Water Mark (non freed mem) : 53.00 Kilobytes
19843 High Water Mark : 56.90 Kilobytes
19845 Allocation Root # 1
19846 -------------------
19847 Number of non freed allocations : 11
19848 Final Water Mark (non freed mem) : 42.97 Kilobytes
19849 High Water Mark : 46.88 Kilobytes
19851 test_gm.adb:11 test_gm.my_alloc
19853 Allocation Root # 2
19854 -------------------
19855 Number of non freed allocations : 1
19856 Final Water Mark (non freed mem) : 10.02 Kilobytes
19857 High Water Mark : 10.02 Kilobytes
19859 s-secsta.adb:81 system.secondary_stack.ss_init
19861 Allocation Root # 3
19862 -------------------
19863 Number of non freed allocations : 1
19864 Final Water Mark (non freed mem) : 12 Bytes
19865 High Water Mark : 12 Bytes
19867 s-secsta.adb:181 system.secondary_stack.ss_init
19871 Note that the GNAT run time contains itself a certain number of
19872 allocations that have no corresponding deallocation,
19873 as shown here for root #2 and root
19874 #3. This is a normal behavior when the number of non-freed allocations
19875 is one, it allocates dynamic data structures that the run time needs for
19876 the complete lifetime of the program. Note also that there is only one
19877 allocation root in the user program with a single line back trace:
19878 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
19879 program shows that 'My_Alloc' is called at 2 different points in the
19880 source (line 21 and line 24). If those two allocation roots need to be
19881 distinguished, the backtrace depth parameter can be used:
19884 $ gnatmem 3 test_gm
19888 which will give the following output:
19893 Total number of allocations : 18
19894 Total number of deallocations : 5
19895 Final Water Mark (non freed mem) : 53.00 Kilobytes
19896 High Water Mark : 56.90 Kilobytes
19898 Allocation Root # 1
19899 -------------------
19900 Number of non freed allocations : 10
19901 Final Water Mark (non freed mem) : 39.06 Kilobytes
19902 High Water Mark : 42.97 Kilobytes
19904 test_gm.adb:11 test_gm.my_alloc
19905 test_gm.adb:24 test_gm
19906 b_test_gm.c:52 main
19908 Allocation Root # 2
19909 -------------------
19910 Number of non freed allocations : 1
19911 Final Water Mark (non freed mem) : 10.02 Kilobytes
19912 High Water Mark : 10.02 Kilobytes
19914 s-secsta.adb:81 system.secondary_stack.ss_init
19915 s-secsta.adb:283 <system__secondary_stack___elabb>
19916 b_test_gm.c:33 adainit
19918 Allocation Root # 3
19919 -------------------
19920 Number of non freed allocations : 1
19921 Final Water Mark (non freed mem) : 3.91 Kilobytes
19922 High Water Mark : 3.91 Kilobytes
19924 test_gm.adb:11 test_gm.my_alloc
19925 test_gm.adb:21 test_gm
19926 b_test_gm.c:52 main
19928 Allocation Root # 4
19929 -------------------
19930 Number of non freed allocations : 1
19931 Final Water Mark (non freed mem) : 12 Bytes
19932 High Water Mark : 12 Bytes
19934 s-secsta.adb:181 system.secondary_stack.ss_init
19935 s-secsta.adb:283 <system__secondary_stack___elabb>
19936 b_test_gm.c:33 adainit
19940 The allocation root #1 of the first example has been split in 2 roots #1
19941 and #3 thanks to the more precise associated backtrace.
19945 @node Stack Related Facilities
19946 @chapter Stack Related Facilities
19949 This chapter describes some useful tools associated with stack
19950 checking and analysis. In
19951 particular, it deals with dynamic and static stack usage measurements.
19954 * Stack Overflow Checking::
19955 * Static Stack Usage Analysis::
19956 * Dynamic Stack Usage Analysis::
19959 @node Stack Overflow Checking
19960 @section Stack Overflow Checking
19961 @cindex Stack Overflow Checking
19962 @cindex -fstack-check
19965 For most operating systems, @command{gcc} does not perform stack overflow
19966 checking by default. This means that if the main environment task or
19967 some other task exceeds the available stack space, then unpredictable
19968 behavior will occur. Most native systems offer some level of protection by
19969 adding a guard page at the end of each task stack. This mechanism is usually
19970 not enough for dealing properly with stack overflow situations because
19971 a large local variable could ``jump'' above the guard page.
19972 Furthermore, when the
19973 guard page is hit, there may not be any space left on the stack for executing
19974 the exception propagation code. Enabling stack checking avoids
19977 To activate stack checking, compile all units with the gcc option
19978 @option{-fstack-check}. For example:
19981 gcc -c -fstack-check package1.adb
19985 Units compiled with this option will generate extra instructions to check
19986 that any use of the stack (for procedure calls or for declaring local
19987 variables in declare blocks) does not exceed the available stack space.
19988 If the space is exceeded, then a @code{Storage_Error} exception is raised.
19990 For declared tasks, the stack size is controlled by the size
19991 given in an applicable @code{Storage_Size} pragma or by the value specified
19992 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
19993 the default size as defined in the GNAT runtime otherwise.
19995 For the environment task, the stack size depends on
19996 system defaults and is unknown to the compiler. Stack checking
19997 may still work correctly if a fixed
19998 size stack is allocated, but this cannot be guaranteed.
20000 To ensure that a clean exception is signalled for stack
20001 overflow, set the environment variable
20002 @env{GNAT_STACK_LIMIT} to indicate the maximum
20003 stack area that can be used, as in:
20004 @cindex GNAT_STACK_LIMIT
20007 SET GNAT_STACK_LIMIT 1600
20011 The limit is given in kilobytes, so the above declaration would
20012 set the stack limit of the environment task to 1.6 megabytes.
20013 Note that the only purpose of this usage is to limit the amount
20014 of stack used by the environment task. If it is necessary to
20015 increase the amount of stack for the environment task, then this
20016 is an operating systems issue, and must be addressed with the
20017 appropriate operating systems commands.
20020 To have a fixed size stack in the environment task, the stack must be put
20021 in the P0 address space and its size specified. Use these switches to
20025 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
20029 The quotes are required to keep case. The number after @samp{STACK=} is the
20030 size of the environmental task stack in pagelets (512 bytes). In this example
20031 the stack size is about 2 megabytes.
20034 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
20035 be placed in P0 space. Refer to @cite{HP OpenVMS Linker Utility Manual} for
20036 more details about the @option{/p0image} qualifier and the @option{stack}
20040 @node Static Stack Usage Analysis
20041 @section Static Stack Usage Analysis
20042 @cindex Static Stack Usage Analysis
20043 @cindex -fstack-usage
20046 A unit compiled with @option{-fstack-usage} will generate an extra file
20048 the maximum amount of stack used, on a per-function basis.
20049 The file has the same
20050 basename as the target object file with a @file{.su} extension.
20051 Each line of this file is made up of three fields:
20055 The name of the function.
20059 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
20062 The second field corresponds to the size of the known part of the function
20065 The qualifier @code{static} means that the function frame size
20067 It usually means that all local variables have a static size.
20068 In this case, the second field is a reliable measure of the function stack
20071 The qualifier @code{dynamic} means that the function frame size is not static.
20072 It happens mainly when some local variables have a dynamic size. When this
20073 qualifier appears alone, the second field is not a reliable measure
20074 of the function stack analysis. When it is qualified with @code{bounded}, it
20075 means that the second field is a reliable maximum of the function stack
20078 @node Dynamic Stack Usage Analysis
20079 @section Dynamic Stack Usage Analysis
20082 It is possible to measure the maximum amount of stack used by a task, by
20083 adding a switch to @command{gnatbind}, as:
20086 $ gnatbind -u0 file
20090 With this option, at each task termination, its stack usage is output on
20092 It is not always convenient to output the stack usage when the program
20093 is still running. Hence, it is possible to delay this output until program
20094 termination. for a given number of tasks specified as the argument of the
20095 @option{-u} option. For instance:
20098 $ gnatbind -u100 file
20102 will buffer the stack usage information of the first 100 tasks to terminate and
20103 output this info at program termination. Results are displayed in four
20107 Index | Task Name | Stack Size | Actual Use [min - max]
20114 is a number associated with each task.
20117 is the name of the task analyzed.
20120 is the maximum size for the stack.
20123 is the measure done by the stack analyzer. In order to prevent overflow,
20124 the stack is not entirely analyzed, and it's not possible to know exactly how
20125 much has actually been used. The real amount of stack used is between the min
20131 The environment task stack, e.g., the stack that contains the main unit, is
20132 only processed when the environment variable GNAT_STACK_LIMIT is set.
20135 @c *********************************
20137 @c *********************************
20138 @node Verifying Properties Using gnatcheck
20139 @chapter Verifying Properties Using @command{gnatcheck}
20141 @cindex @command{gnatcheck}
20144 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
20145 of Ada source files according to a given set of semantic rules.
20148 In order to check compliance with a given rule, @command{gnatcheck} has to
20149 semantically analyze the Ada sources.
20150 Therefore, checks can only be performed on
20151 legal Ada units. Moreover, when a unit depends semantically upon units located
20152 outside the current directory, the source search path has to be provided when
20153 calling @command{gnatcheck}, either through a specified project file or
20154 through @command{gnatcheck} switches as described below.
20156 A number of rules are predefined in @command{gnatcheck} and are described
20157 later in this chapter.
20158 You can also add new rules, by modifying the @command{gnatcheck} code and
20159 rebuilding the tool. In order to add a simple rule making some local checks,
20160 a small amount of straightforward ASIS-based programming is usually needed.
20162 Project support for @command{gnatcheck} is provided by the GNAT
20163 driver (see @ref{The GNAT Driver and Project Files}).
20165 Invoking @command{gnatcheck} on the command line has the form:
20168 $ gnatcheck [@i{switches}] @{@i{filename}@}
20169 [^-files^/FILES^=@{@i{arg_list_filename}@}]
20170 [-cargs @i{gcc_switches}] [-rules @i{rule_options}]
20177 @i{switches} specify the general tool options
20180 Each @i{filename} is the name (including the extension) of a source
20181 file to process. ``Wildcards'' are allowed, and
20182 the file name may contain path information.
20185 Each @i{arg_list_filename} is the name (including the extension) of a text
20186 file containing the names of the source files to process, separated by spaces
20190 @i{gcc_switches} is a list of switches for
20191 @command{gcc}. They will be passed on to all compiler invocations made by
20192 @command{gnatcheck} to generate the ASIS trees. Here you can provide
20193 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
20194 and use the @option{-gnatec} switch to set the configuration file.
20197 @i{rule_options} is a list of options for controlling a set of
20198 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
20202 Either a @i{filename} or an @i{arg_list_filename} must be supplied.
20205 * Format of the Report File::
20206 * General gnatcheck Switches::
20207 * gnatcheck Rule Options::
20208 * Adding the Results of Compiler Checks to gnatcheck Output::
20209 * Project-Wide Checks::
20210 * Predefined Rules::
20213 @node Format of the Report File
20214 @section Format of the Report File
20215 @cindex Report file (for @code{gnatcheck})
20218 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
20220 It also creates, in the current
20221 directory, a text file named @file{^gnatcheck.out^GNATCHECK.OUT^} that
20222 contains the complete report of the last gnatcheck run. This report contains:
20224 @item a list of the Ada source files being checked,
20225 @item a list of enabled and disabled rules,
20226 @item a list of the diagnostic messages, ordered in three different ways
20227 and collected in three separate
20228 sections. Section 1 contains the raw list of diagnostic messages. It
20229 corresponds to the output going to @file{stdout}. Section 2 contains
20230 messages ordered by rules.
20231 Section 3 contains messages ordered by source files.
20234 @node General gnatcheck Switches
20235 @section General @command{gnatcheck} Switches
20238 The following switches control the general @command{gnatcheck} behavior
20242 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
20244 Process all units including those with read-only ALI files such as
20245 those from GNAT Run-Time library.
20249 @cindex @option{-d} (@command{gnatcheck})
20254 @cindex @option{-dd} (@command{gnatcheck})
20256 Progress indicator mode (for use in GPS)
20259 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
20261 List the predefined and user-defined rules. For more details see
20262 @ref{Predefined Rules}.
20264 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
20266 Use full source locations references in the report file. For a construct from
20267 a generic instantiation a full source location is a chain from the location
20268 of this construct in the generic unit to the place where this unit is
20271 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
20273 Quiet mode. All the diagnoses about rule violations are placed in the
20274 @command{gnatcheck} report file only, without duplicating in @file{stdout}.
20276 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
20278 Short format of the report file (no version information, no list of applied
20279 rules, no list of checked sources is included)
20281 @cindex @option{^-s1^/COMPILER_STYLE^} (@command{gnatcheck})
20282 @item ^-s1^/COMPILER_STYLE^
20283 Include the compiler-style section in the report file
20285 @cindex @option{^-s2^/BY_RULES^} (@command{gnatcheck})
20286 @item ^-s2^/BY_RULES^
20287 Include the section containing diagnoses ordered by rules in the report file
20289 @cindex @option{^-s3^/BY_FILES_BY_RULES^} (@command{gnatcheck})
20290 @item ^-s3^/BY_FILES_BY_RULES^
20291 Include the section containing diagnoses ordered by files and then by rules
20294 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
20295 @item ^-v^/VERBOSE^
20296 Verbose mode; @command{gnatcheck} generates version information and then
20297 a trace of sources being processed.
20302 Note that if any of the options @option{^-s1^/COMPILER_STYLE^},
20303 @option{^-s2^/BY_RULES^} or
20304 @option{^-s3^/BY_FILES_BY_RULES^} is specified,
20305 then the @command{gnatcheck} report file will only contain sections
20306 explicitly denoted by these options.
20308 @node gnatcheck Rule Options
20309 @section @command{gnatcheck} Rule Options
20312 The following options control the processing performed by
20313 @command{gnatcheck}.
20316 @cindex @option{+ALL} (@command{gnatcheck})
20318 Turn all the rule checks ON.
20320 @cindex @option{-ALL} (@command{gnatcheck})
20322 Turn all the rule checks OFF.
20324 @cindex @option{+R} (@command{gnatcheck})
20325 @item +R@i{rule_id[:param]}
20326 Turn on the check for a specified rule with the specified parameter, if any.
20327 @i{rule_id} must be the identifier of one of the currently implemented rules
20328 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
20329 are not case-sensitive. The @i{param} item must
20330 be a string representing a valid parameter(s) for the specified rule.
20331 If it contains any space characters then this string must be enclosed in
20334 @cindex @option{-R} (@command{gnatcheck})
20335 @item -R@i{rule_id[:param]}
20336 Turn off the check for a specified rule with the specified parameter, if any.
20338 @cindex @option{-from} (@command{gnatcheck})
20339 @item -from=@i{rule_option_filename}
20340 Read the rule options from the text file @i{rule_option_filename}, referred as
20341 ``rule file'' below.
20346 The default behavior is that all the rule checks are enabled, except for
20347 the checks performed by the compiler.
20349 and the checks associated with the
20353 A rule file is a text file containing a set of rule options.
20354 @cindex Rule file (for @code{gnatcheck})
20355 The file may contain empty lines and Ada-style comments (comment
20356 lines and end-of-line comments). The rule file has free format; that is,
20357 you do not have to start a new rule option on a new line.
20359 A rule file may contain other @option{-from=@i{rule_option_filename}}
20360 options, each such option being replaced with the content of the
20361 corresponding rule file during the rule files processing. In case a
20362 cycle is detected (that is, @i{rule_file_1} reads rule options from
20363 @i{rule_file_2}, and @i{rule_file_2} reads (directly or indirectly)
20364 rule options from @i{rule_file_1}), the processing
20365 of rule files is interrupted and a part of their content is ignored.
20368 @node Adding the Results of Compiler Checks to gnatcheck Output
20369 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
20372 The @command{gnatcheck} tool can include in the generated diagnostic messages
20374 the report file the results of the checks performed by the compiler. Though
20375 disabled by default, this effect may be obtained by using @option{+R} with
20376 the following rule identifiers and parameters:
20380 To record restrictions violations (that are performed by the compiler if the
20381 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
20383 @code{Restrictions} with the same parameters as pragma
20384 @code{Restrictions} or @code{Restriction_Warnings}.
20387 To record compiler style checks(@pxref{Style Checking}), use the rule named
20388 @code{Style_Checks}. A parameter of this rule can be either @code{All_Checks},
20389 which enables all the standard style checks that corresponds to @option{-gnatyy}
20390 GNAT style check option, or a string that has exactly the same
20391 structure and semantics as the @code{string_LITERAL} parameter of GNAT pragma
20392 @code{Style_Checks} (for further information about this pragma,
20393 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}).
20396 To record compiler warnings (@pxref{Warning Message Control}), use the rule
20397 named @code{Warnings} with a parameter that is a valid
20398 @i{static_string_expression} argument of GNAT pragma @code{Warnings}
20399 (for further information about this pragma, @pxref{Pragma Warnings,,,
20400 gnat_rm, GNAT Reference Manual}). Note, that in case of gnatcheck
20401 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
20402 all the specific warnings, but not suppresses the warning mode,
20403 and 'e' parameter, corresponding to @option{-gnatwe} that means
20404 "treat warnings as errors", does not have any effect.
20408 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
20409 option with the corresponding restriction name as a parameter. @code{-R} is
20410 not available for @code{Style_Checks} and @code{Warnings} options, to disable
20411 warnings and style checks, use the corresponding warning and style options.
20413 @node Project-Wide Checks
20414 @section Project-Wide Checks
20415 @cindex Project-wide checks (for @command{gnatcheck})
20418 In order to perform checks on all units of a given project, you can use
20419 the GNAT driver along with the @option{-P} option:
20421 gnat check -Pproj -rules -from=my_rules
20425 If the project @code{proj} depends upon other projects, you can perform
20426 checks on the project closure using the @option{-U} option:
20428 gnat check -Pproj -U -rules -from=my_rules
20432 Finally, if not all the units are relevant to a particular main
20433 program in the project closure, you can perform checks for the set
20434 of units needed to create a given main program (unit closure) using
20435 the @option{-U} option followed by the name of the main unit:
20437 gnat check -Pproj -U main -rules -from=my_rules
20441 @node Predefined Rules
20442 @section Predefined Rules
20443 @cindex Predefined rules (for @command{gnatcheck})
20446 @c (Jan 2007) Since the global rules are still under development and are not
20447 @c documented, there is no point in explaining the difference between
20448 @c global and local rules
20450 A rule in @command{gnatcheck} is either local or global.
20451 A @emph{local rule} is a rule that applies to a well-defined section
20452 of a program and that can be checked by analyzing only this section.
20453 A @emph{global rule} requires analysis of some global properties of the
20454 whole program (mostly related to the program call graph).
20455 As of @value{NOW}, the implementation of global rules should be
20456 considered to be at a preliminary stage. You can use the
20457 @option{+GLOBAL} option to enable all the global rules, and the
20458 @option{-GLOBAL} rule option to disable all the global rules.
20460 All the global rules in the list below are
20461 so indicated by marking them ``GLOBAL''.
20462 This +GLOBAL and -GLOBAL options are not
20463 included in the list of gnatcheck options above, because at the moment they
20464 are considered as a temporary debug options.
20466 @command{gnatcheck} performs rule checks for generic
20467 instances only for global rules. This limitation may be relaxed in a later
20472 The following subsections document the rules implemented in
20473 @command{gnatcheck}.
20474 The subsection title is the same as the rule identifier, which may be
20475 used as a parameter of the @option{+R} or @option{-R} options.
20479 * Abstract_Type_Declarations::
20480 * Anonymous_Arrays::
20481 * Anonymous_Subtypes::
20483 * Boolean_Relational_Operators::
20485 * Ceiling_Violations::
20487 * Controlled_Type_Declarations::
20488 * Declarations_In_Blocks::
20489 * Default_Parameters::
20490 * Discriminated_Records::
20491 * Enumeration_Ranges_In_CASE_Statements::
20492 * Exceptions_As_Control_Flow::
20493 * EXIT_Statements_With_No_Loop_Name::
20494 * Expanded_Loop_Exit_Names::
20495 * Explicit_Full_Discrete_Ranges::
20496 * Float_Equality_Checks::
20497 * Forbidden_Pragmas::
20498 * Function_Style_Procedures::
20499 * Generics_In_Subprograms::
20500 * GOTO_Statements::
20501 * Implicit_IN_Mode_Parameters::
20502 * Implicit_SMALL_For_Fixed_Point_Types::
20503 * Improperly_Located_Instantiations::
20504 * Improper_Returns::
20505 * Library_Level_Subprograms::
20508 * Improperly_Called_Protected_Entries::
20510 * Metrics_Violation::
20511 * Misnamed_Identifiers::
20512 * Multiple_Entries_In_Protected_Definitions::
20514 * Non_Qualified_Aggregates::
20515 * Non_Short_Circuit_Operators::
20516 * Non_SPARK_Attributes::
20517 * Non_Tagged_Derived_Types::
20518 * Non_Visible_Exceptions::
20519 * Numeric_Literals::
20520 * OTHERS_In_Aggregates::
20521 * OTHERS_In_CASE_Statements::
20522 * OTHERS_In_Exception_Handlers::
20523 * Outer_Loop_Exits::
20524 * Overloaded_Operators::
20525 * Overly_Nested_Control_Structures::
20526 * Parameters_Out_Of_Order::
20527 * Positional_Actuals_For_Defaulted_Generic_Parameters::
20528 * Positional_Actuals_For_Defaulted_Parameters::
20529 * Positional_Components::
20530 * Positional_Generic_Parameters::
20531 * Positional_Parameters::
20532 * Predefined_Numeric_Types::
20533 * Raising_External_Exceptions::
20534 * Raising_Predefined_Exceptions::
20535 * Separate_Numeric_Error_Handlers::
20538 * Side_Effect_Functions::
20541 * Unassigned_OUT_Parameters::
20542 * Uncommented_BEGIN_In_Package_Bodies::
20543 * Unconstrained_Array_Returns::
20544 * Universal_Ranges::
20545 * Unnamed_Blocks_And_Loops::
20547 * Unused_Subprograms::
20549 * USE_PACKAGE_Clauses::
20550 * Volatile_Objects_Without_Address_Clauses::
20554 @node Abstract_Type_Declarations
20555 @subsection @code{Abstract_Type_Declarations}
20556 @cindex @code{Abstract_Type_Declarations} rule (for @command{gnatcheck})
20559 Flag all declarations of abstract types. For an abstract private
20560 type, both the private and full type declarations are flagged.
20562 This rule has no parameters.
20565 @node Anonymous_Arrays
20566 @subsection @code{Anonymous_Arrays}
20567 @cindex @code{Anonymous_Arrays} rule (for @command{gnatcheck})
20570 Flag all anonymous array type definitions (by Ada semantics these can only
20571 occur in object declarations).
20573 This rule has no parameters.
20575 @node Anonymous_Subtypes
20576 @subsection @code{Anonymous_Subtypes}
20577 @cindex @code{Anonymous_Subtypes} rule (for @command{gnatcheck})
20580 Flag all uses of anonymous subtypes. A use of an anonymous subtype is
20581 any instance of a subtype indication with a constraint, other than one
20582 that occurs immediately within a subtype declaration. Any use of a range
20583 other than as a constraint used immediately within a subtype declaration
20584 is considered as an anonymous subtype.
20586 An effect of this rule is that @code{for} loops such as the following are
20587 flagged (since @code{1..N} is formally a ``range''):
20589 @smallexample @c ada
20590 for I in 1 .. N loop
20596 Declaring an explicit subtype solves the problem:
20598 @smallexample @c ada
20599 subtype S is Integer range 1..N;
20607 This rule has no parameters.
20610 @subsection @code{Blocks}
20611 @cindex @code{Blocks} rule (for @command{gnatcheck})
20614 Flag each block statement.
20616 This rule has no parameters.
20618 @node Boolean_Relational_Operators
20619 @subsection @code{Boolean_Relational_Operators}
20620 @cindex @code{Boolean_Relational_Operators} rule (for @command{gnatcheck})
20623 Flag each call to a predefined relational operator (``<'', ``>'', ``<='',
20624 ``>='', ``='' and ``/='') for the predefined Boolean type.
20625 (This rule is useful in enforcing the SPARK language restrictions.)
20627 Calls to predefined relational operators of any type derived from
20628 @code{Standard.Boolean} are not detected. Calls to user-defined functions
20629 with these designators, and uses of operators that are renamings
20630 of the predefined relational operators for @code{Standard.Boolean},
20631 are likewise not detected.
20633 This rule has no parameters.
20636 @node Ceiling_Violations
20637 @subsection @code{Ceiling_Violations} (under construction, GLOBAL)
20638 @cindex @code{Ceiling_Violations} rule (for @command{gnatcheck})
20641 Flag invocations of a protected operation by a task whose priority exceeds
20642 the protected object's ceiling.
20644 As of @value{NOW}, this rule has the following limitations:
20649 We consider only pragmas Priority and Interrupt_Priority as means to define
20650 a task/protected operation priority. We do not consider the effect of using
20651 Ada.Dynamic_Priorities.Set_Priority procedure;
20654 We consider only base task priorities, and no priority inheritance. That is,
20655 we do not make a difference between calls issued during task activation and
20656 execution of the sequence of statements from task body;
20659 Any situation when the priority of protected operation caller is set by a
20660 dynamic expression (that is, the corresponding Priority or
20661 Interrupt_Priority pragma has a non-static expression as an argument) we
20662 treat as a priority inconsistency (and, therefore, detect this situation).
20666 At the moment the notion of the main subprogram is not implemented in
20667 gnatcheck, so any pragma Priority in a library level subprogram body (in case
20668 if this subprogram can be a main subprogram of a partition) changes the
20669 priority of an environment task. So if we have more then one such pragma in
20670 the set of processed sources, the pragma that is processed last, defines the
20671 priority of an environment task.
20673 This rule has no parameters.
20676 @node Controlled_Type_Declarations
20677 @subsection @code{Controlled_Type_Declarations}
20678 @cindex @code{Controlled_Type_Declarations} rule (for @command{gnatcheck})
20681 Flag all declarations of controlled types. A declaration of a private type
20682 is flagged if its full declaration declares a controlled type. A declaration
20683 of a derived type is flagged if its ancestor type is controlled. Subtype
20684 declarations are not checked. A declaration of a type that itself is not a
20685 descendant of a type declared in @code{Ada.Finalization} but has a controlled
20686 component is not checked.
20688 This rule has no parameters.
20692 @node Declarations_In_Blocks
20693 @subsection @code{Declarations_In_Blocks}
20694 @cindex @code{Declarations_In_Blocks} rule (for @command{gnatcheck})
20697 Flag all block statements containing local declarations. A @code{declare}
20698 block with an empty @i{declarative_part} or with a @i{declarative part}
20699 containing only pragmas and/or @code{use} clauses is not flagged.
20701 This rule has no parameters.
20704 @node Default_Parameters
20705 @subsection @code{Default_Parameters}
20706 @cindex @code{Default_Parameters} rule (for @command{gnatcheck})
20709 Flag all default expressions for subprogram parameters. Parameter
20710 declarations of formal and generic subprograms are also checked.
20712 This rule has no parameters.
20715 @node Discriminated_Records
20716 @subsection @code{Discriminated_Records}
20717 @cindex @code{Discriminated_Records} rule (for @command{gnatcheck})
20720 Flag all declarations of record types with discriminants. Only the
20721 declarations of record and record extension types are checked. Incomplete,
20722 formal, private, derived and private extension type declarations are not
20723 checked. Task and protected type declarations also are not checked.
20725 This rule has no parameters.
20728 @node Enumeration_Ranges_In_CASE_Statements
20729 @subsection @code{Enumeration_Ranges_In_CASE_Statements}
20730 @cindex @code{Enumeration_Ranges_In_CASE_Statements} (for @command{gnatcheck})
20733 Flag each use of a range of enumeration literals as a choice in a
20734 @code{case} statement.
20735 All forms for specifying a range (explicit ranges
20736 such as @code{A .. B}, subtype marks and @code{'Range} attributes) are flagged.
20737 An enumeration range is
20738 flagged even if contains exactly one enumeration value or no values at all. A
20739 type derived from an enumeration type is considered as an enumeration type.
20741 This rule helps prevent maintenance problems arising from adding an
20742 enumeration value to a type and having it implicitly handled by an existing
20743 @code{case} statement with an enumeration range that includes the new literal.
20745 This rule has no parameters.
20748 @node Exceptions_As_Control_Flow
20749 @subsection @code{Exceptions_As_Control_Flow}
20750 @cindex @code{Exceptions_As_Control_Flow} (for @command{gnatcheck})
20753 Flag each place where an exception is explicitly raised and handled in the
20754 same subprogram body. A @code{raise} statement in an exception handler,
20755 package body, task body or entry body is not flagged.
20757 The rule has no parameters.
20759 @node EXIT_Statements_With_No_Loop_Name
20760 @subsection @code{EXIT_Statements_With_No_Loop_Name}
20761 @cindex @code{EXIT_Statements_With_No_Loop_Name} (for @command{gnatcheck})
20764 Flag each @code{exit} statement that does not specify the name of the loop
20767 The rule has no parameters.
20770 @node Expanded_Loop_Exit_Names
20771 @subsection @code{Expanded_Loop_Exit_Names}
20772 @cindex @code{Expanded_Loop_Exit_Names} rule (for @command{gnatcheck})
20775 Flag all expanded loop names in @code{exit} statements.
20777 This rule has no parameters.
20779 @node Explicit_Full_Discrete_Ranges
20780 @subsection @code{Explicit_Full_Discrete_Ranges}
20781 @cindex @code{Explicit_Full_Discrete_Ranges} rule (for @command{gnatcheck})
20784 Flag each discrete range that has the form @code{A'First .. A'Last}.
20786 This rule has no parameters.
20788 @node Float_Equality_Checks
20789 @subsection @code{Float_Equality_Checks}
20790 @cindex @code{Float_Equality_Checks} rule (for @command{gnatcheck})
20793 Flag all calls to the predefined equality operations for floating-point types.
20794 Both ``@code{=}'' and ``@code{/=}'' operations are checked.
20795 User-defined equality operations are not flagged, nor are ``@code{=}''
20796 and ``@code{/=}'' operations for fixed-point types.
20798 This rule has no parameters.
20801 @node Forbidden_Pragmas
20802 @subsection @code{Forbidden_Pragmas}
20803 @cindex @code{Forbidden_Pragmas} rule (for @command{gnatcheck})
20806 Flag each use of the specified pragmas. The pragmas to be detected
20807 are named in the rule's parameters.
20809 This rule has the following parameters:
20812 @item For the @option{+R} option
20815 @item @emph{Pragma_Name}
20816 Adds the specified pragma to the set of pragmas to be
20817 checked and sets the checks for all the specified pragmas
20818 ON. @emph{Pragma_Name} is treated as a name of a pragma. If it
20819 does not correspond to any pragma name defined in the Ada
20820 standard or to the name of a GNAT-specific pragma defined
20821 in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
20822 Manual}, it is treated as the name of unknown pragma.
20825 All the GNAT-specific pragmas are detected; this sets
20826 the checks for all the specified pragmas ON.
20829 All pragmas are detected; this sets the rule ON.
20832 @item For the @option{-R} option
20834 @item @emph{Pragma_Name}
20835 Removes the specified pragma from the set of pragmas to be
20836 checked without affecting checks for
20837 other pragmas. @emph{Pragma_Name} is treated as a name
20838 of a pragma. If it does not correspond to any pragma
20839 defined in the Ada standard or to any name defined in
20840 @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
20841 this option is treated as turning OFF detection of all unknown pragmas.
20844 Turn OFF detection of all GNAT-specific pragmas
20847 Clear the list of the pragmas to be detected and
20853 Parameters are not case sensitive. If @emph{Pragma_Name} does not have
20854 the syntax of an Ada identifier and therefore can not be considered
20855 as a pragma name, a diagnostic message is generated and the corresponding
20856 parameter is ignored.
20858 When more then one parameter is given in the same rule option, the parameters
20859 must be separated by a comma.
20861 If more then one option for this rule is specified for the @command{gnatcheck}
20862 call, a new option overrides the previous one(s).
20864 The @option{+R} option with no parameters turns the rule ON with the set of
20865 pragmas to be detected defined by the previous rule options.
20866 (By default this set is empty, so if the only option specified for the rule is
20867 @option{+RForbidden_Pragmas} (with
20868 no parameter), then the rule is enabled, but it does not detect anything).
20869 The @option{-R} option with no parameter turns the rule OFF, but it does not
20870 affect the set of pragmas to be detected.
20875 @node Function_Style_Procedures
20876 @subsection @code{Function_Style_Procedures}
20877 @cindex @code{Function_Style_Procedures} rule (for @command{gnatcheck})
20880 Flag each procedure that can be rewritten as a function. A procedure can be
20881 converted into a function if it has exactly one parameter of mode @code{out}
20882 and no parameters of mode @code{in out}. Procedure declarations,
20883 formal procedure declarations, and generic procedure declarations are always
20885 bodies and body stubs are flagged only if they do not have corresponding
20886 separate declarations. Procedure renamings and procedure instantiations are
20889 If a procedure can be rewritten as a function, but its @code{out} parameter is
20890 of a limited type, it is not flagged.
20892 Protected procedures are not flagged. Null procedures also are not flagged.
20894 This rule has no parameters.
20897 @node Generics_In_Subprograms
20898 @subsection @code{Generics_In_Subprograms}
20899 @cindex @code{Generics_In_Subprograms} rule (for @command{gnatcheck})
20902 Flag each declaration of a generic unit in a subprogram. Generic
20903 declarations in the bodies of generic subprograms are also flagged.
20904 A generic unit nested in another generic unit is not flagged.
20905 If a generic unit is
20906 declared in a local package that is declared in a subprogram body, the
20907 generic unit is flagged.
20909 This rule has no parameters.
20912 @node GOTO_Statements
20913 @subsection @code{GOTO_Statements}
20914 @cindex @code{GOTO_Statements} rule (for @command{gnatcheck})
20917 Flag each occurrence of a @code{goto} statement.
20919 This rule has no parameters.
20922 @node Implicit_IN_Mode_Parameters
20923 @subsection @code{Implicit_IN_Mode_Parameters}
20924 @cindex @code{Implicit_IN_Mode_Parameters} rule (for @command{gnatcheck})
20927 Flag each occurrence of a formal parameter with an implicit @code{in} mode.
20928 Note that @code{access} parameters, although they technically behave
20929 like @code{in} parameters, are not flagged.
20931 This rule has no parameters.
20934 @node Implicit_SMALL_For_Fixed_Point_Types
20935 @subsection @code{Implicit_SMALL_For_Fixed_Point_Types}
20936 @cindex @code{Implicit_SMALL_For_Fixed_Point_Types} rule (for @command{gnatcheck})
20939 Flag each fixed point type declaration that lacks an explicit
20940 representation clause to define its @code{'Small} value.
20941 Since @code{'Small} can be defined only for ordinary fixed point types,
20942 decimal fixed point type declarations are not checked.
20944 This rule has no parameters.
20947 @node Improperly_Located_Instantiations
20948 @subsection @code{Improperly_Located_Instantiations}
20949 @cindex @code{Improperly_Located_Instantiations} rule (for @command{gnatcheck})
20952 Flag all generic instantiations in library-level package specs
20953 (including library generic packages) and in all subprogram bodies.
20955 Instantiations in task and entry bodies are not flagged. Instantiations in the
20956 bodies of protected subprograms are flagged.
20958 This rule has no parameters.
20962 @node Improper_Returns
20963 @subsection @code{Improper_Returns}
20964 @cindex @code{Improper_Returns} rule (for @command{gnatcheck})
20967 Flag each explicit @code{return} statement in procedures, and
20968 multiple @code{return} statements in functions.
20969 Diagnostic messages are generated for all @code{return} statements
20970 in a procedure (thus each procedure must be written so that it
20971 returns implicitly at the end of its statement part),
20972 and for all @code{return} statements in a function after the first one.
20973 This rule supports the stylistic convention that each subprogram
20974 should have no more than one point of normal return.
20976 This rule has no parameters.
20979 @node Library_Level_Subprograms
20980 @subsection @code{Library_Level_Subprograms}
20981 @cindex @code{Library_Level_Subprograms} rule (for @command{gnatcheck})
20984 Flag all library-level subprograms (including generic subprogram instantiations).
20986 This rule has no parameters.
20989 @node Local_Packages
20990 @subsection @code{Local_Packages}
20991 @cindex @code{Local_Packages} rule (for @command{gnatcheck})
20994 Flag all local packages declared in package and generic package
20996 Local packages in bodies are not flagged.
20998 This rule has no parameters.
21001 @node Improperly_Called_Protected_Entries
21002 @subsection @code{Improperly_Called_Protected_Entries} (under construction, GLOBAL)
21003 @cindex @code{Improperly_Called_Protected_Entries} rule (for @command{gnatcheck})
21006 Flag each protected entry that can be called from more than one task.
21008 This rule has no parameters.
21011 @node Metrics_Violation
21012 @subsection @code{Metrics_Violation}
21013 @cindex @code{Metrics} rule (for @command{gnatcheck})
21016 This is an umbrella rule for a set of metrics-based checks. The parameters of
21017 the rule specify which metrics should be checked, and a bound (upper or lower,
21018 depending on the metric) for each specified metric. A construct is
21019 flagged if a specified metric can be computed for it, and the resulting value
21020 is higher then the upper bound (or less than the lower bound) specified.
21022 This rule has the following parameters:
21026 For the @option{+R} option:
21028 @item @i{Metric_Check_Name} < @i{LowerBound}
21029 Turns the check for the specified metric ON and specifies the lower bound
21030 for a given metric check
21032 @item @i{Metric_Check_Name} > @i{UpperBound}
21034 Turns the check for the specified metric ON and specifies the upper bound
21035 for a given metric check
21039 For the @option{-R} option:
21041 @item @i{Metric_Check_Name}
21042 Turns the check for the specified metric OFF
21047 Parameters are not case-sensitive. @i{Metric_Check_Name} must be
21048 the name of a metric supported by the @code{Metrics_Violation} rule
21049 (see the table below),
21050 otherwise the parameter is ignored. Whether the upper or lower bound
21051 is specified for a given check, depends on the metric. If a
21052 parameter for the @option{+R} option specifies an invalid limit, a
21053 warning is issued and the parameter is ignored.
21055 The @option{-R} option without parameters turns OFF all the previously enabled
21056 metric checks. the @option{+R} option without parameters turns ON all the
21057 metric checks that have been defined by previous @option{+R} options with
21058 valid parameters. @option{+R} option with a valid
21059 parameter also turns ON all the other metric checks that have been defined
21060 by previous @option{+R} options with valid parameters if they have been
21061 disabled by @option{-R} option without parameters.
21063 By default no metrics checks are ON, so the @option{+R} option without
21064 parameters actually does not specify any check.
21066 The following table shows the available metrics-based checks,
21067 including the constraint that must be satisfied by the bound that
21068 is specified for the check.
21070 @multitable {@code{Cyclomatic_Complexity}}{Cyclomatic complexity}{Positive integer}
21072 @headitem Check Name @tab Description @tab Bounds Value
21075 @item @b{Check Name} @tab @b{Description} @tab @b{Bounds Value}
21077 @c Above conditional code is workaround to bug in texi2html (Feb 2008)
21078 @item @code{Essential_Complexity} @tab Essential complexity @tab Positive integer
21079 @item @code{Cyclomatic_Complexity} @tab Cyclomatic complexity @tab Positive integer
21080 @item @code{LSLOC} @tab Logical Source Lines of Code @tab Positive integer
21084 The meaning and the computed values for all these metrics are exactly
21085 the same as for the corresponding metrics in @command{gnatmetric}.
21087 @emph{Example:} the rule
21089 +RMetrics_Violation: Cyclomatic_Complexity > 7
21092 means that all bodies with cyclomatic complexity exceeding 7 will be flagged.
21094 @node Misnamed_Identifiers
21095 @subsection @code{Misnamed_Identifiers}
21096 @cindex @code{Misnamed_Identifiers} rule (for @command{gnatcheck})
21099 Flag the declaration of each identifier that does not have a suffix
21100 corresponding to the kind of entity being declared.
21101 The following declarations are checked:
21108 constant declarations (but not number declarations)
21111 package renaming declarations (but not generic package renaming
21116 This rule may have parameters. When used without parameters, the rule enforces
21117 the following checks:
21121 type-defining names end with @code{_T}, unless the type is an access type,
21122 in which case the suffix must be @code{_A}
21124 constant names end with @code{_C}
21126 names defining package renamings end with @code{_R}
21130 For a private or incomplete type declaration the following checks are
21131 made for the defining name suffix:
21135 For an incomplete type declaration: if the corresponding full type
21136 declaration is available, the defining identifier from the full type
21137 declaration is checked, but the defining identifier from the incomplete type
21138 declaration is not; otherwise the defining identifier from the incomplete
21139 type declaration is checked against the suffix specified for type
21143 For a private type declaration (including private extensions), the defining
21144 identifier from the private type declaration is checked against the type
21145 suffix (even if the corresponding full declaration is an access type
21146 declaration), and the defining identifier from the corresponding full type
21147 declaration is not checked.
21151 For a deferred constant, the defining name in the corresponding full constant
21152 declaration is not checked.
21154 Defining names of formal types are not checked.
21156 The rule may have the following parameters:
21160 For the @option{+R} option:
21163 Sets the default listed above for all the names to be checked.
21165 @item Type_Suffix=@emph{string}
21166 Specifies the suffix for a type name.
21168 @item Access_Suffix=@emph{string}
21169 Specifies the suffix for an access type name. If
21170 this parameter is set, it overrides for access
21171 types the suffix set by the @code{Type_Suffix} parameter.
21173 @item Constant_Suffix=@emph{string}
21174 Specifies the suffix for a constant name.
21176 @item Renaming_Suffix=@emph{string}
21177 Specifies the suffix for a package renaming name.
21181 For the @option{-R} option:
21184 Remove all the suffixes specified for the
21185 identifier suffix checks, whether by default or
21186 as specified by other rule parameters. All the
21187 checks for this rule are disabled as a result.
21190 Removes the suffix specified for types. This
21191 disables checks for types but does not disable
21192 any other checks for this rule (including the
21193 check for access type names if @code{Access_Suffix} is
21196 @item Access_Suffix
21197 Removes the suffix specified for access types.
21198 This disables checks for access type names but
21199 does not disable any other checks for this rule.
21200 If @code{Type_Suffix} is set, access type names are
21201 checked as ordinary type names.
21203 @item Constant_Suffix
21204 Removes the suffix specified for constants. This
21205 disables checks for constant names but does not
21206 disable any other checks for this rule.
21208 @item Renaming_Suffix
21209 Removes the suffix specified for package
21210 renamings. This disables checks for package
21211 renamings but does not disable any other checks
21217 If more than one parameter is used, parameters must be separated by commas.
21219 If more than one option is specified for the @command{gnatcheck} invocation,
21220 a new option overrides the previous one(s).
21222 The @option{+RMisnamed_Identifiers} option (with no parameter) enables
21224 name suffixes specified by previous options used for this rule.
21226 The @option{-RMisnamed_Identifiers} option (with no parameter) disables
21227 all the checks but keeps
21228 all the suffixes specified by previous options used for this rule.
21230 The @emph{string} value must be a valid suffix for an Ada identifier (after
21231 trimming all the leading and trailing space characters, if any).
21232 Parameters are not case sensitive, except the @emph{string} part.
21234 If any error is detected in a rule parameter, the parameter is ignored.
21235 In such a case the options that are set for the rule are not
21240 @node Multiple_Entries_In_Protected_Definitions
21241 @subsection @code{Multiple_Entries_In_Protected_Definitions}
21242 @cindex @code{Multiple_Entries_In_Protected_Definitions} rule (for @command{gnatcheck})
21245 Flag each protected definition (i.e., each protected object/type declaration)
21246 that defines more than one entry.
21247 Diagnostic messages are generated for all the entry declarations
21248 except the first one. An entry family is counted as one entry. Entries from
21249 the private part of the protected definition are also checked.
21251 This rule has no parameters.
21254 @subsection @code{Name_Clashes}
21255 @cindex @code{Name_Clashes} rule (for @command{gnatcheck})
21258 Check that certain names are not used as defining identifiers. To activate
21259 this rule, you need to supply a reference to the dictionary file(s) as a rule
21260 parameter(s) (more then one dictionary file can be specified). If no
21261 dictionary file is set, this rule will not cause anything to be flagged.
21262 Only defining occurrences, not references, are checked.
21263 The check is not case-sensitive.
21265 This rule is enabled by default, but without setting any corresponding
21266 dictionary file(s); thus the default effect is to do no checks.
21268 A dictionary file is a plain text file. The maximum line length for this file
21269 is 1024 characters. If the line is longer then this limit, extra characters
21272 Each line can be either an empty line, a comment line, or a line containing
21273 a list of identifiers separated by space or HT characters.
21274 A comment is an Ada-style comment (from @code{--} to end-of-line).
21275 Identifiers must follow the Ada syntax for identifiers.
21276 A line containing one or more identifiers may end with a comment.
21278 @node Non_Qualified_Aggregates
21279 @subsection @code{Non_Qualified_Aggregates}
21280 @cindex @code{Non_Qualified_Aggregates} rule (for @command{gnatcheck})
21283 Flag each non-qualified aggregate.
21284 A non-qualified aggregate is an
21285 aggregate that is not the expression of a qualified expression. A
21286 string literal is not considered an aggregate, but an array
21287 aggregate of a string type is considered as a normal aggregate.
21288 Aggregates of anonymous array types are not flagged.
21290 This rule has no parameters.
21293 @node Non_Short_Circuit_Operators
21294 @subsection @code{Non_Short_Circuit_Operators}
21295 @cindex @code{Non_Short_Circuit_Operators} rule (for @command{gnatcheck})
21298 Flag all calls to predefined @code{and} and @code{or} operators for
21299 any boolean type. Calls to
21300 user-defined @code{and} and @code{or} and to operators defined by renaming
21301 declarations are not flagged. Calls to predefined @code{and} and @code{or}
21302 operators for modular types or boolean array types are not flagged.
21304 This rule has no parameters.
21308 @node Non_SPARK_Attributes
21309 @subsection @code{Non_SPARK_Attributes}
21310 @cindex @code{Non_SPARK_Attributes} rule (for @command{gnatcheck})
21313 The SPARK language defines the following subset of Ada 95 attribute
21314 designators as those that can be used in SPARK programs. The use of
21315 any other attribute is flagged.
21318 @item @code{'Adjacent}
21321 @item @code{'Ceiling}
21322 @item @code{'Component_Size}
21323 @item @code{'Compose}
21324 @item @code{'Copy_Sign}
21325 @item @code{'Delta}
21326 @item @code{'Denorm}
21327 @item @code{'Digits}
21328 @item @code{'Exponent}
21329 @item @code{'First}
21330 @item @code{'Floor}
21332 @item @code{'Fraction}
21334 @item @code{'Leading_Part}
21335 @item @code{'Length}
21336 @item @code{'Machine}
21337 @item @code{'Machine_Emax}
21338 @item @code{'Machine_Emin}
21339 @item @code{'Machine_Mantissa}
21340 @item @code{'Machine_Overflows}
21341 @item @code{'Machine_Radix}
21342 @item @code{'Machine_Rounds}
21345 @item @code{'Model}
21346 @item @code{'Model_Emin}
21347 @item @code{'Model_Epsilon}
21348 @item @code{'Model_Mantissa}
21349 @item @code{'Model_Small}
21350 @item @code{'Modulus}
21353 @item @code{'Range}
21354 @item @code{'Remainder}
21355 @item @code{'Rounding}
21356 @item @code{'Safe_First}
21357 @item @code{'Safe_Last}
21358 @item @code{'Scaling}
21359 @item @code{'Signed_Zeros}
21361 @item @code{'Small}
21363 @item @code{'Truncation}
21364 @item @code{'Unbiased_Rounding}
21366 @item @code{'Valid}
21370 This rule has no parameters.
21373 @node Non_Tagged_Derived_Types
21374 @subsection @code{Non_Tagged_Derived_Types}
21375 @cindex @code{Non_Tagged_Derived_Types} rule (for @command{gnatcheck})
21378 Flag all derived type declarations that do not have a record extension part.
21380 This rule has no parameters.
21384 @node Non_Visible_Exceptions
21385 @subsection @code{Non_Visible_Exceptions}
21386 @cindex @code{Non_Visible_Exceptions} rule (for @command{gnatcheck})
21389 Flag constructs leading to the possibility of propagating an exception
21390 out of the scope in which the exception is declared.
21391 Two cases are detected:
21395 An exception declaration in a subprogram body, task body or block
21396 statement is flagged if the body or statement does not contain a handler for
21397 that exception or a handler with an @code{others} choice.
21400 A @code{raise} statement in an exception handler of a subprogram body,
21401 task body or block statement is flagged if it (re)raises a locally
21402 declared exception. This may occur under the following circumstances:
21405 it explicitly raises a locally declared exception, or
21407 it does not specify an exception name (i.e., it is simply @code{raise;})
21408 and the enclosing handler contains a locally declared exception in its
21414 Renamings of local exceptions are not flagged.
21416 This rule has no parameters.
21419 @node Numeric_Literals
21420 @subsection @code{Numeric_Literals}
21421 @cindex @code{Numeric_Literals} rule (for @command{gnatcheck})
21424 Flag each use of a numeric literal in an index expression, and in any
21425 circumstance except for the following:
21429 a literal occurring in the initialization expression for a constant
21430 declaration or a named number declaration, or
21433 an integer literal that is less than or equal to a value
21434 specified by the @option{N} rule parameter.
21438 This rule may have the following parameters for the @option{+R} option:
21442 @emph{N} is an integer literal used as the maximal value that is not flagged
21443 (i.e., integer literals not exceeding this value are allowed)
21446 All integer literals are flagged
21450 If no parameters are set, the maximum unflagged value is 1.
21452 The last specified check limit (or the fact that there is no limit at
21453 all) is used when multiple @option{+R} options appear.
21455 The @option{-R} option for this rule has no parameters.
21456 It disables the rule but retains the last specified maximum unflagged value.
21457 If the @option{+R} option subsequently appears, this value is used as the
21458 threshold for the check.
21461 @node OTHERS_In_Aggregates
21462 @subsection @code{OTHERS_In_Aggregates}
21463 @cindex @code{OTHERS_In_Aggregates} rule (for @command{gnatcheck})
21466 Flag each use of an @code{others} choice in extension aggregates.
21467 In record and array aggregates, an @code{others} choice is flagged unless
21468 it is used to refer to all components, or to all but one component.
21470 If, in case of a named array aggregate, there are two associations, one
21471 with an @code{others} choice and another with a discrete range, the
21472 @code{others} choice is flagged even if the discrete range specifies
21473 exactly one component; for example, @code{(1..1 => 0, others => 1)}.
21475 This rule has no parameters.
21477 @node OTHERS_In_CASE_Statements
21478 @subsection @code{OTHERS_In_CASE_Statements}
21479 @cindex @code{OTHERS_In_CASE_Statements} rule (for @command{gnatcheck})
21482 Flag any use of an @code{others} choice in a @code{case} statement.
21484 This rule has no parameters.
21486 @node OTHERS_In_Exception_Handlers
21487 @subsection @code{OTHERS_In_Exception_Handlers}
21488 @cindex @code{OTHERS_In_Exception_Handlers} rule (for @command{gnatcheck})
21491 Flag any use of an @code{others} choice in an exception handler.
21493 This rule has no parameters.
21496 @node Outer_Loop_Exits
21497 @subsection @code{Outer_Loop_Exits}
21498 @cindex @code{Outer_Loop_Exits} rule (for @command{gnatcheck})
21501 Flag each @code{exit} statement containing a loop name that is not the name
21502 of the immediately enclosing @code{loop} statement.
21504 This rule has no parameters.
21507 @node Overloaded_Operators
21508 @subsection @code{Overloaded_Operators}
21509 @cindex @code{Overloaded_Operators} rule (for @command{gnatcheck})
21512 Flag each function declaration that overloads an operator symbol.
21513 A function body is checked only if the body does not have a
21514 separate spec. Formal functions are also checked. For a
21515 renaming declaration, only renaming-as-declaration is checked
21517 This rule has no parameters.
21520 @node Overly_Nested_Control_Structures
21521 @subsection @code{Overly_Nested_Control_Structures}
21522 @cindex @code{Overly_Nested_Control_Structures} rule (for @command{gnatcheck})
21525 Flag each control structure whose nesting level exceeds the value provided
21526 in the rule parameter.
21528 The control structures checked are the following:
21531 @item @code{if} statement
21532 @item @code{case} statement
21533 @item @code{loop} statement
21534 @item Selective accept statement
21535 @item Timed entry call statement
21536 @item Conditional entry call
21537 @item Asynchronous select statement
21541 The rule may have the following parameter for the @option{+R} option:
21545 Positive integer specifying the maximal control structure nesting
21546 level that is not flagged
21550 If the parameter for the @option{+R} option is not a positive integer,
21551 the parameter is ignored and the rule is turned ON with the most recently
21552 specified maximal non-flagged nesting level.
21554 If more then one option is specified for the gnatcheck call, the later option and
21555 new parameter override the previous one(s).
21557 A @option{+R} option with no parameter turns the rule ON using the maximal
21558 non-flagged nesting level specified by the most recent @option{+R} option with
21559 a parameter, or the value 4 if there is no such previous @option{+R} option.
21563 @node Parameters_Out_Of_Order
21564 @subsection @code{Parameters_Out_Of_Order}
21565 @cindex @code{Parameters_Out_Of_Order} rule (for @command{gnatcheck})
21568 Flag each subprogram and entry declaration whose formal parameters are not
21569 ordered according to the following scheme:
21573 @item @code{in} and @code{access} parameters first,
21574 then @code{in out} parameters,
21575 and then @code{out} parameters;
21577 @item for @code{in} mode, parameters with default initialization expressions
21582 Only the first violation of the described order is flagged.
21584 The following constructs are checked:
21587 @item subprogram declarations (including null procedures);
21588 @item generic subprogram declarations;
21589 @item formal subprogram declarations;
21590 @item entry declarations;
21591 @item subprogram bodies and subprogram body stubs that do not
21592 have separate specifications
21596 Subprogram renamings are not checked.
21598 This rule has no parameters.
21601 @node Positional_Actuals_For_Defaulted_Generic_Parameters
21602 @subsection @code{Positional_Actuals_For_Defaulted_Generic_Parameters}
21603 @cindex @code{Positional_Actuals_For_Defaulted_Generic_Parameters} rule (for @command{gnatcheck})
21606 Flag each generic actual parameter corresponding to a generic formal
21607 parameter with a default initialization, if positional notation is used.
21609 This rule has no parameters.
21611 @node Positional_Actuals_For_Defaulted_Parameters
21612 @subsection @code{Positional_Actuals_For_Defaulted_Parameters}
21613 @cindex @code{Positional_Actuals_For_Defaulted_Parameters} rule (for @command{gnatcheck})
21616 Flag each actual parameter to a subprogram or entry call where the
21617 corresponding formal parameter has a default expression, if positional
21620 This rule has no parameters.
21622 @node Positional_Components
21623 @subsection @code{Positional_Components}
21624 @cindex @code{Positional_Components} rule (for @command{gnatcheck})
21627 Flag each array, record and extension aggregate that includes positional
21630 This rule has no parameters.
21633 @node Positional_Generic_Parameters
21634 @subsection @code{Positional_Generic_Parameters}
21635 @cindex @code{Positional_Generic_Parameters} rule (for @command{gnatcheck})
21638 Flag each instantiation using positional parameter notation.
21640 This rule has no parameters.
21643 @node Positional_Parameters
21644 @subsection @code{Positional_Parameters}
21645 @cindex @code{Positional_Parameters} rule (for @command{gnatcheck})
21648 Flag each subprogram or entry call using positional parameter notation,
21649 except for the following:
21653 Invocations of prefix or infix operators are not flagged
21655 If the called subprogram or entry has only one formal parameter,
21656 the call is not flagged;
21658 If a subprogram call uses the @emph{Object.Operation} notation, then
21661 the first parameter (that is, @emph{Object}) is not flagged;
21663 if the called subprogram has only two parameters, the second parameter
21664 of the call is not flagged;
21669 This rule has no parameters.
21674 @node Predefined_Numeric_Types
21675 @subsection @code{Predefined_Numeric_Types}
21676 @cindex @code{Predefined_Numeric_Types} rule (for @command{gnatcheck})
21679 Flag each explicit use of the name of any numeric type or subtype defined
21680 in package @code{Standard}.
21682 The rationale for this rule is to detect when the
21683 program may depend on platform-specific characteristics of the implementation
21684 of the predefined numeric types. Note that this rule is over-pessimistic;
21685 for example, a program that uses @code{String} indexing
21686 likely needs a variable of type @code{Integer}.
21687 Another example is the flagging of predefined numeric types with explicit
21690 @smallexample @c ada
21691 subtype My_Integer is Integer range Left .. Right;
21692 Vy_Var : My_Integer;
21696 This rule detects only numeric types and subtypes defined in
21697 @code{Standard}. The use of numeric types and subtypes defined in other
21698 predefined packages (such as @code{System.Any_Priority} or
21699 @code{Ada.Text_IO.Count}) is not flagged
21701 This rule has no parameters.
21705 @node Raising_External_Exceptions
21706 @subsection @code{Raising_External_Exceptions}
21707 @cindex @code{Raising_External_Exceptions} rule (for @command{gnatcheck})
21710 Flag any @code{raise} statement, in a program unit declared in a library
21711 package or in a generic library package, for an exception that is
21712 neither a predefined exception nor an exception that is also declared (or
21713 renamed) in the visible part of the package.
21715 This rule has no parameters.
21719 @node Raising_Predefined_Exceptions
21720 @subsection @code{Raising_Predefined_Exceptions}
21721 @cindex @code{Raising_Predefined_Exceptions} rule (for @command{gnatcheck})
21724 Flag each @code{raise} statement that raises a predefined exception
21725 (i.e., one of the exceptions @code{Constraint_Error}, @code{Numeric_Error},
21726 @code{Program_Error}, @code{Storage_Error}, or @code{Tasking_Error}).
21728 This rule has no parameters.
21730 @node Separate_Numeric_Error_Handlers
21731 @subsection @code{Separate_Numeric_Error_Handlers}
21732 @cindex @code{Separate_Numeric_Error_Handlers} rule (for @command{gnatcheck})
21735 Flags each exception handler that contains a choice for
21736 the predefined @code{Constraint_Error} exception, but does not contain
21737 the choice for the predefined @code{Numeric_Error} exception, or
21738 that contains the choice for @code{Numeric_Error}, but does not contain the
21739 choice for @code{Constraint_Error}.
21741 This rule has no parameters.
21745 @subsection @code{Recursion} (under construction, GLOBAL)
21746 @cindex @code{Recursion} rule (for @command{gnatcheck})
21749 Flag recursive subprograms (cycles in the call graph). Declarations, and not
21750 calls, of recursive subprograms are detected.
21752 This rule has no parameters.
21756 @node Side_Effect_Functions
21757 @subsection @code{Side_Effect_Functions} (under construction, GLOBAL)
21758 @cindex @code{Side_Effect_Functions} rule (for @command{gnatcheck})
21761 Flag functions with side effects.
21763 We define a side effect as changing any data object that is not local for the
21764 body of this function.
21766 At the moment, we do NOT consider a side effect any input-output operations
21767 (changing a state or a content of any file).
21769 We do not consider protected functions for this rule (???)
21771 There are the following sources of side effect:
21774 @item Explicit (or direct) side-effect:
21778 direct assignment to a non-local variable;
21781 direct call to an entity that is known to change some data object that is
21782 not local for the body of this function (Note, that if F1 calls F2 and F2
21783 does have a side effect, this does not automatically mean that F1 also
21784 have a side effect, because it may be the case that F2 is declared in
21785 F1's body and it changes some data object that is global for F2, but
21789 @item Indirect side-effect:
21792 Subprogram calls implicitly issued by:
21795 computing initialization expressions from type declarations as a part
21796 of object elaboration or allocator evaluation;
21798 computing implicit parameters of subprogram or entry calls or generic
21803 activation of a task that change some non-local data object (directly or
21807 elaboration code of a package that is a result of a package instantiation;
21810 controlled objects;
21813 @item Situations when we can suspect a side-effect, but the full static check
21814 is either impossible or too hard:
21817 assignment to access variables or to the objects pointed by access
21821 call to a subprogram pointed by access-to-subprogram value
21829 This rule has no parameters.
21833 @subsection @code{Slices}
21834 @cindex @code{Slices} rule (for @command{gnatcheck})
21837 Flag all uses of array slicing
21839 This rule has no parameters.
21842 @node Unassigned_OUT_Parameters
21843 @subsection @code{Unassigned_OUT_Parameters}
21844 @cindex @code{Unassigned_OUT_Parameters} rule (for @command{gnatcheck})
21847 Flags procedures' @code{out} parameters that are not assigned, and
21848 identifies the contexts in which the assignments are missing.
21850 An @code{out} parameter is flagged in the statements in the procedure
21851 body's handled sequence of statements (before the procedure body's
21852 @code{exception} part, if any) if this sequence of statements contains
21853 no assignments to the parameter.
21855 An @code{out} parameter is flagged in an exception handler in the exception
21856 part of the procedure body's handled sequence of statements if the handler
21857 contains no assignment to the parameter.
21859 Bodies of generic procedures are also considered.
21861 The following are treated as assignments to an @code{out} parameter:
21865 an assignment statement, with the parameter or some component as the target;
21868 passing the parameter (or one of its components) as an @code{out} or
21869 @code{in out} parameter.
21873 This rule does not have any parameters.
21877 @node Uncommented_BEGIN_In_Package_Bodies
21878 @subsection @code{Uncommented_BEGIN_In_Package_Bodies}
21879 @cindex @code{Uncommented_BEGIN_In_Package_Bodies} rule (for @command{gnatcheck})
21882 Flags each package body with declarations and a statement part that does not
21883 include a trailing comment on the line containing the @code{begin} keyword;
21884 this trailing comment needs to specify the package name and nothing else.
21885 The @code{begin} is not flagged if the package body does not
21886 contain any declarations.
21888 If the @code{begin} keyword is placed on the
21889 same line as the last declaration or the first statement, it is flagged
21890 independently of whether the line contains a trailing comment. The
21891 diagnostic message is attached to the line containing the first statement.
21893 This rule has no parameters.
21896 @node Unconstrained_Array_Returns
21897 @subsection @code{Unconstrained_Array_Returns}
21898 @cindex @code{Unconstrained_Array_Returns} rule (for @command{gnatcheck})
21901 Flag each function returning an unconstrained array. Function declarations,
21902 function bodies (and body stubs) having no separate specifications,
21903 and generic function instantiations are checked.
21904 Generic function declarations, function calls and function renamings are
21907 This rule has no parameters.
21909 @node Universal_Ranges
21910 @subsection @code{Universal_Ranges}
21911 @cindex @code{Universal_Ranges} rule (for @command{gnatcheck})
21914 Flag discrete ranges that are a part of an index constraint, constrained
21915 array definition, or @code{for}-loop parameter specification, and whose bounds
21916 are both of type @i{universal_integer}. Ranges that have at least one
21917 bound of a specific type (such as @code{1 .. N}, where @code{N} is a variable
21918 or an expression of non-universal type) are not flagged.
21920 This rule has no parameters.
21923 @node Unnamed_Blocks_And_Loops
21924 @subsection @code{Unnamed_Blocks_And_Loops}
21925 @cindex @code{Unnamed_Blocks_And_Loops} rule (for @command{gnatcheck})
21928 Flag each unnamed block statement and loop statement.
21930 The rule has no parameters.
21935 @node Unused_Subprograms
21936 @subsection @code{Unused_Subprograms} (under construction, GLOBAL)
21937 @cindex @code{Unused_Subprograms} rule (for @command{gnatcheck})
21940 Flag all unused subprograms.
21942 This rule has no parameters.
21948 @node USE_PACKAGE_Clauses
21949 @subsection @code{USE_PACKAGE_Clauses}
21950 @cindex @code{USE_PACKAGE_Clauses} rule (for @command{gnatcheck})
21953 Flag all @code{use} clauses for packages; @code{use type} clauses are
21956 This rule has no parameters.
21960 @node Volatile_Objects_Without_Address_Clauses
21961 @subsection @code{Volatile_Objects_Without_Address_Clauses}
21962 @cindex @code{Volatile_Objects_Without_Address_Clauses} rule (for @command{gnatcheck})
21965 Flag each volatile object that does not have an address clause.
21967 The following check is made: if the pragma @code{Volatile} is applied to a
21968 data object or to its type, then an address clause must
21969 be supplied for this object.
21971 This rule does not check the components of data objects,
21972 array components that are volatile as a result of the pragma
21973 @code{Volatile_Components}, or objects that are volatile because
21974 they are atomic as a result of pragmas @code{Atomic} or
21975 @code{Atomic_Components}.
21977 Only variable declarations, and not constant declarations, are checked.
21979 This rule has no parameters.
21982 @c *********************************
21983 @node Creating Sample Bodies Using gnatstub
21984 @chapter Creating Sample Bodies Using @command{gnatstub}
21988 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
21989 for library unit declarations.
21991 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
21992 driver (see @ref{The GNAT Driver and Project Files}).
21994 To create a body stub, @command{gnatstub} has to compile the library
21995 unit declaration. Therefore, bodies can be created only for legal
21996 library units. Moreover, if a library unit depends semantically upon
21997 units located outside the current directory, you have to provide
21998 the source search path when calling @command{gnatstub}, see the description
21999 of @command{gnatstub} switches below.
22002 * Running gnatstub::
22003 * Switches for gnatstub::
22006 @node Running gnatstub
22007 @section Running @command{gnatstub}
22010 @command{gnatstub} has the command-line interface of the form
22013 $ gnatstub [switches] filename [directory]
22020 is the name of the source file that contains a library unit declaration
22021 for which a body must be created. The file name may contain the path
22023 The file name does not have to follow the GNAT file name conventions. If the
22025 does not follow GNAT file naming conventions, the name of the body file must
22027 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
22028 If the file name follows the GNAT file naming
22029 conventions and the name of the body file is not provided,
22032 of the body file from the argument file name by replacing the @file{.ads}
22034 with the @file{.adb} suffix.
22037 indicates the directory in which the body stub is to be placed (the default
22042 is an optional sequence of switches as described in the next section
22045 @node Switches for gnatstub
22046 @section Switches for @command{gnatstub}
22052 @cindex @option{^-f^/FULL^} (@command{gnatstub})
22053 If the destination directory already contains a file with the name of the
22055 for the argument spec file, replace it with the generated body stub.
22057 @item ^-hs^/HEADER=SPEC^
22058 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
22059 Put the comment header (i.e., all the comments preceding the
22060 compilation unit) from the source of the library unit declaration
22061 into the body stub.
22063 @item ^-hg^/HEADER=GENERAL^
22064 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
22065 Put a sample comment header into the body stub.
22067 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
22068 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
22069 Use the content of the file as the comment header for a generated body stub.
22073 @cindex @option{-IDIR} (@command{gnatstub})
22075 @cindex @option{-I-} (@command{gnatstub})
22078 @item /NOCURRENT_DIRECTORY
22079 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
22081 ^These switches have ^This switch has^ the same meaning as in calls to
22083 ^They define ^It defines ^ the source search path in the call to
22084 @command{gcc} issued
22085 by @command{gnatstub} to compile an argument source file.
22087 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
22088 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
22089 This switch has the same meaning as in calls to @command{gcc}.
22090 It defines the additional configuration file to be passed to the call to
22091 @command{gcc} issued
22092 by @command{gnatstub} to compile an argument source file.
22094 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
22095 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
22096 (@var{n} is a non-negative integer). Set the maximum line length in the
22097 body stub to @var{n}; the default is 79. The maximum value that can be
22098 specified is 32767. Note that in the special case of configuration
22099 pragma files, the maximum is always 32767 regardless of whether or
22100 not this switch appears.
22102 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
22103 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
22104 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
22105 the generated body sample to @var{n}.
22106 The default indentation is 3.
22108 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
22109 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
22110 Order local bodies alphabetically. (By default local bodies are ordered
22111 in the same way as the corresponding local specs in the argument spec file.)
22113 @item ^-i^/INDENTATION=^@var{n}
22114 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
22115 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
22117 @item ^-k^/TREE_FILE=SAVE^
22118 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
22119 Do not remove the tree file (i.e., the snapshot of the compiler internal
22120 structures used by @command{gnatstub}) after creating the body stub.
22122 @item ^-l^/LINE_LENGTH=^@var{n}
22123 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
22124 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
22126 @item ^-o^/BODY=^@var{body-name}
22127 @cindex @option{^-o^/BODY^} (@command{gnatstub})
22128 Body file name. This should be set if the argument file name does not
22130 the GNAT file naming
22131 conventions. If this switch is omitted the default name for the body will be
22133 from the argument file name according to the GNAT file naming conventions.
22136 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
22137 Quiet mode: do not generate a confirmation when a body is
22138 successfully created, and do not generate a message when a body is not
22142 @item ^-r^/TREE_FILE=REUSE^
22143 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
22144 Reuse the tree file (if it exists) instead of creating it. Instead of
22145 creating the tree file for the library unit declaration, @command{gnatstub}
22146 tries to find it in the current directory and use it for creating
22147 a body. If the tree file is not found, no body is created. This option
22148 also implies @option{^-k^/SAVE^}, whether or not
22149 the latter is set explicitly.
22151 @item ^-t^/TREE_FILE=OVERWRITE^
22152 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
22153 Overwrite the existing tree file. If the current directory already
22154 contains the file which, according to the GNAT file naming rules should
22155 be considered as a tree file for the argument source file,
22157 will refuse to create the tree file needed to create a sample body
22158 unless this option is set.
22160 @item ^-v^/VERBOSE^
22161 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
22162 Verbose mode: generate version information.
22166 @node Other Utility Programs
22167 @chapter Other Utility Programs
22170 This chapter discusses some other utility programs available in the Ada
22174 * Using Other Utility Programs with GNAT::
22175 * The External Symbol Naming Scheme of GNAT::
22176 * Converting Ada Files to html with gnathtml::
22177 * Installing gnathtml::
22184 @node Using Other Utility Programs with GNAT
22185 @section Using Other Utility Programs with GNAT
22188 The object files generated by GNAT are in standard system format and in
22189 particular the debugging information uses this format. This means
22190 programs generated by GNAT can be used with existing utilities that
22191 depend on these formats.
22194 In general, any utility program that works with C will also often work with
22195 Ada programs generated by GNAT. This includes software utilities such as
22196 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
22200 @node The External Symbol Naming Scheme of GNAT
22201 @section The External Symbol Naming Scheme of GNAT
22204 In order to interpret the output from GNAT, when using tools that are
22205 originally intended for use with other languages, it is useful to
22206 understand the conventions used to generate link names from the Ada
22209 All link names are in all lowercase letters. With the exception of library
22210 procedure names, the mechanism used is simply to use the full expanded
22211 Ada name with dots replaced by double underscores. For example, suppose
22212 we have the following package spec:
22214 @smallexample @c ada
22225 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
22226 the corresponding link name is @code{qrs__mn}.
22228 Of course if a @code{pragma Export} is used this may be overridden:
22230 @smallexample @c ada
22235 pragma Export (Var1, C, External_Name => "var1_name");
22237 pragma Export (Var2, C, Link_Name => "var2_link_name");
22244 In this case, the link name for @var{Var1} is whatever link name the
22245 C compiler would assign for the C function @var{var1_name}. This typically
22246 would be either @var{var1_name} or @var{_var1_name}, depending on operating
22247 system conventions, but other possibilities exist. The link name for
22248 @var{Var2} is @var{var2_link_name}, and this is not operating system
22252 One exception occurs for library level procedures. A potential ambiguity
22253 arises between the required name @code{_main} for the C main program,
22254 and the name we would otherwise assign to an Ada library level procedure
22255 called @code{Main} (which might well not be the main program).
22257 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
22258 names. So if we have a library level procedure such as
22260 @smallexample @c ada
22263 procedure Hello (S : String);
22269 the external name of this procedure will be @var{_ada_hello}.
22272 @node Converting Ada Files to html with gnathtml
22273 @section Converting Ada Files to HTML with @code{gnathtml}
22276 This @code{Perl} script allows Ada source files to be browsed using
22277 standard Web browsers. For installation procedure, see the section
22278 @xref{Installing gnathtml}.
22280 Ada reserved keywords are highlighted in a bold font and Ada comments in
22281 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
22282 switch to suppress the generation of cross-referencing information, user
22283 defined variables and types will appear in a different color; you will
22284 be able to click on any identifier and go to its declaration.
22286 The command line is as follow:
22288 $ perl gnathtml.pl [^switches^options^] ada-files
22292 You can pass it as many Ada files as you want. @code{gnathtml} will generate
22293 an html file for every ada file, and a global file called @file{index.htm}.
22294 This file is an index of every identifier defined in the files.
22296 The available ^switches^options^ are the following ones:
22300 @cindex @option{-83} (@code{gnathtml})
22301 Only the Ada 83 subset of keywords will be highlighted.
22303 @item -cc @var{color}
22304 @cindex @option{-cc} (@code{gnathtml})
22305 This option allows you to change the color used for comments. The default
22306 value is green. The color argument can be any name accepted by html.
22309 @cindex @option{-d} (@code{gnathtml})
22310 If the Ada files depend on some other files (for instance through
22311 @code{with} clauses, the latter files will also be converted to html.
22312 Only the files in the user project will be converted to html, not the files
22313 in the run-time library itself.
22316 @cindex @option{-D} (@code{gnathtml})
22317 This command is the same as @option{-d} above, but @command{gnathtml} will
22318 also look for files in the run-time library, and generate html files for them.
22320 @item -ext @var{extension}
22321 @cindex @option{-ext} (@code{gnathtml})
22322 This option allows you to change the extension of the generated HTML files.
22323 If you do not specify an extension, it will default to @file{htm}.
22326 @cindex @option{-f} (@code{gnathtml})
22327 By default, gnathtml will generate html links only for global entities
22328 ('with'ed units, global variables and types,@dots{}). If you specify
22329 @option{-f} on the command line, then links will be generated for local
22332 @item -l @var{number}
22333 @cindex @option{-l} (@code{gnathtml})
22334 If this ^switch^option^ is provided and @var{number} is not 0, then
22335 @code{gnathtml} will number the html files every @var{number} line.
22338 @cindex @option{-I} (@code{gnathtml})
22339 Specify a directory to search for library files (@file{.ALI} files) and
22340 source files. You can provide several -I switches on the command line,
22341 and the directories will be parsed in the order of the command line.
22344 @cindex @option{-o} (@code{gnathtml})
22345 Specify the output directory for html files. By default, gnathtml will
22346 saved the generated html files in a subdirectory named @file{html/}.
22348 @item -p @var{file}
22349 @cindex @option{-p} (@code{gnathtml})
22350 If you are using Emacs and the most recent Emacs Ada mode, which provides
22351 a full Integrated Development Environment for compiling, checking,
22352 running and debugging applications, you may use @file{.gpr} files
22353 to give the directories where Emacs can find sources and object files.
22355 Using this ^switch^option^, you can tell gnathtml to use these files.
22356 This allows you to get an html version of your application, even if it
22357 is spread over multiple directories.
22359 @item -sc @var{color}
22360 @cindex @option{-sc} (@code{gnathtml})
22361 This ^switch^option^ allows you to change the color used for symbol
22363 The default value is red. The color argument can be any name accepted by html.
22365 @item -t @var{file}
22366 @cindex @option{-t} (@code{gnathtml})
22367 This ^switch^option^ provides the name of a file. This file contains a list of
22368 file names to be converted, and the effect is exactly as though they had
22369 appeared explicitly on the command line. This
22370 is the recommended way to work around the command line length limit on some
22375 @node Installing gnathtml
22376 @section Installing @code{gnathtml}
22379 @code{Perl} needs to be installed on your machine to run this script.
22380 @code{Perl} is freely available for almost every architecture and
22381 Operating System via the Internet.
22383 On Unix systems, you may want to modify the first line of the script
22384 @code{gnathtml}, to explicitly tell the Operating system where Perl
22385 is. The syntax of this line is:
22387 #!full_path_name_to_perl
22391 Alternatively, you may run the script using the following command line:
22394 $ perl gnathtml.pl [switches] files
22403 The GNAT distribution provides an Ada 95 template for the HP Language
22404 Sensitive Editor (LSE), a component of DECset. In order to
22405 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
22412 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
22413 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
22414 the collection phase with the /DEBUG qualifier.
22417 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
22418 $ DEFINE LIB$DEBUG PCA$COLLECTOR
22419 $ RUN/DEBUG <PROGRAM_NAME>
22425 @c ******************************
22426 @node Code Coverage and Profiling
22427 @chapter Code Coverage and Profiling
22428 @cindex Code Coverage
22432 This chapter describes how to use @code{gcov} - coverage testing tool - and
22433 @code{gprof} - profiler tool - on your Ada programs.
22436 * Code Coverage of Ada Programs using gcov::
22437 * Profiling an Ada Program using gprof::
22440 @node Code Coverage of Ada Programs using gcov
22441 @section Code Coverage of Ada Programs using gcov
22443 @cindex -fprofile-arcs
22444 @cindex -ftest-coverage
22446 @cindex Code Coverage
22449 @code{gcov} is a test coverage program: it analyzes the execution of a given
22450 program on selected tests, to help you determine the portions of the program
22451 that are still untested.
22453 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
22454 User's Guide. You can refer to this documentation for a more complete
22457 This chapter provides a quick startup guide, and
22458 details some Gnat-specific features.
22461 * Quick startup guide::
22465 @node Quick startup guide
22466 @subsection Quick startup guide
22468 In order to perform coverage analysis of a program using @code{gcov}, 3
22473 Code instrumentation during the compilation process
22475 Execution of the instrumented program
22477 Execution of the @code{gcov} tool to generate the result.
22480 The code instrumentation needed by gcov is created at the object level:
22481 The source code is not modified in any way, because the instrumentation code is
22482 inserted by gcc during the compilation process. To compile your code with code
22483 coverage activated, you need to recompile your whole project using the
22485 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
22486 @code{-fprofile-arcs}.
22489 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
22490 -largs -fprofile-arcs
22493 This compilation process will create @file{.gcno} files together with
22494 the usual object files.
22496 Once the program is compiled with coverage instrumentation, you can
22497 run it as many times as needed - on portions of a test suite for
22498 example. The first execution will produce @file{.gcda} files at the
22499 same location as the @file{.gcno} files. The following executions
22500 will update those files, so that a cumulative result of the covered
22501 portions of the program is generated.
22503 Finally, you need to call the @code{gcov} tool. The different options of
22504 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
22506 This will create annotated source files with a @file{.gcov} extension:
22507 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
22509 @node Gnat specifics
22510 @subsection Gnat specifics
22512 Because Ada semantics, portions of the source code may be shared among
22513 several object files. This is the case for example when generics are
22514 involved, when inlining is active or when declarations generate initialisation
22515 calls. In order to take
22516 into account this shared code, you need to call @code{gcov} on all
22517 source files of the tested program at once.
22519 The list of source files might exceed the system's maximum command line
22520 length. In order to bypass this limitation, a new mechanism has been
22521 implemented in @code{gcov}: you can now list all your project's files into a
22522 text file, and provide this file to gcov as a parameter, preceded by a @@
22523 (e.g. @samp{gcov @@mysrclist.txt}).
22525 @node Profiling an Ada Program using gprof
22526 @section Profiling an Ada Program using gprof
22532 This section is not meant to be an exhaustive documentation of @code{gprof}.
22533 Full documentation for it can be found in the GNU Profiler User's Guide
22534 documentation that is part of this GNAT distribution.
22536 Profiling a program helps determine the parts of a program that are executed
22537 most often, and are therefore the most time-consuming.
22539 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
22540 better handle Ada programs and multitasking.
22541 It is currently supported on the following platforms
22546 solaris sparc/sparc64/x86
22552 In order to profile a program using @code{gprof}, 3 steps are needed:
22556 Code instrumentation, requiring a full recompilation of the project with the
22559 Execution of the program under the analysis conditions, i.e. with the desired
22562 Analysis of the results using the @code{gprof} tool.
22566 The following sections detail the different steps, and indicate how
22567 to interpret the results:
22569 * Compilation for profiling::
22570 * Program execution::
22572 * Interpretation of profiling results::
22575 @node Compilation for profiling
22576 @subsection Compilation for profiling
22580 In order to profile a program the first step is to tell the compiler
22581 to generate the necessary profiling information. The compiler switch to be used
22582 is @code{-pg}, which must be added to other compilation switches. This
22583 switch needs to be specified both during compilation and link stages, and can
22584 be specified once when using gnatmake:
22587 gnatmake -f -pg -P my_project
22591 Note that only the objects that were compiled with the @samp{-pg} switch will be
22592 profiled; if you need to profile your whole project, use the
22593 @samp{-f} gnatmake switch to force full recompilation.
22595 @node Program execution
22596 @subsection Program execution
22599 Once the program has been compiled for profiling, you can run it as usual.
22601 The only constraint imposed by profiling is that the program must terminate
22602 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
22605 Once the program completes execution, a data file called @file{gmon.out} is
22606 generated in the directory where the program was launched from. If this file
22607 already exists, it will be overwritten.
22609 @node Running gprof
22610 @subsection Running gprof
22613 The @code{gprof} tool is called as follow:
22616 gprof my_prog gmon.out
22627 The complete form of the gprof command line is the following:
22630 gprof [^switches^options^] [executable [data-file]]
22634 @code{gprof} supports numerous ^switch^options^. The order of these
22635 ^switch^options^ does not matter. The full list of options can be found in
22636 the GNU Profiler User's Guide documentation that comes with this documentation.
22638 The following is the subset of those switches that is most relevant:
22642 @item --demangle[=@var{style}]
22643 @itemx --no-demangle
22644 @cindex @option{--demangle} (@code{gprof})
22645 These options control whether symbol names should be demangled when
22646 printing output. The default is to demangle C++ symbols. The
22647 @code{--no-demangle} option may be used to turn off demangling. Different
22648 compilers have different mangling styles. The optional demangling style
22649 argument can be used to choose an appropriate demangling style for your
22650 compiler, in particular Ada symbols generated by GNAT can be demangled using
22651 @code{--demangle=gnat}.
22653 @item -e @var{function_name}
22654 @cindex @option{-e} (@code{gprof})
22655 The @samp{-e @var{function}} option tells @code{gprof} not to print
22656 information about the function @var{function_name} (and its
22657 children@dots{}) in the call graph. The function will still be listed
22658 as a child of any functions that call it, but its index number will be
22659 shown as @samp{[not printed]}. More than one @samp{-e} option may be
22660 given; only one @var{function_name} may be indicated with each @samp{-e}
22663 @item -E @var{function_name}
22664 @cindex @option{-E} (@code{gprof})
22665 The @code{-E @var{function}} option works like the @code{-e} option, but
22666 execution time spent in the function (and children who were not called from
22667 anywhere else), will not be used to compute the percentages-of-time for
22668 the call graph. More than one @samp{-E} option may be given; only one
22669 @var{function_name} may be indicated with each @samp{-E} option.
22671 @item -f @var{function_name}
22672 @cindex @option{-f} (@code{gprof})
22673 The @samp{-f @var{function}} option causes @code{gprof} to limit the
22674 call graph to the function @var{function_name} and its children (and
22675 their children@dots{}). More than one @samp{-f} option may be given;
22676 only one @var{function_name} may be indicated with each @samp{-f}
22679 @item -F @var{function_name}
22680 @cindex @option{-F} (@code{gprof})
22681 The @samp{-F @var{function}} option works like the @code{-f} option, but
22682 only time spent in the function and its children (and their
22683 children@dots{}) will be used to determine total-time and
22684 percentages-of-time for the call graph. More than one @samp{-F} option
22685 may be given; only one @var{function_name} may be indicated with each
22686 @samp{-F} option. The @samp{-F} option overrides the @samp{-E} option.
22690 @node Interpretation of profiling results
22691 @subsection Interpretation of profiling results
22695 The results of the profiling analysis are represented by two arrays: the
22696 'flat profile' and the 'call graph'. Full documentation of those outputs
22697 can be found in the GNU Profiler User's Guide.
22699 The flat profile shows the time spent in each function of the program, and how
22700 many time it has been called. This allows you to locate easily the most
22701 time-consuming functions.
22703 The call graph shows, for each subprogram, the subprograms that call it,
22704 and the subprograms that it calls. It also provides an estimate of the time
22705 spent in each of those callers/called subprograms.
22708 @c ******************************
22709 @node Running and Debugging Ada Programs
22710 @chapter Running and Debugging Ada Programs
22714 This chapter discusses how to debug Ada programs.
22716 It applies to GNAT on the Alpha OpenVMS platform;
22717 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
22718 since HP has implemented Ada support in the OpenVMS debugger on I64.
22721 An incorrect Ada program may be handled in three ways by the GNAT compiler:
22725 The illegality may be a violation of the static semantics of Ada. In
22726 that case GNAT diagnoses the constructs in the program that are illegal.
22727 It is then a straightforward matter for the user to modify those parts of
22731 The illegality may be a violation of the dynamic semantics of Ada. In
22732 that case the program compiles and executes, but may generate incorrect
22733 results, or may terminate abnormally with some exception.
22736 When presented with a program that contains convoluted errors, GNAT
22737 itself may terminate abnormally without providing full diagnostics on
22738 the incorrect user program.
22742 * The GNAT Debugger GDB::
22744 * Introduction to GDB Commands::
22745 * Using Ada Expressions::
22746 * Calling User-Defined Subprograms::
22747 * Using the Next Command in a Function::
22750 * Debugging Generic Units::
22751 * GNAT Abnormal Termination or Failure to Terminate::
22752 * Naming Conventions for GNAT Source Files::
22753 * Getting Internal Debugging Information::
22754 * Stack Traceback::
22760 @node The GNAT Debugger GDB
22761 @section The GNAT Debugger GDB
22764 @code{GDB} is a general purpose, platform-independent debugger that
22765 can be used to debug mixed-language programs compiled with @command{gcc},
22766 and in particular is capable of debugging Ada programs compiled with
22767 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
22768 complex Ada data structures.
22770 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
22772 located in the GNU:[DOCS] directory,
22774 for full details on the usage of @code{GDB}, including a section on
22775 its usage on programs. This manual should be consulted for full
22776 details. The section that follows is a brief introduction to the
22777 philosophy and use of @code{GDB}.
22779 When GNAT programs are compiled, the compiler optionally writes debugging
22780 information into the generated object file, including information on
22781 line numbers, and on declared types and variables. This information is
22782 separate from the generated code. It makes the object files considerably
22783 larger, but it does not add to the size of the actual executable that
22784 will be loaded into memory, and has no impact on run-time performance. The
22785 generation of debug information is triggered by the use of the
22786 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
22787 used to carry out the compilations. It is important to emphasize that
22788 the use of these options does not change the generated code.
22790 The debugging information is written in standard system formats that
22791 are used by many tools, including debuggers and profilers. The format
22792 of the information is typically designed to describe C types and
22793 semantics, but GNAT implements a translation scheme which allows full
22794 details about Ada types and variables to be encoded into these
22795 standard C formats. Details of this encoding scheme may be found in
22796 the file exp_dbug.ads in the GNAT source distribution. However, the
22797 details of this encoding are, in general, of no interest to a user,
22798 since @code{GDB} automatically performs the necessary decoding.
22800 When a program is bound and linked, the debugging information is
22801 collected from the object files, and stored in the executable image of
22802 the program. Again, this process significantly increases the size of
22803 the generated executable file, but it does not increase the size of
22804 the executable program itself. Furthermore, if this program is run in
22805 the normal manner, it runs exactly as if the debug information were
22806 not present, and takes no more actual memory.
22808 However, if the program is run under control of @code{GDB}, the
22809 debugger is activated. The image of the program is loaded, at which
22810 point it is ready to run. If a run command is given, then the program
22811 will run exactly as it would have if @code{GDB} were not present. This
22812 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
22813 entirely non-intrusive until a breakpoint is encountered. If no
22814 breakpoint is ever hit, the program will run exactly as it would if no
22815 debugger were present. When a breakpoint is hit, @code{GDB} accesses
22816 the debugging information and can respond to user commands to inspect
22817 variables, and more generally to report on the state of execution.
22821 @section Running GDB
22824 This section describes how to initiate the debugger.
22825 @c The above sentence is really just filler, but it was otherwise
22826 @c clumsy to get the first paragraph nonindented given the conditional
22827 @c nature of the description
22830 The debugger can be launched from a @code{GPS} menu or
22831 directly from the command line. The description below covers the latter use.
22832 All the commands shown can be used in the @code{GPS} debug console window,
22833 but there are usually more GUI-based ways to achieve the same effect.
22836 The command to run @code{GDB} is
22839 $ ^gdb program^GDB PROGRAM^
22843 where @code{^program^PROGRAM^} is the name of the executable file. This
22844 activates the debugger and results in a prompt for debugger commands.
22845 The simplest command is simply @code{run}, which causes the program to run
22846 exactly as if the debugger were not present. The following section
22847 describes some of the additional commands that can be given to @code{GDB}.
22849 @c *******************************
22850 @node Introduction to GDB Commands
22851 @section Introduction to GDB Commands
22854 @code{GDB} contains a large repertoire of commands. @xref{Top,,
22855 Debugging with GDB, gdb, Debugging with GDB},
22857 located in the GNU:[DOCS] directory,
22859 for extensive documentation on the use
22860 of these commands, together with examples of their use. Furthermore,
22861 the command @command{help} invoked from within GDB activates a simple help
22862 facility which summarizes the available commands and their options.
22863 In this section we summarize a few of the most commonly
22864 used commands to give an idea of what @code{GDB} is about. You should create
22865 a simple program with debugging information and experiment with the use of
22866 these @code{GDB} commands on the program as you read through the
22870 @item set args @var{arguments}
22871 The @var{arguments} list above is a list of arguments to be passed to
22872 the program on a subsequent run command, just as though the arguments
22873 had been entered on a normal invocation of the program. The @code{set args}
22874 command is not needed if the program does not require arguments.
22877 The @code{run} command causes execution of the program to start from
22878 the beginning. If the program is already running, that is to say if
22879 you are currently positioned at a breakpoint, then a prompt will ask
22880 for confirmation that you want to abandon the current execution and
22883 @item breakpoint @var{location}
22884 The breakpoint command sets a breakpoint, that is to say a point at which
22885 execution will halt and @code{GDB} will await further
22886 commands. @var{location} is
22887 either a line number within a file, given in the format @code{file:linenumber},
22888 or it is the name of a subprogram. If you request that a breakpoint be set on
22889 a subprogram that is overloaded, a prompt will ask you to specify on which of
22890 those subprograms you want to breakpoint. You can also
22891 specify that all of them should be breakpointed. If the program is run
22892 and execution encounters the breakpoint, then the program
22893 stops and @code{GDB} signals that the breakpoint was encountered by
22894 printing the line of code before which the program is halted.
22896 @item breakpoint exception @var{name}
22897 A special form of the breakpoint command which breakpoints whenever
22898 exception @var{name} is raised.
22899 If @var{name} is omitted,
22900 then a breakpoint will occur when any exception is raised.
22902 @item print @var{expression}
22903 This will print the value of the given expression. Most simple
22904 Ada expression formats are properly handled by @code{GDB}, so the expression
22905 can contain function calls, variables, operators, and attribute references.
22908 Continues execution following a breakpoint, until the next breakpoint or the
22909 termination of the program.
22912 Executes a single line after a breakpoint. If the next statement
22913 is a subprogram call, execution continues into (the first statement of)
22914 the called subprogram.
22917 Executes a single line. If this line is a subprogram call, executes and
22918 returns from the call.
22921 Lists a few lines around the current source location. In practice, it
22922 is usually more convenient to have a separate edit window open with the
22923 relevant source file displayed. Successive applications of this command
22924 print subsequent lines. The command can be given an argument which is a
22925 line number, in which case it displays a few lines around the specified one.
22928 Displays a backtrace of the call chain. This command is typically
22929 used after a breakpoint has occurred, to examine the sequence of calls that
22930 leads to the current breakpoint. The display includes one line for each
22931 activation record (frame) corresponding to an active subprogram.
22934 At a breakpoint, @code{GDB} can display the values of variables local
22935 to the current frame. The command @code{up} can be used to
22936 examine the contents of other active frames, by moving the focus up
22937 the stack, that is to say from callee to caller, one frame at a time.
22940 Moves the focus of @code{GDB} down from the frame currently being
22941 examined to the frame of its callee (the reverse of the previous command),
22943 @item frame @var{n}
22944 Inspect the frame with the given number. The value 0 denotes the frame
22945 of the current breakpoint, that is to say the top of the call stack.
22950 The above list is a very short introduction to the commands that
22951 @code{GDB} provides. Important additional capabilities, including conditional
22952 breakpoints, the ability to execute command sequences on a breakpoint,
22953 the ability to debug at the machine instruction level and many other
22954 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
22955 Debugging with GDB}. Note that most commands can be abbreviated
22956 (for example, c for continue, bt for backtrace).
22958 @node Using Ada Expressions
22959 @section Using Ada Expressions
22960 @cindex Ada expressions
22963 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
22964 extensions. The philosophy behind the design of this subset is
22968 That @code{GDB} should provide basic literals and access to operations for
22969 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
22970 leaving more sophisticated computations to subprograms written into the
22971 program (which therefore may be called from @code{GDB}).
22974 That type safety and strict adherence to Ada language restrictions
22975 are not particularly important to the @code{GDB} user.
22978 That brevity is important to the @code{GDB} user.
22982 Thus, for brevity, the debugger acts as if there were
22983 implicit @code{with} and @code{use} clauses in effect for all user-written
22984 packages, thus making it unnecessary to fully qualify most names with
22985 their packages, regardless of context. Where this causes ambiguity,
22986 @code{GDB} asks the user's intent.
22988 For details on the supported Ada syntax, see @ref{Top,, Debugging with
22989 GDB, gdb, Debugging with GDB}.
22991 @node Calling User-Defined Subprograms
22992 @section Calling User-Defined Subprograms
22995 An important capability of @code{GDB} is the ability to call user-defined
22996 subprograms while debugging. This is achieved simply by entering
22997 a subprogram call statement in the form:
23000 call subprogram-name (parameters)
23004 The keyword @code{call} can be omitted in the normal case where the
23005 @code{subprogram-name} does not coincide with any of the predefined
23006 @code{GDB} commands.
23008 The effect is to invoke the given subprogram, passing it the
23009 list of parameters that is supplied. The parameters can be expressions and
23010 can include variables from the program being debugged. The
23011 subprogram must be defined
23012 at the library level within your program, and @code{GDB} will call the
23013 subprogram within the environment of your program execution (which
23014 means that the subprogram is free to access or even modify variables
23015 within your program).
23017 The most important use of this facility is in allowing the inclusion of
23018 debugging routines that are tailored to particular data structures
23019 in your program. Such debugging routines can be written to provide a suitably
23020 high-level description of an abstract type, rather than a low-level dump
23021 of its physical layout. After all, the standard
23022 @code{GDB print} command only knows the physical layout of your
23023 types, not their abstract meaning. Debugging routines can provide information
23024 at the desired semantic level and are thus enormously useful.
23026 For example, when debugging GNAT itself, it is crucial to have access to
23027 the contents of the tree nodes used to represent the program internally.
23028 But tree nodes are represented simply by an integer value (which in turn
23029 is an index into a table of nodes).
23030 Using the @code{print} command on a tree node would simply print this integer
23031 value, which is not very useful. But the PN routine (defined in file
23032 treepr.adb in the GNAT sources) takes a tree node as input, and displays
23033 a useful high level representation of the tree node, which includes the
23034 syntactic category of the node, its position in the source, the integers
23035 that denote descendant nodes and parent node, as well as varied
23036 semantic information. To study this example in more detail, you might want to
23037 look at the body of the PN procedure in the stated file.
23039 @node Using the Next Command in a Function
23040 @section Using the Next Command in a Function
23043 When you use the @code{next} command in a function, the current source
23044 location will advance to the next statement as usual. A special case
23045 arises in the case of a @code{return} statement.
23047 Part of the code for a return statement is the ``epilog'' of the function.
23048 This is the code that returns to the caller. There is only one copy of
23049 this epilog code, and it is typically associated with the last return
23050 statement in the function if there is more than one return. In some
23051 implementations, this epilog is associated with the first statement
23054 The result is that if you use the @code{next} command from a return
23055 statement that is not the last return statement of the function you
23056 may see a strange apparent jump to the last return statement or to
23057 the start of the function. You should simply ignore this odd jump.
23058 The value returned is always that from the first return statement
23059 that was stepped through.
23061 @node Ada Exceptions
23062 @section Breaking on Ada Exceptions
23066 You can set breakpoints that trip when your program raises
23067 selected exceptions.
23070 @item break exception
23071 Set a breakpoint that trips whenever (any task in the) program raises
23074 @item break exception @var{name}
23075 Set a breakpoint that trips whenever (any task in the) program raises
23076 the exception @var{name}.
23078 @item break exception unhandled
23079 Set a breakpoint that trips whenever (any task in the) program raises an
23080 exception for which there is no handler.
23082 @item info exceptions
23083 @itemx info exceptions @var{regexp}
23084 The @code{info exceptions} command permits the user to examine all defined
23085 exceptions within Ada programs. With a regular expression, @var{regexp}, as
23086 argument, prints out only those exceptions whose name matches @var{regexp}.
23094 @code{GDB} allows the following task-related commands:
23098 This command shows a list of current Ada tasks, as in the following example:
23105 ID TID P-ID Thread Pri State Name
23106 1 8088000 0 807e000 15 Child Activation Wait main_task
23107 2 80a4000 1 80ae000 15 Accept/Select Wait b
23108 3 809a800 1 80a4800 15 Child Activation Wait a
23109 * 4 80ae800 3 80b8000 15 Running c
23113 In this listing, the asterisk before the first task indicates it to be the
23114 currently running task. The first column lists the task ID that is used
23115 to refer to tasks in the following commands.
23117 @item break @var{linespec} task @var{taskid}
23118 @itemx break @var{linespec} task @var{taskid} if @dots{}
23119 @cindex Breakpoints and tasks
23120 These commands are like the @code{break @dots{} thread @dots{}}.
23121 @var{linespec} specifies source lines.
23123 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
23124 to specify that you only want @code{GDB} to stop the program when a
23125 particular Ada task reaches this breakpoint. @var{taskid} is one of the
23126 numeric task identifiers assigned by @code{GDB}, shown in the first
23127 column of the @samp{info tasks} display.
23129 If you do not specify @samp{task @var{taskid}} when you set a
23130 breakpoint, the breakpoint applies to @emph{all} tasks of your
23133 You can use the @code{task} qualifier on conditional breakpoints as
23134 well; in this case, place @samp{task @var{taskid}} before the
23135 breakpoint condition (before the @code{if}).
23137 @item task @var{taskno}
23138 @cindex Task switching
23140 This command allows to switch to the task referred by @var{taskno}. In
23141 particular, This allows to browse the backtrace of the specified
23142 task. It is advised to switch back to the original task before
23143 continuing execution otherwise the scheduling of the program may be
23148 For more detailed information on the tasking support,
23149 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
23151 @node Debugging Generic Units
23152 @section Debugging Generic Units
23153 @cindex Debugging Generic Units
23157 GNAT always uses code expansion for generic instantiation. This means that
23158 each time an instantiation occurs, a complete copy of the original code is
23159 made, with appropriate substitutions of formals by actuals.
23161 It is not possible to refer to the original generic entities in
23162 @code{GDB}, but it is always possible to debug a particular instance of
23163 a generic, by using the appropriate expanded names. For example, if we have
23165 @smallexample @c ada
23170 generic package k is
23171 procedure kp (v1 : in out integer);
23175 procedure kp (v1 : in out integer) is
23181 package k1 is new k;
23182 package k2 is new k;
23184 var : integer := 1;
23197 Then to break on a call to procedure kp in the k2 instance, simply
23201 (gdb) break g.k2.kp
23205 When the breakpoint occurs, you can step through the code of the
23206 instance in the normal manner and examine the values of local variables, as for
23209 @node GNAT Abnormal Termination or Failure to Terminate
23210 @section GNAT Abnormal Termination or Failure to Terminate
23211 @cindex GNAT Abnormal Termination or Failure to Terminate
23214 When presented with programs that contain serious errors in syntax
23216 GNAT may on rare occasions experience problems in operation, such
23218 segmentation fault or illegal memory access, raising an internal
23219 exception, terminating abnormally, or failing to terminate at all.
23220 In such cases, you can activate
23221 various features of GNAT that can help you pinpoint the construct in your
23222 program that is the likely source of the problem.
23224 The following strategies are presented in increasing order of
23225 difficulty, corresponding to your experience in using GNAT and your
23226 familiarity with compiler internals.
23230 Run @command{gcc} with the @option{-gnatf}. This first
23231 switch causes all errors on a given line to be reported. In its absence,
23232 only the first error on a line is displayed.
23234 The @option{-gnatdO} switch causes errors to be displayed as soon as they
23235 are encountered, rather than after compilation is terminated. If GNAT
23236 terminates prematurely or goes into an infinite loop, the last error
23237 message displayed may help to pinpoint the culprit.
23240 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
23241 mode, @command{gcc} produces ongoing information about the progress of the
23242 compilation and provides the name of each procedure as code is
23243 generated. This switch allows you to find which Ada procedure was being
23244 compiled when it encountered a code generation problem.
23247 @cindex @option{-gnatdc} switch
23248 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
23249 switch that does for the front-end what @option{^-v^VERBOSE^} does
23250 for the back end. The system prints the name of each unit,
23251 either a compilation unit or nested unit, as it is being analyzed.
23253 Finally, you can start
23254 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
23255 front-end of GNAT, and can be run independently (normally it is just
23256 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
23257 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
23258 @code{where} command is the first line of attack; the variable
23259 @code{lineno} (seen by @code{print lineno}), used by the second phase of
23260 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
23261 which the execution stopped, and @code{input_file name} indicates the name of
23265 @node Naming Conventions for GNAT Source Files
23266 @section Naming Conventions for GNAT Source Files
23269 In order to examine the workings of the GNAT system, the following
23270 brief description of its organization may be helpful:
23274 Files with prefix @file{^sc^SC^} contain the lexical scanner.
23277 All files prefixed with @file{^par^PAR^} are components of the parser. The
23278 numbers correspond to chapters of the Ada Reference Manual. For example,
23279 parsing of select statements can be found in @file{par-ch9.adb}.
23282 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
23283 numbers correspond to chapters of the Ada standard. For example, all
23284 issues involving context clauses can be found in @file{sem_ch10.adb}. In
23285 addition, some features of the language require sufficient special processing
23286 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
23287 dynamic dispatching, etc.
23290 All files prefixed with @file{^exp^EXP^} perform normalization and
23291 expansion of the intermediate representation (abstract syntax tree, or AST).
23292 these files use the same numbering scheme as the parser and semantics files.
23293 For example, the construction of record initialization procedures is done in
23294 @file{exp_ch3.adb}.
23297 The files prefixed with @file{^bind^BIND^} implement the binder, which
23298 verifies the consistency of the compilation, determines an order of
23299 elaboration, and generates the bind file.
23302 The files @file{atree.ads} and @file{atree.adb} detail the low-level
23303 data structures used by the front-end.
23306 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
23307 the abstract syntax tree as produced by the parser.
23310 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
23311 all entities, computed during semantic analysis.
23314 Library management issues are dealt with in files with prefix
23320 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
23321 defined in Annex A.
23326 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
23327 defined in Annex B.
23331 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
23332 both language-defined children and GNAT run-time routines.
23336 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
23337 general-purpose packages, fully documented in their specs. All
23338 the other @file{.c} files are modifications of common @command{gcc} files.
23341 @node Getting Internal Debugging Information
23342 @section Getting Internal Debugging Information
23345 Most compilers have internal debugging switches and modes. GNAT
23346 does also, except GNAT internal debugging switches and modes are not
23347 secret. A summary and full description of all the compiler and binder
23348 debug flags are in the file @file{debug.adb}. You must obtain the
23349 sources of the compiler to see the full detailed effects of these flags.
23351 The switches that print the source of the program (reconstructed from
23352 the internal tree) are of general interest for user programs, as are the
23354 the full internal tree, and the entity table (the symbol table
23355 information). The reconstructed source provides a readable version of the
23356 program after the front-end has completed analysis and expansion,
23357 and is useful when studying the performance of specific constructs.
23358 For example, constraint checks are indicated, complex aggregates
23359 are replaced with loops and assignments, and tasking primitives
23360 are replaced with run-time calls.
23362 @node Stack Traceback
23363 @section Stack Traceback
23365 @cindex stack traceback
23366 @cindex stack unwinding
23369 Traceback is a mechanism to display the sequence of subprogram calls that
23370 leads to a specified execution point in a program. Often (but not always)
23371 the execution point is an instruction at which an exception has been raised.
23372 This mechanism is also known as @i{stack unwinding} because it obtains
23373 its information by scanning the run-time stack and recovering the activation
23374 records of all active subprograms. Stack unwinding is one of the most
23375 important tools for program debugging.
23377 The first entry stored in traceback corresponds to the deepest calling level,
23378 that is to say the subprogram currently executing the instruction
23379 from which we want to obtain the traceback.
23381 Note that there is no runtime performance penalty when stack traceback
23382 is enabled, and no exception is raised during program execution.
23385 * Non-Symbolic Traceback::
23386 * Symbolic Traceback::
23389 @node Non-Symbolic Traceback
23390 @subsection Non-Symbolic Traceback
23391 @cindex traceback, non-symbolic
23394 Note: this feature is not supported on all platforms. See
23395 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
23399 * Tracebacks From an Unhandled Exception::
23400 * Tracebacks From Exception Occurrences (non-symbolic)::
23401 * Tracebacks From Anywhere in a Program (non-symbolic)::
23404 @node Tracebacks From an Unhandled Exception
23405 @subsubsection Tracebacks From an Unhandled Exception
23408 A runtime non-symbolic traceback is a list of addresses of call instructions.
23409 To enable this feature you must use the @option{-E}
23410 @code{gnatbind}'s option. With this option a stack traceback is stored as part
23411 of exception information. You can retrieve this information using the
23412 @code{addr2line} tool.
23414 Here is a simple example:
23416 @smallexample @c ada
23422 raise Constraint_Error;
23437 $ gnatmake stb -bargs -E
23440 Execution terminated by unhandled exception
23441 Exception name: CONSTRAINT_ERROR
23443 Call stack traceback locations:
23444 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
23448 As we see the traceback lists a sequence of addresses for the unhandled
23449 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
23450 guess that this exception come from procedure P1. To translate these
23451 addresses into the source lines where the calls appear, the
23452 @code{addr2line} tool, described below, is invaluable. The use of this tool
23453 requires the program to be compiled with debug information.
23456 $ gnatmake -g stb -bargs -E
23459 Execution terminated by unhandled exception
23460 Exception name: CONSTRAINT_ERROR
23462 Call stack traceback locations:
23463 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
23465 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
23466 0x4011f1 0x77e892a4
23468 00401373 at d:/stb/stb.adb:5
23469 0040138B at d:/stb/stb.adb:10
23470 0040139C at d:/stb/stb.adb:14
23471 00401335 at d:/stb/b~stb.adb:104
23472 004011C4 at /build/@dots{}/crt1.c:200
23473 004011F1 at /build/@dots{}/crt1.c:222
23474 77E892A4 in ?? at ??:0
23478 The @code{addr2line} tool has several other useful options:
23482 to get the function name corresponding to any location
23484 @item --demangle=gnat
23485 to use the gnat decoding mode for the function names. Note that
23486 for binutils version 2.9.x the option is simply @option{--demangle}.
23490 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
23491 0x40139c 0x401335 0x4011c4 0x4011f1
23493 00401373 in stb.p1 at d:/stb/stb.adb:5
23494 0040138B in stb.p2 at d:/stb/stb.adb:10
23495 0040139C in stb at d:/stb/stb.adb:14
23496 00401335 in main at d:/stb/b~stb.adb:104
23497 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
23498 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
23502 From this traceback we can see that the exception was raised in
23503 @file{stb.adb} at line 5, which was reached from a procedure call in
23504 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
23505 which contains the call to the main program.
23506 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
23507 and the output will vary from platform to platform.
23509 It is also possible to use @code{GDB} with these traceback addresses to debug
23510 the program. For example, we can break at a given code location, as reported
23511 in the stack traceback:
23517 Furthermore, this feature is not implemented inside Windows DLL. Only
23518 the non-symbolic traceback is reported in this case.
23521 (gdb) break *0x401373
23522 Breakpoint 1 at 0x401373: file stb.adb, line 5.
23526 It is important to note that the stack traceback addresses
23527 do not change when debug information is included. This is particularly useful
23528 because it makes it possible to release software without debug information (to
23529 minimize object size), get a field report that includes a stack traceback
23530 whenever an internal bug occurs, and then be able to retrieve the sequence
23531 of calls with the same program compiled with debug information.
23533 @node Tracebacks From Exception Occurrences (non-symbolic)
23534 @subsubsection Tracebacks From Exception Occurrences
23537 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
23538 The stack traceback is attached to the exception information string, and can
23539 be retrieved in an exception handler within the Ada program, by means of the
23540 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
23542 @smallexample @c ada
23544 with Ada.Exceptions;
23549 use Ada.Exceptions;
23557 Text_IO.Put_Line (Exception_Information (E));
23571 This program will output:
23576 Exception name: CONSTRAINT_ERROR
23577 Message: stb.adb:12
23578 Call stack traceback locations:
23579 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
23582 @node Tracebacks From Anywhere in a Program (non-symbolic)
23583 @subsubsection Tracebacks From Anywhere in a Program
23586 It is also possible to retrieve a stack traceback from anywhere in a
23587 program. For this you need to
23588 use the @code{GNAT.Traceback} API. This package includes a procedure called
23589 @code{Call_Chain} that computes a complete stack traceback, as well as useful
23590 display procedures described below. It is not necessary to use the
23591 @option{-E gnatbind} option in this case, because the stack traceback mechanism
23592 is invoked explicitly.
23595 In the following example we compute a traceback at a specific location in
23596 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
23597 convert addresses to strings:
23599 @smallexample @c ada
23601 with GNAT.Traceback;
23602 with GNAT.Debug_Utilities;
23608 use GNAT.Traceback;
23611 TB : Tracebacks_Array (1 .. 10);
23612 -- We are asking for a maximum of 10 stack frames.
23614 -- Len will receive the actual number of stack frames returned.
23616 Call_Chain (TB, Len);
23618 Text_IO.Put ("In STB.P1 : ");
23620 for K in 1 .. Len loop
23621 Text_IO.Put (Debug_Utilities.Image (TB (K)));
23642 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
23643 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
23647 You can then get further information by invoking the @code{addr2line}
23648 tool as described earlier (note that the hexadecimal addresses
23649 need to be specified in C format, with a leading ``0x'').
23651 @node Symbolic Traceback
23652 @subsection Symbolic Traceback
23653 @cindex traceback, symbolic
23656 A symbolic traceback is a stack traceback in which procedure names are
23657 associated with each code location.
23660 Note that this feature is not supported on all platforms. See
23661 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
23662 list of currently supported platforms.
23665 Note that the symbolic traceback requires that the program be compiled
23666 with debug information. If it is not compiled with debug information
23667 only the non-symbolic information will be valid.
23670 * Tracebacks From Exception Occurrences (symbolic)::
23671 * Tracebacks From Anywhere in a Program (symbolic)::
23674 @node Tracebacks From Exception Occurrences (symbolic)
23675 @subsubsection Tracebacks From Exception Occurrences
23677 @smallexample @c ada
23679 with GNAT.Traceback.Symbolic;
23685 raise Constraint_Error;
23702 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
23707 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
23710 0040149F in stb.p1 at stb.adb:8
23711 004014B7 in stb.p2 at stb.adb:13
23712 004014CF in stb.p3 at stb.adb:18
23713 004015DD in ada.stb at stb.adb:22
23714 00401461 in main at b~stb.adb:168
23715 004011C4 in __mingw_CRTStartup at crt1.c:200
23716 004011F1 in mainCRTStartup at crt1.c:222
23717 77E892A4 in ?? at ??:0
23721 In the above example the ``.\'' syntax in the @command{gnatmake} command
23722 is currently required by @command{addr2line} for files that are in
23723 the current working directory.
23724 Moreover, the exact sequence of linker options may vary from platform
23726 The above @option{-largs} section is for Windows platforms. By contrast,
23727 under Unix there is no need for the @option{-largs} section.
23728 Differences across platforms are due to details of linker implementation.
23730 @node Tracebacks From Anywhere in a Program (symbolic)
23731 @subsubsection Tracebacks From Anywhere in a Program
23734 It is possible to get a symbolic stack traceback
23735 from anywhere in a program, just as for non-symbolic tracebacks.
23736 The first step is to obtain a non-symbolic
23737 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
23738 information. Here is an example:
23740 @smallexample @c ada
23742 with GNAT.Traceback;
23743 with GNAT.Traceback.Symbolic;
23748 use GNAT.Traceback;
23749 use GNAT.Traceback.Symbolic;
23752 TB : Tracebacks_Array (1 .. 10);
23753 -- We are asking for a maximum of 10 stack frames.
23755 -- Len will receive the actual number of stack frames returned.
23757 Call_Chain (TB, Len);
23758 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
23771 @c ******************************
23773 @node Compatibility with HP Ada
23774 @chapter Compatibility with HP Ada
23775 @cindex Compatibility
23780 @cindex Compatibility between GNAT and HP Ada
23781 This chapter compares HP Ada (formerly known as ``DEC Ada'')
23782 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
23783 GNAT is highly compatible
23784 with HP Ada, and it should generally be straightforward to port code
23785 from the HP Ada environment to GNAT. However, there are a few language
23786 and implementation differences of which the user must be aware. These
23787 differences are discussed in this chapter. In
23788 addition, the operating environment and command structure for the
23789 compiler are different, and these differences are also discussed.
23791 For further details on these and other compatibility issues,
23792 see Appendix E of the HP publication
23793 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
23795 Except where otherwise indicated, the description of GNAT for OpenVMS
23796 applies to both the Alpha and I64 platforms.
23798 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
23799 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
23801 The discussion in this chapter addresses specifically the implementation
23802 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
23803 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
23804 GNAT always follows the Alpha implementation.
23806 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
23807 attributes are recognized, although only a subset of them can sensibly
23808 be implemented. The description of pragmas in
23809 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
23810 indicates whether or not they are applicable to non-VMS systems.
23813 * Ada Language Compatibility::
23814 * Differences in the Definition of Package System::
23815 * Language-Related Features::
23816 * The Package STANDARD::
23817 * The Package SYSTEM::
23818 * Tasking and Task-Related Features::
23819 * Pragmas and Pragma-Related Features::
23820 * Library of Predefined Units::
23822 * Main Program Definition::
23823 * Implementation-Defined Attributes::
23824 * Compiler and Run-Time Interfacing::
23825 * Program Compilation and Library Management::
23827 * Implementation Limits::
23828 * Tools and Utilities::
23831 @node Ada Language Compatibility
23832 @section Ada Language Compatibility
23835 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
23836 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
23837 with Ada 83, and therefore Ada 83 programs will compile
23838 and run under GNAT with
23839 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
23840 provides details on specific incompatibilities.
23842 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
23843 as well as the pragma @code{ADA_83}, to force the compiler to
23844 operate in Ada 83 mode. This mode does not guarantee complete
23845 conformance to Ada 83, but in practice is sufficient to
23846 eliminate most sources of incompatibilities.
23847 In particular, it eliminates the recognition of the
23848 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
23849 in Ada 83 programs is legal, and handles the cases of packages
23850 with optional bodies, and generics that instantiate unconstrained
23851 types without the use of @code{(<>)}.
23853 @node Differences in the Definition of Package System
23854 @section Differences in the Definition of Package @code{System}
23857 An Ada compiler is allowed to add
23858 implementation-dependent declarations to package @code{System}.
23860 GNAT does not take advantage of this permission, and the version of
23861 @code{System} provided by GNAT exactly matches that defined in the Ada
23864 However, HP Ada adds an extensive set of declarations to package
23866 as fully documented in the HP Ada manuals. To minimize changes required
23867 for programs that make use of these extensions, GNAT provides the pragma
23868 @code{Extend_System} for extending the definition of package System. By using:
23869 @cindex pragma @code{Extend_System}
23870 @cindex @code{Extend_System} pragma
23872 @smallexample @c ada
23875 pragma Extend_System (Aux_DEC);
23881 the set of definitions in @code{System} is extended to include those in
23882 package @code{System.Aux_DEC}.
23883 @cindex @code{System.Aux_DEC} package
23884 @cindex @code{Aux_DEC} package (child of @code{System})
23885 These definitions are incorporated directly into package @code{System},
23886 as though they had been declared there. For a
23887 list of the declarations added, see the spec of this package,
23888 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
23889 @cindex @file{s-auxdec.ads} file
23890 The pragma @code{Extend_System} is a configuration pragma, which means that
23891 it can be placed in the file @file{gnat.adc}, so that it will automatically
23892 apply to all subsequent compilations. See @ref{Configuration Pragmas},
23893 for further details.
23895 An alternative approach that avoids the use of the non-standard
23896 @code{Extend_System} pragma is to add a context clause to the unit that
23897 references these facilities:
23899 @smallexample @c ada
23901 with System.Aux_DEC;
23902 use System.Aux_DEC;
23907 The effect is not quite semantically identical to incorporating
23908 the declarations directly into package @code{System},
23909 but most programs will not notice a difference
23910 unless they use prefix notation (e.g.@: @code{System.Integer_8})
23911 to reference the entities directly in package @code{System}.
23912 For units containing such references,
23913 the prefixes must either be removed, or the pragma @code{Extend_System}
23916 @node Language-Related Features
23917 @section Language-Related Features
23920 The following sections highlight differences in types,
23921 representations of types, operations, alignment, and
23925 * Integer Types and Representations::
23926 * Floating-Point Types and Representations::
23927 * Pragmas Float_Representation and Long_Float::
23928 * Fixed-Point Types and Representations::
23929 * Record and Array Component Alignment::
23930 * Address Clauses::
23931 * Other Representation Clauses::
23934 @node Integer Types and Representations
23935 @subsection Integer Types and Representations
23938 The set of predefined integer types is identical in HP Ada and GNAT.
23939 Furthermore the representation of these integer types is also identical,
23940 including the capability of size clauses forcing biased representation.
23943 HP Ada for OpenVMS Alpha systems has defined the
23944 following additional integer types in package @code{System}:
23961 @code{LARGEST_INTEGER}
23965 In GNAT, the first four of these types may be obtained from the
23966 standard Ada package @code{Interfaces}.
23967 Alternatively, by use of the pragma @code{Extend_System}, identical
23968 declarations can be referenced directly in package @code{System}.
23969 On both GNAT and HP Ada, the maximum integer size is 64 bits.
23971 @node Floating-Point Types and Representations
23972 @subsection Floating-Point Types and Representations
23973 @cindex Floating-Point types
23976 The set of predefined floating-point types is identical in HP Ada and GNAT.
23977 Furthermore the representation of these floating-point
23978 types is also identical. One important difference is that the default
23979 representation for HP Ada is @code{VAX_Float}, but the default representation
23982 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
23983 pragma @code{Float_Representation} as described in the HP Ada
23985 For example, the declarations:
23987 @smallexample @c ada
23989 type F_Float is digits 6;
23990 pragma Float_Representation (VAX_Float, F_Float);
23995 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
23997 This set of declarations actually appears in @code{System.Aux_DEC},
23999 the full set of additional floating-point declarations provided in
24000 the HP Ada version of package @code{System}.
24001 This and similar declarations may be accessed in a user program
24002 by using pragma @code{Extend_System}. The use of this
24003 pragma, and the related pragma @code{Long_Float} is described in further
24004 detail in the following section.
24006 @node Pragmas Float_Representation and Long_Float
24007 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
24010 HP Ada provides the pragma @code{Float_Representation}, which
24011 acts as a program library switch to allow control over
24012 the internal representation chosen for the predefined
24013 floating-point types declared in the package @code{Standard}.
24014 The format of this pragma is as follows:
24016 @smallexample @c ada
24018 pragma Float_Representation(VAX_Float | IEEE_Float);
24023 This pragma controls the representation of floating-point
24028 @code{VAX_Float} specifies that floating-point
24029 types are represented by default with the VAX system hardware types
24030 @code{F-floating}, @code{D-floating}, @code{G-floating}.
24031 Note that the @code{H-floating}
24032 type was available only on VAX systems, and is not available
24033 in either HP Ada or GNAT.
24036 @code{IEEE_Float} specifies that floating-point
24037 types are represented by default with the IEEE single and
24038 double floating-point types.
24042 GNAT provides an identical implementation of the pragma
24043 @code{Float_Representation}, except that it functions as a
24044 configuration pragma. Note that the
24045 notion of configuration pragma corresponds closely to the
24046 HP Ada notion of a program library switch.
24048 When no pragma is used in GNAT, the default is @code{IEEE_Float},
24050 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
24051 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
24052 advisable to change the format of numbers passed to standard library
24053 routines, and if necessary explicit type conversions may be needed.
24055 The use of @code{IEEE_Float} is recommended in GNAT since it is more
24056 efficient, and (given that it conforms to an international standard)
24057 potentially more portable.
24058 The situation in which @code{VAX_Float} may be useful is in interfacing
24059 to existing code and data that expect the use of @code{VAX_Float}.
24060 In such a situation use the predefined @code{VAX_Float}
24061 types in package @code{System}, as extended by
24062 @code{Extend_System}. For example, use @code{System.F_Float}
24063 to specify the 32-bit @code{F-Float} format.
24066 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
24067 to allow control over the internal representation chosen
24068 for the predefined type @code{Long_Float} and for floating-point
24069 type declarations with digits specified in the range 7 .. 15.
24070 The format of this pragma is as follows:
24072 @smallexample @c ada
24074 pragma Long_Float (D_FLOAT | G_FLOAT);
24078 @node Fixed-Point Types and Representations
24079 @subsection Fixed-Point Types and Representations
24082 On HP Ada for OpenVMS Alpha systems, rounding is
24083 away from zero for both positive and negative numbers.
24084 Therefore, @code{+0.5} rounds to @code{1},
24085 and @code{-0.5} rounds to @code{-1}.
24087 On GNAT the results of operations
24088 on fixed-point types are in accordance with the Ada
24089 rules. In particular, results of operations on decimal
24090 fixed-point types are truncated.
24092 @node Record and Array Component Alignment
24093 @subsection Record and Array Component Alignment
24096 On HP Ada for OpenVMS Alpha, all non-composite components
24097 are aligned on natural boundaries. For example, 1-byte
24098 components are aligned on byte boundaries, 2-byte
24099 components on 2-byte boundaries, 4-byte components on 4-byte
24100 byte boundaries, and so on. The OpenVMS Alpha hardware
24101 runs more efficiently with naturally aligned data.
24103 On GNAT, alignment rules are compatible
24104 with HP Ada for OpenVMS Alpha.
24106 @node Address Clauses
24107 @subsection Address Clauses
24110 In HP Ada and GNAT, address clauses are supported for
24111 objects and imported subprograms.
24112 The predefined type @code{System.Address} is a private type
24113 in both compilers on Alpha OpenVMS, with the same representation
24114 (it is simply a machine pointer). Addition, subtraction, and comparison
24115 operations are available in the standard Ada package
24116 @code{System.Storage_Elements}, or in package @code{System}
24117 if it is extended to include @code{System.Aux_DEC} using a
24118 pragma @code{Extend_System} as previously described.
24120 Note that code that @code{with}'s both this extended package @code{System}
24121 and the package @code{System.Storage_Elements} should not @code{use}
24122 both packages, or ambiguities will result. In general it is better
24123 not to mix these two sets of facilities. The Ada package was
24124 designed specifically to provide the kind of features that HP Ada
24125 adds directly to package @code{System}.
24127 The type @code{System.Address} is a 64-bit integer type in GNAT for
24128 I64 OpenVMS. For more information,
24129 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
24131 GNAT is compatible with HP Ada in its handling of address
24132 clauses, except for some limitations in
24133 the form of address clauses for composite objects with
24134 initialization. Such address clauses are easily replaced
24135 by the use of an explicitly-defined constant as described
24136 in the Ada Reference Manual (13.1(22)). For example, the sequence
24139 @smallexample @c ada
24141 X, Y : Integer := Init_Func;
24142 Q : String (X .. Y) := "abc";
24144 for Q'Address use Compute_Address;
24149 will be rejected by GNAT, since the address cannot be computed at the time
24150 that @code{Q} is declared. To achieve the intended effect, write instead:
24152 @smallexample @c ada
24155 X, Y : Integer := Init_Func;
24156 Q_Address : constant Address := Compute_Address;
24157 Q : String (X .. Y) := "abc";
24159 for Q'Address use Q_Address;
24165 which will be accepted by GNAT (and other Ada compilers), and is also
24166 compatible with Ada 83. A fuller description of the restrictions
24167 on address specifications is found in @ref{Top, GNAT Reference Manual,
24168 About This Guide, gnat_rm, GNAT Reference Manual}.
24170 @node Other Representation Clauses
24171 @subsection Other Representation Clauses
24174 GNAT implements in a compatible manner all the representation
24175 clauses supported by HP Ada. In addition, GNAT
24176 implements the representation clause forms that were introduced in Ada 95,
24177 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
24179 @node The Package STANDARD
24180 @section The Package @code{STANDARD}
24183 The package @code{STANDARD}, as implemented by HP Ada, is fully
24184 described in the @cite{Ada Reference Manual} and in the
24185 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
24186 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
24188 In addition, HP Ada supports the Latin-1 character set in
24189 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
24190 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
24191 the type @code{WIDE_CHARACTER}.
24193 The floating-point types supported by GNAT are those
24194 supported by HP Ada, but the defaults are different, and are controlled by
24195 pragmas. See @ref{Floating-Point Types and Representations}, for details.
24197 @node The Package SYSTEM
24198 @section The Package @code{SYSTEM}
24201 HP Ada provides a specific version of the package
24202 @code{SYSTEM} for each platform on which the language is implemented.
24203 For the complete spec of the package @code{SYSTEM}, see
24204 Appendix F of the @cite{HP Ada Language Reference Manual}.
24206 On HP Ada, the package @code{SYSTEM} includes the following conversion
24209 @item @code{TO_ADDRESS(INTEGER)}
24211 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
24213 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
24215 @item @code{TO_INTEGER(ADDRESS)}
24217 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
24219 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
24220 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
24224 By default, GNAT supplies a version of @code{SYSTEM} that matches
24225 the definition given in the @cite{Ada Reference Manual}.
24227 is a subset of the HP system definitions, which is as
24228 close as possible to the original definitions. The only difference
24229 is that the definition of @code{SYSTEM_NAME} is different:
24231 @smallexample @c ada
24233 type Name is (SYSTEM_NAME_GNAT);
24234 System_Name : constant Name := SYSTEM_NAME_GNAT;
24239 Also, GNAT adds the Ada declarations for
24240 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
24242 However, the use of the following pragma causes GNAT
24243 to extend the definition of package @code{SYSTEM} so that it
24244 encompasses the full set of HP-specific extensions,
24245 including the functions listed above:
24247 @smallexample @c ada
24249 pragma Extend_System (Aux_DEC);
24254 The pragma @code{Extend_System} is a configuration pragma that
24255 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
24256 Extend_System,,, gnat_rm, GNAT Reference Manual} for further details.
24258 HP Ada does not allow the recompilation of the package
24259 @code{SYSTEM}. Instead HP Ada provides several pragmas
24260 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
24261 to modify values in the package @code{SYSTEM}.
24262 On OpenVMS Alpha systems, the pragma
24263 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
24264 its single argument.
24266 GNAT does permit the recompilation of package @code{SYSTEM} using
24267 the special switch @option{-gnatg}, and this switch can be used if
24268 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
24269 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
24270 or @code{MEMORY_SIZE} by any other means.
24272 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
24273 enumeration literal @code{SYSTEM_NAME_GNAT}.
24275 The definitions provided by the use of
24277 @smallexample @c ada
24278 pragma Extend_System (AUX_Dec);
24282 are virtually identical to those provided by the HP Ada 83 package
24283 @code{SYSTEM}. One important difference is that the name of the
24285 function for type @code{UNSIGNED_LONGWORD} is changed to
24286 @code{TO_ADDRESS_LONG}.
24287 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual} for a
24288 discussion of why this change was necessary.
24291 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
24293 an extension to Ada 83 not strictly compatible with the reference manual.
24294 GNAT, in order to be exactly compatible with the standard,
24295 does not provide this capability. In HP Ada 83, the
24296 point of this definition is to deal with a call like:
24298 @smallexample @c ada
24299 TO_ADDRESS (16#12777#);
24303 Normally, according to Ada 83 semantics, one would expect this to be
24304 ambiguous, since it matches both the @code{INTEGER} and
24305 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
24306 However, in HP Ada 83, there is no ambiguity, since the
24307 definition using @i{universal_integer} takes precedence.
24309 In GNAT, since the version with @i{universal_integer} cannot be supplied,
24311 not possible to be 100% compatible. Since there are many programs using
24312 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
24314 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
24315 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
24317 @smallexample @c ada
24318 function To_Address (X : Integer) return Address;
24319 pragma Pure_Function (To_Address);
24321 function To_Address_Long (X : Unsigned_Longword) return Address;
24322 pragma Pure_Function (To_Address_Long);
24326 This means that programs using @code{TO_ADDRESS} for
24327 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
24329 @node Tasking and Task-Related Features
24330 @section Tasking and Task-Related Features
24333 This section compares the treatment of tasking in GNAT
24334 and in HP Ada for OpenVMS Alpha.
24335 The GNAT description applies to both Alpha and I64 OpenVMS.
24336 For detailed information on tasking in
24337 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
24338 relevant run-time reference manual.
24341 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
24342 * Assigning Task IDs::
24343 * Task IDs and Delays::
24344 * Task-Related Pragmas::
24345 * Scheduling and Task Priority::
24347 * External Interrupts::
24350 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
24351 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
24354 On OpenVMS Alpha systems, each Ada task (except a passive
24355 task) is implemented as a single stream of execution
24356 that is created and managed by the kernel. On these
24357 systems, HP Ada tasking support is based on DECthreads,
24358 an implementation of the POSIX standard for threads.
24360 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
24361 code that calls DECthreads routines can be used together.
24362 The interaction between Ada tasks and DECthreads routines
24363 can have some benefits. For example when on OpenVMS Alpha,
24364 HP Ada can call C code that is already threaded.
24366 GNAT uses the facilities of DECthreads,
24367 and Ada tasks are mapped to threads.
24369 @node Assigning Task IDs
24370 @subsection Assigning Task IDs
24373 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
24374 the environment task that executes the main program. On
24375 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
24376 that have been created but are not yet activated.
24378 On OpenVMS Alpha systems, task IDs are assigned at
24379 activation. On GNAT systems, task IDs are also assigned at
24380 task creation but do not have the same form or values as
24381 task ID values in HP Ada. There is no null task, and the
24382 environment task does not have a specific task ID value.
24384 @node Task IDs and Delays
24385 @subsection Task IDs and Delays
24388 On OpenVMS Alpha systems, tasking delays are implemented
24389 using Timer System Services. The Task ID is used for the
24390 identification of the timer request (the @code{REQIDT} parameter).
24391 If Timers are used in the application take care not to use
24392 @code{0} for the identification, because cancelling such a timer
24393 will cancel all timers and may lead to unpredictable results.
24395 @node Task-Related Pragmas
24396 @subsection Task-Related Pragmas
24399 Ada supplies the pragma @code{TASK_STORAGE}, which allows
24400 specification of the size of the guard area for a task
24401 stack. (The guard area forms an area of memory that has no
24402 read or write access and thus helps in the detection of
24403 stack overflow.) On OpenVMS Alpha systems, if the pragma
24404 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
24405 area is created. In the absence of a pragma @code{TASK_STORAGE},
24406 a default guard area is created.
24408 GNAT supplies the following task-related pragmas:
24411 @item @code{TASK_INFO}
24413 This pragma appears within a task definition and
24414 applies to the task in which it appears. The argument
24415 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
24417 @item @code{TASK_STORAGE}
24419 GNAT implements pragma @code{TASK_STORAGE} in the same way as
24421 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
24422 @code{SUPPRESS}, and @code{VOLATILE}.
24424 @node Scheduling and Task Priority
24425 @subsection Scheduling and Task Priority
24428 HP Ada implements the Ada language requirement that
24429 when two tasks are eligible for execution and they have
24430 different priorities, the lower priority task does not
24431 execute while the higher priority task is waiting. The HP
24432 Ada Run-Time Library keeps a task running until either the
24433 task is suspended or a higher priority task becomes ready.
24435 On OpenVMS Alpha systems, the default strategy is round-
24436 robin with preemption. Tasks of equal priority take turns
24437 at the processor. A task is run for a certain period of
24438 time and then placed at the tail of the ready queue for
24439 its priority level.
24441 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
24442 which can be used to enable or disable round-robin
24443 scheduling of tasks with the same priority.
24444 See the relevant HP Ada run-time reference manual for
24445 information on using the pragmas to control HP Ada task
24448 GNAT follows the scheduling rules of Annex D (Real-Time
24449 Annex) of the @cite{Ada Reference Manual}. In general, this
24450 scheduling strategy is fully compatible with HP Ada
24451 although it provides some additional constraints (as
24452 fully documented in Annex D).
24453 GNAT implements time slicing control in a manner compatible with
24454 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
24455 are identical to the HP Ada 83 pragma of the same name.
24456 Note that it is not possible to mix GNAT tasking and
24457 HP Ada 83 tasking in the same program, since the two run-time
24458 libraries are not compatible.
24460 @node The Task Stack
24461 @subsection The Task Stack
24464 In HP Ada, a task stack is allocated each time a
24465 non-passive task is activated. As soon as the task is
24466 terminated, the storage for the task stack is deallocated.
24467 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
24468 a default stack size is used. Also, regardless of the size
24469 specified, some additional space is allocated for task
24470 management purposes. On OpenVMS Alpha systems, at least
24471 one page is allocated.
24473 GNAT handles task stacks in a similar manner. In accordance with
24474 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
24475 an alternative method for controlling the task stack size.
24476 The specification of the attribute @code{T'STORAGE_SIZE} is also
24477 supported in a manner compatible with HP Ada.
24479 @node External Interrupts
24480 @subsection External Interrupts
24483 On HP Ada, external interrupts can be associated with task entries.
24484 GNAT is compatible with HP Ada in its handling of external interrupts.
24486 @node Pragmas and Pragma-Related Features
24487 @section Pragmas and Pragma-Related Features
24490 Both HP Ada and GNAT supply all language-defined pragmas
24491 as specified by the Ada 83 standard. GNAT also supplies all
24492 language-defined pragmas introduced by Ada 95 and Ada 2005.
24493 In addition, GNAT implements the implementation-defined pragmas
24497 @item @code{AST_ENTRY}
24499 @item @code{COMMON_OBJECT}
24501 @item @code{COMPONENT_ALIGNMENT}
24503 @item @code{EXPORT_EXCEPTION}
24505 @item @code{EXPORT_FUNCTION}
24507 @item @code{EXPORT_OBJECT}
24509 @item @code{EXPORT_PROCEDURE}
24511 @item @code{EXPORT_VALUED_PROCEDURE}
24513 @item @code{FLOAT_REPRESENTATION}
24517 @item @code{IMPORT_EXCEPTION}
24519 @item @code{IMPORT_FUNCTION}
24521 @item @code{IMPORT_OBJECT}
24523 @item @code{IMPORT_PROCEDURE}
24525 @item @code{IMPORT_VALUED_PROCEDURE}
24527 @item @code{INLINE_GENERIC}
24529 @item @code{INTERFACE_NAME}
24531 @item @code{LONG_FLOAT}
24533 @item @code{MAIN_STORAGE}
24535 @item @code{PASSIVE}
24537 @item @code{PSECT_OBJECT}
24539 @item @code{SHARE_GENERIC}
24541 @item @code{SUPPRESS_ALL}
24543 @item @code{TASK_STORAGE}
24545 @item @code{TIME_SLICE}
24551 These pragmas are all fully implemented, with the exception of @code{TITLE},
24552 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
24553 recognized, but which have no
24554 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
24555 use of Ada protected objects. In GNAT, all generics are inlined.
24557 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
24558 a separate subprogram specification which must appear before the
24561 GNAT also supplies a number of implementation-defined pragmas as follows:
24563 @item @code{ABORT_DEFER}
24565 @item @code{ADA_83}
24567 @item @code{ADA_95}
24569 @item @code{ADA_05}
24571 @item @code{ANNOTATE}
24573 @item @code{ASSERT}
24575 @item @code{C_PASS_BY_COPY}
24577 @item @code{CPP_CLASS}
24579 @item @code{CPP_CONSTRUCTOR}
24581 @item @code{CPP_DESTRUCTOR}
24585 @item @code{EXTEND_SYSTEM}
24587 @item @code{LINKER_ALIAS}
24589 @item @code{LINKER_SECTION}
24591 @item @code{MACHINE_ATTRIBUTE}
24593 @item @code{NO_RETURN}
24595 @item @code{PURE_FUNCTION}
24597 @item @code{SOURCE_FILE_NAME}
24599 @item @code{SOURCE_REFERENCE}
24601 @item @code{TASK_INFO}
24603 @item @code{UNCHECKED_UNION}
24605 @item @code{UNIMPLEMENTED_UNIT}
24607 @item @code{UNIVERSAL_DATA}
24609 @item @code{UNSUPPRESS}
24611 @item @code{WARNINGS}
24613 @item @code{WEAK_EXTERNAL}
24617 For full details on these GNAT implementation-defined pragmas,
24618 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
24622 * Restrictions on the Pragma INLINE::
24623 * Restrictions on the Pragma INTERFACE::
24624 * Restrictions on the Pragma SYSTEM_NAME::
24627 @node Restrictions on the Pragma INLINE
24628 @subsection Restrictions on Pragma @code{INLINE}
24631 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
24633 @item Parameters cannot have a task type.
24635 @item Function results cannot be task types, unconstrained
24636 array types, or unconstrained types with discriminants.
24638 @item Bodies cannot declare the following:
24640 @item Subprogram body or stub (imported subprogram is allowed)
24644 @item Generic declarations
24646 @item Instantiations
24650 @item Access types (types derived from access types allowed)
24652 @item Array or record types
24654 @item Dependent tasks
24656 @item Direct recursive calls of subprogram or containing
24657 subprogram, directly or via a renaming
24663 In GNAT, the only restriction on pragma @code{INLINE} is that the
24664 body must occur before the call if both are in the same
24665 unit, and the size must be appropriately small. There are
24666 no other specific restrictions which cause subprograms to
24667 be incapable of being inlined.
24669 @node Restrictions on the Pragma INTERFACE
24670 @subsection Restrictions on Pragma @code{INTERFACE}
24673 The following restrictions on pragma @code{INTERFACE}
24674 are enforced by both HP Ada and GNAT:
24676 @item Languages accepted: Ada, Bliss, C, Fortran, Default.
24677 Default is the default on OpenVMS Alpha systems.
24679 @item Parameter passing: Language specifies default
24680 mechanisms but can be overridden with an @code{EXPORT} pragma.
24683 @item Ada: Use internal Ada rules.
24685 @item Bliss, C: Parameters must be mode @code{in}; cannot be
24686 record or task type. Result cannot be a string, an
24687 array, or a record.
24689 @item Fortran: Parameters cannot have a task type. Result cannot
24690 be a string, an array, or a record.
24695 GNAT is entirely upwards compatible with HP Ada, and in addition allows
24696 record parameters for all languages.
24698 @node Restrictions on the Pragma SYSTEM_NAME
24699 @subsection Restrictions on Pragma @code{SYSTEM_NAME}
24702 For HP Ada for OpenVMS Alpha, the enumeration literal
24703 for the type @code{NAME} is @code{OPENVMS_AXP}.
24704 In GNAT, the enumeration
24705 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
24707 @node Library of Predefined Units
24708 @section Library of Predefined Units
24711 A library of predefined units is provided as part of the
24712 HP Ada and GNAT implementations. HP Ada does not provide
24713 the package @code{MACHINE_CODE} but instead recommends importing
24716 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
24717 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
24719 The HP Ada Predefined Library units are modified to remove post-Ada 83
24720 incompatibilities and to make them interoperable with GNAT
24721 (@pxref{Changes to DECLIB}, for details).
24722 The units are located in the @file{DECLIB} directory.
24724 The GNAT RTL is contained in
24725 the @file{ADALIB} directory, and
24726 the default search path is set up to find @code{DECLIB} units in preference
24727 to @code{ADALIB} units with the same name (@code{TEXT_IO},
24728 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
24731 * Changes to DECLIB::
24734 @node Changes to DECLIB
24735 @subsection Changes to @code{DECLIB}
24738 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
24739 compatibility are minor and include the following:
24742 @item Adjusting the location of pragmas and record representation
24743 clauses to obey Ada 95 (and thus Ada 2005) rules
24745 @item Adding the proper notation to generic formal parameters
24746 that take unconstrained types in instantiation
24748 @item Adding pragma @code{ELABORATE_BODY} to package specs
24749 that have package bodies not otherwise allowed
24751 @item Replacing occurrences of the identifier ``@code{PROTECTED}'' by
24752 ``@code{PROTECTD}''.
24753 Currently these are found only in the @code{STARLET} package spec.
24755 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
24756 where the address size is constrained to 32 bits.
24760 None of the above changes is visible to users.
24766 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
24769 @item Command Language Interpreter (CLI interface)
24771 @item DECtalk Run-Time Library (DTK interface)
24773 @item Librarian utility routines (LBR interface)
24775 @item General Purpose Run-Time Library (LIB interface)
24777 @item Math Run-Time Library (MTH interface)
24779 @item National Character Set Run-Time Library (NCS interface)
24781 @item Compiled Code Support Run-Time Library (OTS interface)
24783 @item Parallel Processing Run-Time Library (PPL interface)
24785 @item Screen Management Run-Time Library (SMG interface)
24787 @item Sort Run-Time Library (SOR interface)
24789 @item String Run-Time Library (STR interface)
24791 @item STARLET System Library
24794 @item X Window System Version 11R4 and 11R5 (X, XLIB interface)
24796 @item X Windows Toolkit (XT interface)
24798 @item X/Motif Version 1.1.3 and 1.2 (XM interface)
24802 GNAT provides implementations of these HP bindings in the @code{DECLIB}
24803 directory, on both the Alpha and I64 OpenVMS platforms.
24805 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
24807 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
24808 A pragma @code{Linker_Options} has been added to packages @code{Xm},
24809 @code{Xt}, and @code{X_Lib}
24810 causing the default X/Motif sharable image libraries to be linked in. This
24811 is done via options files named @file{xm.opt}, @file{xt.opt}, and
24812 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
24814 It may be necessary to edit these options files to update or correct the
24815 library names if, for example, the newer X/Motif bindings from
24816 @file{ADA$EXAMPLES}
24817 had been (previous to installing GNAT) copied and renamed to supersede the
24818 default @file{ADA$PREDEFINED} versions.
24821 * Shared Libraries and Options Files::
24822 * Interfaces to C::
24825 @node Shared Libraries and Options Files
24826 @subsection Shared Libraries and Options Files
24829 When using the HP Ada
24830 predefined X and Motif bindings, the linking with their sharable images is
24831 done automatically by @command{GNAT LINK}.
24832 When using other X and Motif bindings, you need
24833 to add the corresponding sharable images to the command line for
24834 @code{GNAT LINK}. When linking with shared libraries, or with
24835 @file{.OPT} files, you must
24836 also add them to the command line for @command{GNAT LINK}.
24838 A shared library to be used with GNAT is built in the same way as other
24839 libraries under VMS. The VMS Link command can be used in standard fashion.
24841 @node Interfaces to C
24842 @subsection Interfaces to C
24846 provides the following Ada types and operations:
24849 @item C types package (@code{C_TYPES})
24851 @item C strings (@code{C_TYPES.NULL_TERMINATED})
24853 @item Other_types (@code{SHORT_INT})
24857 Interfacing to C with GNAT, you can use the above approach
24858 described for HP Ada or the facilities of Annex B of
24859 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
24860 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
24861 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
24863 The @option{-gnatF} qualifier forces default and explicit
24864 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
24865 to be uppercased for compatibility with the default behavior
24866 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
24868 @node Main Program Definition
24869 @section Main Program Definition
24872 The following section discusses differences in the
24873 definition of main programs on HP Ada and GNAT.
24874 On HP Ada, main programs are defined to meet the
24875 following conditions:
24877 @item Procedure with no formal parameters (returns @code{0} upon
24880 @item Procedure with no formal parameters (returns @code{42} when
24881 an unhandled exception is raised)
24883 @item Function with no formal parameters whose returned value
24884 is of a discrete type
24886 @item Procedure with one @code{out} formal of a discrete type for
24887 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE}
24893 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
24894 a main function or main procedure returns a discrete
24895 value whose size is less than 64 bits (32 on VAX systems),
24896 the value is zero- or sign-extended as appropriate.
24897 On GNAT, main programs are defined as follows:
24899 @item Must be a non-generic, parameterless subprogram that
24900 is either a procedure or function returning an Ada
24901 @code{STANDARD.INTEGER} (the predefined type)
24903 @item Cannot be a generic subprogram or an instantiation of a
24907 @node Implementation-Defined Attributes
24908 @section Implementation-Defined Attributes
24911 GNAT provides all HP Ada implementation-defined
24914 @node Compiler and Run-Time Interfacing
24915 @section Compiler and Run-Time Interfacing
24918 HP Ada provides the following qualifiers to pass options to the linker
24921 @item @option{/WAIT} and @option{/SUBMIT}
24923 @item @option{/COMMAND}
24925 @item @option{/[NO]MAP}
24927 @item @option{/OUTPUT=@i{file-spec}}
24929 @item @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK}
24933 To pass options to the linker, GNAT provides the following
24937 @item @option{/EXECUTABLE=@i{exec-name}}
24939 @item @option{/VERBOSE}
24941 @item @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK}
24945 For more information on these switches, see
24946 @ref{Switches for gnatlink}.
24947 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
24948 to control optimization. HP Ada also supplies the
24951 @item @code{OPTIMIZE}
24953 @item @code{INLINE}
24955 @item @code{INLINE_GENERIC}
24957 @item @code{SUPPRESS_ALL}
24959 @item @code{PASSIVE}
24963 In GNAT, optimization is controlled strictly by command
24964 line parameters, as described in the corresponding section of this guide.
24965 The HP pragmas for control of optimization are
24966 recognized but ignored.
24968 Note that in GNAT, the default is optimization off, whereas in HP Ada
24969 the default is that optimization is turned on.
24971 @node Program Compilation and Library Management
24972 @section Program Compilation and Library Management
24975 HP Ada and GNAT provide a comparable set of commands to
24976 build programs. HP Ada also provides a program library,
24977 which is a concept that does not exist on GNAT. Instead,
24978 GNAT provides directories of sources that are compiled as
24981 The following table summarizes
24982 the HP Ada commands and provides
24983 equivalent GNAT commands. In this table, some GNAT
24984 equivalents reflect the fact that GNAT does not use the
24985 concept of a program library. Instead, it uses a model
24986 in which collections of source and object files are used
24987 in a manner consistent with other languages like C and
24988 Fortran. Therefore, standard system file commands are used
24989 to manipulate these elements. Those GNAT commands are marked with
24991 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
24994 @multitable @columnfractions .35 .65
24996 @item @emph{HP Ada Command}
24997 @tab @emph{GNAT Equivalent / Description}
24999 @item @command{ADA}
25000 @tab @command{GNAT COMPILE}@*
25001 Invokes the compiler to compile one or more Ada source files.
25003 @item @command{ACS ATTACH}@*
25004 @tab [No equivalent]@*
25005 Switches control of terminal from current process running the program
25008 @item @command{ACS CHECK}
25009 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
25010 Forms the execution closure of one
25011 or more compiled units and checks completeness and currency.
25013 @item @command{ACS COMPILE}
25014 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
25015 Forms the execution closure of one or
25016 more specified units, checks completeness and currency,
25017 identifies units that have revised source files, compiles same,
25018 and recompiles units that are or will become obsolete.
25019 Also completes incomplete generic instantiations.
25021 @item @command{ACS COPY FOREIGN}
25023 Copies a foreign object file into the program library as a
25026 @item @command{ACS COPY UNIT}
25028 Copies a compiled unit from one program library to another.
25030 @item @command{ACS CREATE LIBRARY}
25031 @tab Create /directory (*)@*
25032 Creates a program library.
25034 @item @command{ACS CREATE SUBLIBRARY}
25035 @tab Create /directory (*)@*
25036 Creates a program sublibrary.
25038 @item @command{ACS DELETE LIBRARY}
25040 Deletes a program library and its contents.
25042 @item @command{ACS DELETE SUBLIBRARY}
25044 Deletes a program sublibrary and its contents.
25046 @item @command{ACS DELETE UNIT}
25047 @tab Delete file (*)@*
25048 On OpenVMS systems, deletes one or more compiled units from
25049 the current program library.
25051 @item @command{ACS DIRECTORY}
25052 @tab Directory (*)@*
25053 On OpenVMS systems, lists units contained in the current
25056 @item @command{ACS ENTER FOREIGN}
25058 Allows the import of a foreign body as an Ada library
25059 spec and enters a reference to a pointer.
25061 @item @command{ACS ENTER UNIT}
25063 Enters a reference (pointer) from the current program library to
25064 a unit compiled into another program library.
25066 @item @command{ACS EXIT}
25067 @tab [No equivalent]@*
25068 Exits from the program library manager.
25070 @item @command{ACS EXPORT}
25072 Creates an object file that contains system-specific object code
25073 for one or more units. With GNAT, object files can simply be copied
25074 into the desired directory.
25076 @item @command{ACS EXTRACT SOURCE}
25078 Allows access to the copied source file for each Ada compilation unit
25080 @item @command{ACS HELP}
25081 @tab @command{HELP GNAT}@*
25082 Provides online help.
25084 @item @command{ACS LINK}
25085 @tab @command{GNAT LINK}@*
25086 Links an object file containing Ada units into an executable file.
25088 @item @command{ACS LOAD}
25090 Loads (partially compiles) Ada units into the program library.
25091 Allows loading a program from a collection of files into a library
25092 without knowing the relationship among units.
25094 @item @command{ACS MERGE}
25096 Merges into the current program library, one or more units from
25097 another library where they were modified.
25099 @item @command{ACS RECOMPILE}
25100 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
25101 Recompiles from external or copied source files any obsolete
25102 unit in the closure. Also, completes any incomplete generic
25105 @item @command{ACS REENTER}
25106 @tab @command{GNAT MAKE}@*
25107 Reenters current references to units compiled after last entered
25108 with the @command{ACS ENTER UNIT} command.
25110 @item @command{ACS SET LIBRARY}
25111 @tab Set default (*)@*
25112 Defines a program library to be the compilation context as well
25113 as the target library for compiler output and commands in general.
25115 @item @command{ACS SET PRAGMA}
25116 @tab Edit @file{gnat.adc} (*)@*
25117 Redefines specified values of the library characteristics
25118 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
25119 and @code{Float_Representation}.
25121 @item @command{ACS SET SOURCE}
25122 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
25123 Defines the source file search list for the @command{ACS COMPILE} command.
25125 @item @command{ACS SHOW LIBRARY}
25126 @tab Directory (*)@*
25127 Lists information about one or more program libraries.
25129 @item @command{ACS SHOW PROGRAM}
25130 @tab [No equivalent]@*
25131 Lists information about the execution closure of one or
25132 more units in the program library.
25134 @item @command{ACS SHOW SOURCE}
25135 @tab Show logical @code{ADA_INCLUDE_PATH}@*
25136 Shows the source file search used when compiling units.
25138 @item @command{ACS SHOW VERSION}
25139 @tab Compile with @option{VERBOSE} option
25140 Displays the version number of the compiler and program library
25143 @item @command{ACS SPAWN}
25144 @tab [No equivalent]@*
25145 Creates a subprocess of the current process (same as @command{DCL SPAWN}
25148 @item @command{ACS VERIFY}
25149 @tab [No equivalent]@*
25150 Performs a series of consistency checks on a program library to
25151 determine whether the library structure and library files are in
25158 @section Input-Output
25161 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
25162 Management Services (RMS) to perform operations on
25166 HP Ada and GNAT predefine an identical set of input-
25167 output packages. To make the use of the
25168 generic @code{TEXT_IO} operations more convenient, HP Ada
25169 provides predefined library packages that instantiate the
25170 integer and floating-point operations for the predefined
25171 integer and floating-point types as shown in the following table.
25173 @multitable @columnfractions .45 .55
25174 @item @emph{Package Name} @tab Instantiation
25176 @item @code{INTEGER_TEXT_IO}
25177 @tab @code{INTEGER_IO(INTEGER)}
25179 @item @code{SHORT_INTEGER_TEXT_IO}
25180 @tab @code{INTEGER_IO(SHORT_INTEGER)}
25182 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
25183 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
25185 @item @code{FLOAT_TEXT_IO}
25186 @tab @code{FLOAT_IO(FLOAT)}
25188 @item @code{LONG_FLOAT_TEXT_IO}
25189 @tab @code{FLOAT_IO(LONG_FLOAT)}
25193 The HP Ada predefined packages and their operations
25194 are implemented using OpenVMS Alpha files and input-output
25195 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
25196 Familiarity with the following is recommended:
25198 @item RMS file organizations and access methods
25200 @item OpenVMS file specifications and directories
25202 @item OpenVMS File Definition Language (FDL)
25206 GNAT provides I/O facilities that are completely
25207 compatible with HP Ada. The distribution includes the
25208 standard HP Ada versions of all I/O packages, operating
25209 in a manner compatible with HP Ada. In particular, the
25210 following packages are by default the HP Ada (Ada 83)
25211 versions of these packages rather than the renamings
25212 suggested in Annex J of the Ada Reference Manual:
25214 @item @code{TEXT_IO}
25216 @item @code{SEQUENTIAL_IO}
25218 @item @code{DIRECT_IO}
25222 The use of the standard child package syntax (for
25223 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
25225 GNAT provides HP-compatible predefined instantiations
25226 of the @code{TEXT_IO} packages, and also
25227 provides the standard predefined instantiations required
25228 by the @cite{Ada Reference Manual}.
25230 For further information on how GNAT interfaces to the file
25231 system or how I/O is implemented in programs written in
25232 mixed languages, see @ref{Implementation of the Standard I/O,,,
25233 gnat_rm, GNAT Reference Manual}.
25234 This chapter covers the following:
25236 @item Standard I/O packages
25238 @item @code{FORM} strings
25240 @item @code{ADA.DIRECT_IO}
25242 @item @code{ADA.SEQUENTIAL_IO}
25244 @item @code{ADA.TEXT_IO}
25246 @item Stream pointer positioning
25248 @item Reading and writing non-regular files
25250 @item @code{GET_IMMEDIATE}
25252 @item Treating @code{TEXT_IO} files as streams
25259 @node Implementation Limits
25260 @section Implementation Limits
25263 The following table lists implementation limits for HP Ada
25265 @multitable @columnfractions .60 .20 .20
25267 @item @emph{Compilation Parameter}
25272 @item In a subprogram or entry declaration, maximum number of
25273 formal parameters that are of an unconstrained record type
25278 @item Maximum identifier length (number of characters)
25283 @item Maximum number of characters in a source line
25288 @item Maximum collection size (number of bytes)
25293 @item Maximum number of discriminants for a record type
25298 @item Maximum number of formal parameters in an entry or
25299 subprogram declaration
25304 @item Maximum number of dimensions in an array type
25309 @item Maximum number of library units and subunits in a compilation.
25314 @item Maximum number of library units and subunits in an execution.
25319 @item Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
25320 or @code{PSECT_OBJECT}
25325 @item Maximum number of enumeration literals in an enumeration type
25331 @item Maximum number of lines in a source file
25336 @item Maximum number of bits in any object
25341 @item Maximum size of the static portion of a stack frame (approximate)
25346 @node Tools and Utilities
25347 @section Tools and Utilities
25350 The following table lists some of the OpenVMS development tools
25351 available for HP Ada, and the corresponding tools for
25352 use with @value{EDITION} on Alpha and I64 platforms.
25353 Aside from the debugger, all the OpenVMS tools identified are part
25354 of the DECset package.
25357 @c Specify table in TeX since Texinfo does a poor job
25361 \settabs\+Language-Sensitive Editor\quad
25362 &Product with HP Ada\quad
25365 &\it Product with HP Ada
25366 & \it Product with GNAT Pro\cr
25368 \+Code Management System
25372 \+Language-Sensitive Editor
25374 & emacs or HP LSE (Alpha)\cr
25384 & OpenVMS Debug (I64)\cr
25386 \+Source Code Analyzer /
25403 \+Coverage Analyzer
25407 \+Module Management
25409 & Not applicable\cr
25419 @c This is the Texinfo version of the table. It renders poorly in pdf, hence
25420 @c the TeX version above for the printed version
25422 @c @multitable @columnfractions .3 .4 .4
25423 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
25425 @tab @i{Tool with HP Ada}
25426 @tab @i{Tool with @value{EDITION}}
25427 @item Code Management@*System
25430 @item Language-Sensitive@*Editor
25432 @tab emacs or HP LSE (Alpha)
25441 @tab OpenVMS Debug (I64)
25442 @item Source Code Analyzer /@*Cross Referencer
25446 @tab HP Digital Test@*Manager (DTM)
25448 @item Performance and@*Coverage Analyzer
25451 @item Module Management@*System
25453 @tab Not applicable
25460 @c **************************************
25461 @node Platform-Specific Information for the Run-Time Libraries
25462 @appendix Platform-Specific Information for the Run-Time Libraries
25463 @cindex Tasking and threads libraries
25464 @cindex Threads libraries and tasking
25465 @cindex Run-time libraries (platform-specific information)
25468 The GNAT run-time implementation may vary with respect to both the
25469 underlying threads library and the exception handling scheme.
25470 For threads support, one or more of the following are supplied:
25472 @item @b{native threads library}, a binding to the thread package from
25473 the underlying operating system
25475 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
25476 POSIX thread package
25480 For exception handling, either or both of two models are supplied:
25482 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
25483 Most programs should experience a substantial speed improvement by
25484 being compiled with a ZCX run-time.
25485 This is especially true for
25486 tasking applications or applications with many exception handlers.}
25487 @cindex Zero-Cost Exceptions
25488 @cindex ZCX (Zero-Cost Exceptions)
25489 which uses binder-generated tables that
25490 are interrogated at run time to locate a handler
25492 @item @b{setjmp / longjmp} (``SJLJ''),
25493 @cindex setjmp/longjmp Exception Model
25494 @cindex SJLJ (setjmp/longjmp Exception Model)
25495 which uses dynamically-set data to establish
25496 the set of handlers
25500 This appendix summarizes which combinations of threads and exception support
25501 are supplied on various GNAT platforms.
25502 It then shows how to select a particular library either
25503 permanently or temporarily,
25504 explains the properties of (and tradeoffs among) the various threads
25505 libraries, and provides some additional
25506 information about several specific platforms.
25509 * Summary of Run-Time Configurations::
25510 * Specifying a Run-Time Library::
25511 * Choosing the Scheduling Policy::
25512 * Solaris-Specific Considerations::
25513 * Linux-Specific Considerations::
25514 * AIX-Specific Considerations::
25515 * Irix-Specific Considerations::
25518 @node Summary of Run-Time Configurations
25519 @section Summary of Run-Time Configurations
25521 @multitable @columnfractions .30 .70
25522 @item @b{alpha-openvms}
25523 @item @code{@ @ }@i{rts-native (default)}
25524 @item @code{@ @ @ @ }Tasking @tab native VMS threads
25525 @item @code{@ @ @ @ }Exceptions @tab ZCX
25527 @item @b{alpha-tru64}
25528 @item @code{@ @ }@i{rts-native (default)}
25529 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
25530 @item @code{@ @ @ @ }Exceptions @tab ZCX
25532 @item @code{@ @ }@i{rts-sjlj}
25533 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
25534 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25536 @item @b{ia64-hp_linux}
25537 @item @code{@ @ }@i{rts-native (default)}
25538 @item @code{@ @ @ @ }Tasking @tab pthread library
25539 @item @code{@ @ @ @ }Exceptions @tab ZCX
25541 @item @b{ia64-hpux}
25542 @item @code{@ @ }@i{rts-native (default)}
25543 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
25544 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25546 @item @b{ia64-openvms}
25547 @item @code{@ @ }@i{rts-native (default)}
25548 @item @code{@ @ @ @ }Tasking @tab native VMS threads
25549 @item @code{@ @ @ @ }Exceptions @tab ZCX
25551 @item @b{ia64-sgi_linux}
25552 @item @code{@ @ }@i{rts-native (default)}
25553 @item @code{@ @ @ @ }Tasking @tab pthread library
25554 @item @code{@ @ @ @ }Exceptions @tab ZCX
25556 @item @b{mips-irix}
25557 @item @code{@ @ }@i{rts-native (default)}
25558 @item @code{@ @ @ @ }Tasking @tab native IRIX threads
25559 @item @code{@ @ @ @ }Exceptions @tab ZCX
25562 @item @code{@ @ }@i{rts-native (default)}
25563 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
25564 @item @code{@ @ @ @ }Exceptions @tab ZCX
25566 @item @code{@ @ }@i{rts-sjlj}
25567 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
25568 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25571 @item @code{@ @ }@i{rts-native (default)}
25572 @item @code{@ @ @ @ }Tasking @tab native AIX threads
25573 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25575 @item @b{ppc-darwin}
25576 @item @code{@ @ }@i{rts-native (default)}
25577 @item @code{@ @ @ @ }Tasking @tab native MacOS threads
25578 @item @code{@ @ @ @ }Exceptions @tab ZCX
25580 @item @b{sparc-solaris} @tab
25581 @item @code{@ @ }@i{rts-native (default)}
25582 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
25583 @item @code{@ @ @ @ }Exceptions @tab ZCX
25585 @item @code{@ @ }@i{rts-pthread}
25586 @item @code{@ @ @ @ }Tasking @tab pthread library
25587 @item @code{@ @ @ @ }Exceptions @tab ZCX
25589 @item @code{@ @ }@i{rts-sjlj}
25590 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
25591 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25593 @item @b{sparc64-solaris} @tab
25594 @item @code{@ @ }@i{rts-native (default)}
25595 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
25596 @item @code{@ @ @ @ }Exceptions @tab ZCX
25598 @item @b{x86-linux}
25599 @item @code{@ @ }@i{rts-native (default)}
25600 @item @code{@ @ @ @ }Tasking @tab pthread library
25601 @item @code{@ @ @ @ }Exceptions @tab ZCX
25603 @item @code{@ @ }@i{rts-sjlj}
25604 @item @code{@ @ @ @ }Tasking @tab pthread library
25605 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25608 @item @code{@ @ }@i{rts-native (default)}
25609 @item @code{@ @ @ @ }Tasking @tab native LynxOS threads
25610 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25612 @item @b{x86-solaris}
25613 @item @code{@ @ }@i{rts-native (default)}
25614 @item @code{@ @ @ @ }Tasking @tab native Solaris threads
25615 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25617 @item @b{x86-windows}
25618 @item @code{@ @ }@i{rts-native (default)}
25619 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
25620 @item @code{@ @ @ @ }Exceptions @tab ZCX
25622 @item @code{@ @ }@i{rts-sjlj (default)}
25623 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
25624 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25626 @item @b{x86_64-linux}
25627 @item @code{@ @ }@i{rts-native (default)}
25628 @item @code{@ @ @ @ }Tasking @tab pthread library
25629 @item @code{@ @ @ @ }Exceptions @tab ZCX
25631 @item @code{@ @ }@i{rts-sjlj}
25632 @item @code{@ @ @ @ }Tasking @tab pthread library
25633 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25637 @node Specifying a Run-Time Library
25638 @section Specifying a Run-Time Library
25641 The @file{adainclude} subdirectory containing the sources of the GNAT
25642 run-time library, and the @file{adalib} subdirectory containing the
25643 @file{ALI} files and the static and/or shared GNAT library, are located
25644 in the gcc target-dependent area:
25647 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
25651 As indicated above, on some platforms several run-time libraries are supplied.
25652 These libraries are installed in the target dependent area and
25653 contain a complete source and binary subdirectory. The detailed description
25654 below explains the differences between the different libraries in terms of
25655 their thread support.
25657 The default run-time library (when GNAT is installed) is @emph{rts-native}.
25658 This default run time is selected by the means of soft links.
25659 For example on x86-linux:
25665 +--- adainclude----------+
25667 +--- adalib-----------+ |
25669 +--- rts-native | |
25671 | +--- adainclude <---+
25673 | +--- adalib <----+
25684 If the @i{rts-sjlj} library is to be selected on a permanent basis,
25685 these soft links can be modified with the following commands:
25689 $ rm -f adainclude adalib
25690 $ ln -s rts-sjlj/adainclude adainclude
25691 $ ln -s rts-sjlj/adalib adalib
25695 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
25696 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
25697 @file{$target/ada_object_path}.
25699 Selecting another run-time library temporarily can be
25700 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
25701 @cindex @option{--RTS} option
25703 @node Choosing the Scheduling Policy
25704 @section Choosing the Scheduling Policy
25707 When using a POSIX threads implementation, you have a choice of several
25708 scheduling policies: @code{SCHED_FIFO},
25709 @cindex @code{SCHED_FIFO} scheduling policy
25711 @cindex @code{SCHED_RR} scheduling policy
25712 and @code{SCHED_OTHER}.
25713 @cindex @code{SCHED_OTHER} scheduling policy
25714 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
25715 or @code{SCHED_RR} requires special (e.g., root) privileges.
25717 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
25719 @cindex @code{SCHED_FIFO} scheduling policy
25720 you can use one of the following:
25724 @code{pragma Time_Slice (0.0)}
25725 @cindex pragma Time_Slice
25727 the corresponding binder option @option{-T0}
25728 @cindex @option{-T0} option
25730 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
25731 @cindex pragma Task_Dispatching_Policy
25735 To specify @code{SCHED_RR},
25736 @cindex @code{SCHED_RR} scheduling policy
25737 you should use @code{pragma Time_Slice} with a
25738 value greater than @code{0.0}, or else use the corresponding @option{-T}
25741 @node Solaris-Specific Considerations
25742 @section Solaris-Specific Considerations
25743 @cindex Solaris Sparc threads libraries
25746 This section addresses some topics related to the various threads libraries
25750 * Solaris Threads Issues::
25753 @node Solaris Threads Issues
25754 @subsection Solaris Threads Issues
25757 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
25758 library based on POSIX threads --- @emph{rts-pthread}.
25759 @cindex rts-pthread threads library
25760 This run-time library has the advantage of being mostly shared across all
25761 POSIX-compliant thread implementations, and it also provides under
25762 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
25763 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
25764 and @code{PTHREAD_PRIO_PROTECT}
25765 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
25766 semantics that can be selected using the predefined pragma
25767 @code{Locking_Policy}
25768 @cindex pragma Locking_Policy (under rts-pthread)
25770 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
25771 @cindex @code{Inheritance_Locking} (under rts-pthread)
25772 @cindex @code{Ceiling_Locking} (under rts-pthread)
25774 As explained above, the native run-time library is based on the Solaris thread
25775 library (@code{libthread}) and is the default library.
25777 When the Solaris threads library is used (this is the default), programs
25778 compiled with GNAT can automatically take advantage of
25779 and can thus execute on multiple processors.
25780 The user can alternatively specify a processor on which the program should run
25781 to emulate a single-processor system. The multiprocessor / uniprocessor choice
25783 setting the environment variable @env{GNAT_PROCESSOR}
25784 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
25785 to one of the following:
25789 Use the default configuration (run the program on all
25790 available processors) - this is the same as having
25791 @code{GNAT_PROCESSOR} unset
25794 Let the run-time implementation choose one processor and run the program on
25797 @item 0 .. Last_Proc
25798 Run the program on the specified processor.
25799 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
25800 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
25803 @node Linux-Specific Considerations
25804 @section Linux-Specific Considerations
25805 @cindex Linux threads libraries
25808 On GNU/Linux without NPTL support (usually system with GNU C Library
25809 older than 2.3), the signal model is not POSIX compliant, which means
25810 that to send a signal to the process, you need to send the signal to all
25811 threads, e.g.@: by using @code{killpg()}.
25813 @node AIX-Specific Considerations
25814 @section AIX-Specific Considerations
25815 @cindex AIX resolver library
25818 On AIX, the resolver library initializes some internal structure on
25819 the first call to @code{get*by*} functions, which are used to implement
25820 @code{GNAT.Sockets.Get_Host_By_Name} and
25821 @code{GNAT.Sockets.Get_Host_By_Address}.
25822 If such initialization occurs within an Ada task, and the stack size for
25823 the task is the default size, a stack overflow may occur.
25825 To avoid this overflow, the user should either ensure that the first call
25826 to @code{GNAT.Sockets.Get_Host_By_Name} or
25827 @code{GNAT.Sockets.Get_Host_By_Addrss}
25828 occurs in the environment task, or use @code{pragma Storage_Size} to
25829 specify a sufficiently large size for the stack of the task that contains
25832 @node Irix-Specific Considerations
25833 @section Irix-Specific Considerations
25834 @cindex Irix libraries
25837 The GCC support libraries coming with the Irix compiler have moved to
25838 their canonical place with respect to the general Irix ABI related
25839 conventions. Running applications built with the default shared GNAT
25840 run-time now requires the LD_LIBRARY_PATH environment variable to
25841 include this location. A possible way to achieve this is to issue the
25842 following command line on a bash prompt:
25846 $ LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
25850 @c *******************************
25851 @node Example of Binder Output File
25852 @appendix Example of Binder Output File
25855 This Appendix displays the source code for @command{gnatbind}'s output
25856 file generated for a simple ``Hello World'' program.
25857 Comments have been added for clarification purposes.
25859 @smallexample @c adanocomment
25863 -- The package is called Ada_Main unless this name is actually used
25864 -- as a unit name in the partition, in which case some other unique
25868 package ada_main is
25870 Elab_Final_Code : Integer;
25871 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
25873 -- The main program saves the parameters (argument count,
25874 -- argument values, environment pointer) in global variables
25875 -- for later access by other units including
25876 -- Ada.Command_Line.
25878 gnat_argc : Integer;
25879 gnat_argv : System.Address;
25880 gnat_envp : System.Address;
25882 -- The actual variables are stored in a library routine. This
25883 -- is useful for some shared library situations, where there
25884 -- are problems if variables are not in the library.
25886 pragma Import (C, gnat_argc);
25887 pragma Import (C, gnat_argv);
25888 pragma Import (C, gnat_envp);
25890 -- The exit status is similarly an external location
25892 gnat_exit_status : Integer;
25893 pragma Import (C, gnat_exit_status);
25895 GNAT_Version : constant String :=
25896 "GNAT Version: 6.0.0w (20061115)";
25897 pragma Export (C, GNAT_Version, "__gnat_version");
25899 -- This is the generated adafinal routine that performs
25900 -- finalization at the end of execution. In the case where
25901 -- Ada is the main program, this main program makes a call
25902 -- to adafinal at program termination.
25904 procedure adafinal;
25905 pragma Export (C, adafinal, "adafinal");
25907 -- This is the generated adainit routine that performs
25908 -- initialization at the start of execution. In the case
25909 -- where Ada is the main program, this main program makes
25910 -- a call to adainit at program startup.
25913 pragma Export (C, adainit, "adainit");
25915 -- This routine is called at the start of execution. It is
25916 -- a dummy routine that is used by the debugger to breakpoint
25917 -- at the start of execution.
25919 procedure Break_Start;
25920 pragma Import (C, Break_Start, "__gnat_break_start");
25922 -- This is the actual generated main program (it would be
25923 -- suppressed if the no main program switch were used). As
25924 -- required by standard system conventions, this program has
25925 -- the external name main.
25929 argv : System.Address;
25930 envp : System.Address)
25932 pragma Export (C, main, "main");
25934 -- The following set of constants give the version
25935 -- identification values for every unit in the bound
25936 -- partition. This identification is computed from all
25937 -- dependent semantic units, and corresponds to the
25938 -- string that would be returned by use of the
25939 -- Body_Version or Version attributes.
25941 type Version_32 is mod 2 ** 32;
25942 u00001 : constant Version_32 := 16#7880BEB3#;
25943 u00002 : constant Version_32 := 16#0D24CBD0#;
25944 u00003 : constant Version_32 := 16#3283DBEB#;
25945 u00004 : constant Version_32 := 16#2359F9ED#;
25946 u00005 : constant Version_32 := 16#664FB847#;
25947 u00006 : constant Version_32 := 16#68E803DF#;
25948 u00007 : constant Version_32 := 16#5572E604#;
25949 u00008 : constant Version_32 := 16#46B173D8#;
25950 u00009 : constant Version_32 := 16#156A40CF#;
25951 u00010 : constant Version_32 := 16#033DABE0#;
25952 u00011 : constant Version_32 := 16#6AB38FEA#;
25953 u00012 : constant Version_32 := 16#22B6217D#;
25954 u00013 : constant Version_32 := 16#68A22947#;
25955 u00014 : constant Version_32 := 16#18CC4A56#;
25956 u00015 : constant Version_32 := 16#08258E1B#;
25957 u00016 : constant Version_32 := 16#367D5222#;
25958 u00017 : constant Version_32 := 16#20C9ECA4#;
25959 u00018 : constant Version_32 := 16#50D32CB6#;
25960 u00019 : constant Version_32 := 16#39A8BB77#;
25961 u00020 : constant Version_32 := 16#5CF8FA2B#;
25962 u00021 : constant Version_32 := 16#2F1EB794#;
25963 u00022 : constant Version_32 := 16#31AB6444#;
25964 u00023 : constant Version_32 := 16#1574B6E9#;
25965 u00024 : constant Version_32 := 16#5109C189#;
25966 u00025 : constant Version_32 := 16#56D770CD#;
25967 u00026 : constant Version_32 := 16#02F9DE3D#;
25968 u00027 : constant Version_32 := 16#08AB6B2C#;
25969 u00028 : constant Version_32 := 16#3FA37670#;
25970 u00029 : constant Version_32 := 16#476457A0#;
25971 u00030 : constant Version_32 := 16#731E1B6E#;
25972 u00031 : constant Version_32 := 16#23C2E789#;
25973 u00032 : constant Version_32 := 16#0F1BD6A1#;
25974 u00033 : constant Version_32 := 16#7C25DE96#;
25975 u00034 : constant Version_32 := 16#39ADFFA2#;
25976 u00035 : constant Version_32 := 16#571DE3E7#;
25977 u00036 : constant Version_32 := 16#5EB646AB#;
25978 u00037 : constant Version_32 := 16#4249379B#;
25979 u00038 : constant Version_32 := 16#0357E00A#;
25980 u00039 : constant Version_32 := 16#3784FB72#;
25981 u00040 : constant Version_32 := 16#2E723019#;
25982 u00041 : constant Version_32 := 16#623358EA#;
25983 u00042 : constant Version_32 := 16#107F9465#;
25984 u00043 : constant Version_32 := 16#6843F68A#;
25985 u00044 : constant Version_32 := 16#63305874#;
25986 u00045 : constant Version_32 := 16#31E56CE1#;
25987 u00046 : constant Version_32 := 16#02917970#;
25988 u00047 : constant Version_32 := 16#6CCBA70E#;
25989 u00048 : constant Version_32 := 16#41CD4204#;
25990 u00049 : constant Version_32 := 16#572E3F58#;
25991 u00050 : constant Version_32 := 16#20729FF5#;
25992 u00051 : constant Version_32 := 16#1D4F93E8#;
25993 u00052 : constant Version_32 := 16#30B2EC3D#;
25994 u00053 : constant Version_32 := 16#34054F96#;
25995 u00054 : constant Version_32 := 16#5A199860#;
25996 u00055 : constant Version_32 := 16#0E7F912B#;
25997 u00056 : constant Version_32 := 16#5760634A#;
25998 u00057 : constant Version_32 := 16#5D851835#;
26000 -- The following Export pragmas export the version numbers
26001 -- with symbolic names ending in B (for body) or S
26002 -- (for spec) so that they can be located in a link. The
26003 -- information provided here is sufficient to track down
26004 -- the exact versions of units used in a given build.
26006 pragma Export (C, u00001, "helloB");
26007 pragma Export (C, u00002, "system__standard_libraryB");
26008 pragma Export (C, u00003, "system__standard_libraryS");
26009 pragma Export (C, u00004, "adaS");
26010 pragma Export (C, u00005, "ada__text_ioB");
26011 pragma Export (C, u00006, "ada__text_ioS");
26012 pragma Export (C, u00007, "ada__exceptionsB");
26013 pragma Export (C, u00008, "ada__exceptionsS");
26014 pragma Export (C, u00009, "gnatS");
26015 pragma Export (C, u00010, "gnat__heap_sort_aB");
26016 pragma Export (C, u00011, "gnat__heap_sort_aS");
26017 pragma Export (C, u00012, "systemS");
26018 pragma Export (C, u00013, "system__exception_tableB");
26019 pragma Export (C, u00014, "system__exception_tableS");
26020 pragma Export (C, u00015, "gnat__htableB");
26021 pragma Export (C, u00016, "gnat__htableS");
26022 pragma Export (C, u00017, "system__exceptionsS");
26023 pragma Export (C, u00018, "system__machine_state_operationsB");
26024 pragma Export (C, u00019, "system__machine_state_operationsS");
26025 pragma Export (C, u00020, "system__machine_codeS");
26026 pragma Export (C, u00021, "system__storage_elementsB");
26027 pragma Export (C, u00022, "system__storage_elementsS");
26028 pragma Export (C, u00023, "system__secondary_stackB");
26029 pragma Export (C, u00024, "system__secondary_stackS");
26030 pragma Export (C, u00025, "system__parametersB");
26031 pragma Export (C, u00026, "system__parametersS");
26032 pragma Export (C, u00027, "system__soft_linksB");
26033 pragma Export (C, u00028, "system__soft_linksS");
26034 pragma Export (C, u00029, "system__stack_checkingB");
26035 pragma Export (C, u00030, "system__stack_checkingS");
26036 pragma Export (C, u00031, "system__tracebackB");
26037 pragma Export (C, u00032, "system__tracebackS");
26038 pragma Export (C, u00033, "ada__streamsS");
26039 pragma Export (C, u00034, "ada__tagsB");
26040 pragma Export (C, u00035, "ada__tagsS");
26041 pragma Export (C, u00036, "system__string_opsB");
26042 pragma Export (C, u00037, "system__string_opsS");
26043 pragma Export (C, u00038, "interfacesS");
26044 pragma Export (C, u00039, "interfaces__c_streamsB");
26045 pragma Export (C, u00040, "interfaces__c_streamsS");
26046 pragma Export (C, u00041, "system__file_ioB");
26047 pragma Export (C, u00042, "system__file_ioS");
26048 pragma Export (C, u00043, "ada__finalizationB");
26049 pragma Export (C, u00044, "ada__finalizationS");
26050 pragma Export (C, u00045, "system__finalization_rootB");
26051 pragma Export (C, u00046, "system__finalization_rootS");
26052 pragma Export (C, u00047, "system__finalization_implementationB");
26053 pragma Export (C, u00048, "system__finalization_implementationS");
26054 pragma Export (C, u00049, "system__string_ops_concat_3B");
26055 pragma Export (C, u00050, "system__string_ops_concat_3S");
26056 pragma Export (C, u00051, "system__stream_attributesB");
26057 pragma Export (C, u00052, "system__stream_attributesS");
26058 pragma Export (C, u00053, "ada__io_exceptionsS");
26059 pragma Export (C, u00054, "system__unsigned_typesS");
26060 pragma Export (C, u00055, "system__file_control_blockS");
26061 pragma Export (C, u00056, "ada__finalization__list_controllerB");
26062 pragma Export (C, u00057, "ada__finalization__list_controllerS");
26064 -- BEGIN ELABORATION ORDER
26067 -- gnat.heap_sort_a (spec)
26068 -- gnat.heap_sort_a (body)
26069 -- gnat.htable (spec)
26070 -- gnat.htable (body)
26071 -- interfaces (spec)
26073 -- system.machine_code (spec)
26074 -- system.parameters (spec)
26075 -- system.parameters (body)
26076 -- interfaces.c_streams (spec)
26077 -- interfaces.c_streams (body)
26078 -- system.standard_library (spec)
26079 -- ada.exceptions (spec)
26080 -- system.exception_table (spec)
26081 -- system.exception_table (body)
26082 -- ada.io_exceptions (spec)
26083 -- system.exceptions (spec)
26084 -- system.storage_elements (spec)
26085 -- system.storage_elements (body)
26086 -- system.machine_state_operations (spec)
26087 -- system.machine_state_operations (body)
26088 -- system.secondary_stack (spec)
26089 -- system.stack_checking (spec)
26090 -- system.soft_links (spec)
26091 -- system.soft_links (body)
26092 -- system.stack_checking (body)
26093 -- system.secondary_stack (body)
26094 -- system.standard_library (body)
26095 -- system.string_ops (spec)
26096 -- system.string_ops (body)
26099 -- ada.streams (spec)
26100 -- system.finalization_root (spec)
26101 -- system.finalization_root (body)
26102 -- system.string_ops_concat_3 (spec)
26103 -- system.string_ops_concat_3 (body)
26104 -- system.traceback (spec)
26105 -- system.traceback (body)
26106 -- ada.exceptions (body)
26107 -- system.unsigned_types (spec)
26108 -- system.stream_attributes (spec)
26109 -- system.stream_attributes (body)
26110 -- system.finalization_implementation (spec)
26111 -- system.finalization_implementation (body)
26112 -- ada.finalization (spec)
26113 -- ada.finalization (body)
26114 -- ada.finalization.list_controller (spec)
26115 -- ada.finalization.list_controller (body)
26116 -- system.file_control_block (spec)
26117 -- system.file_io (spec)
26118 -- system.file_io (body)
26119 -- ada.text_io (spec)
26120 -- ada.text_io (body)
26122 -- END ELABORATION ORDER
26126 -- The following source file name pragmas allow the generated file
26127 -- names to be unique for different main programs. They are needed
26128 -- since the package name will always be Ada_Main.
26130 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
26131 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
26133 -- Generated package body for Ada_Main starts here
26135 package body ada_main is
26137 -- The actual finalization is performed by calling the
26138 -- library routine in System.Standard_Library.Adafinal
26140 procedure Do_Finalize;
26141 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
26148 procedure adainit is
26150 -- These booleans are set to True once the associated unit has
26151 -- been elaborated. It is also used to avoid elaborating the
26152 -- same unit twice.
26155 pragma Import (Ada, E040, "interfaces__c_streams_E");
26158 pragma Import (Ada, E008, "ada__exceptions_E");
26161 pragma Import (Ada, E014, "system__exception_table_E");
26164 pragma Import (Ada, E053, "ada__io_exceptions_E");
26167 pragma Import (Ada, E017, "system__exceptions_E");
26170 pragma Import (Ada, E024, "system__secondary_stack_E");
26173 pragma Import (Ada, E030, "system__stack_checking_E");
26176 pragma Import (Ada, E028, "system__soft_links_E");
26179 pragma Import (Ada, E035, "ada__tags_E");
26182 pragma Import (Ada, E033, "ada__streams_E");
26185 pragma Import (Ada, E046, "system__finalization_root_E");
26188 pragma Import (Ada, E048, "system__finalization_implementation_E");
26191 pragma Import (Ada, E044, "ada__finalization_E");
26194 pragma Import (Ada, E057, "ada__finalization__list_controller_E");
26197 pragma Import (Ada, E055, "system__file_control_block_E");
26200 pragma Import (Ada, E042, "system__file_io_E");
26203 pragma Import (Ada, E006, "ada__text_io_E");
26205 -- Set_Globals is a library routine that stores away the
26206 -- value of the indicated set of global values in global
26207 -- variables within the library.
26209 procedure Set_Globals
26210 (Main_Priority : Integer;
26211 Time_Slice_Value : Integer;
26212 WC_Encoding : Character;
26213 Locking_Policy : Character;
26214 Queuing_Policy : Character;
26215 Task_Dispatching_Policy : Character;
26216 Adafinal : System.Address;
26217 Unreserve_All_Interrupts : Integer;
26218 Exception_Tracebacks : Integer);
26219 @findex __gnat_set_globals
26220 pragma Import (C, Set_Globals, "__gnat_set_globals");
26222 -- SDP_Table_Build is a library routine used to build the
26223 -- exception tables. See unit Ada.Exceptions in files
26224 -- a-except.ads/adb for full details of how zero cost
26225 -- exception handling works. This procedure, the call to
26226 -- it, and the two following tables are all omitted if the
26227 -- build is in longjmp/setjmp exception mode.
26229 @findex SDP_Table_Build
26230 @findex Zero Cost Exceptions
26231 procedure SDP_Table_Build
26232 (SDP_Addresses : System.Address;
26233 SDP_Count : Natural;
26234 Elab_Addresses : System.Address;
26235 Elab_Addr_Count : Natural);
26236 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
26238 -- Table of Unit_Exception_Table addresses. Used for zero
26239 -- cost exception handling to build the top level table.
26241 ST : aliased constant array (1 .. 23) of System.Address := (
26243 Ada.Text_Io'UET_Address,
26244 Ada.Exceptions'UET_Address,
26245 Gnat.Heap_Sort_A'UET_Address,
26246 System.Exception_Table'UET_Address,
26247 System.Machine_State_Operations'UET_Address,
26248 System.Secondary_Stack'UET_Address,
26249 System.Parameters'UET_Address,
26250 System.Soft_Links'UET_Address,
26251 System.Stack_Checking'UET_Address,
26252 System.Traceback'UET_Address,
26253 Ada.Streams'UET_Address,
26254 Ada.Tags'UET_Address,
26255 System.String_Ops'UET_Address,
26256 Interfaces.C_Streams'UET_Address,
26257 System.File_Io'UET_Address,
26258 Ada.Finalization'UET_Address,
26259 System.Finalization_Root'UET_Address,
26260 System.Finalization_Implementation'UET_Address,
26261 System.String_Ops_Concat_3'UET_Address,
26262 System.Stream_Attributes'UET_Address,
26263 System.File_Control_Block'UET_Address,
26264 Ada.Finalization.List_Controller'UET_Address);
26266 -- Table of addresses of elaboration routines. Used for
26267 -- zero cost exception handling to make sure these
26268 -- addresses are included in the top level procedure
26271 EA : aliased constant array (1 .. 23) of System.Address := (
26272 adainit'Code_Address,
26273 Do_Finalize'Code_Address,
26274 Ada.Exceptions'Elab_Spec'Address,
26275 System.Exceptions'Elab_Spec'Address,
26276 Interfaces.C_Streams'Elab_Spec'Address,
26277 System.Exception_Table'Elab_Body'Address,
26278 Ada.Io_Exceptions'Elab_Spec'Address,
26279 System.Stack_Checking'Elab_Spec'Address,
26280 System.Soft_Links'Elab_Body'Address,
26281 System.Secondary_Stack'Elab_Body'Address,
26282 Ada.Tags'Elab_Spec'Address,
26283 Ada.Tags'Elab_Body'Address,
26284 Ada.Streams'Elab_Spec'Address,
26285 System.Finalization_Root'Elab_Spec'Address,
26286 Ada.Exceptions'Elab_Body'Address,
26287 System.Finalization_Implementation'Elab_Spec'Address,
26288 System.Finalization_Implementation'Elab_Body'Address,
26289 Ada.Finalization'Elab_Spec'Address,
26290 Ada.Finalization.List_Controller'Elab_Spec'Address,
26291 System.File_Control_Block'Elab_Spec'Address,
26292 System.File_Io'Elab_Body'Address,
26293 Ada.Text_Io'Elab_Spec'Address,
26294 Ada.Text_Io'Elab_Body'Address);
26296 -- Start of processing for adainit
26300 -- Call SDP_Table_Build to build the top level procedure
26301 -- table for zero cost exception handling (omitted in
26302 -- longjmp/setjmp mode).
26304 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
26306 -- Call Set_Globals to record various information for
26307 -- this partition. The values are derived by the binder
26308 -- from information stored in the ali files by the compiler.
26310 @findex __gnat_set_globals
26312 (Main_Priority => -1,
26313 -- Priority of main program, -1 if no pragma Priority used
26315 Time_Slice_Value => -1,
26316 -- Time slice from Time_Slice pragma, -1 if none used
26318 WC_Encoding => 'b',
26319 -- Wide_Character encoding used, default is brackets
26321 Locking_Policy => ' ',
26322 -- Locking_Policy used, default of space means not
26323 -- specified, otherwise it is the first character of
26324 -- the policy name.
26326 Queuing_Policy => ' ',
26327 -- Queuing_Policy used, default of space means not
26328 -- specified, otherwise it is the first character of
26329 -- the policy name.
26331 Task_Dispatching_Policy => ' ',
26332 -- Task_Dispatching_Policy used, default of space means
26333 -- not specified, otherwise first character of the
26336 Adafinal => System.Null_Address,
26337 -- Address of Adafinal routine, not used anymore
26339 Unreserve_All_Interrupts => 0,
26340 -- Set true if pragma Unreserve_All_Interrupts was used
26342 Exception_Tracebacks => 0);
26343 -- Indicates if exception tracebacks are enabled
26345 Elab_Final_Code := 1;
26347 -- Now we have the elaboration calls for all units in the partition.
26348 -- The Elab_Spec and Elab_Body attributes generate references to the
26349 -- implicit elaboration procedures generated by the compiler for
26350 -- each unit that requires elaboration.
26353 Interfaces.C_Streams'Elab_Spec;
26357 Ada.Exceptions'Elab_Spec;
26360 System.Exception_Table'Elab_Body;
26364 Ada.Io_Exceptions'Elab_Spec;
26368 System.Exceptions'Elab_Spec;
26372 System.Stack_Checking'Elab_Spec;
26375 System.Soft_Links'Elab_Body;
26380 System.Secondary_Stack'Elab_Body;
26384 Ada.Tags'Elab_Spec;
26387 Ada.Tags'Elab_Body;
26391 Ada.Streams'Elab_Spec;
26395 System.Finalization_Root'Elab_Spec;
26399 Ada.Exceptions'Elab_Body;
26403 System.Finalization_Implementation'Elab_Spec;
26406 System.Finalization_Implementation'Elab_Body;
26410 Ada.Finalization'Elab_Spec;
26414 Ada.Finalization.List_Controller'Elab_Spec;
26418 System.File_Control_Block'Elab_Spec;
26422 System.File_Io'Elab_Body;
26426 Ada.Text_Io'Elab_Spec;
26429 Ada.Text_Io'Elab_Body;
26433 Elab_Final_Code := 0;
26441 procedure adafinal is
26450 -- main is actually a function, as in the ANSI C standard,
26451 -- defined to return the exit status. The three parameters
26452 -- are the argument count, argument values and environment
26455 @findex Main Program
26458 argv : System.Address;
26459 envp : System.Address)
26462 -- The initialize routine performs low level system
26463 -- initialization using a standard library routine which
26464 -- sets up signal handling and performs any other
26465 -- required setup. The routine can be found in file
26468 @findex __gnat_initialize
26469 procedure initialize;
26470 pragma Import (C, initialize, "__gnat_initialize");
26472 -- The finalize routine performs low level system
26473 -- finalization using a standard library routine. The
26474 -- routine is found in file a-final.c and in the standard
26475 -- distribution is a dummy routine that does nothing, so
26476 -- really this is a hook for special user finalization.
26478 @findex __gnat_finalize
26479 procedure finalize;
26480 pragma Import (C, finalize, "__gnat_finalize");
26482 -- We get to the main program of the partition by using
26483 -- pragma Import because if we try to with the unit and
26484 -- call it Ada style, then not only do we waste time
26485 -- recompiling it, but also, we don't really know the right
26486 -- switches (e.g.@: identifier character set) to be used
26489 procedure Ada_Main_Program;
26490 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
26492 -- Start of processing for main
26495 -- Save global variables
26501 -- Call low level system initialization
26505 -- Call our generated Ada initialization routine
26509 -- This is the point at which we want the debugger to get
26514 -- Now we call the main program of the partition
26518 -- Perform Ada finalization
26522 -- Perform low level system finalization
26526 -- Return the proper exit status
26527 return (gnat_exit_status);
26530 -- This section is entirely comments, so it has no effect on the
26531 -- compilation of the Ada_Main package. It provides the list of
26532 -- object files and linker options, as well as some standard
26533 -- libraries needed for the link. The gnatlink utility parses
26534 -- this b~hello.adb file to read these comment lines to generate
26535 -- the appropriate command line arguments for the call to the
26536 -- system linker. The BEGIN/END lines are used for sentinels for
26537 -- this parsing operation.
26539 -- The exact file names will of course depend on the environment,
26540 -- host/target and location of files on the host system.
26542 @findex Object file list
26543 -- BEGIN Object file/option list
26546 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
26547 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
26548 -- END Object file/option list
26554 The Ada code in the above example is exactly what is generated by the
26555 binder. We have added comments to more clearly indicate the function
26556 of each part of the generated @code{Ada_Main} package.
26558 The code is standard Ada in all respects, and can be processed by any
26559 tools that handle Ada. In particular, it is possible to use the debugger
26560 in Ada mode to debug the generated @code{Ada_Main} package. For example,
26561 suppose that for reasons that you do not understand, your program is crashing
26562 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
26563 you can place a breakpoint on the call:
26565 @smallexample @c ada
26566 Ada.Text_Io'Elab_Body;
26570 and trace the elaboration routine for this package to find out where
26571 the problem might be (more usually of course you would be debugging
26572 elaboration code in your own application).
26574 @node Elaboration Order Handling in GNAT
26575 @appendix Elaboration Order Handling in GNAT
26576 @cindex Order of elaboration
26577 @cindex Elaboration control
26580 * Elaboration Code::
26581 * Checking the Elaboration Order::
26582 * Controlling the Elaboration Order::
26583 * Controlling Elaboration in GNAT - Internal Calls::
26584 * Controlling Elaboration in GNAT - External Calls::
26585 * Default Behavior in GNAT - Ensuring Safety::
26586 * Treatment of Pragma Elaborate::
26587 * Elaboration Issues for Library Tasks::
26588 * Mixing Elaboration Models::
26589 * What to Do If the Default Elaboration Behavior Fails::
26590 * Elaboration for Access-to-Subprogram Values::
26591 * Summary of Procedures for Elaboration Control::
26592 * Other Elaboration Order Considerations::
26596 This chapter describes the handling of elaboration code in Ada and
26597 in GNAT, and discusses how the order of elaboration of program units can
26598 be controlled in GNAT, either automatically or with explicit programming
26601 @node Elaboration Code
26602 @section Elaboration Code
26605 Ada provides rather general mechanisms for executing code at elaboration
26606 time, that is to say before the main program starts executing. Such code arises
26610 @item Initializers for variables.
26611 Variables declared at the library level, in package specs or bodies, can
26612 require initialization that is performed at elaboration time, as in:
26613 @smallexample @c ada
26615 Sqrt_Half : Float := Sqrt (0.5);
26619 @item Package initialization code
26620 Code in a @code{BEGIN-END} section at the outer level of a package body is
26621 executed as part of the package body elaboration code.
26623 @item Library level task allocators
26624 Tasks that are declared using task allocators at the library level
26625 start executing immediately and hence can execute at elaboration time.
26629 Subprogram calls are possible in any of these contexts, which means that
26630 any arbitrary part of the program may be executed as part of the elaboration
26631 code. It is even possible to write a program which does all its work at
26632 elaboration time, with a null main program, although stylistically this
26633 would usually be considered an inappropriate way to structure
26636 An important concern arises in the context of elaboration code:
26637 we have to be sure that it is executed in an appropriate order. What we
26638 have is a series of elaboration code sections, potentially one section
26639 for each unit in the program. It is important that these execute
26640 in the correct order. Correctness here means that, taking the above
26641 example of the declaration of @code{Sqrt_Half},
26642 if some other piece of
26643 elaboration code references @code{Sqrt_Half},
26644 then it must run after the
26645 section of elaboration code that contains the declaration of
26648 There would never be any order of elaboration problem if we made a rule
26649 that whenever you @code{with} a unit, you must elaborate both the spec and body
26650 of that unit before elaborating the unit doing the @code{with}'ing:
26652 @smallexample @c ada
26656 package Unit_2 is @dots{}
26662 would require that both the body and spec of @code{Unit_1} be elaborated
26663 before the spec of @code{Unit_2}. However, a rule like that would be far too
26664 restrictive. In particular, it would make it impossible to have routines
26665 in separate packages that were mutually recursive.
26667 You might think that a clever enough compiler could look at the actual
26668 elaboration code and determine an appropriate correct order of elaboration,
26669 but in the general case, this is not possible. Consider the following
26672 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
26674 the variable @code{Sqrt_1}, which is declared in the elaboration code
26675 of the body of @code{Unit_1}:
26677 @smallexample @c ada
26679 Sqrt_1 : Float := Sqrt (0.1);
26684 The elaboration code of the body of @code{Unit_1} also contains:
26686 @smallexample @c ada
26689 if expression_1 = 1 then
26690 Q := Unit_2.Func_2;
26697 @code{Unit_2} is exactly parallel,
26698 it has a procedure @code{Func_2} that references
26699 the variable @code{Sqrt_2}, which is declared in the elaboration code of
26700 the body @code{Unit_2}:
26702 @smallexample @c ada
26704 Sqrt_2 : Float := Sqrt (0.1);
26709 The elaboration code of the body of @code{Unit_2} also contains:
26711 @smallexample @c ada
26714 if expression_2 = 2 then
26715 Q := Unit_1.Func_1;
26722 Now the question is, which of the following orders of elaboration is
26747 If you carefully analyze the flow here, you will see that you cannot tell
26748 at compile time the answer to this question.
26749 If @code{expression_1} is not equal to 1,
26750 and @code{expression_2} is not equal to 2,
26751 then either order is acceptable, because neither of the function calls is
26752 executed. If both tests evaluate to true, then neither order is acceptable
26753 and in fact there is no correct order.
26755 If one of the two expressions is true, and the other is false, then one
26756 of the above orders is correct, and the other is incorrect. For example,
26757 if @code{expression_1} /= 1 and @code{expression_2} = 2,
26758 then the call to @code{Func_1}
26759 will occur, but not the call to @code{Func_2.}
26760 This means that it is essential
26761 to elaborate the body of @code{Unit_1} before
26762 the body of @code{Unit_2}, so the first
26763 order of elaboration is correct and the second is wrong.
26765 By making @code{expression_1} and @code{expression_2}
26766 depend on input data, or perhaps
26767 the time of day, we can make it impossible for the compiler or binder
26768 to figure out which of these expressions will be true, and hence it
26769 is impossible to guarantee a safe order of elaboration at run time.
26771 @node Checking the Elaboration Order
26772 @section Checking the Elaboration Order
26775 In some languages that involve the same kind of elaboration problems,
26776 e.g.@: Java and C++, the programmer is expected to worry about these
26777 ordering problems himself, and it is common to
26778 write a program in which an incorrect elaboration order gives
26779 surprising results, because it references variables before they
26781 Ada is designed to be a safe language, and a programmer-beware approach is
26782 clearly not sufficient. Consequently, the language provides three lines
26786 @item Standard rules
26787 Some standard rules restrict the possible choice of elaboration
26788 order. In particular, if you @code{with} a unit, then its spec is always
26789 elaborated before the unit doing the @code{with}. Similarly, a parent
26790 spec is always elaborated before the child spec, and finally
26791 a spec is always elaborated before its corresponding body.
26793 @item Dynamic elaboration checks
26794 @cindex Elaboration checks
26795 @cindex Checks, elaboration
26796 Dynamic checks are made at run time, so that if some entity is accessed
26797 before it is elaborated (typically by means of a subprogram call)
26798 then the exception (@code{Program_Error}) is raised.
26800 @item Elaboration control
26801 Facilities are provided for the programmer to specify the desired order
26805 Let's look at these facilities in more detail. First, the rules for
26806 dynamic checking. One possible rule would be simply to say that the
26807 exception is raised if you access a variable which has not yet been
26808 elaborated. The trouble with this approach is that it could require
26809 expensive checks on every variable reference. Instead Ada has two
26810 rules which are a little more restrictive, but easier to check, and
26814 @item Restrictions on calls
26815 A subprogram can only be called at elaboration time if its body
26816 has been elaborated. The rules for elaboration given above guarantee
26817 that the spec of the subprogram has been elaborated before the
26818 call, but not the body. If this rule is violated, then the
26819 exception @code{Program_Error} is raised.
26821 @item Restrictions on instantiations
26822 A generic unit can only be instantiated if the body of the generic
26823 unit has been elaborated. Again, the rules for elaboration given above
26824 guarantee that the spec of the generic unit has been elaborated
26825 before the instantiation, but not the body. If this rule is
26826 violated, then the exception @code{Program_Error} is raised.
26830 The idea is that if the body has been elaborated, then any variables
26831 it references must have been elaborated; by checking for the body being
26832 elaborated we guarantee that none of its references causes any
26833 trouble. As we noted above, this is a little too restrictive, because a
26834 subprogram that has no non-local references in its body may in fact be safe
26835 to call. However, it really would be unsafe to rely on this, because
26836 it would mean that the caller was aware of details of the implementation
26837 in the body. This goes against the basic tenets of Ada.
26839 A plausible implementation can be described as follows.
26840 A Boolean variable is associated with each subprogram
26841 and each generic unit. This variable is initialized to False, and is set to
26842 True at the point body is elaborated. Every call or instantiation checks the
26843 variable, and raises @code{Program_Error} if the variable is False.
26845 Note that one might think that it would be good enough to have one Boolean
26846 variable for each package, but that would not deal with cases of trying
26847 to call a body in the same package as the call
26848 that has not been elaborated yet.
26849 Of course a compiler may be able to do enough analysis to optimize away
26850 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
26851 does such optimizations, but still the easiest conceptual model is to
26852 think of there being one variable per subprogram.
26854 @node Controlling the Elaboration Order
26855 @section Controlling the Elaboration Order
26858 In the previous section we discussed the rules in Ada which ensure
26859 that @code{Program_Error} is raised if an incorrect elaboration order is
26860 chosen. This prevents erroneous executions, but we need mechanisms to
26861 specify a correct execution and avoid the exception altogether.
26862 To achieve this, Ada provides a number of features for controlling
26863 the order of elaboration. We discuss these features in this section.
26865 First, there are several ways of indicating to the compiler that a given
26866 unit has no elaboration problems:
26869 @item packages that do not require a body
26870 A library package that does not require a body does not permit
26871 a body (this rule was introduced in Ada 95).
26872 Thus if we have a such a package, as in:
26874 @smallexample @c ada
26877 package Definitions is
26879 type m is new integer;
26881 type a is array (1 .. 10) of m;
26882 type b is array (1 .. 20) of m;
26890 A package that @code{with}'s @code{Definitions} may safely instantiate
26891 @code{Definitions.Subp} because the compiler can determine that there
26892 definitely is no package body to worry about in this case
26895 @cindex pragma Pure
26897 Places sufficient restrictions on a unit to guarantee that
26898 no call to any subprogram in the unit can result in an
26899 elaboration problem. This means that the compiler does not need
26900 to worry about the point of elaboration of such units, and in
26901 particular, does not need to check any calls to any subprograms
26904 @item pragma Preelaborate
26905 @findex Preelaborate
26906 @cindex pragma Preelaborate
26907 This pragma places slightly less stringent restrictions on a unit than
26909 but these restrictions are still sufficient to ensure that there
26910 are no elaboration problems with any calls to the unit.
26912 @item pragma Elaborate_Body
26913 @findex Elaborate_Body
26914 @cindex pragma Elaborate_Body
26915 This pragma requires that the body of a unit be elaborated immediately
26916 after its spec. Suppose a unit @code{A} has such a pragma,
26917 and unit @code{B} does
26918 a @code{with} of unit @code{A}. Recall that the standard rules require
26919 the spec of unit @code{A}
26920 to be elaborated before the @code{with}'ing unit; given the pragma in
26921 @code{A}, we also know that the body of @code{A}
26922 will be elaborated before @code{B}, so
26923 that calls to @code{A} are safe and do not need a check.
26928 unlike pragma @code{Pure} and pragma @code{Preelaborate},
26930 @code{Elaborate_Body} does not guarantee that the program is
26931 free of elaboration problems, because it may not be possible
26932 to satisfy the requested elaboration order.
26933 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
26935 marks @code{Unit_1} as @code{Elaborate_Body},
26936 and not @code{Unit_2,} then the order of
26937 elaboration will be:
26949 Now that means that the call to @code{Func_1} in @code{Unit_2}
26950 need not be checked,
26951 it must be safe. But the call to @code{Func_2} in
26952 @code{Unit_1} may still fail if
26953 @code{Expression_1} is equal to 1,
26954 and the programmer must still take
26955 responsibility for this not being the case.
26957 If all units carry a pragma @code{Elaborate_Body}, then all problems are
26958 eliminated, except for calls entirely within a body, which are
26959 in any case fully under programmer control. However, using the pragma
26960 everywhere is not always possible.
26961 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
26962 we marked both of them as having pragma @code{Elaborate_Body}, then
26963 clearly there would be no possible elaboration order.
26965 The above pragmas allow a server to guarantee safe use by clients, and
26966 clearly this is the preferable approach. Consequently a good rule
26967 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
26968 and if this is not possible,
26969 mark them as @code{Elaborate_Body} if possible.
26970 As we have seen, there are situations where neither of these
26971 three pragmas can be used.
26972 So we also provide methods for clients to control the
26973 order of elaboration of the servers on which they depend:
26976 @item pragma Elaborate (unit)
26978 @cindex pragma Elaborate
26979 This pragma is placed in the context clause, after a @code{with} clause,
26980 and it requires that the body of the named unit be elaborated before
26981 the unit in which the pragma occurs. The idea is to use this pragma
26982 if the current unit calls at elaboration time, directly or indirectly,
26983 some subprogram in the named unit.
26985 @item pragma Elaborate_All (unit)
26986 @findex Elaborate_All
26987 @cindex pragma Elaborate_All
26988 This is a stronger version of the Elaborate pragma. Consider the
26992 Unit A @code{with}'s unit B and calls B.Func in elab code
26993 Unit B @code{with}'s unit C, and B.Func calls C.Func
26997 Now if we put a pragma @code{Elaborate (B)}
26998 in unit @code{A}, this ensures that the
26999 body of @code{B} is elaborated before the call, but not the
27000 body of @code{C}, so
27001 the call to @code{C.Func} could still cause @code{Program_Error} to
27004 The effect of a pragma @code{Elaborate_All} is stronger, it requires
27005 not only that the body of the named unit be elaborated before the
27006 unit doing the @code{with}, but also the bodies of all units that the
27007 named unit uses, following @code{with} links transitively. For example,
27008 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
27010 not only that the body of @code{B} be elaborated before @code{A},
27012 body of @code{C}, because @code{B} @code{with}'s @code{C}.
27016 We are now in a position to give a usage rule in Ada for avoiding
27017 elaboration problems, at least if dynamic dispatching and access to
27018 subprogram values are not used. We will handle these cases separately
27021 The rule is simple. If a unit has elaboration code that can directly or
27022 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
27023 a generic package in a @code{with}'ed unit,
27024 then if the @code{with}'ed unit does not have
27025 pragma @code{Pure} or @code{Preelaborate}, then the client should have
27026 a pragma @code{Elaborate_All}
27027 for the @code{with}'ed unit. By following this rule a client is
27028 assured that calls can be made without risk of an exception.
27030 For generic subprogram instantiations, the rule can be relaxed to
27031 require only a pragma @code{Elaborate} since elaborating the body
27032 of a subprogram cannot cause any transitive elaboration (we are
27033 not calling the subprogram in this case, just elaborating its
27036 If this rule is not followed, then a program may be in one of four
27040 @item No order exists
27041 No order of elaboration exists which follows the rules, taking into
27042 account any @code{Elaborate}, @code{Elaborate_All},
27043 or @code{Elaborate_Body} pragmas. In
27044 this case, an Ada compiler must diagnose the situation at bind
27045 time, and refuse to build an executable program.
27047 @item One or more orders exist, all incorrect
27048 One or more acceptable elaboration orders exist, and all of them
27049 generate an elaboration order problem. In this case, the binder
27050 can build an executable program, but @code{Program_Error} will be raised
27051 when the program is run.
27053 @item Several orders exist, some right, some incorrect
27054 One or more acceptable elaboration orders exists, and some of them
27055 work, and some do not. The programmer has not controlled
27056 the order of elaboration, so the binder may or may not pick one of
27057 the correct orders, and the program may or may not raise an
27058 exception when it is run. This is the worst case, because it means
27059 that the program may fail when moved to another compiler, or even
27060 another version of the same compiler.
27062 @item One or more orders exists, all correct
27063 One ore more acceptable elaboration orders exist, and all of them
27064 work. In this case the program runs successfully. This state of
27065 affairs can be guaranteed by following the rule we gave above, but
27066 may be true even if the rule is not followed.
27070 Note that one additional advantage of following our rules on the use
27071 of @code{Elaborate} and @code{Elaborate_All}
27072 is that the program continues to stay in the ideal (all orders OK) state
27073 even if maintenance
27074 changes some bodies of some units. Conversely, if a program that does
27075 not follow this rule happens to be safe at some point, this state of affairs
27076 may deteriorate silently as a result of maintenance changes.
27078 You may have noticed that the above discussion did not mention
27079 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
27080 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
27081 code in the body makes calls to some other unit, so it is still necessary
27082 to use @code{Elaborate_All} on such units.
27084 @node Controlling Elaboration in GNAT - Internal Calls
27085 @section Controlling Elaboration in GNAT - Internal Calls
27088 In the case of internal calls, i.e., calls within a single package, the
27089 programmer has full control over the order of elaboration, and it is up
27090 to the programmer to elaborate declarations in an appropriate order. For
27093 @smallexample @c ada
27096 function One return Float;
27100 function One return Float is
27109 will obviously raise @code{Program_Error} at run time, because function
27110 One will be called before its body is elaborated. In this case GNAT will
27111 generate a warning that the call will raise @code{Program_Error}:
27117 2. function One return Float;
27119 4. Q : Float := One;
27121 >>> warning: cannot call "One" before body is elaborated
27122 >>> warning: Program_Error will be raised at run time
27125 6. function One return Float is
27138 Note that in this particular case, it is likely that the call is safe, because
27139 the function @code{One} does not access any global variables.
27140 Nevertheless in Ada, we do not want the validity of the check to depend on
27141 the contents of the body (think about the separate compilation case), so this
27142 is still wrong, as we discussed in the previous sections.
27144 The error is easily corrected by rearranging the declarations so that the
27145 body of @code{One} appears before the declaration containing the call
27146 (note that in Ada 95 and Ada 2005,
27147 declarations can appear in any order, so there is no restriction that
27148 would prevent this reordering, and if we write:
27150 @smallexample @c ada
27153 function One return Float;
27155 function One return Float is
27166 then all is well, no warning is generated, and no
27167 @code{Program_Error} exception
27169 Things are more complicated when a chain of subprograms is executed:
27171 @smallexample @c ada
27174 function A return Integer;
27175 function B return Integer;
27176 function C return Integer;
27178 function B return Integer is begin return A; end;
27179 function C return Integer is begin return B; end;
27183 function A return Integer is begin return 1; end;
27189 Now the call to @code{C}
27190 at elaboration time in the declaration of @code{X} is correct, because
27191 the body of @code{C} is already elaborated,
27192 and the call to @code{B} within the body of
27193 @code{C} is correct, but the call
27194 to @code{A} within the body of @code{B} is incorrect, because the body
27195 of @code{A} has not been elaborated, so @code{Program_Error}
27196 will be raised on the call to @code{A}.
27197 In this case GNAT will generate a
27198 warning that @code{Program_Error} may be
27199 raised at the point of the call. Let's look at the warning:
27205 2. function A return Integer;
27206 3. function B return Integer;
27207 4. function C return Integer;
27209 6. function B return Integer is begin return A; end;
27211 >>> warning: call to "A" before body is elaborated may
27212 raise Program_Error
27213 >>> warning: "B" called at line 7
27214 >>> warning: "C" called at line 9
27216 7. function C return Integer is begin return B; end;
27218 9. X : Integer := C;
27220 11. function A return Integer is begin return 1; end;
27230 Note that the message here says ``may raise'', instead of the direct case,
27231 where the message says ``will be raised''. That's because whether
27233 actually called depends in general on run-time flow of control.
27234 For example, if the body of @code{B} said
27236 @smallexample @c ada
27239 function B return Integer is
27241 if some-condition-depending-on-input-data then
27252 then we could not know until run time whether the incorrect call to A would
27253 actually occur, so @code{Program_Error} might
27254 or might not be raised. It is possible for a compiler to
27255 do a better job of analyzing bodies, to
27256 determine whether or not @code{Program_Error}
27257 might be raised, but it certainly
27258 couldn't do a perfect job (that would require solving the halting problem
27259 and is provably impossible), and because this is a warning anyway, it does
27260 not seem worth the effort to do the analysis. Cases in which it
27261 would be relevant are rare.
27263 In practice, warnings of either of the forms given
27264 above will usually correspond to
27265 real errors, and should be examined carefully and eliminated.
27266 In the rare case where a warning is bogus, it can be suppressed by any of
27267 the following methods:
27271 Compile with the @option{-gnatws} switch set
27274 Suppress @code{Elaboration_Check} for the called subprogram
27277 Use pragma @code{Warnings_Off} to turn warnings off for the call
27281 For the internal elaboration check case,
27282 GNAT by default generates the
27283 necessary run-time checks to ensure
27284 that @code{Program_Error} is raised if any
27285 call fails an elaboration check. Of course this can only happen if a
27286 warning has been issued as described above. The use of pragma
27287 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
27288 some of these checks, meaning that it may be possible (but is not
27289 guaranteed) for a program to be able to call a subprogram whose body
27290 is not yet elaborated, without raising a @code{Program_Error} exception.
27292 @node Controlling Elaboration in GNAT - External Calls
27293 @section Controlling Elaboration in GNAT - External Calls
27296 The previous section discussed the case in which the execution of a
27297 particular thread of elaboration code occurred entirely within a
27298 single unit. This is the easy case to handle, because a programmer
27299 has direct and total control over the order of elaboration, and
27300 furthermore, checks need only be generated in cases which are rare
27301 and which the compiler can easily detect.
27302 The situation is more complex when separate compilation is taken into account.
27303 Consider the following:
27305 @smallexample @c ada
27309 function Sqrt (Arg : Float) return Float;
27312 package body Math is
27313 function Sqrt (Arg : Float) return Float is
27322 X : Float := Math.Sqrt (0.5);
27335 where @code{Main} is the main program. When this program is executed, the
27336 elaboration code must first be executed, and one of the jobs of the
27337 binder is to determine the order in which the units of a program are
27338 to be elaborated. In this case we have four units: the spec and body
27340 the spec of @code{Stuff} and the body of @code{Main}).
27341 In what order should the four separate sections of elaboration code
27344 There are some restrictions in the order of elaboration that the binder
27345 can choose. In particular, if unit U has a @code{with}
27346 for a package @code{X}, then you
27347 are assured that the spec of @code{X}
27348 is elaborated before U , but you are
27349 not assured that the body of @code{X}
27350 is elaborated before U.
27351 This means that in the above case, the binder is allowed to choose the
27362 but that's not good, because now the call to @code{Math.Sqrt}
27363 that happens during
27364 the elaboration of the @code{Stuff}
27365 spec happens before the body of @code{Math.Sqrt} is
27366 elaborated, and hence causes @code{Program_Error} exception to be raised.
27367 At first glance, one might say that the binder is misbehaving, because
27368 obviously you want to elaborate the body of something you @code{with}
27370 that is not a general rule that can be followed in all cases. Consider
27372 @smallexample @c ada
27375 package X is @dots{}
27377 package Y is @dots{}
27380 package body Y is @dots{}
27383 package body X is @dots{}
27389 This is a common arrangement, and, apart from the order of elaboration
27390 problems that might arise in connection with elaboration code, this works fine.
27391 A rule that says that you must first elaborate the body of anything you
27392 @code{with} cannot work in this case:
27393 the body of @code{X} @code{with}'s @code{Y},
27394 which means you would have to
27395 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
27397 you have to elaborate the body of @code{X} first, but @dots{} and we have a
27398 loop that cannot be broken.
27400 It is true that the binder can in many cases guess an order of elaboration
27401 that is unlikely to cause a @code{Program_Error}
27402 exception to be raised, and it tries to do so (in the
27403 above example of @code{Math/Stuff/Spec}, the GNAT binder will
27405 elaborate the body of @code{Math} right after its spec, so all will be well).
27407 However, a program that blindly relies on the binder to be helpful can
27408 get into trouble, as we discussed in the previous sections, so
27410 provides a number of facilities for assisting the programmer in
27411 developing programs that are robust with respect to elaboration order.
27413 @node Default Behavior in GNAT - Ensuring Safety
27414 @section Default Behavior in GNAT - Ensuring Safety
27417 The default behavior in GNAT ensures elaboration safety. In its
27418 default mode GNAT implements the
27419 rule we previously described as the right approach. Let's restate it:
27423 @emph{If a unit has elaboration code that can directly or indirectly make a
27424 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
27425 package in a @code{with}'ed unit, then if the @code{with}'ed unit
27426 does not have pragma @code{Pure} or
27427 @code{Preelaborate}, then the client should have an
27428 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
27430 @emph{In the case of instantiating a generic subprogram, it is always
27431 sufficient to have only an @code{Elaborate} pragma for the
27432 @code{with}'ed unit.}
27436 By following this rule a client is assured that calls and instantiations
27437 can be made without risk of an exception.
27439 In this mode GNAT traces all calls that are potentially made from
27440 elaboration code, and puts in any missing implicit @code{Elaborate}
27441 and @code{Elaborate_All} pragmas.
27442 The advantage of this approach is that no elaboration problems
27443 are possible if the binder can find an elaboration order that is
27444 consistent with these implicit @code{Elaborate} and
27445 @code{Elaborate_All} pragmas. The
27446 disadvantage of this approach is that no such order may exist.
27448 If the binder does not generate any diagnostics, then it means that it has
27449 found an elaboration order that is guaranteed to be safe. However, the binder
27450 may still be relying on implicitly generated @code{Elaborate} and
27451 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
27454 If it is important to guarantee portability, then the compilations should
27457 (warn on elaboration problems) switch. This will cause warning messages
27458 to be generated indicating the missing @code{Elaborate} and
27459 @code{Elaborate_All} pragmas.
27460 Consider the following source program:
27462 @smallexample @c ada
27467 m : integer := k.r;
27474 where it is clear that there
27475 should be a pragma @code{Elaborate_All}
27476 for unit @code{k}. An implicit pragma will be generated, and it is
27477 likely that the binder will be able to honor it. However, if you want
27478 to port this program to some other Ada compiler than GNAT.
27479 it is safer to include the pragma explicitly in the source. If this
27480 unit is compiled with the
27482 switch, then the compiler outputs a warning:
27489 3. m : integer := k.r;
27491 >>> warning: call to "r" may raise Program_Error
27492 >>> warning: missing pragma Elaborate_All for "k"
27500 and these warnings can be used as a guide for supplying manually
27501 the missing pragmas. It is usually a bad idea to use this warning
27502 option during development. That's because it will warn you when
27503 you need to put in a pragma, but cannot warn you when it is time
27504 to take it out. So the use of pragma @code{Elaborate_All} may lead to
27505 unnecessary dependencies and even false circularities.
27507 This default mode is more restrictive than the Ada Reference
27508 Manual, and it is possible to construct programs which will compile
27509 using the dynamic model described there, but will run into a
27510 circularity using the safer static model we have described.
27512 Of course any Ada compiler must be able to operate in a mode
27513 consistent with the requirements of the Ada Reference Manual,
27514 and in particular must have the capability of implementing the
27515 standard dynamic model of elaboration with run-time checks.
27517 In GNAT, this standard mode can be achieved either by the use of
27518 the @option{-gnatE} switch on the compiler (@command{gcc} or
27519 @command{gnatmake}) command, or by the use of the configuration pragma:
27521 @smallexample @c ada
27522 pragma Elaboration_Checks (RM);
27526 Either approach will cause the unit affected to be compiled using the
27527 standard dynamic run-time elaboration checks described in the Ada
27528 Reference Manual. The static model is generally preferable, since it
27529 is clearly safer to rely on compile and link time checks rather than
27530 run-time checks. However, in the case of legacy code, it may be
27531 difficult to meet the requirements of the static model. This
27532 issue is further discussed in
27533 @ref{What to Do If the Default Elaboration Behavior Fails}.
27535 Note that the static model provides a strict subset of the allowed
27536 behavior and programs of the Ada Reference Manual, so if you do
27537 adhere to the static model and no circularities exist,
27538 then you are assured that your program will
27539 work using the dynamic model, providing that you remove any
27540 pragma Elaborate statements from the source.
27542 @node Treatment of Pragma Elaborate
27543 @section Treatment of Pragma Elaborate
27544 @cindex Pragma Elaborate
27547 The use of @code{pragma Elaborate}
27548 should generally be avoided in Ada 95 and Ada 2005 programs,
27549 since there is no guarantee that transitive calls
27550 will be properly handled. Indeed at one point, this pragma was placed
27551 in Annex J (Obsolescent Features), on the grounds that it is never useful.
27553 Now that's a bit restrictive. In practice, the case in which
27554 @code{pragma Elaborate} is useful is when the caller knows that there
27555 are no transitive calls, or that the called unit contains all necessary
27556 transitive @code{pragma Elaborate} statements, and legacy code often
27557 contains such uses.
27559 Strictly speaking the static mode in GNAT should ignore such pragmas,
27560 since there is no assurance at compile time that the necessary safety
27561 conditions are met. In practice, this would cause GNAT to be incompatible
27562 with correctly written Ada 83 code that had all necessary
27563 @code{pragma Elaborate} statements in place. Consequently, we made the
27564 decision that GNAT in its default mode will believe that if it encounters
27565 a @code{pragma Elaborate} then the programmer knows what they are doing,
27566 and it will trust that no elaboration errors can occur.
27568 The result of this decision is two-fold. First to be safe using the
27569 static mode, you should remove all @code{pragma Elaborate} statements.
27570 Second, when fixing circularities in existing code, you can selectively
27571 use @code{pragma Elaborate} statements to convince the static mode of
27572 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
27575 When using the static mode with @option{-gnatwl}, any use of
27576 @code{pragma Elaborate} will generate a warning about possible
27579 @node Elaboration Issues for Library Tasks
27580 @section Elaboration Issues for Library Tasks
27581 @cindex Library tasks, elaboration issues
27582 @cindex Elaboration of library tasks
27585 In this section we examine special elaboration issues that arise for
27586 programs that declare library level tasks.
27588 Generally the model of execution of an Ada program is that all units are
27589 elaborated, and then execution of the program starts. However, the
27590 declaration of library tasks definitely does not fit this model. The
27591 reason for this is that library tasks start as soon as they are declared
27592 (more precisely, as soon as the statement part of the enclosing package
27593 body is reached), that is to say before elaboration
27594 of the program is complete. This means that if such a task calls a
27595 subprogram, or an entry in another task, the callee may or may not be
27596 elaborated yet, and in the standard
27597 Reference Manual model of dynamic elaboration checks, you can even
27598 get timing dependent Program_Error exceptions, since there can be
27599 a race between the elaboration code and the task code.
27601 The static model of elaboration in GNAT seeks to avoid all such
27602 dynamic behavior, by being conservative, and the conservative
27603 approach in this particular case is to assume that all the code
27604 in a task body is potentially executed at elaboration time if
27605 a task is declared at the library level.
27607 This can definitely result in unexpected circularities. Consider
27608 the following example
27610 @smallexample @c ada
27616 type My_Int is new Integer;
27618 function Ident (M : My_Int) return My_Int;
27622 package body Decls is
27623 task body Lib_Task is
27629 function Ident (M : My_Int) return My_Int is
27637 procedure Put_Val (Arg : Decls.My_Int);
27641 package body Utils is
27642 procedure Put_Val (Arg : Decls.My_Int) is
27644 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
27651 Decls.Lib_Task.Start;
27656 If the above example is compiled in the default static elaboration
27657 mode, then a circularity occurs. The circularity comes from the call
27658 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
27659 this call occurs in elaboration code, we need an implicit pragma
27660 @code{Elaborate_All} for @code{Utils}. This means that not only must
27661 the spec and body of @code{Utils} be elaborated before the body
27662 of @code{Decls}, but also the spec and body of any unit that is
27663 @code{with'ed} by the body of @code{Utils} must also be elaborated before
27664 the body of @code{Decls}. This is the transitive implication of
27665 pragma @code{Elaborate_All} and it makes sense, because in general
27666 the body of @code{Put_Val} might have a call to something in a
27667 @code{with'ed} unit.
27669 In this case, the body of Utils (actually its spec) @code{with's}
27670 @code{Decls}. Unfortunately this means that the body of @code{Decls}
27671 must be elaborated before itself, in case there is a call from the
27672 body of @code{Utils}.
27674 Here is the exact chain of events we are worrying about:
27678 In the body of @code{Decls} a call is made from within the body of a library
27679 task to a subprogram in the package @code{Utils}. Since this call may
27680 occur at elaboration time (given that the task is activated at elaboration
27681 time), we have to assume the worst, i.e., that the
27682 call does happen at elaboration time.
27685 This means that the body and spec of @code{Util} must be elaborated before
27686 the body of @code{Decls} so that this call does not cause an access before
27690 Within the body of @code{Util}, specifically within the body of
27691 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
27695 One such @code{with}'ed package is package @code{Decls}, so there
27696 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
27697 In fact there is such a call in this example, but we would have to
27698 assume that there was such a call even if it were not there, since
27699 we are not supposed to write the body of @code{Decls} knowing what
27700 is in the body of @code{Utils}; certainly in the case of the
27701 static elaboration model, the compiler does not know what is in
27702 other bodies and must assume the worst.
27705 This means that the spec and body of @code{Decls} must also be
27706 elaborated before we elaborate the unit containing the call, but
27707 that unit is @code{Decls}! This means that the body of @code{Decls}
27708 must be elaborated before itself, and that's a circularity.
27712 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
27713 the body of @code{Decls} you will get a true Ada Reference Manual
27714 circularity that makes the program illegal.
27716 In practice, we have found that problems with the static model of
27717 elaboration in existing code often arise from library tasks, so
27718 we must address this particular situation.
27720 Note that if we compile and run the program above, using the dynamic model of
27721 elaboration (that is to say use the @option{-gnatE} switch),
27722 then it compiles, binds,
27723 links, and runs, printing the expected result of 2. Therefore in some sense
27724 the circularity here is only apparent, and we need to capture
27725 the properties of this program that distinguish it from other library-level
27726 tasks that have real elaboration problems.
27728 We have four possible answers to this question:
27733 Use the dynamic model of elaboration.
27735 If we use the @option{-gnatE} switch, then as noted above, the program works.
27736 Why is this? If we examine the task body, it is apparent that the task cannot
27738 @code{accept} statement until after elaboration has been completed, because
27739 the corresponding entry call comes from the main program, not earlier.
27740 This is why the dynamic model works here. But that's really giving
27741 up on a precise analysis, and we prefer to take this approach only if we cannot
27743 problem in any other manner. So let us examine two ways to reorganize
27744 the program to avoid the potential elaboration problem.
27747 Split library tasks into separate packages.
27749 Write separate packages, so that library tasks are isolated from
27750 other declarations as much as possible. Let us look at a variation on
27753 @smallexample @c ada
27761 package body Decls1 is
27762 task body Lib_Task is
27770 type My_Int is new Integer;
27771 function Ident (M : My_Int) return My_Int;
27775 package body Decls2 is
27776 function Ident (M : My_Int) return My_Int is
27784 procedure Put_Val (Arg : Decls2.My_Int);
27788 package body Utils is
27789 procedure Put_Val (Arg : Decls2.My_Int) is
27791 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
27798 Decls1.Lib_Task.Start;
27803 All we have done is to split @code{Decls} into two packages, one
27804 containing the library task, and one containing everything else. Now
27805 there is no cycle, and the program compiles, binds, links and executes
27806 using the default static model of elaboration.
27809 Declare separate task types.
27811 A significant part of the problem arises because of the use of the
27812 single task declaration form. This means that the elaboration of
27813 the task type, and the elaboration of the task itself (i.e.@: the
27814 creation of the task) happen at the same time. A good rule
27815 of style in Ada is to always create explicit task types. By
27816 following the additional step of placing task objects in separate
27817 packages from the task type declaration, many elaboration problems
27818 are avoided. Here is another modified example of the example program:
27820 @smallexample @c ada
27822 task type Lib_Task_Type is
27826 type My_Int is new Integer;
27828 function Ident (M : My_Int) return My_Int;
27832 package body Decls is
27833 task body Lib_Task_Type is
27839 function Ident (M : My_Int) return My_Int is
27847 procedure Put_Val (Arg : Decls.My_Int);
27851 package body Utils is
27852 procedure Put_Val (Arg : Decls.My_Int) is
27854 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
27860 Lib_Task : Decls.Lib_Task_Type;
27866 Declst.Lib_Task.Start;
27871 What we have done here is to replace the @code{task} declaration in
27872 package @code{Decls} with a @code{task type} declaration. Then we
27873 introduce a separate package @code{Declst} to contain the actual
27874 task object. This separates the elaboration issues for
27875 the @code{task type}
27876 declaration, which causes no trouble, from the elaboration issues
27877 of the task object, which is also unproblematic, since it is now independent
27878 of the elaboration of @code{Utils}.
27879 This separation of concerns also corresponds to
27880 a generally sound engineering principle of separating declarations
27881 from instances. This version of the program also compiles, binds, links,
27882 and executes, generating the expected output.
27885 Use No_Entry_Calls_In_Elaboration_Code restriction.
27886 @cindex No_Entry_Calls_In_Elaboration_Code
27888 The previous two approaches described how a program can be restructured
27889 to avoid the special problems caused by library task bodies. in practice,
27890 however, such restructuring may be difficult to apply to existing legacy code,
27891 so we must consider solutions that do not require massive rewriting.
27893 Let us consider more carefully why our original sample program works
27894 under the dynamic model of elaboration. The reason is that the code
27895 in the task body blocks immediately on the @code{accept}
27896 statement. Now of course there is nothing to prohibit elaboration
27897 code from making entry calls (for example from another library level task),
27898 so we cannot tell in isolation that
27899 the task will not execute the accept statement during elaboration.
27901 However, in practice it is very unusual to see elaboration code
27902 make any entry calls, and the pattern of tasks starting
27903 at elaboration time and then immediately blocking on @code{accept} or
27904 @code{select} statements is very common. What this means is that
27905 the compiler is being too pessimistic when it analyzes the
27906 whole package body as though it might be executed at elaboration
27909 If we know that the elaboration code contains no entry calls, (a very safe
27910 assumption most of the time, that could almost be made the default
27911 behavior), then we can compile all units of the program under control
27912 of the following configuration pragma:
27915 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
27919 This pragma can be placed in the @file{gnat.adc} file in the usual
27920 manner. If we take our original unmodified program and compile it
27921 in the presence of a @file{gnat.adc} containing the above pragma,
27922 then once again, we can compile, bind, link, and execute, obtaining
27923 the expected result. In the presence of this pragma, the compiler does
27924 not trace calls in a task body, that appear after the first @code{accept}
27925 or @code{select} statement, and therefore does not report a potential
27926 circularity in the original program.
27928 The compiler will check to the extent it can that the above
27929 restriction is not violated, but it is not always possible to do a
27930 complete check at compile time, so it is important to use this
27931 pragma only if the stated restriction is in fact met, that is to say
27932 no task receives an entry call before elaboration of all units is completed.
27936 @node Mixing Elaboration Models
27937 @section Mixing Elaboration Models
27939 So far, we have assumed that the entire program is either compiled
27940 using the dynamic model or static model, ensuring consistency. It
27941 is possible to mix the two models, but rules have to be followed
27942 if this mixing is done to ensure that elaboration checks are not
27945 The basic rule is that @emph{a unit compiled with the static model cannot
27946 be @code{with'ed} by a unit compiled with the dynamic model}. The
27947 reason for this is that in the static model, a unit assumes that
27948 its clients guarantee to use (the equivalent of) pragma
27949 @code{Elaborate_All} so that no elaboration checks are required
27950 in inner subprograms, and this assumption is violated if the
27951 client is compiled with dynamic checks.
27953 The precise rule is as follows. A unit that is compiled with dynamic
27954 checks can only @code{with} a unit that meets at least one of the
27955 following criteria:
27960 The @code{with'ed} unit is itself compiled with dynamic elaboration
27961 checks (that is with the @option{-gnatE} switch.
27964 The @code{with'ed} unit is an internal GNAT implementation unit from
27965 the System, Interfaces, Ada, or GNAT hierarchies.
27968 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
27971 The @code{with'ing} unit (that is the client) has an explicit pragma
27972 @code{Elaborate_All} for the @code{with'ed} unit.
27977 If this rule is violated, that is if a unit with dynamic elaboration
27978 checks @code{with's} a unit that does not meet one of the above four
27979 criteria, then the binder (@code{gnatbind}) will issue a warning
27980 similar to that in the following example:
27983 warning: "x.ads" has dynamic elaboration checks and with's
27984 warning: "y.ads" which has static elaboration checks
27988 These warnings indicate that the rule has been violated, and that as a result
27989 elaboration checks may be missed in the resulting executable file.
27990 This warning may be suppressed using the @option{-ws} binder switch
27991 in the usual manner.
27993 One useful application of this mixing rule is in the case of a subsystem
27994 which does not itself @code{with} units from the remainder of the
27995 application. In this case, the entire subsystem can be compiled with
27996 dynamic checks to resolve a circularity in the subsystem, while
27997 allowing the main application that uses this subsystem to be compiled
27998 using the more reliable default static model.
28000 @node What to Do If the Default Elaboration Behavior Fails
28001 @section What to Do If the Default Elaboration Behavior Fails
28004 If the binder cannot find an acceptable order, it outputs detailed
28005 diagnostics. For example:
28011 error: elaboration circularity detected
28012 info: "proc (body)" must be elaborated before "pack (body)"
28013 info: reason: Elaborate_All probably needed in unit "pack (body)"
28014 info: recompile "pack (body)" with -gnatwl
28015 info: for full details
28016 info: "proc (body)"
28017 info: is needed by its spec:
28018 info: "proc (spec)"
28019 info: which is withed by:
28020 info: "pack (body)"
28021 info: "pack (body)" must be elaborated before "proc (body)"
28022 info: reason: pragma Elaborate in unit "proc (body)"
28028 In this case we have a cycle that the binder cannot break. On the one
28029 hand, there is an explicit pragma Elaborate in @code{proc} for
28030 @code{pack}. This means that the body of @code{pack} must be elaborated
28031 before the body of @code{proc}. On the other hand, there is elaboration
28032 code in @code{pack} that calls a subprogram in @code{proc}. This means
28033 that for maximum safety, there should really be a pragma
28034 Elaborate_All in @code{pack} for @code{proc} which would require that
28035 the body of @code{proc} be elaborated before the body of
28036 @code{pack}. Clearly both requirements cannot be satisfied.
28037 Faced with a circularity of this kind, you have three different options.
28040 @item Fix the program
28041 The most desirable option from the point of view of long-term maintenance
28042 is to rearrange the program so that the elaboration problems are avoided.
28043 One useful technique is to place the elaboration code into separate
28044 child packages. Another is to move some of the initialization code to
28045 explicitly called subprograms, where the program controls the order
28046 of initialization explicitly. Although this is the most desirable option,
28047 it may be impractical and involve too much modification, especially in
28048 the case of complex legacy code.
28050 @item Perform dynamic checks
28051 If the compilations are done using the
28053 (dynamic elaboration check) switch, then GNAT behaves in a quite different
28054 manner. Dynamic checks are generated for all calls that could possibly result
28055 in raising an exception. With this switch, the compiler does not generate
28056 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
28057 exactly as specified in the @cite{Ada Reference Manual}.
28058 The binder will generate
28059 an executable program that may or may not raise @code{Program_Error}, and then
28060 it is the programmer's job to ensure that it does not raise an exception. Note
28061 that it is important to compile all units with the switch, it cannot be used
28064 @item Suppress checks
28065 The drawback of dynamic checks is that they generate a
28066 significant overhead at run time, both in space and time. If you
28067 are absolutely sure that your program cannot raise any elaboration
28068 exceptions, and you still want to use the dynamic elaboration model,
28069 then you can use the configuration pragma
28070 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
28071 example this pragma could be placed in the @file{gnat.adc} file.
28073 @item Suppress checks selectively
28074 When you know that certain calls or instantiations in elaboration code cannot
28075 possibly lead to an elaboration error, and the binder nevertheless complains
28076 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
28077 elaboration circularities, it is possible to remove those warnings locally and
28078 obtain a program that will bind. Clearly this can be unsafe, and it is the
28079 responsibility of the programmer to make sure that the resulting program has no
28080 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
28081 used with different granularity to suppress warnings and break elaboration
28086 Place the pragma that names the called subprogram in the declarative part
28087 that contains the call.
28090 Place the pragma in the declarative part, without naming an entity. This
28091 disables warnings on all calls in the corresponding declarative region.
28094 Place the pragma in the package spec that declares the called subprogram,
28095 and name the subprogram. This disables warnings on all elaboration calls to
28099 Place the pragma in the package spec that declares the called subprogram,
28100 without naming any entity. This disables warnings on all elaboration calls to
28101 all subprograms declared in this spec.
28103 @item Use Pragma Elaborate
28104 As previously described in section @xref{Treatment of Pragma Elaborate},
28105 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
28106 that no elaboration checks are required on calls to the designated unit.
28107 There may be cases in which the caller knows that no transitive calls
28108 can occur, so that a @code{pragma Elaborate} will be sufficient in a
28109 case where @code{pragma Elaborate_All} would cause a circularity.
28113 These five cases are listed in order of decreasing safety, and therefore
28114 require increasing programmer care in their application. Consider the
28117 @smallexample @c adanocomment
28119 function F1 return Integer;
28124 function F2 return Integer;
28125 function Pure (x : integer) return integer;
28126 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
28127 -- pragma Suppress (Elaboration_Check); -- (4)
28131 package body Pack1 is
28132 function F1 return Integer is
28136 Val : integer := Pack2.Pure (11); -- Elab. call (1)
28139 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
28140 -- pragma Suppress(Elaboration_Check); -- (2)
28142 X1 := Pack2.F2 + 1; -- Elab. call (2)
28147 package body Pack2 is
28148 function F2 return Integer is
28152 function Pure (x : integer) return integer is
28154 return x ** 3 - 3 * x;
28158 with Pack1, Ada.Text_IO;
28161 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
28164 In the absence of any pragmas, an attempt to bind this program produces
28165 the following diagnostics:
28171 error: elaboration circularity detected
28172 info: "pack1 (body)" must be elaborated before "pack1 (body)"
28173 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
28174 info: recompile "pack1 (body)" with -gnatwl for full details
28175 info: "pack1 (body)"
28176 info: must be elaborated along with its spec:
28177 info: "pack1 (spec)"
28178 info: which is withed by:
28179 info: "pack2 (body)"
28180 info: which must be elaborated along with its spec:
28181 info: "pack2 (spec)"
28182 info: which is withed by:
28183 info: "pack1 (body)"
28186 The sources of the circularity are the two calls to @code{Pack2.Pure} and
28187 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
28188 F2 is safe, even though F2 calls F1, because the call appears after the
28189 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
28190 remove the warning on the call. It is also possible to use pragma (2)
28191 because there are no other potentially unsafe calls in the block.
28194 The call to @code{Pure} is safe because this function does not depend on the
28195 state of @code{Pack2}. Therefore any call to this function is safe, and it
28196 is correct to place pragma (3) in the corresponding package spec.
28199 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
28200 warnings on all calls to functions declared therein. Note that this is not
28201 necessarily safe, and requires more detailed examination of the subprogram
28202 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
28203 be already elaborated.
28207 It is hard to generalize on which of these four approaches should be
28208 taken. Obviously if it is possible to fix the program so that the default
28209 treatment works, this is preferable, but this may not always be practical.
28210 It is certainly simple enough to use
28212 but the danger in this case is that, even if the GNAT binder
28213 finds a correct elaboration order, it may not always do so,
28214 and certainly a binder from another Ada compiler might not. A
28215 combination of testing and analysis (for which the warnings generated
28218 switch can be useful) must be used to ensure that the program is free
28219 of errors. One switch that is useful in this testing is the
28220 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
28223 Normally the binder tries to find an order that has the best chance
28224 of avoiding elaboration problems. However, if this switch is used, the binder
28225 plays a devil's advocate role, and tries to choose the order that
28226 has the best chance of failing. If your program works even with this
28227 switch, then it has a better chance of being error free, but this is still
28230 For an example of this approach in action, consider the C-tests (executable
28231 tests) from the ACVC suite. If these are compiled and run with the default
28232 treatment, then all but one of them succeed without generating any error
28233 diagnostics from the binder. However, there is one test that fails, and
28234 this is not surprising, because the whole point of this test is to ensure
28235 that the compiler can handle cases where it is impossible to determine
28236 a correct order statically, and it checks that an exception is indeed
28237 raised at run time.
28239 This one test must be compiled and run using the
28241 switch, and then it passes. Alternatively, the entire suite can
28242 be run using this switch. It is never wrong to run with the dynamic
28243 elaboration switch if your code is correct, and we assume that the
28244 C-tests are indeed correct (it is less efficient, but efficiency is
28245 not a factor in running the ACVC tests.)
28247 @node Elaboration for Access-to-Subprogram Values
28248 @section Elaboration for Access-to-Subprogram Values
28249 @cindex Access-to-subprogram
28252 Access-to-subprogram types (introduced in Ada 95) complicate
28253 the handling of elaboration. The trouble is that it becomes
28254 impossible to tell at compile time which procedure
28255 is being called. This means that it is not possible for the binder
28256 to analyze the elaboration requirements in this case.
28258 If at the point at which the access value is created
28259 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
28260 the body of the subprogram is
28261 known to have been elaborated, then the access value is safe, and its use
28262 does not require a check. This may be achieved by appropriate arrangement
28263 of the order of declarations if the subprogram is in the current unit,
28264 or, if the subprogram is in another unit, by using pragma
28265 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
28266 on the referenced unit.
28268 If the referenced body is not known to have been elaborated at the point
28269 the access value is created, then any use of the access value must do a
28270 dynamic check, and this dynamic check will fail and raise a
28271 @code{Program_Error} exception if the body has not been elaborated yet.
28272 GNAT will generate the necessary checks, and in addition, if the
28274 switch is set, will generate warnings that such checks are required.
28276 The use of dynamic dispatching for tagged types similarly generates
28277 a requirement for dynamic checks, and premature calls to any primitive
28278 operation of a tagged type before the body of the operation has been
28279 elaborated, will result in the raising of @code{Program_Error}.
28281 @node Summary of Procedures for Elaboration Control
28282 @section Summary of Procedures for Elaboration Control
28283 @cindex Elaboration control
28286 First, compile your program with the default options, using none of
28287 the special elaboration control switches. If the binder successfully
28288 binds your program, then you can be confident that, apart from issues
28289 raised by the use of access-to-subprogram types and dynamic dispatching,
28290 the program is free of elaboration errors. If it is important that the
28291 program be portable, then use the
28293 switch to generate warnings about missing @code{Elaborate} or
28294 @code{Elaborate_All} pragmas, and supply the missing pragmas.
28296 If the program fails to bind using the default static elaboration
28297 handling, then you can fix the program to eliminate the binder
28298 message, or recompile the entire program with the
28299 @option{-gnatE} switch to generate dynamic elaboration checks,
28300 and, if you are sure there really are no elaboration problems,
28301 use a global pragma @code{Suppress (Elaboration_Check)}.
28303 @node Other Elaboration Order Considerations
28304 @section Other Elaboration Order Considerations
28306 This section has been entirely concerned with the issue of finding a valid
28307 elaboration order, as defined by the Ada Reference Manual. In a case
28308 where several elaboration orders are valid, the task is to find one
28309 of the possible valid elaboration orders (and the static model in GNAT
28310 will ensure that this is achieved).
28312 The purpose of the elaboration rules in the Ada Reference Manual is to
28313 make sure that no entity is accessed before it has been elaborated. For
28314 a subprogram, this means that the spec and body must have been elaborated
28315 before the subprogram is called. For an object, this means that the object
28316 must have been elaborated before its value is read or written. A violation
28317 of either of these two requirements is an access before elaboration order,
28318 and this section has been all about avoiding such errors.
28320 In the case where more than one order of elaboration is possible, in the
28321 sense that access before elaboration errors are avoided, then any one of
28322 the orders is ``correct'' in the sense that it meets the requirements of
28323 the Ada Reference Manual, and no such error occurs.
28325 However, it may be the case for a given program, that there are
28326 constraints on the order of elaboration that come not from consideration
28327 of avoiding elaboration errors, but rather from extra-lingual logic
28328 requirements. Consider this example:
28330 @smallexample @c ada
28331 with Init_Constants;
28332 package Constants is
28337 package Init_Constants is
28338 procedure P; -- require a body
28339 end Init_Constants;
28342 package body Init_Constants is
28343 procedure P is begin null; end;
28347 end Init_Constants;
28351 Z : Integer := Constants.X + Constants.Y;
28355 with Text_IO; use Text_IO;
28358 Put_Line (Calc.Z'Img);
28363 In this example, there is more than one valid order of elaboration. For
28364 example both the following are correct orders:
28367 Init_Constants spec
28370 Init_Constants body
28375 Init_Constants spec
28376 Init_Constants body
28383 There is no language rule to prefer one or the other, both are correct
28384 from an order of elaboration point of view. But the programmatic effects
28385 of the two orders are very different. In the first, the elaboration routine
28386 of @code{Calc} initializes @code{Z} to zero, and then the main program
28387 runs with this value of zero. But in the second order, the elaboration
28388 routine of @code{Calc} runs after the body of Init_Constants has set
28389 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
28392 One could perhaps by applying pretty clever non-artificial intelligence
28393 to the situation guess that it is more likely that the second order of
28394 elaboration is the one desired, but there is no formal linguistic reason
28395 to prefer one over the other. In fact in this particular case, GNAT will
28396 prefer the second order, because of the rule that bodies are elaborated
28397 as soon as possible, but it's just luck that this is what was wanted
28398 (if indeed the second order was preferred).
28400 If the program cares about the order of elaboration routines in a case like
28401 this, it is important to specify the order required. In this particular
28402 case, that could have been achieved by adding to the spec of Calc:
28404 @smallexample @c ada
28405 pragma Elaborate_All (Constants);
28409 which requires that the body (if any) and spec of @code{Constants},
28410 as well as the body and spec of any unit @code{with}'ed by
28411 @code{Constants} be elaborated before @code{Calc} is elaborated.
28413 Clearly no automatic method can always guess which alternative you require,
28414 and if you are working with legacy code that had constraints of this kind
28415 which were not properly specified by adding @code{Elaborate} or
28416 @code{Elaborate_All} pragmas, then indeed it is possible that two different
28417 compilers can choose different orders.
28419 However, GNAT does attempt to diagnose the common situation where there
28420 are uninitialized variables in the visible part of a package spec, and the
28421 corresponding package body has an elaboration block that directly or
28422 indirectly initialized one or more of these variables. This is the situation
28423 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
28424 a warning that suggests this addition if it detects this situation.
28426 The @code{gnatbind}
28427 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
28428 out problems. This switch causes bodies to be elaborated as late as possible
28429 instead of as early as possible. In the example above, it would have forced
28430 the choice of the first elaboration order. If you get different results
28431 when using this switch, and particularly if one set of results is right,
28432 and one is wrong as far as you are concerned, it shows that you have some
28433 missing @code{Elaborate} pragmas. For the example above, we have the
28437 gnatmake -f -q main
28440 gnatmake -f -q main -bargs -p
28446 It is of course quite unlikely that both these results are correct, so
28447 it is up to you in a case like this to investigate the source of the
28448 difference, by looking at the two elaboration orders that are chosen,
28449 and figuring out which is correct, and then adding the necessary
28450 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
28454 @c *******************************
28455 @node Conditional Compilation
28456 @appendix Conditional Compilation
28457 @c *******************************
28458 @cindex Conditional compilation
28461 It is often necessary to arrange for a single source program
28462 to serve multiple purposes, where it is compiled in different
28463 ways to achieve these different goals. Some examples of the
28464 need for this feature are
28467 @item Adapting a program to a different hardware environment
28468 @item Adapting a program to a different target architecture
28469 @item Turning debugging features on and off
28470 @item Arranging for a program to compile with different compilers
28474 In C, or C++, the typical approach would be to use the preprocessor
28475 that is defined as part of the language. The Ada language does not
28476 contain such a feature. This is not an oversight, but rather a very
28477 deliberate design decision, based on the experience that overuse of
28478 the preprocessing features in C and C++ can result in programs that
28479 are extremely difficult to maintain. For example, if we have ten
28480 switches that can be on or off, this means that there are a thousand
28481 separate programs, any one of which might not even be syntactically
28482 correct, and even if syntactically correct, the resulting program
28483 might not work correctly. Testing all combinations can quickly become
28486 Nevertheless, the need to tailor programs certainly exists, and in
28487 this Appendix we will discuss how this can
28488 be achieved using Ada in general, and GNAT in particular.
28491 * Use of Boolean Constants::
28492 * Debugging - A Special Case::
28493 * Conditionalizing Declarations::
28494 * Use of Alternative Implementations::
28498 @node Use of Boolean Constants
28499 @section Use of Boolean Constants
28502 In the case where the difference is simply which code
28503 sequence is executed, the cleanest solution is to use Boolean
28504 constants to control which code is executed.
28506 @smallexample @c ada
28508 FP_Initialize_Required : constant Boolean := True;
28510 if FP_Initialize_Required then
28517 Not only will the code inside the @code{if} statement not be executed if
28518 the constant Boolean is @code{False}, but it will also be completely
28519 deleted from the program.
28520 However, the code is only deleted after the @code{if} statement
28521 has been checked for syntactic and semantic correctness.
28522 (In contrast, with preprocessors the code is deleted before the
28523 compiler ever gets to see it, so it is not checked until the switch
28525 @cindex Preprocessors (contrasted with conditional compilation)
28527 Typically the Boolean constants will be in a separate package,
28530 @smallexample @c ada
28533 FP_Initialize_Required : constant Boolean := True;
28534 Reset_Available : constant Boolean := False;
28541 The @code{Config} package exists in multiple forms for the various targets,
28542 with an appropriate script selecting the version of @code{Config} needed.
28543 Then any other unit requiring conditional compilation can do a @code{with}
28544 of @code{Config} to make the constants visible.
28547 @node Debugging - A Special Case
28548 @section Debugging - A Special Case
28551 A common use of conditional code is to execute statements (for example
28552 dynamic checks, or output of intermediate results) under control of a
28553 debug switch, so that the debugging behavior can be turned on and off.
28554 This can be done using a Boolean constant to control whether the code
28557 @smallexample @c ada
28560 Put_Line ("got to the first stage!");
28568 @smallexample @c ada
28570 if Debugging and then Temperature > 999.0 then
28571 raise Temperature_Crazy;
28577 Since this is a common case, there are special features to deal with
28578 this in a convenient manner. For the case of tests, Ada 2005 has added
28579 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
28580 @cindex pragma @code{Assert}
28581 on the @code{Assert} pragma that has always been available in GNAT, so this
28582 feature may be used with GNAT even if you are not using Ada 2005 features.
28583 The use of pragma @code{Assert} is described in
28584 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
28585 example, the last test could be written:
28587 @smallexample @c ada
28588 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
28594 @smallexample @c ada
28595 pragma Assert (Temperature <= 999.0);
28599 In both cases, if assertions are active and the temperature is excessive,
28600 the exception @code{Assert_Failure} will be raised, with the given string in
28601 the first case or a string indicating the location of the pragma in the second
28602 case used as the exception message.
28604 You can turn assertions on and off by using the @code{Assertion_Policy}
28606 @cindex pragma @code{Assertion_Policy}
28607 This is an Ada 2005 pragma which is implemented in all modes by
28608 GNAT, but only in the latest versions of GNAT which include Ada 2005
28609 capability. Alternatively, you can use the @option{-gnata} switch
28610 @cindex @option{-gnata} switch
28611 to enable assertions from the command line (this is recognized by all versions
28614 For the example above with the @code{Put_Line}, the GNAT-specific pragma
28615 @code{Debug} can be used:
28616 @cindex pragma @code{Debug}
28618 @smallexample @c ada
28619 pragma Debug (Put_Line ("got to the first stage!"));
28623 If debug pragmas are enabled, the argument, which must be of the form of
28624 a procedure call, is executed (in this case, @code{Put_Line} will be called).
28625 Only one call can be present, but of course a special debugging procedure
28626 containing any code you like can be included in the program and then
28627 called in a pragma @code{Debug} argument as needed.
28629 One advantage of pragma @code{Debug} over the @code{if Debugging then}
28630 construct is that pragma @code{Debug} can appear in declarative contexts,
28631 such as at the very beginning of a procedure, before local declarations have
28634 Debug pragmas are enabled using either the @option{-gnata} switch that also
28635 controls assertions, or with a separate Debug_Policy pragma.
28636 @cindex pragma @code{Debug_Policy}
28637 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
28638 in Ada 95 and Ada 83 programs as well), and is analogous to
28639 pragma @code{Assertion_Policy} to control assertions.
28641 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
28642 and thus they can appear in @file{gnat.adc} if you are not using a
28643 project file, or in the file designated to contain configuration pragmas
28645 They then apply to all subsequent compilations. In practice the use of
28646 the @option{-gnata} switch is often the most convenient method of controlling
28647 the status of these pragmas.
28649 Note that a pragma is not a statement, so in contexts where a statement
28650 sequence is required, you can't just write a pragma on its own. You have
28651 to add a @code{null} statement.
28653 @smallexample @c ada
28656 @dots{} -- some statements
28658 pragma Assert (Num_Cases < 10);
28665 @node Conditionalizing Declarations
28666 @section Conditionalizing Declarations
28669 In some cases, it may be necessary to conditionalize declarations to meet
28670 different requirements. For example we might want a bit string whose length
28671 is set to meet some hardware message requirement.
28673 In some cases, it may be possible to do this using declare blocks controlled
28674 by conditional constants:
28676 @smallexample @c ada
28678 if Small_Machine then
28680 X : Bit_String (1 .. 10);
28686 X : Large_Bit_String (1 .. 1000);
28695 Note that in this approach, both declarations are analyzed by the
28696 compiler so this can only be used where both declarations are legal,
28697 even though one of them will not be used.
28699 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word}, or
28700 Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
28701 that are parameterized by these constants. For example
28703 @smallexample @c ada
28706 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
28712 If @code{Bits_Per_Word} is set to 32, this generates either
28714 @smallexample @c ada
28717 Field1 at 0 range 0 .. 32;
28723 for the big endian case, or
28725 @smallexample @c ada
28728 Field1 at 0 range 10 .. 32;
28734 for the little endian case. Since a powerful subset of Ada expression
28735 notation is usable for creating static constants, clever use of this
28736 feature can often solve quite difficult problems in conditionalizing
28737 compilation (note incidentally that in Ada 95, the little endian
28738 constant was introduced as @code{System.Default_Bit_Order}, so you do not
28739 need to define this one yourself).
28742 @node Use of Alternative Implementations
28743 @section Use of Alternative Implementations
28746 In some cases, none of the approaches described above are adequate. This
28747 can occur for example if the set of declarations required is radically
28748 different for two different configurations.
28750 In this situation, the official Ada way of dealing with conditionalizing
28751 such code is to write separate units for the different cases. As long as
28752 this does not result in excessive duplication of code, this can be done
28753 without creating maintenance problems. The approach is to share common
28754 code as far as possible, and then isolate the code and declarations
28755 that are different. Subunits are often a convenient method for breaking
28756 out a piece of a unit that is to be conditionalized, with separate files
28757 for different versions of the subunit for different targets, where the
28758 build script selects the right one to give to the compiler.
28759 @cindex Subunits (and conditional compilation)
28761 As an example, consider a situation where a new feature in Ada 2005
28762 allows something to be done in a really nice way. But your code must be able
28763 to compile with an Ada 95 compiler. Conceptually you want to say:
28765 @smallexample @c ada
28768 @dots{} neat Ada 2005 code
28770 @dots{} not quite as neat Ada 95 code
28776 where @code{Ada_2005} is a Boolean constant.
28778 But this won't work when @code{Ada_2005} is set to @code{False},
28779 since the @code{then} clause will be illegal for an Ada 95 compiler.
28780 (Recall that although such unreachable code would eventually be deleted
28781 by the compiler, it still needs to be legal. If it uses features
28782 introduced in Ada 2005, it will be illegal in Ada 95.)
28784 So instead we write
28786 @smallexample @c ada
28787 procedure Insert is separate;
28791 Then we have two files for the subunit @code{Insert}, with the two sets of
28793 If the package containing this is called @code{File_Queries}, then we might
28797 @item @file{file_queries-insert-2005.adb}
28798 @item @file{file_queries-insert-95.adb}
28802 and the build script renames the appropriate file to
28805 file_queries-insert.adb
28809 and then carries out the compilation.
28811 This can also be done with project files' naming schemes. For example:
28813 @smallexample @c project
28814 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
28818 Note also that with project files it is desirable to use a different extension
28819 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
28820 conflict may arise through another commonly used feature: to declare as part
28821 of the project a set of directories containing all the sources obeying the
28822 default naming scheme.
28824 The use of alternative units is certainly feasible in all situations,
28825 and for example the Ada part of the GNAT run-time is conditionalized
28826 based on the target architecture using this approach. As a specific example,
28827 consider the implementation of the AST feature in VMS. There is one
28835 which is the same for all architectures, and three bodies:
28839 used for all non-VMS operating systems
28840 @item s-asthan-vms-alpha.adb
28841 used for VMS on the Alpha
28842 @item s-asthan-vms-ia64.adb
28843 used for VMS on the ia64
28847 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
28848 this operating system feature is not available, and the two remaining
28849 versions interface with the corresponding versions of VMS to provide
28850 VMS-compatible AST handling. The GNAT build script knows the architecture
28851 and operating system, and automatically selects the right version,
28852 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
28854 Another style for arranging alternative implementations is through Ada's
28855 access-to-subprogram facility.
28856 In case some functionality is to be conditionally included,
28857 you can declare an access-to-procedure variable @code{Ref} that is initialized
28858 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
28860 In some library package, set @code{Ref} to @code{Proc'Access} for some
28861 procedure @code{Proc} that performs the relevant processing.
28862 The initialization only occurs if the library package is included in the
28864 The same idea can also be implemented using tagged types and dispatching
28868 @node Preprocessing
28869 @section Preprocessing
28870 @cindex Preprocessing
28873 Although it is quite possible to conditionalize code without the use of
28874 C-style preprocessing, as described earlier in this section, it is
28875 nevertheless convenient in some cases to use the C approach. Moreover,
28876 older Ada compilers have often provided some preprocessing capability,
28877 so legacy code may depend on this approach, even though it is not
28880 To accommodate such use, GNAT provides a preprocessor (modeled to a large
28881 extent on the various preprocessors that have been used
28882 with legacy code on other compilers, to enable easier transition).
28884 The preprocessor may be used in two separate modes. It can be used quite
28885 separately from the compiler, to generate a separate output source file
28886 that is then fed to the compiler as a separate step. This is the
28887 @code{gnatprep} utility, whose use is fully described in
28888 @ref{Preprocessing Using gnatprep}.
28889 @cindex @code{gnatprep}
28891 The preprocessing language allows such constructs as
28895 #if DEBUG or PRIORITY > 4 then
28896 bunch of declarations
28898 completely different bunch of declarations
28904 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
28905 defined either on the command line or in a separate file.
28907 The other way of running the preprocessor is even closer to the C style and
28908 often more convenient. In this approach the preprocessing is integrated into
28909 the compilation process. The compiler is fed the preprocessor input which
28910 includes @code{#if} lines etc, and then the compiler carries out the
28911 preprocessing internally and processes the resulting output.
28912 For more details on this approach, see @ref{Integrated Preprocessing}.
28915 @c *******************************
28916 @node Inline Assembler
28917 @appendix Inline Assembler
28918 @c *******************************
28921 If you need to write low-level software that interacts directly
28922 with the hardware, Ada provides two ways to incorporate assembly
28923 language code into your program. First, you can import and invoke
28924 external routines written in assembly language, an Ada feature fully
28925 supported by GNAT@. However, for small sections of code it may be simpler
28926 or more efficient to include assembly language statements directly
28927 in your Ada source program, using the facilities of the implementation-defined
28928 package @code{System.Machine_Code}, which incorporates the gcc
28929 Inline Assembler. The Inline Assembler approach offers a number of advantages,
28930 including the following:
28933 @item No need to use non-Ada tools
28934 @item Consistent interface over different targets
28935 @item Automatic usage of the proper calling conventions
28936 @item Access to Ada constants and variables
28937 @item Definition of intrinsic routines
28938 @item Possibility of inlining a subprogram comprising assembler code
28939 @item Code optimizer can take Inline Assembler code into account
28942 This chapter presents a series of examples to show you how to use
28943 the Inline Assembler. Although it focuses on the Intel x86,
28944 the general approach applies also to other processors.
28945 It is assumed that you are familiar with Ada
28946 and with assembly language programming.
28949 * Basic Assembler Syntax::
28950 * A Simple Example of Inline Assembler::
28951 * Output Variables in Inline Assembler::
28952 * Input Variables in Inline Assembler::
28953 * Inlining Inline Assembler Code::
28954 * Other Asm Functionality::
28957 @c ---------------------------------------------------------------------------
28958 @node Basic Assembler Syntax
28959 @section Basic Assembler Syntax
28962 The assembler used by GNAT and gcc is based not on the Intel assembly
28963 language, but rather on a language that descends from the AT&T Unix
28964 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
28965 The following table summarizes the main features of @emph{as} syntax
28966 and points out the differences from the Intel conventions.
28967 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
28968 pre-processor) documentation for further information.
28971 @item Register names
28972 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
28974 Intel: No extra punctuation; for example @code{eax}
28976 @item Immediate operand
28977 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
28979 Intel: No extra punctuation; for example @code{4}
28982 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
28984 Intel: No extra punctuation; for example @code{loc}
28986 @item Memory contents
28987 gcc / @emph{as}: No extra punctuation; for example @code{loc}
28989 Intel: Square brackets; for example @code{[loc]}
28991 @item Register contents
28992 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
28994 Intel: Square brackets; for example @code{[eax]}
28996 @item Hexadecimal numbers
28997 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
28999 Intel: Trailing ``h''; for example @code{A0h}
29002 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
29005 Intel: Implicit, deduced by assembler; for example @code{mov}
29007 @item Instruction repetition
29008 gcc / @emph{as}: Split into two lines; for example
29014 Intel: Keep on one line; for example @code{rep stosl}
29016 @item Order of operands
29017 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
29019 Intel: Destination first; for example @code{mov eax, 4}
29022 @c ---------------------------------------------------------------------------
29023 @node A Simple Example of Inline Assembler
29024 @section A Simple Example of Inline Assembler
29027 The following example will generate a single assembly language statement,
29028 @code{nop}, which does nothing. Despite its lack of run-time effect,
29029 the example will be useful in illustrating the basics of
29030 the Inline Assembler facility.
29032 @smallexample @c ada
29034 with System.Machine_Code; use System.Machine_Code;
29035 procedure Nothing is
29042 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
29043 here it takes one parameter, a @emph{template string} that must be a static
29044 expression and that will form the generated instruction.
29045 @code{Asm} may be regarded as a compile-time procedure that parses
29046 the template string and additional parameters (none here),
29047 from which it generates a sequence of assembly language instructions.
29049 The examples in this chapter will illustrate several of the forms
29050 for invoking @code{Asm}; a complete specification of the syntax
29051 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
29054 Under the standard GNAT conventions, the @code{Nothing} procedure
29055 should be in a file named @file{nothing.adb}.
29056 You can build the executable in the usual way:
29060 However, the interesting aspect of this example is not its run-time behavior
29061 but rather the generated assembly code.
29062 To see this output, invoke the compiler as follows:
29064 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
29066 where the options are:
29070 compile only (no bind or link)
29072 generate assembler listing
29073 @item -fomit-frame-pointer
29074 do not set up separate stack frames
29076 do not add runtime checks
29079 This gives a human-readable assembler version of the code. The resulting
29080 file will have the same name as the Ada source file, but with a @code{.s}
29081 extension. In our example, the file @file{nothing.s} has the following
29086 .file "nothing.adb"
29088 ___gnu_compiled_ada:
29091 .globl __ada_nothing
29103 The assembly code you included is clearly indicated by
29104 the compiler, between the @code{#APP} and @code{#NO_APP}
29105 delimiters. The character before the 'APP' and 'NOAPP'
29106 can differ on different targets. For example, GNU/Linux uses '#APP' while
29107 on NT you will see '/APP'.
29109 If you make a mistake in your assembler code (such as using the
29110 wrong size modifier, or using a wrong operand for the instruction) GNAT
29111 will report this error in a temporary file, which will be deleted when
29112 the compilation is finished. Generating an assembler file will help
29113 in such cases, since you can assemble this file separately using the
29114 @emph{as} assembler that comes with gcc.
29116 Assembling the file using the command
29119 as @file{nothing.s}
29122 will give you error messages whose lines correspond to the assembler
29123 input file, so you can easily find and correct any mistakes you made.
29124 If there are no errors, @emph{as} will generate an object file
29125 @file{nothing.out}.
29127 @c ---------------------------------------------------------------------------
29128 @node Output Variables in Inline Assembler
29129 @section Output Variables in Inline Assembler
29132 The examples in this section, showing how to access the processor flags,
29133 illustrate how to specify the destination operands for assembly language
29136 @smallexample @c ada
29138 with Interfaces; use Interfaces;
29139 with Ada.Text_IO; use Ada.Text_IO;
29140 with System.Machine_Code; use System.Machine_Code;
29141 procedure Get_Flags is
29142 Flags : Unsigned_32;
29145 Asm ("pushfl" & LF & HT & -- push flags on stack
29146 "popl %%eax" & LF & HT & -- load eax with flags
29147 "movl %%eax, %0", -- store flags in variable
29148 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29149 Put_Line ("Flags register:" & Flags'Img);
29154 In order to have a nicely aligned assembly listing, we have separated
29155 multiple assembler statements in the Asm template string with linefeed
29156 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
29157 The resulting section of the assembly output file is:
29164 movl %eax, -40(%ebp)
29169 It would have been legal to write the Asm invocation as:
29172 Asm ("pushfl popl %%eax movl %%eax, %0")
29175 but in the generated assembler file, this would come out as:
29179 pushfl popl %eax movl %eax, -40(%ebp)
29183 which is not so convenient for the human reader.
29185 We use Ada comments
29186 at the end of each line to explain what the assembler instructions
29187 actually do. This is a useful convention.
29189 When writing Inline Assembler instructions, you need to precede each register
29190 and variable name with a percent sign. Since the assembler already requires
29191 a percent sign at the beginning of a register name, you need two consecutive
29192 percent signs for such names in the Asm template string, thus @code{%%eax}.
29193 In the generated assembly code, one of the percent signs will be stripped off.
29195 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
29196 variables: operands you later define using @code{Input} or @code{Output}
29197 parameters to @code{Asm}.
29198 An output variable is illustrated in
29199 the third statement in the Asm template string:
29203 The intent is to store the contents of the eax register in a variable that can
29204 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
29205 necessarily work, since the compiler might optimize by using a register
29206 to hold Flags, and the expansion of the @code{movl} instruction would not be
29207 aware of this optimization. The solution is not to store the result directly
29208 but rather to advise the compiler to choose the correct operand form;
29209 that is the purpose of the @code{%0} output variable.
29211 Information about the output variable is supplied in the @code{Outputs}
29212 parameter to @code{Asm}:
29214 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29217 The output is defined by the @code{Asm_Output} attribute of the target type;
29218 the general format is
29220 Type'Asm_Output (constraint_string, variable_name)
29223 The constraint string directs the compiler how
29224 to store/access the associated variable. In the example
29226 Unsigned_32'Asm_Output ("=m", Flags);
29228 the @code{"m"} (memory) constraint tells the compiler that the variable
29229 @code{Flags} should be stored in a memory variable, thus preventing
29230 the optimizer from keeping it in a register. In contrast,
29232 Unsigned_32'Asm_Output ("=r", Flags);
29234 uses the @code{"r"} (register) constraint, telling the compiler to
29235 store the variable in a register.
29237 If the constraint is preceded by the equal character (@strong{=}), it tells
29238 the compiler that the variable will be used to store data into it.
29240 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
29241 allowing the optimizer to choose whatever it deems best.
29243 There are a fairly large number of constraints, but the ones that are
29244 most useful (for the Intel x86 processor) are the following:
29250 global (i.e.@: can be stored anywhere)
29268 use one of eax, ebx, ecx or edx
29270 use one of eax, ebx, ecx, edx, esi or edi
29273 The full set of constraints is described in the gcc and @emph{as}
29274 documentation; note that it is possible to combine certain constraints
29275 in one constraint string.
29277 You specify the association of an output variable with an assembler operand
29278 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
29280 @smallexample @c ada
29282 Asm ("pushfl" & LF & HT & -- push flags on stack
29283 "popl %%eax" & LF & HT & -- load eax with flags
29284 "movl %%eax, %0", -- store flags in variable
29285 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29289 @code{%0} will be replaced in the expanded code by the appropriate operand,
29291 the compiler decided for the @code{Flags} variable.
29293 In general, you may have any number of output variables:
29296 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
29298 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
29299 of @code{Asm_Output} attributes
29303 @smallexample @c ada
29305 Asm ("movl %%eax, %0" & LF & HT &
29306 "movl %%ebx, %1" & LF & HT &
29308 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
29309 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
29310 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
29314 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
29315 in the Ada program.
29317 As a variation on the @code{Get_Flags} example, we can use the constraints
29318 string to direct the compiler to store the eax register into the @code{Flags}
29319 variable, instead of including the store instruction explicitly in the
29320 @code{Asm} template string:
29322 @smallexample @c ada
29324 with Interfaces; use Interfaces;
29325 with Ada.Text_IO; use Ada.Text_IO;
29326 with System.Machine_Code; use System.Machine_Code;
29327 procedure Get_Flags_2 is
29328 Flags : Unsigned_32;
29331 Asm ("pushfl" & LF & HT & -- push flags on stack
29332 "popl %%eax", -- save flags in eax
29333 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
29334 Put_Line ("Flags register:" & Flags'Img);
29340 The @code{"a"} constraint tells the compiler that the @code{Flags}
29341 variable will come from the eax register. Here is the resulting code:
29349 movl %eax,-40(%ebp)
29354 The compiler generated the store of eax into Flags after
29355 expanding the assembler code.
29357 Actually, there was no need to pop the flags into the eax register;
29358 more simply, we could just pop the flags directly into the program variable:
29360 @smallexample @c ada
29362 with Interfaces; use Interfaces;
29363 with Ada.Text_IO; use Ada.Text_IO;
29364 with System.Machine_Code; use System.Machine_Code;
29365 procedure Get_Flags_3 is
29366 Flags : Unsigned_32;
29369 Asm ("pushfl" & LF & HT & -- push flags on stack
29370 "pop %0", -- save flags in Flags
29371 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29372 Put_Line ("Flags register:" & Flags'Img);
29377 @c ---------------------------------------------------------------------------
29378 @node Input Variables in Inline Assembler
29379 @section Input Variables in Inline Assembler
29382 The example in this section illustrates how to specify the source operands
29383 for assembly language statements.
29384 The program simply increments its input value by 1:
29386 @smallexample @c ada
29388 with Interfaces; use Interfaces;
29389 with Ada.Text_IO; use Ada.Text_IO;
29390 with System.Machine_Code; use System.Machine_Code;
29391 procedure Increment is
29393 function Incr (Value : Unsigned_32) return Unsigned_32 is
29394 Result : Unsigned_32;
29397 Inputs => Unsigned_32'Asm_Input ("a", Value),
29398 Outputs => Unsigned_32'Asm_Output ("=a", Result));
29402 Value : Unsigned_32;
29406 Put_Line ("Value before is" & Value'Img);
29407 Value := Incr (Value);
29408 Put_Line ("Value after is" & Value'Img);
29413 The @code{Outputs} parameter to @code{Asm} specifies
29414 that the result will be in the eax register and that it is to be stored
29415 in the @code{Result} variable.
29417 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
29418 but with an @code{Asm_Input} attribute.
29419 The @code{"="} constraint, indicating an output value, is not present.
29421 You can have multiple input variables, in the same way that you can have more
29422 than one output variable.
29424 The parameter count (%0, %1) etc, now starts at the first input
29425 statement, and continues with the output statements.
29426 When both parameters use the same variable, the
29427 compiler will treat them as the same %n operand, which is the case here.
29429 Just as the @code{Outputs} parameter causes the register to be stored into the
29430 target variable after execution of the assembler statements, so does the
29431 @code{Inputs} parameter cause its variable to be loaded into the register
29432 before execution of the assembler statements.
29434 Thus the effect of the @code{Asm} invocation is:
29436 @item load the 32-bit value of @code{Value} into eax
29437 @item execute the @code{incl %eax} instruction
29438 @item store the contents of eax into the @code{Result} variable
29441 The resulting assembler file (with @option{-O2} optimization) contains:
29444 _increment__incr.1:
29457 @c ---------------------------------------------------------------------------
29458 @node Inlining Inline Assembler Code
29459 @section Inlining Inline Assembler Code
29462 For a short subprogram such as the @code{Incr} function in the previous
29463 section, the overhead of the call and return (creating / deleting the stack
29464 frame) can be significant, compared to the amount of code in the subprogram
29465 body. A solution is to apply Ada's @code{Inline} pragma to the subprogram,
29466 which directs the compiler to expand invocations of the subprogram at the
29467 point(s) of call, instead of setting up a stack frame for out-of-line calls.
29468 Here is the resulting program:
29470 @smallexample @c ada
29472 with Interfaces; use Interfaces;
29473 with Ada.Text_IO; use Ada.Text_IO;
29474 with System.Machine_Code; use System.Machine_Code;
29475 procedure Increment_2 is
29477 function Incr (Value : Unsigned_32) return Unsigned_32 is
29478 Result : Unsigned_32;
29481 Inputs => Unsigned_32'Asm_Input ("a", Value),
29482 Outputs => Unsigned_32'Asm_Output ("=a", Result));
29485 pragma Inline (Increment);
29487 Value : Unsigned_32;
29491 Put_Line ("Value before is" & Value'Img);
29492 Value := Increment (Value);
29493 Put_Line ("Value after is" & Value'Img);
29498 Compile the program with both optimization (@option{-O2}) and inlining
29499 (@option{-gnatn}) enabled.
29501 The @code{Incr} function is still compiled as usual, but at the
29502 point in @code{Increment} where our function used to be called:
29507 call _increment__incr.1
29512 the code for the function body directly appears:
29525 thus saving the overhead of stack frame setup and an out-of-line call.
29527 @c ---------------------------------------------------------------------------
29528 @node Other Asm Functionality
29529 @section Other @code{Asm} Functionality
29532 This section describes two important parameters to the @code{Asm}
29533 procedure: @code{Clobber}, which identifies register usage;
29534 and @code{Volatile}, which inhibits unwanted optimizations.
29537 * The Clobber Parameter::
29538 * The Volatile Parameter::
29541 @c ---------------------------------------------------------------------------
29542 @node The Clobber Parameter
29543 @subsection The @code{Clobber} Parameter
29546 One of the dangers of intermixing assembly language and a compiled language
29547 such as Ada is that the compiler needs to be aware of which registers are
29548 being used by the assembly code. In some cases, such as the earlier examples,
29549 the constraint string is sufficient to indicate register usage (e.g.,
29551 the eax register). But more generally, the compiler needs an explicit
29552 identification of the registers that are used by the Inline Assembly
29555 Using a register that the compiler doesn't know about
29556 could be a side effect of an instruction (like @code{mull}
29557 storing its result in both eax and edx).
29558 It can also arise from explicit register usage in your
29559 assembly code; for example:
29562 Asm ("movl %0, %%ebx" & LF & HT &
29564 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
29565 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
29569 where the compiler (since it does not analyze the @code{Asm} template string)
29570 does not know you are using the ebx register.
29572 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
29573 to identify the registers that will be used by your assembly code:
29577 Asm ("movl %0, %%ebx" & LF & HT &
29579 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
29580 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
29585 The Clobber parameter is a static string expression specifying the
29586 register(s) you are using. Note that register names are @emph{not} prefixed
29587 by a percent sign. Also, if more than one register is used then their names
29588 are separated by commas; e.g., @code{"eax, ebx"}
29590 The @code{Clobber} parameter has several additional uses:
29592 @item Use ``register'' name @code{cc} to indicate that flags might have changed
29593 @item Use ``register'' name @code{memory} if you changed a memory location
29596 @c ---------------------------------------------------------------------------
29597 @node The Volatile Parameter
29598 @subsection The @code{Volatile} Parameter
29599 @cindex Volatile parameter
29602 Compiler optimizations in the presence of Inline Assembler may sometimes have
29603 unwanted effects. For example, when an @code{Asm} invocation with an input
29604 variable is inside a loop, the compiler might move the loading of the input
29605 variable outside the loop, regarding it as a one-time initialization.
29607 If this effect is not desired, you can disable such optimizations by setting
29608 the @code{Volatile} parameter to @code{True}; for example:
29610 @smallexample @c ada
29612 Asm ("movl %0, %%ebx" & LF & HT &
29614 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
29615 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
29621 By default, @code{Volatile} is set to @code{False} unless there is no
29622 @code{Outputs} parameter.
29624 Although setting @code{Volatile} to @code{True} prevents unwanted
29625 optimizations, it will also disable other optimizations that might be
29626 important for efficiency. In general, you should set @code{Volatile}
29627 to @code{True} only if the compiler's optimizations have created
29629 @c END OF INLINE ASSEMBLER CHAPTER
29630 @c ===============================
29632 @c ***********************************
29633 @c * Compatibility and Porting Guide *
29634 @c ***********************************
29635 @node Compatibility and Porting Guide
29636 @appendix Compatibility and Porting Guide
29639 This chapter describes the compatibility issues that may arise between
29640 GNAT and other Ada compilation systems (including those for Ada 83),
29641 and shows how GNAT can expedite porting
29642 applications developed in other Ada environments.
29645 * Compatibility with Ada 83::
29646 * Compatibility between Ada 95 and Ada 2005::
29647 * Implementation-dependent characteristics::
29648 * Compatibility with Other Ada Systems::
29649 * Representation Clauses::
29651 @c Brief section is only in non-VMS version
29652 @c Full chapter is in VMS version
29653 * Compatibility with HP Ada 83::
29656 * Transitioning to 64-Bit GNAT for OpenVMS::
29660 @node Compatibility with Ada 83
29661 @section Compatibility with Ada 83
29662 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
29665 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83. In
29666 particular, the design intention was that the difficulties associated
29667 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
29668 that occur when moving from one Ada 83 system to another.
29670 However, there are a number of points at which there are minor
29671 incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains
29672 full details of these issues,
29673 and should be consulted for a complete treatment.
29675 following subsections treat the most likely issues to be encountered.
29678 * Legal Ada 83 programs that are illegal in Ada 95::
29679 * More deterministic semantics::
29680 * Changed semantics::
29681 * Other language compatibility issues::
29684 @node Legal Ada 83 programs that are illegal in Ada 95
29685 @subsection Legal Ada 83 programs that are illegal in Ada 95
29687 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
29688 Ada 95 and thus also in Ada 2005:
29691 @item Character literals
29692 Some uses of character literals are ambiguous. Since Ada 95 has introduced
29693 @code{Wide_Character} as a new predefined character type, some uses of
29694 character literals that were legal in Ada 83 are illegal in Ada 95.
29696 @smallexample @c ada
29697 for Char in 'A' .. 'Z' loop @dots{} end loop;
29701 The problem is that @code{'A'} and @code{'Z'} could be from either
29702 @code{Character} or @code{Wide_Character}. The simplest correction
29703 is to make the type explicit; e.g.:
29704 @smallexample @c ada
29705 for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
29708 @item New reserved words
29709 The identifiers @code{abstract}, @code{aliased}, @code{protected},
29710 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
29711 Existing Ada 83 code using any of these identifiers must be edited to
29712 use some alternative name.
29714 @item Freezing rules
29715 The rules in Ada 95 are slightly different with regard to the point at
29716 which entities are frozen, and representation pragmas and clauses are
29717 not permitted past the freeze point. This shows up most typically in
29718 the form of an error message complaining that a representation item
29719 appears too late, and the appropriate corrective action is to move
29720 the item nearer to the declaration of the entity to which it refers.
29722 A particular case is that representation pragmas
29725 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
29727 cannot be applied to a subprogram body. If necessary, a separate subprogram
29728 declaration must be introduced to which the pragma can be applied.
29730 @item Optional bodies for library packages
29731 In Ada 83, a package that did not require a package body was nevertheless
29732 allowed to have one. This lead to certain surprises in compiling large
29733 systems (situations in which the body could be unexpectedly ignored by the
29734 binder). In Ada 95, if a package does not require a body then it is not
29735 permitted to have a body. To fix this problem, simply remove a redundant
29736 body if it is empty, or, if it is non-empty, introduce a dummy declaration
29737 into the spec that makes the body required. One approach is to add a private
29738 part to the package declaration (if necessary), and define a parameterless
29739 procedure called @code{Requires_Body}, which must then be given a dummy
29740 procedure body in the package body, which then becomes required.
29741 Another approach (assuming that this does not introduce elaboration
29742 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
29743 since one effect of this pragma is to require the presence of a package body.
29745 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
29746 In Ada 95, the exception @code{Numeric_Error} is a renaming of
29747 @code{Constraint_Error}.
29748 This means that it is illegal to have separate exception handlers for
29749 the two exceptions. The fix is simply to remove the handler for the
29750 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
29751 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
29753 @item Indefinite subtypes in generics
29754 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
29755 as the actual for a generic formal private type, but then the instantiation
29756 would be illegal if there were any instances of declarations of variables
29757 of this type in the generic body. In Ada 95, to avoid this clear violation
29758 of the methodological principle known as the ``contract model'',
29759 the generic declaration explicitly indicates whether
29760 or not such instantiations are permitted. If a generic formal parameter
29761 has explicit unknown discriminants, indicated by using @code{(<>)} after the
29762 type name, then it can be instantiated with indefinite types, but no
29763 stand-alone variables can be declared of this type. Any attempt to declare
29764 such a variable will result in an illegality at the time the generic is
29765 declared. If the @code{(<>)} notation is not used, then it is illegal
29766 to instantiate the generic with an indefinite type.
29767 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
29768 It will show up as a compile time error, and
29769 the fix is usually simply to add the @code{(<>)} to the generic declaration.
29772 @node More deterministic semantics
29773 @subsection More deterministic semantics
29777 Conversions from real types to integer types round away from 0. In Ada 83
29778 the conversion Integer(2.5) could deliver either 2 or 3 as its value. This
29779 implementation freedom was intended to support unbiased rounding in
29780 statistical applications, but in practice it interfered with portability.
29781 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
29782 is required. Numeric code may be affected by this change in semantics.
29783 Note, though, that this issue is no worse than already existed in Ada 83
29784 when porting code from one vendor to another.
29787 The Real-Time Annex introduces a set of policies that define the behavior of
29788 features that were implementation dependent in Ada 83, such as the order in
29789 which open select branches are executed.
29792 @node Changed semantics
29793 @subsection Changed semantics
29796 The worst kind of incompatibility is one where a program that is legal in
29797 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
29798 possible in Ada 83. Fortunately this is extremely rare, but the one
29799 situation that you should be alert to is the change in the predefined type
29800 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
29803 @item Range of type @code{Character}
29804 The range of @code{Standard.Character} is now the full 256 characters
29805 of Latin-1, whereas in most Ada 83 implementations it was restricted
29806 to 128 characters. Although some of the effects of
29807 this change will be manifest in compile-time rejection of legal
29808 Ada 83 programs it is possible for a working Ada 83 program to have
29809 a different effect in Ada 95, one that was not permitted in Ada 83.
29810 As an example, the expression
29811 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
29812 delivers @code{255} as its value.
29813 In general, you should look at the logic of any
29814 character-processing Ada 83 program and see whether it needs to be adapted
29815 to work correctly with Latin-1. Note that the predefined Ada 95 API has a
29816 character handling package that may be relevant if code needs to be adapted
29817 to account for the additional Latin-1 elements.
29818 The desirable fix is to
29819 modify the program to accommodate the full character set, but in some cases
29820 it may be convenient to define a subtype or derived type of Character that
29821 covers only the restricted range.
29825 @node Other language compatibility issues
29826 @subsection Other language compatibility issues
29829 @item @option{-gnat83} switch
29830 All implementations of GNAT provide a switch that causes GNAT to operate
29831 in Ada 83 mode. In this mode, some but not all compatibility problems
29832 of the type described above are handled automatically. For example, the
29833 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
29834 as identifiers as in Ada 83.
29836 in practice, it is usually advisable to make the necessary modifications
29837 to the program to remove the need for using this switch.
29838 See @ref{Compiling Different Versions of Ada}.
29840 @item Support for removed Ada 83 pragmas and attributes
29841 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
29842 generally because they were replaced by other mechanisms. Ada 95 and Ada 2005
29843 compilers are allowed, but not required, to implement these missing
29844 elements. In contrast with some other compilers, GNAT implements all
29845 such pragmas and attributes, eliminating this compatibility concern. These
29846 include @code{pragma Interface} and the floating point type attributes
29847 (@code{Emax}, @code{Mantissa}, etc.), among other items.
29851 @node Compatibility between Ada 95 and Ada 2005
29852 @section Compatibility between Ada 95 and Ada 2005
29853 @cindex Compatibility between Ada 95 and Ada 2005
29856 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
29857 a number of incompatibilities. Several are enumerated below;
29858 for a complete description please see the
29859 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
29860 @cite{Rationale for Ada 2005}.
29863 @item New reserved words.
29864 The words @code{interface}, @code{overriding} and @code{synchronized} are
29865 reserved in Ada 2005.
29866 A pre-Ada 2005 program that uses any of these as an identifier will be
29869 @item New declarations in predefined packages.
29870 A number of packages in the predefined environment contain new declarations:
29871 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
29872 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
29873 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
29874 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
29875 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
29876 If an Ada 95 program does a @code{with} and @code{use} of any of these
29877 packages, the new declarations may cause name clashes.
29879 @item Access parameters.
29880 A nondispatching subprogram with an access parameter cannot be renamed
29881 as a dispatching operation. This was permitted in Ada 95.
29883 @item Access types, discriminants, and constraints.
29884 Rule changes in this area have led to some incompatibilities; for example,
29885 constrained subtypes of some access types are not permitted in Ada 2005.
29887 @item Aggregates for limited types.
29888 The allowance of aggregates for limited types in Ada 2005 raises the
29889 possibility of ambiguities in legal Ada 95 programs, since additional types
29890 now need to be considered in expression resolution.
29892 @item Fixed-point multiplication and division.
29893 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
29894 were legal in Ada 95 and invoked the predefined versions of these operations,
29896 The ambiguity may be resolved either by applying a type conversion to the
29897 expression, or by explicitly invoking the operation from package
29900 @item Return-by-reference types.
29901 The Ada 95 return-by-reference mechanism has been removed. Instead, the user
29902 can declare a function returning a value from an anonymous access type.
29906 @node Implementation-dependent characteristics
29907 @section Implementation-dependent characteristics
29909 Although the Ada language defines the semantics of each construct as
29910 precisely as practical, in some situations (for example for reasons of
29911 efficiency, or where the effect is heavily dependent on the host or target
29912 platform) the implementation is allowed some freedom. In porting Ada 83
29913 code to GNAT, you need to be aware of whether / how the existing code
29914 exercised such implementation dependencies. Such characteristics fall into
29915 several categories, and GNAT offers specific support in assisting the
29916 transition from certain Ada 83 compilers.
29919 * Implementation-defined pragmas::
29920 * Implementation-defined attributes::
29922 * Elaboration order::
29923 * Target-specific aspects::
29926 @node Implementation-defined pragmas
29927 @subsection Implementation-defined pragmas
29930 Ada compilers are allowed to supplement the language-defined pragmas, and
29931 these are a potential source of non-portability. All GNAT-defined pragmas
29932 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
29933 Reference Manual}, and these include several that are specifically
29934 intended to correspond to other vendors' Ada 83 pragmas.
29935 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
29936 For compatibility with HP Ada 83, GNAT supplies the pragmas
29937 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
29938 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
29939 and @code{Volatile}.
29940 Other relevant pragmas include @code{External} and @code{Link_With}.
29941 Some vendor-specific
29942 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
29944 avoiding compiler rejection of units that contain such pragmas; they are not
29945 relevant in a GNAT context and hence are not otherwise implemented.
29947 @node Implementation-defined attributes
29948 @subsection Implementation-defined attributes
29950 Analogous to pragmas, the set of attributes may be extended by an
29951 implementation. All GNAT-defined attributes are described in
29952 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
29953 Manual}, and these include several that are specifically intended
29954 to correspond to other vendors' Ada 83 attributes. For migrating from VADS,
29955 the attribute @code{VADS_Size} may be useful. For compatibility with HP
29956 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
29960 @subsection Libraries
29962 Vendors may supply libraries to supplement the standard Ada API. If Ada 83
29963 code uses vendor-specific libraries then there are several ways to manage
29964 this in Ada 95 or Ada 2005:
29967 If the source code for the libraries (specs and bodies) are
29968 available, then the libraries can be migrated in the same way as the
29971 If the source code for the specs but not the bodies are
29972 available, then you can reimplement the bodies.
29974 Some features introduced by Ada 95 obviate the need for library support. For
29975 example most Ada 83 vendors supplied a package for unsigned integers. The
29976 Ada 95 modular type feature is the preferred way to handle this need, so
29977 instead of migrating or reimplementing the unsigned integer package it may
29978 be preferable to retrofit the application using modular types.
29981 @node Elaboration order
29982 @subsection Elaboration order
29984 The implementation can choose any elaboration order consistent with the unit
29985 dependency relationship. This freedom means that some orders can result in
29986 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
29987 to invoke a subprogram its body has been elaborated, or to instantiate a
29988 generic before the generic body has been elaborated. By default GNAT
29989 attempts to choose a safe order (one that will not encounter access before
29990 elaboration problems) by implicitly inserting @code{Elaborate} or
29991 @code{Elaborate_All} pragmas where
29992 needed. However, this can lead to the creation of elaboration circularities
29993 and a resulting rejection of the program by gnatbind. This issue is
29994 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
29995 In brief, there are several
29996 ways to deal with this situation:
30000 Modify the program to eliminate the circularities, e.g.@: by moving
30001 elaboration-time code into explicitly-invoked procedures
30003 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
30004 @code{Elaborate} pragmas, and then inhibit the generation of implicit
30005 @code{Elaborate_All}
30006 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
30007 (by selectively suppressing elaboration checks via pragma
30008 @code{Suppress(Elaboration_Check)} when it is safe to do so).
30011 @node Target-specific aspects
30012 @subsection Target-specific aspects
30014 Low-level applications need to deal with machine addresses, data
30015 representations, interfacing with assembler code, and similar issues. If
30016 such an Ada 83 application is being ported to different target hardware (for
30017 example where the byte endianness has changed) then you will need to
30018 carefully examine the program logic; the porting effort will heavily depend
30019 on the robustness of the original design. Moreover, Ada 95 (and thus
30020 Ada 2005) are sometimes
30021 incompatible with typical Ada 83 compiler practices regarding implicit
30022 packing, the meaning of the Size attribute, and the size of access values.
30023 GNAT's approach to these issues is described in @ref{Representation Clauses}.
30025 @node Compatibility with Other Ada Systems
30026 @section Compatibility with Other Ada Systems
30029 If programs avoid the use of implementation dependent and
30030 implementation defined features, as documented in the @cite{Ada
30031 Reference Manual}, there should be a high degree of portability between
30032 GNAT and other Ada systems. The following are specific items which
30033 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
30034 compilers, but do not affect porting code to GNAT@.
30035 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
30036 the following issues may or may not arise for Ada 2005 programs
30037 when other compilers appear.)
30040 @item Ada 83 Pragmas and Attributes
30041 Ada 95 compilers are allowed, but not required, to implement the missing
30042 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
30043 GNAT implements all such pragmas and attributes, eliminating this as
30044 a compatibility concern, but some other Ada 95 compilers reject these
30045 pragmas and attributes.
30047 @item Specialized Needs Annexes
30048 GNAT implements the full set of special needs annexes. At the
30049 current time, it is the only Ada 95 compiler to do so. This means that
30050 programs making use of these features may not be portable to other Ada
30051 95 compilation systems.
30053 @item Representation Clauses
30054 Some other Ada 95 compilers implement only the minimal set of
30055 representation clauses required by the Ada 95 reference manual. GNAT goes
30056 far beyond this minimal set, as described in the next section.
30059 @node Representation Clauses
30060 @section Representation Clauses
30063 The Ada 83 reference manual was quite vague in describing both the minimal
30064 required implementation of representation clauses, and also their precise
30065 effects. Ada 95 (and thus also Ada 2005) are much more explicit, but the
30066 minimal set of capabilities required is still quite limited.
30068 GNAT implements the full required set of capabilities in
30069 Ada 95 and Ada 2005, but also goes much further, and in particular
30070 an effort has been made to be compatible with existing Ada 83 usage to the
30071 greatest extent possible.
30073 A few cases exist in which Ada 83 compiler behavior is incompatible with
30074 the requirements in Ada 95 (and thus also Ada 2005). These are instances of
30075 intentional or accidental dependence on specific implementation dependent
30076 characteristics of these Ada 83 compilers. The following is a list of
30077 the cases most likely to arise in existing Ada 83 code.
30080 @item Implicit Packing
30081 Some Ada 83 compilers allowed a Size specification to cause implicit
30082 packing of an array or record. This could cause expensive implicit
30083 conversions for change of representation in the presence of derived
30084 types, and the Ada design intends to avoid this possibility.
30085 Subsequent AI's were issued to make it clear that such implicit
30086 change of representation in response to a Size clause is inadvisable,
30087 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
30088 Reference Manuals as implementation advice that is followed by GNAT@.
30089 The problem will show up as an error
30090 message rejecting the size clause. The fix is simply to provide
30091 the explicit pragma @code{Pack}, or for more fine tuned control, provide
30092 a Component_Size clause.
30094 @item Meaning of Size Attribute
30095 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
30096 the minimal number of bits required to hold values of the type. For example,
30097 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
30098 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and
30099 some 32 in this situation. This problem will usually show up as a compile
30100 time error, but not always. It is a good idea to check all uses of the
30101 'Size attribute when porting Ada 83 code. The GNAT specific attribute
30102 Object_Size can provide a useful way of duplicating the behavior of
30103 some Ada 83 compiler systems.
30105 @item Size of Access Types
30106 A common assumption in Ada 83 code is that an access type is in fact a pointer,
30107 and that therefore it will be the same size as a System.Address value. This
30108 assumption is true for GNAT in most cases with one exception. For the case of
30109 a pointer to an unconstrained array type (where the bounds may vary from one
30110 value of the access type to another), the default is to use a ``fat pointer'',
30111 which is represented as two separate pointers, one to the bounds, and one to
30112 the array. This representation has a number of advantages, including improved
30113 efficiency. However, it may cause some difficulties in porting existing Ada 83
30114 code which makes the assumption that, for example, pointers fit in 32 bits on
30115 a machine with 32-bit addressing.
30117 To get around this problem, GNAT also permits the use of ``thin pointers'' for
30118 access types in this case (where the designated type is an unconstrained array
30119 type). These thin pointers are indeed the same size as a System.Address value.
30120 To specify a thin pointer, use a size clause for the type, for example:
30122 @smallexample @c ada
30123 type X is access all String;
30124 for X'Size use Standard'Address_Size;
30128 which will cause the type X to be represented using a single pointer.
30129 When using this representation, the bounds are right behind the array.
30130 This representation is slightly less efficient, and does not allow quite
30131 such flexibility in the use of foreign pointers or in using the
30132 Unrestricted_Access attribute to create pointers to non-aliased objects.
30133 But for any standard portable use of the access type it will work in
30134 a functionally correct manner and allow porting of existing code.
30135 Note that another way of forcing a thin pointer representation
30136 is to use a component size clause for the element size in an array,
30137 or a record representation clause for an access field in a record.
30141 @c This brief section is only in the non-VMS version
30142 @c The complete chapter on HP Ada is in the VMS version
30143 @node Compatibility with HP Ada 83
30144 @section Compatibility with HP Ada 83
30147 The VMS version of GNAT fully implements all the pragmas and attributes
30148 provided by HP Ada 83, as well as providing the standard HP Ada 83
30149 libraries, including Starlet. In addition, data layouts and parameter
30150 passing conventions are highly compatible. This means that porting
30151 existing HP Ada 83 code to GNAT in VMS systems should be easier than
30152 most other porting efforts. The following are some of the most
30153 significant differences between GNAT and HP Ada 83.
30156 @item Default floating-point representation
30157 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
30158 it is VMS format. GNAT does implement the necessary pragmas
30159 (Long_Float, Float_Representation) for changing this default.
30162 The package System in GNAT exactly corresponds to the definition in the
30163 Ada 95 reference manual, which means that it excludes many of the
30164 HP Ada 83 extensions. However, a separate package Aux_DEC is provided
30165 that contains the additional definitions, and a special pragma,
30166 Extend_System allows this package to be treated transparently as an
30167 extension of package System.
30170 The definitions provided by Aux_DEC are exactly compatible with those
30171 in the HP Ada 83 version of System, with one exception.
30172 HP Ada provides the following declarations:
30174 @smallexample @c ada
30175 TO_ADDRESS (INTEGER)
30176 TO_ADDRESS (UNSIGNED_LONGWORD)
30177 TO_ADDRESS (@i{universal_integer})
30181 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
30182 an extension to Ada 83 not strictly compatible with the reference manual.
30183 In GNAT, we are constrained to be exactly compatible with the standard,
30184 and this means we cannot provide this capability. In HP Ada 83, the
30185 point of this definition is to deal with a call like:
30187 @smallexample @c ada
30188 TO_ADDRESS (16#12777#);
30192 Normally, according to the Ada 83 standard, one would expect this to be
30193 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
30194 of TO_ADDRESS@. However, in HP Ada 83, there is no ambiguity, since the
30195 definition using @i{universal_integer} takes precedence.
30197 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
30198 is not possible to be 100% compatible. Since there are many programs using
30199 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
30200 to change the name of the function in the UNSIGNED_LONGWORD case, so the
30201 declarations provided in the GNAT version of AUX_Dec are:
30203 @smallexample @c ada
30204 function To_Address (X : Integer) return Address;
30205 pragma Pure_Function (To_Address);
30207 function To_Address_Long (X : Unsigned_Longword)
30209 pragma Pure_Function (To_Address_Long);
30213 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
30214 change the name to TO_ADDRESS_LONG@.
30216 @item Task_Id values
30217 The Task_Id values assigned will be different in the two systems, and GNAT
30218 does not provide a specified value for the Task_Id of the environment task,
30219 which in GNAT is treated like any other declared task.
30223 For full details on these and other less significant compatibility issues,
30224 see appendix E of the HP publication entitled @cite{HP Ada, Technical
30225 Overview and Comparison on HP Platforms}.
30227 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
30228 attributes are recognized, although only a subset of them can sensibly
30229 be implemented. The description of pragmas in @ref{Implementation
30230 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
30231 indicates whether or not they are applicable to non-VMS systems.
30235 @node Transitioning to 64-Bit GNAT for OpenVMS
30236 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
30239 This section is meant to assist users of pre-2006 @value{EDITION}
30240 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
30241 the version of the GNAT technology supplied in 2006 and later for
30242 OpenVMS on both Alpha and I64.
30245 * Introduction to transitioning::
30246 * Migration of 32 bit code::
30247 * Taking advantage of 64 bit addressing::
30248 * Technical details::
30251 @node Introduction to transitioning
30252 @subsection Introduction
30255 64-bit @value{EDITION} for Open VMS has been designed to meet
30260 Providing a full conforming implementation of Ada 95 and Ada 2005
30263 Allowing maximum backward compatibility, thus easing migration of existing
30267 Supplying a path for exploiting the full 64-bit address range
30271 Ada's strong typing semantics has made it
30272 impractical to have different 32-bit and 64-bit modes. As soon as
30273 one object could possibly be outside the 32-bit address space, this
30274 would make it necessary for the @code{System.Address} type to be 64 bits.
30275 In particular, this would cause inconsistencies if 32-bit code is
30276 called from 64-bit code that raises an exception.
30278 This issue has been resolved by always using 64-bit addressing
30279 at the system level, but allowing for automatic conversions between
30280 32-bit and 64-bit addresses where required. Thus users who
30281 do not currently require 64-bit addressing capabilities, can
30282 recompile their code with only minimal changes (and indeed
30283 if the code is written in portable Ada, with no assumptions about
30284 the size of the @code{Address} type, then no changes at all are necessary).
30286 this approach provides a simple, gradual upgrade path to future
30287 use of larger memories than available for 32-bit systems.
30288 Also, newly written applications or libraries will by default
30289 be fully compatible with future systems exploiting 64-bit
30290 addressing capabilities.
30292 @ref{Migration of 32 bit code}, will focus on porting applications
30293 that do not require more than 2 GB of
30294 addressable memory. This code will be referred to as
30295 @emph{32-bit code}.
30296 For applications intending to exploit the full 64-bit address space,
30297 @ref{Taking advantage of 64 bit addressing},
30298 will consider further changes that may be required.
30299 Such code will be referred to below as @emph{64-bit code}.
30301 @node Migration of 32 bit code
30302 @subsection Migration of 32-bit code
30307 * Unchecked conversions::
30308 * Predefined constants::
30309 * Interfacing with C::
30310 * Experience with source compatibility::
30313 @node Address types
30314 @subsubsection Address types
30317 To solve the problem of mixing 64-bit and 32-bit addressing,
30318 while maintaining maximum backward compatibility, the following
30319 approach has been taken:
30323 @code{System.Address} always has a size of 64 bits
30326 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
30330 Since @code{System.Short_Address} is a subtype of @code{System.Address},
30331 a @code{Short_Address}
30332 may be used where an @code{Address} is required, and vice versa, without
30333 needing explicit type conversions.
30334 By virtue of the Open VMS parameter passing conventions,
30336 and exported subprograms that have 32-bit address parameters are
30337 compatible with those that have 64-bit address parameters.
30338 (See @ref{Making code 64 bit clean} for details.)
30340 The areas that may need attention are those where record types have
30341 been defined that contain components of the type @code{System.Address}, and
30342 where objects of this type are passed to code expecting a record layout with
30345 Different compilers on different platforms cannot be
30346 expected to represent the same type in the same way,
30347 since alignment constraints
30348 and other system-dependent properties affect the compiler's decision.
30349 For that reason, Ada code
30350 generally uses representation clauses to specify the expected
30351 layout where required.
30353 If such a representation clause uses 32 bits for a component having
30354 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
30355 will detect that error and produce a specific diagnostic message.
30356 The developer should then determine whether the representation
30357 should be 64 bits or not and make either of two changes:
30358 change the size to 64 bits and leave the type as @code{System.Address}, or
30359 leave the size as 32 bits and change the type to @code{System.Short_Address}.
30360 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
30361 required in any code setting or accessing the field; the compiler will
30362 automatically perform any needed conversions between address
30366 @subsubsection Access types
30369 By default, objects designated by access values are always
30370 allocated in the 32-bit
30371 address space. Thus legacy code will never contain
30372 any objects that are not addressable with 32-bit addresses, and
30373 the compiler will never raise exceptions as result of mixing
30374 32-bit and 64-bit addresses.
30376 However, the access values themselves are represented in 64 bits, for optimum
30377 performance and future compatibility with 64-bit code. As was
30378 the case with @code{System.Address}, the compiler will give an error message
30379 if an object or record component has a representation clause that
30380 requires the access value to fit in 32 bits. In such a situation,
30381 an explicit size clause for the access type, specifying 32 bits,
30382 will have the desired effect.
30384 General access types (declared with @code{access all}) can never be
30385 32 bits, as values of such types must be able to refer to any object
30386 of the designated type,
30387 including objects residing outside the 32-bit address range.
30388 Existing Ada 83 code will not contain such type definitions,
30389 however, since general access types were introduced in Ada 95.
30391 @node Unchecked conversions
30392 @subsubsection Unchecked conversions
30395 In the case of an @code{Unchecked_Conversion} where the source type is a
30396 64-bit access type or the type @code{System.Address}, and the target
30397 type is a 32-bit type, the compiler will generate a warning.
30398 Even though the generated code will still perform the required
30399 conversions, it is highly recommended in these cases to use
30400 respectively a 32-bit access type or @code{System.Short_Address}
30401 as the source type.
30403 @node Predefined constants
30404 @subsubsection Predefined constants
30407 The following table shows the correspondence between pre-2006 versions of
30408 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
30411 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
30412 @item @b{Constant} @tab @b{Old} @tab @b{New}
30413 @item @code{System.Word_Size} @tab 32 @tab 64
30414 @item @code{System.Memory_Size} @tab 2**32 @tab 2**64
30415 @item @code{System.Short_Memory_Size} @tab 2**32 @tab 2**32
30416 @item @code{System.Address_Size} @tab 32 @tab 64
30420 If you need to refer to the specific
30421 memory size of a 32-bit implementation, instead of the
30422 actual memory size, use @code{System.Short_Memory_Size}
30423 rather than @code{System.Memory_Size}.
30424 Similarly, references to @code{System.Address_Size} may need
30425 to be replaced by @code{System.Short_Address'Size}.
30426 The program @command{gnatfind} may be useful for locating
30427 references to the above constants, so that you can verify that they
30430 @node Interfacing with C
30431 @subsubsection Interfacing with C
30434 In order to minimize the impact of the transition to 64-bit addresses on
30435 legacy programs, some fundamental types in the @code{Interfaces.C}
30436 package hierarchy continue to be represented in 32 bits.
30437 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
30438 This eases integration with the default HP C layout choices, for example
30439 as found in the system routines in @code{DECC$SHR.EXE}.
30440 Because of this implementation choice, the type fully compatible with
30441 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
30442 Depending on the context the compiler will issue a
30443 warning or an error when type @code{Address} is used, alerting the user to a
30444 potential problem. Otherwise 32-bit programs that use
30445 @code{Interfaces.C} should normally not require code modifications
30447 The other issue arising with C interfacing concerns pragma @code{Convention}.
30448 For VMS 64-bit systems, there is an issue of the appropriate default size
30449 of C convention pointers in the absence of an explicit size clause. The HP
30450 C compiler can choose either 32 or 64 bits depending on compiler options.
30451 GNAT chooses 32-bits rather than 64-bits in the default case where no size
30452 clause is given. This proves a better choice for porting 32-bit legacy
30453 applications. In order to have a 64-bit representation, it is necessary to
30454 specify a size representation clause. For example:
30456 @smallexample @c ada
30457 type int_star is access Interfaces.C.int;
30458 pragma Convention(C, int_star);
30459 for int_star'Size use 64; -- Necessary to get 64 and not 32 bits
30462 @node Experience with source compatibility
30463 @subsubsection Experience with source compatibility
30466 The Security Server and STARLET on I64 provide an interesting ``test case''
30467 for source compatibility issues, since it is in such system code
30468 where assumptions about @code{Address} size might be expected to occur.
30469 Indeed, there were a small number of occasions in the Security Server
30470 file @file{jibdef.ads}
30471 where a representation clause for a record type specified
30472 32 bits for a component of type @code{Address}.
30473 All of these errors were detected by the compiler.
30474 The repair was obvious and immediate; to simply replace @code{Address} by
30475 @code{Short_Address}.
30477 In the case of STARLET, there were several record types that should
30478 have had representation clauses but did not. In these record types
30479 there was an implicit assumption that an @code{Address} value occupied
30481 These compiled without error, but their usage resulted in run-time error
30482 returns from STARLET system calls.
30483 Future GNAT technology enhancements may include a tool that detects and flags
30484 these sorts of potential source code porting problems.
30486 @c ****************************************
30487 @node Taking advantage of 64 bit addressing
30488 @subsection Taking advantage of 64-bit addressing
30491 * Making code 64 bit clean::
30492 * Allocating memory from the 64 bit storage pool::
30493 * Restrictions on use of 64 bit objects::
30494 * Using 64 bit storage pools by default::
30495 * General access types::
30496 * STARLET and other predefined libraries::
30499 @node Making code 64 bit clean
30500 @subsubsection Making code 64-bit clean
30503 In order to prevent problems that may occur when (parts of) a
30504 system start using memory outside the 32-bit address range,
30505 we recommend some additional guidelines:
30509 For imported subprograms that take parameters of the
30510 type @code{System.Address}, ensure that these subprograms can
30511 indeed handle 64-bit addresses. If not, or when in doubt,
30512 change the subprogram declaration to specify
30513 @code{System.Short_Address} instead.
30516 Resolve all warnings related to size mismatches in
30517 unchecked conversions. Failing to do so causes
30518 erroneous execution if the source object is outside
30519 the 32-bit address space.
30522 (optional) Explicitly use the 32-bit storage pool
30523 for access types used in a 32-bit context, or use
30524 generic access types where possible
30525 (@pxref{Restrictions on use of 64 bit objects}).
30529 If these rules are followed, the compiler will automatically insert
30530 any necessary checks to ensure that no addresses or access values
30531 passed to 32-bit code ever refer to objects outside the 32-bit
30533 Any attempt to do this will raise @code{Constraint_Error}.
30535 @node Allocating memory from the 64 bit storage pool
30536 @subsubsection Allocating memory from the 64-bit storage pool
30539 For any access type @code{T} that potentially requires memory allocations
30540 beyond the 32-bit address space,
30541 use the following representation clause:
30543 @smallexample @c ada
30544 for T'Storage_Pool use System.Pool_64;
30547 @node Restrictions on use of 64 bit objects
30548 @subsubsection Restrictions on use of 64-bit objects
30551 Taking the address of an object allocated from a 64-bit storage pool,
30552 and then passing this address to a subprogram expecting
30553 @code{System.Short_Address},
30554 or assigning it to a variable of type @code{Short_Address}, will cause
30555 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
30556 (@pxref{Making code 64 bit clean}), or checks are suppressed,
30557 no exception is raised and execution
30558 will become erroneous.
30560 @node Using 64 bit storage pools by default
30561 @subsubsection Using 64-bit storage pools by default
30564 In some cases it may be desirable to have the compiler allocate
30565 from 64-bit storage pools by default. This may be the case for
30566 libraries that are 64-bit clean, but may be used in both 32-bit
30567 and 64-bit contexts. For these cases the following configuration
30568 pragma may be specified:
30570 @smallexample @c ada
30571 pragma Pool_64_Default;
30575 Any code compiled in the context of this pragma will by default
30576 use the @code{System.Pool_64} storage pool. This default may be overridden
30577 for a specific access type @code{T} by the representation clause:
30579 @smallexample @c ada
30580 for T'Storage_Pool use System.Pool_32;
30584 Any object whose address may be passed to a subprogram with a
30585 @code{Short_Address} argument, or assigned to a variable of type
30586 @code{Short_Address}, needs to be allocated from this pool.
30588 @node General access types
30589 @subsubsection General access types
30592 Objects designated by access values from a
30593 general access type (declared with @code{access all}) are never allocated
30594 from a 64-bit storage pool. Code that uses general access types will
30595 accept objects allocated in either 32-bit or 64-bit address spaces,
30596 but never allocate objects outside the 32-bit address space.
30597 Using general access types ensures maximum compatibility with both
30598 32-bit and 64-bit code.
30600 @node STARLET and other predefined libraries
30601 @subsubsection STARLET and other predefined libraries
30604 All code that comes as part of GNAT is 64-bit clean, but the
30605 restrictions given in @ref{Restrictions on use of 64 bit objects},
30606 still apply. Look at the package
30607 specs to see in which contexts objects allocated
30608 in 64-bit address space are acceptable.
30610 @node Technical details
30611 @subsection Technical details
30614 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
30615 Ada standard with respect to the type of @code{System.Address}. Previous
30616 versions of GNAT Pro have defined this type as private and implemented it as a
30619 In order to allow defining @code{System.Short_Address} as a proper subtype,
30620 and to match the implicit sign extension in parameter passing,
30621 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
30622 visible (i.e., non-private) integer type.
30623 Standard operations on the type, such as the binary operators ``+'', ``-'',
30624 etc., that take @code{Address} operands and return an @code{Address} result,
30625 have been hidden by declaring these
30626 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
30627 ambiguities that would otherwise result from overloading.
30628 (Note that, although @code{Address} is a visible integer type,
30629 good programming practice dictates against exploiting the type's
30630 integer properties such as literals, since this will compromise
30633 Defining @code{Address} as a visible integer type helps achieve
30634 maximum compatibility for existing Ada code,
30635 without sacrificing the capabilities of the 64-bit architecture.
30638 @c ************************************************
30640 @node Microsoft Windows Topics
30641 @appendix Microsoft Windows Topics
30647 This chapter describes topics that are specific to the Microsoft Windows
30648 platforms (NT, 2000, and XP Professional).
30651 * Using GNAT on Windows::
30652 * Using a network installation of GNAT::
30653 * CONSOLE and WINDOWS subsystems::
30654 * Temporary Files::
30655 * Mixed-Language Programming on Windows::
30656 * Windows Calling Conventions::
30657 * Introduction to Dynamic Link Libraries (DLLs)::
30658 * Using DLLs with GNAT::
30659 * Building DLLs with GNAT::
30660 * Building DLLs with GNAT Project files::
30661 * Building DLLs with gnatdll::
30662 * GNAT and Windows Resources::
30663 * Debugging a DLL::
30664 * Setting Stack Size from gnatlink::
30665 * Setting Heap Size from gnatlink::
30668 @node Using GNAT on Windows
30669 @section Using GNAT on Windows
30672 One of the strengths of the GNAT technology is that its tool set
30673 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
30674 @code{gdb} debugger, etc.) is used in the same way regardless of the
30677 On Windows this tool set is complemented by a number of Microsoft-specific
30678 tools that have been provided to facilitate interoperability with Windows
30679 when this is required. With these tools:
30684 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
30688 You can use any Dynamically Linked Library (DLL) in your Ada code (both
30689 relocatable and non-relocatable DLLs are supported).
30692 You can build Ada DLLs for use in other applications. These applications
30693 can be written in a language other than Ada (e.g., C, C++, etc). Again both
30694 relocatable and non-relocatable Ada DLLs are supported.
30697 You can include Windows resources in your Ada application.
30700 You can use or create COM/DCOM objects.
30704 Immediately below are listed all known general GNAT-for-Windows restrictions.
30705 Other restrictions about specific features like Windows Resources and DLLs
30706 are listed in separate sections below.
30711 It is not possible to use @code{GetLastError} and @code{SetLastError}
30712 when tasking, protected records, or exceptions are used. In these
30713 cases, in order to implement Ada semantics, the GNAT run-time system
30714 calls certain Win32 routines that set the last error variable to 0 upon
30715 success. It should be possible to use @code{GetLastError} and
30716 @code{SetLastError} when tasking, protected record, and exception
30717 features are not used, but it is not guaranteed to work.
30720 It is not possible to link against Microsoft libraries except for
30721 import libraries. The library must be built to be compatible with
30722 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
30723 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
30724 not be compatible with the GNAT runtime. Even if the library is
30725 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
30728 When the compilation environment is located on FAT32 drives, users may
30729 experience recompilations of the source files that have not changed if
30730 Daylight Saving Time (DST) state has changed since the last time files
30731 were compiled. NTFS drives do not have this problem.
30734 No components of the GNAT toolset use any entries in the Windows
30735 registry. The only entries that can be created are file associations and
30736 PATH settings, provided the user has chosen to create them at installation
30737 time, as well as some minimal book-keeping information needed to correctly
30738 uninstall or integrate different GNAT products.
30741 @node Using a network installation of GNAT
30742 @section Using a network installation of GNAT
30745 Make sure the system on which GNAT is installed is accessible from the
30746 current machine, i.e., the install location is shared over the network.
30747 Shared resources are accessed on Windows by means of UNC paths, which
30748 have the format @code{\\server\sharename\path}
30750 In order to use such a network installation, simply add the UNC path of the
30751 @file{bin} directory of your GNAT installation in front of your PATH. For
30752 example, if GNAT is installed in @file{\GNAT} directory of a share location
30753 called @file{c-drive} on a machine @file{LOKI}, the following command will
30756 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
30758 Be aware that every compilation using the network installation results in the
30759 transfer of large amounts of data across the network and will likely cause
30760 serious performance penalty.
30762 @node CONSOLE and WINDOWS subsystems
30763 @section CONSOLE and WINDOWS subsystems
30764 @cindex CONSOLE Subsystem
30765 @cindex WINDOWS Subsystem
30769 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
30770 (which is the default subsystem) will always create a console when
30771 launching the application. This is not something desirable when the
30772 application has a Windows GUI. To get rid of this console the
30773 application must be using the @code{WINDOWS} subsystem. To do so
30774 the @option{-mwindows} linker option must be specified.
30777 $ gnatmake winprog -largs -mwindows
30780 @node Temporary Files
30781 @section Temporary Files
30782 @cindex Temporary files
30785 It is possible to control where temporary files gets created by setting
30786 the @env{TMP} environment variable. The file will be created:
30789 @item Under the directory pointed to by the @env{TMP} environment variable if
30790 this directory exists.
30792 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
30793 set (or not pointing to a directory) and if this directory exists.
30795 @item Under the current working directory otherwise.
30799 This allows you to determine exactly where the temporary
30800 file will be created. This is particularly useful in networked
30801 environments where you may not have write access to some
30804 @node Mixed-Language Programming on Windows
30805 @section Mixed-Language Programming on Windows
30808 Developing pure Ada applications on Windows is no different than on
30809 other GNAT-supported platforms. However, when developing or porting an
30810 application that contains a mix of Ada and C/C++, the choice of your
30811 Windows C/C++ development environment conditions your overall
30812 interoperability strategy.
30814 If you use @command{gcc} to compile the non-Ada part of your application,
30815 there are no Windows-specific restrictions that affect the overall
30816 interoperability with your Ada code. If you plan to use
30817 Microsoft tools (e.g.@: Microsoft Visual C/C++), you should be aware of
30818 the following limitations:
30822 You cannot link your Ada code with an object or library generated with
30823 Microsoft tools if these use the @code{.tls} section (Thread Local
30824 Storage section) since the GNAT linker does not yet support this section.
30827 You cannot link your Ada code with an object or library generated with
30828 Microsoft tools if these use I/O routines other than those provided in
30829 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
30830 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
30831 libraries can cause a conflict with @code{msvcrt.dll} services. For
30832 instance Visual C++ I/O stream routines conflict with those in
30837 If you do want to use the Microsoft tools for your non-Ada code and hit one
30838 of the above limitations, you have two choices:
30842 Encapsulate your non-Ada code in a DLL to be linked with your Ada
30843 application. In this case, use the Microsoft or whatever environment to
30844 build the DLL and use GNAT to build your executable
30845 (@pxref{Using DLLs with GNAT}).
30848 Or you can encapsulate your Ada code in a DLL to be linked with the
30849 other part of your application. In this case, use GNAT to build the DLL
30850 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
30851 environment to build your executable.
30854 @node Windows Calling Conventions
30855 @section Windows Calling Conventions
30860 * C Calling Convention::
30861 * Stdcall Calling Convention::
30862 * Win32 Calling Convention::
30863 * DLL Calling Convention::
30867 When a subprogram @code{F} (caller) calls a subprogram @code{G}
30868 (callee), there are several ways to push @code{G}'s parameters on the
30869 stack and there are several possible scenarios to clean up the stack
30870 upon @code{G}'s return. A calling convention is an agreed upon software
30871 protocol whereby the responsibilities between the caller (@code{F}) and
30872 the callee (@code{G}) are clearly defined. Several calling conventions
30873 are available for Windows:
30877 @code{C} (Microsoft defined)
30880 @code{Stdcall} (Microsoft defined)
30883 @code{Win32} (GNAT specific)
30886 @code{DLL} (GNAT specific)
30889 @node C Calling Convention
30890 @subsection @code{C} Calling Convention
30893 This is the default calling convention used when interfacing to C/C++
30894 routines compiled with either @command{gcc} or Microsoft Visual C++.
30896 In the @code{C} calling convention subprogram parameters are pushed on the
30897 stack by the caller from right to left. The caller itself is in charge of
30898 cleaning up the stack after the call. In addition, the name of a routine
30899 with @code{C} calling convention is mangled by adding a leading underscore.
30901 The name to use on the Ada side when importing (or exporting) a routine
30902 with @code{C} calling convention is the name of the routine. For
30903 instance the C function:
30906 int get_val (long);
30910 should be imported from Ada as follows:
30912 @smallexample @c ada
30914 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30915 pragma Import (C, Get_Val, External_Name => "get_val");
30920 Note that in this particular case the @code{External_Name} parameter could
30921 have been omitted since, when missing, this parameter is taken to be the
30922 name of the Ada entity in lower case. When the @code{Link_Name} parameter
30923 is missing, as in the above example, this parameter is set to be the
30924 @code{External_Name} with a leading underscore.
30926 When importing a variable defined in C, you should always use the @code{C}
30927 calling convention unless the object containing the variable is part of a
30928 DLL (in which case you should use the @code{Stdcall} calling
30929 convention, @pxref{Stdcall Calling Convention}).
30931 @node Stdcall Calling Convention
30932 @subsection @code{Stdcall} Calling Convention
30935 This convention, which was the calling convention used for Pascal
30936 programs, is used by Microsoft for all the routines in the Win32 API for
30937 efficiency reasons. It must be used to import any routine for which this
30938 convention was specified.
30940 In the @code{Stdcall} calling convention subprogram parameters are pushed
30941 on the stack by the caller from right to left. The callee (and not the
30942 caller) is in charge of cleaning the stack on routine exit. In addition,
30943 the name of a routine with @code{Stdcall} calling convention is mangled by
30944 adding a leading underscore (as for the @code{C} calling convention) and a
30945 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
30946 bytes) of the parameters passed to the routine.
30948 The name to use on the Ada side when importing a C routine with a
30949 @code{Stdcall} calling convention is the name of the C routine. The leading
30950 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
30951 the compiler. For instance the Win32 function:
30954 @b{APIENTRY} int get_val (long);
30958 should be imported from Ada as follows:
30960 @smallexample @c ada
30962 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30963 pragma Import (Stdcall, Get_Val);
30964 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
30969 As for the @code{C} calling convention, when the @code{External_Name}
30970 parameter is missing, it is taken to be the name of the Ada entity in lower
30971 case. If instead of writing the above import pragma you write:
30973 @smallexample @c ada
30975 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30976 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
30981 then the imported routine is @code{_retrieve_val@@4}. However, if instead
30982 of specifying the @code{External_Name} parameter you specify the
30983 @code{Link_Name} as in the following example:
30985 @smallexample @c ada
30987 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30988 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
30993 then the imported routine is @code{retrieve_val}, that is, there is no
30994 decoration at all. No leading underscore and no Stdcall suffix
30995 @code{@@}@code{@i{nn}}.
30998 This is especially important as in some special cases a DLL's entry
30999 point name lacks a trailing @code{@@}@code{@i{nn}} while the exported
31000 name generated for a call has it.
31003 It is also possible to import variables defined in a DLL by using an
31004 import pragma for a variable. As an example, if a DLL contains a
31005 variable defined as:
31012 then, to access this variable from Ada you should write:
31014 @smallexample @c ada
31016 My_Var : Interfaces.C.int;
31017 pragma Import (Stdcall, My_Var);
31022 Note that to ease building cross-platform bindings this convention
31023 will be handled as a @code{C} calling convention on non-Windows platforms.
31025 @node Win32 Calling Convention
31026 @subsection @code{Win32} Calling Convention
31029 This convention, which is GNAT-specific is fully equivalent to the
31030 @code{Stdcall} calling convention described above.
31032 @node DLL Calling Convention
31033 @subsection @code{DLL} Calling Convention
31036 This convention, which is GNAT-specific is fully equivalent to the
31037 @code{Stdcall} calling convention described above.
31039 @node Introduction to Dynamic Link Libraries (DLLs)
31040 @section Introduction to Dynamic Link Libraries (DLLs)
31044 A Dynamically Linked Library (DLL) is a library that can be shared by
31045 several applications running under Windows. A DLL can contain any number of
31046 routines and variables.
31048 One advantage of DLLs is that you can change and enhance them without
31049 forcing all the applications that depend on them to be relinked or
31050 recompiled. However, you should be aware than all calls to DLL routines are
31051 slower since, as you will understand below, such calls are indirect.
31053 To illustrate the remainder of this section, suppose that an application
31054 wants to use the services of a DLL @file{API.dll}. To use the services
31055 provided by @file{API.dll} you must statically link against the DLL or
31056 an import library which contains a jump table with an entry for each
31057 routine and variable exported by the DLL. In the Microsoft world this
31058 import library is called @file{API.lib}. When using GNAT this import
31059 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
31060 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
31062 After you have linked your application with the DLL or the import library
31063 and you run your application, here is what happens:
31067 Your application is loaded into memory.
31070 The DLL @file{API.dll} is mapped into the address space of your
31071 application. This means that:
31075 The DLL will use the stack of the calling thread.
31078 The DLL will use the virtual address space of the calling process.
31081 The DLL will allocate memory from the virtual address space of the calling
31085 Handles (pointers) can be safely exchanged between routines in the DLL
31086 routines and routines in the application using the DLL.
31090 The entries in the jump table (from the import library @file{libAPI.dll.a}
31091 or @file{API.lib} or automatically created when linking against a DLL)
31092 which is part of your application are initialized with the addresses
31093 of the routines and variables in @file{API.dll}.
31096 If present in @file{API.dll}, routines @code{DllMain} or
31097 @code{DllMainCRTStartup} are invoked. These routines typically contain
31098 the initialization code needed for the well-being of the routines and
31099 variables exported by the DLL.
31103 There is an additional point which is worth mentioning. In the Windows
31104 world there are two kind of DLLs: relocatable and non-relocatable
31105 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
31106 in the target application address space. If the addresses of two
31107 non-relocatable DLLs overlap and these happen to be used by the same
31108 application, a conflict will occur and the application will run
31109 incorrectly. Hence, when possible, it is always preferable to use and
31110 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
31111 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
31112 User's Guide) removes the debugging symbols from the DLL but the DLL can
31113 still be relocated.
31115 As a side note, an interesting difference between Microsoft DLLs and
31116 Unix shared libraries, is the fact that on most Unix systems all public
31117 routines are exported by default in a Unix shared library, while under
31118 Windows it is possible (but not required) to list exported routines in
31119 a definition file (@pxref{The Definition File}).
31121 @node Using DLLs with GNAT
31122 @section Using DLLs with GNAT
31125 * Creating an Ada Spec for the DLL Services::
31126 * Creating an Import Library::
31130 To use the services of a DLL, say @file{API.dll}, in your Ada application
31135 The Ada spec for the routines and/or variables you want to access in
31136 @file{API.dll}. If not available this Ada spec must be built from the C/C++
31137 header files provided with the DLL.
31140 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
31141 mentioned an import library is a statically linked library containing the
31142 import table which will be filled at load time to point to the actual
31143 @file{API.dll} routines. Sometimes you don't have an import library for the
31144 DLL you want to use. The following sections will explain how to build
31145 one. Note that this is optional.
31148 The actual DLL, @file{API.dll}.
31152 Once you have all the above, to compile an Ada application that uses the
31153 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
31154 you simply issue the command
31157 $ gnatmake my_ada_app -largs -lAPI
31161 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
31162 tells the GNAT linker to look first for a library named @file{API.lib}
31163 (Microsoft-style name) and if not found for a libraries named
31164 @file{libAPI.dll.a}, @file{API.dll.a} or @file{libAPI.a}.
31165 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
31166 contains the following pragma
31168 @smallexample @c ada
31169 pragma Linker_Options ("-lAPI");
31173 you do not have to add @option{-largs -lAPI} at the end of the
31174 @command{gnatmake} command.
31176 If any one of the items above is missing you will have to create it
31177 yourself. The following sections explain how to do so using as an
31178 example a fictitious DLL called @file{API.dll}.
31180 @node Creating an Ada Spec for the DLL Services
31181 @subsection Creating an Ada Spec for the DLL Services
31184 A DLL typically comes with a C/C++ header file which provides the
31185 definitions of the routines and variables exported by the DLL. The Ada
31186 equivalent of this header file is a package spec that contains definitions
31187 for the imported entities. If the DLL you intend to use does not come with
31188 an Ada spec you have to generate one such spec yourself. For example if
31189 the header file of @file{API.dll} is a file @file{api.h} containing the
31190 following two definitions:
31202 then the equivalent Ada spec could be:
31204 @smallexample @c ada
31207 with Interfaces.C.Strings;
31212 function Get (Str : C.Strings.Chars_Ptr) return C.int;
31215 pragma Import (C, Get);
31216 pragma Import (DLL, Some_Var);
31223 Note that a variable is
31224 @strong{always imported with a Stdcall convention}. A function
31225 can have @code{C} or @code{Stdcall} convention.
31226 (@pxref{Windows Calling Conventions}).
31228 @node Creating an Import Library
31229 @subsection Creating an Import Library
31230 @cindex Import library
31233 * The Definition File::
31234 * GNAT-Style Import Library::
31235 * Microsoft-Style Import Library::
31239 If a Microsoft-style import library @file{API.lib} or a GNAT-style
31240 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
31241 with @file{API.dll} you can skip this section. You can also skip this
31242 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
31243 as in this case it is possible to link directly against the
31244 DLL. Otherwise read on.
31246 @node The Definition File
31247 @subsubsection The Definition File
31248 @cindex Definition file
31252 As previously mentioned, and unlike Unix systems, the list of symbols
31253 that are exported from a DLL must be provided explicitly in Windows.
31254 The main goal of a definition file is precisely that: list the symbols
31255 exported by a DLL. A definition file (usually a file with a @code{.def}
31256 suffix) has the following structure:
31262 [DESCRIPTION @i{string}]
31272 @item LIBRARY @i{name}
31273 This section, which is optional, gives the name of the DLL.
31275 @item DESCRIPTION @i{string}
31276 This section, which is optional, gives a description string that will be
31277 embedded in the import library.
31280 This section gives the list of exported symbols (procedures, functions or
31281 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
31282 section of @file{API.def} looks like:
31296 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
31297 (@pxref{Windows Calling Conventions}) for a Stdcall
31298 calling convention function in the exported symbols list.
31301 There can actually be other sections in a definition file, but these
31302 sections are not relevant to the discussion at hand.
31304 @node GNAT-Style Import Library
31305 @subsubsection GNAT-Style Import Library
31308 To create a static import library from @file{API.dll} with the GNAT tools
31309 you should proceed as follows:
31313 Create the definition file @file{API.def} (@pxref{The Definition File}).
31314 For that use the @code{dll2def} tool as follows:
31317 $ dll2def API.dll > API.def
31321 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
31322 to standard output the list of entry points in the DLL. Note that if
31323 some routines in the DLL have the @code{Stdcall} convention
31324 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
31325 suffix then you'll have to edit @file{api.def} to add it, and specify
31326 @option{-k} to @command{gnatdll} when creating the import library.
31329 Here are some hints to find the right @code{@@}@i{nn} suffix.
31333 If you have the Microsoft import library (.lib), it is possible to get
31334 the right symbols by using Microsoft @code{dumpbin} tool (see the
31335 corresponding Microsoft documentation for further details).
31338 $ dumpbin /exports api.lib
31342 If you have a message about a missing symbol at link time the compiler
31343 tells you what symbol is expected. You just have to go back to the
31344 definition file and add the right suffix.
31348 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
31349 (@pxref{Using gnatdll}) as follows:
31352 $ gnatdll -e API.def -d API.dll
31356 @code{gnatdll} takes as input a definition file @file{API.def} and the
31357 name of the DLL containing the services listed in the definition file
31358 @file{API.dll}. The name of the static import library generated is
31359 computed from the name of the definition file as follows: if the
31360 definition file name is @i{xyz}@code{.def}, the import library name will
31361 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
31362 @option{-e} could have been removed because the name of the definition
31363 file (before the ``@code{.def}'' suffix) is the same as the name of the
31364 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
31367 @node Microsoft-Style Import Library
31368 @subsubsection Microsoft-Style Import Library
31371 With GNAT you can either use a GNAT-style or Microsoft-style import
31372 library. A Microsoft import library is needed only if you plan to make an
31373 Ada DLL available to applications developed with Microsoft
31374 tools (@pxref{Mixed-Language Programming on Windows}).
31376 To create a Microsoft-style import library for @file{API.dll} you
31377 should proceed as follows:
31381 Create the definition file @file{API.def} from the DLL. For this use either
31382 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
31383 tool (see the corresponding Microsoft documentation for further details).
31386 Build the actual import library using Microsoft's @code{lib} utility:
31389 $ lib -machine:IX86 -def:API.def -out:API.lib
31393 If you use the above command the definition file @file{API.def} must
31394 contain a line giving the name of the DLL:
31401 See the Microsoft documentation for further details about the usage of
31405 @node Building DLLs with GNAT
31406 @section Building DLLs with GNAT
31407 @cindex DLLs, building
31410 This section explain how to build DLLs using the GNAT built-in DLL
31411 support. With the following procedure it is straight forward to build
31412 and use DLLs with GNAT.
31416 @item building object files
31418 The first step is to build all objects files that are to be included
31419 into the DLL. This is done by using the standard @command{gnatmake} tool.
31421 @item building the DLL
31423 To build the DLL you must use @command{gcc}'s @option{-shared}
31424 option. It is quite simple to use this method:
31427 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
31430 It is important to note that in this case all symbols found in the
31431 object files are automatically exported. It is possible to restrict
31432 the set of symbols to export by passing to @command{gcc} a definition
31433 file, @pxref{The Definition File}. For example:
31436 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
31439 If you use a definition file you must export the elaboration procedures
31440 for every package that required one. Elaboration procedures are named
31441 using the package name followed by "_E".
31443 @item preparing DLL to be used
31445 For the DLL to be used by client programs the bodies must be hidden
31446 from it and the .ali set with read-only attribute. This is very important
31447 otherwise GNAT will recompile all packages and will not actually use
31448 the code in the DLL. For example:
31452 $ copy *.ads *.ali api.dll apilib
31453 $ attrib +R apilib\*.ali
31458 At this point it is possible to use the DLL by directly linking
31459 against it. Note that you must use the GNAT shared runtime when using
31460 GNAT shared libraries. This is achieved by using @option{-shared} binder's
31464 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
31467 @node Building DLLs with GNAT Project files
31468 @section Building DLLs with GNAT Project files
31469 @cindex DLLs, building
31472 There is nothing specific to Windows in the build process.
31473 @pxref{Library Projects}.
31476 Due to a system limitation, it is not possible under Windows to create threads
31477 when inside the @code{DllMain} routine which is used for auto-initialization
31478 of shared libraries, so it is not possible to have library level tasks in SALs.
31480 @node Building DLLs with gnatdll
31481 @section Building DLLs with gnatdll
31482 @cindex DLLs, building
31485 * Limitations When Using Ada DLLs from Ada::
31486 * Exporting Ada Entities::
31487 * Ada DLLs and Elaboration::
31488 * Ada DLLs and Finalization::
31489 * Creating a Spec for Ada DLLs::
31490 * Creating the Definition File::
31495 Note that it is preferred to use the built-in GNAT DLL support
31496 (@pxref{Building DLLs with GNAT}) or GNAT Project files
31497 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
31499 This section explains how to build DLLs containing Ada code using
31500 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
31501 remainder of this section.
31503 The steps required to build an Ada DLL that is to be used by Ada as well as
31504 non-Ada applications are as follows:
31508 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
31509 @code{Stdcall} calling convention to avoid any Ada name mangling for the
31510 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
31511 skip this step if you plan to use the Ada DLL only from Ada applications.
31514 Your Ada code must export an initialization routine which calls the routine
31515 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
31516 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
31517 routine exported by the Ada DLL must be invoked by the clients of the DLL
31518 to initialize the DLL.
31521 When useful, the DLL should also export a finalization routine which calls
31522 routine @code{adafinal} generated by @command{gnatbind} to perform the
31523 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
31524 The finalization routine exported by the Ada DLL must be invoked by the
31525 clients of the DLL when the DLL services are no further needed.
31528 You must provide a spec for the services exported by the Ada DLL in each
31529 of the programming languages to which you plan to make the DLL available.
31532 You must provide a definition file listing the exported entities
31533 (@pxref{The Definition File}).
31536 Finally you must use @code{gnatdll} to produce the DLL and the import
31537 library (@pxref{Using gnatdll}).
31541 Note that a relocatable DLL stripped using the @code{strip}
31542 binutils tool will not be relocatable anymore. To build a DLL without
31543 debug information pass @code{-largs -s} to @code{gnatdll}. This
31544 restriction does not apply to a DLL built using a Library Project.
31545 @pxref{Library Projects}.
31547 @node Limitations When Using Ada DLLs from Ada
31548 @subsection Limitations When Using Ada DLLs from Ada
31551 When using Ada DLLs from Ada applications there is a limitation users
31552 should be aware of. Because on Windows the GNAT run time is not in a DLL of
31553 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
31554 each Ada DLL includes the services of the GNAT run time that are necessary
31555 to the Ada code inside the DLL. As a result, when an Ada program uses an
31556 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
31557 one in the main program.
31559 It is therefore not possible to exchange GNAT run-time objects between the
31560 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
31561 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
31564 It is completely safe to exchange plain elementary, array or record types,
31565 Windows object handles, etc.
31567 @node Exporting Ada Entities
31568 @subsection Exporting Ada Entities
31569 @cindex Export table
31572 Building a DLL is a way to encapsulate a set of services usable from any
31573 application. As a result, the Ada entities exported by a DLL should be
31574 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
31575 any Ada name mangling. As an example here is an Ada package
31576 @code{API}, spec and body, exporting two procedures, a function, and a
31579 @smallexample @c ada
31582 with Interfaces.C; use Interfaces;
31584 Count : C.int := 0;
31585 function Factorial (Val : C.int) return C.int;
31587 procedure Initialize_API;
31588 procedure Finalize_API;
31589 -- Initialization & Finalization routines. More in the next section.
31591 pragma Export (C, Initialize_API);
31592 pragma Export (C, Finalize_API);
31593 pragma Export (C, Count);
31594 pragma Export (C, Factorial);
31600 @smallexample @c ada
31603 package body API is
31604 function Factorial (Val : C.int) return C.int is
31607 Count := Count + 1;
31608 for K in 1 .. Val loop
31614 procedure Initialize_API is
31616 pragma Import (C, Adainit);
31619 end Initialize_API;
31621 procedure Finalize_API is
31622 procedure Adafinal;
31623 pragma Import (C, Adafinal);
31633 If the Ada DLL you are building will only be used by Ada applications
31634 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
31635 convention. As an example, the previous package could be written as
31638 @smallexample @c ada
31642 Count : Integer := 0;
31643 function Factorial (Val : Integer) return Integer;
31645 procedure Initialize_API;
31646 procedure Finalize_API;
31647 -- Initialization and Finalization routines.
31653 @smallexample @c ada
31656 package body API is
31657 function Factorial (Val : Integer) return Integer is
31658 Fact : Integer := 1;
31660 Count := Count + 1;
31661 for K in 1 .. Val loop
31668 -- The remainder of this package body is unchanged.
31675 Note that if you do not export the Ada entities with a @code{C} or
31676 @code{Stdcall} convention you will have to provide the mangled Ada names
31677 in the definition file of the Ada DLL
31678 (@pxref{Creating the Definition File}).
31680 @node Ada DLLs and Elaboration
31681 @subsection Ada DLLs and Elaboration
31682 @cindex DLLs and elaboration
31685 The DLL that you are building contains your Ada code as well as all the
31686 routines in the Ada library that are needed by it. The first thing a
31687 user of your DLL must do is elaborate the Ada code
31688 (@pxref{Elaboration Order Handling in GNAT}).
31690 To achieve this you must export an initialization routine
31691 (@code{Initialize_API} in the previous example), which must be invoked
31692 before using any of the DLL services. This elaboration routine must call
31693 the Ada elaboration routine @code{adainit} generated by the GNAT binder
31694 (@pxref{Binding with Non-Ada Main Programs}). See the body of
31695 @code{Initialize_Api} for an example. Note that the GNAT binder is
31696 automatically invoked during the DLL build process by the @code{gnatdll}
31697 tool (@pxref{Using gnatdll}).
31699 When a DLL is loaded, Windows systematically invokes a routine called
31700 @code{DllMain}. It would therefore be possible to call @code{adainit}
31701 directly from @code{DllMain} without having to provide an explicit
31702 initialization routine. Unfortunately, it is not possible to call
31703 @code{adainit} from the @code{DllMain} if your program has library level
31704 tasks because access to the @code{DllMain} entry point is serialized by
31705 the system (that is, only a single thread can execute ``through'' it at a
31706 time), which means that the GNAT run time will deadlock waiting for the
31707 newly created task to complete its initialization.
31709 @node Ada DLLs and Finalization
31710 @subsection Ada DLLs and Finalization
31711 @cindex DLLs and finalization
31714 When the services of an Ada DLL are no longer needed, the client code should
31715 invoke the DLL finalization routine, if available. The DLL finalization
31716 routine is in charge of releasing all resources acquired by the DLL. In the
31717 case of the Ada code contained in the DLL, this is achieved by calling
31718 routine @code{adafinal} generated by the GNAT binder
31719 (@pxref{Binding with Non-Ada Main Programs}).
31720 See the body of @code{Finalize_Api} for an
31721 example. As already pointed out the GNAT binder is automatically invoked
31722 during the DLL build process by the @code{gnatdll} tool
31723 (@pxref{Using gnatdll}).
31725 @node Creating a Spec for Ada DLLs
31726 @subsection Creating a Spec for Ada DLLs
31729 To use the services exported by the Ada DLL from another programming
31730 language (e.g.@: C), you have to translate the specs of the exported Ada
31731 entities in that language. For instance in the case of @code{API.dll},
31732 the corresponding C header file could look like:
31737 extern int *_imp__count;
31738 #define count (*_imp__count)
31739 int factorial (int);
31745 It is important to understand that when building an Ada DLL to be used by
31746 other Ada applications, you need two different specs for the packages
31747 contained in the DLL: one for building the DLL and the other for using
31748 the DLL. This is because the @code{DLL} calling convention is needed to
31749 use a variable defined in a DLL, but when building the DLL, the variable
31750 must have either the @code{Ada} or @code{C} calling convention. As an
31751 example consider a DLL comprising the following package @code{API}:
31753 @smallexample @c ada
31757 Count : Integer := 0;
31759 -- Remainder of the package omitted.
31766 After producing a DLL containing package @code{API}, the spec that
31767 must be used to import @code{API.Count} from Ada code outside of the
31770 @smallexample @c ada
31775 pragma Import (DLL, Count);
31781 @node Creating the Definition File
31782 @subsection Creating the Definition File
31785 The definition file is the last file needed to build the DLL. It lists
31786 the exported symbols. As an example, the definition file for a DLL
31787 containing only package @code{API} (where all the entities are exported
31788 with a @code{C} calling convention) is:
31803 If the @code{C} calling convention is missing from package @code{API},
31804 then the definition file contains the mangled Ada names of the above
31805 entities, which in this case are:
31814 api__initialize_api
31819 @node Using gnatdll
31820 @subsection Using @code{gnatdll}
31824 * gnatdll Example::
31825 * gnatdll behind the Scenes::
31830 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
31831 and non-Ada sources that make up your DLL have been compiled.
31832 @code{gnatdll} is actually in charge of two distinct tasks: build the
31833 static import library for the DLL and the actual DLL. The form of the
31834 @code{gnatdll} command is
31838 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
31843 where @i{list-of-files} is a list of ALI and object files. The object
31844 file list must be the exact list of objects corresponding to the non-Ada
31845 sources whose services are to be included in the DLL. The ALI file list
31846 must be the exact list of ALI files for the corresponding Ada sources
31847 whose services are to be included in the DLL. If @i{list-of-files} is
31848 missing, only the static import library is generated.
31851 You may specify any of the following switches to @code{gnatdll}:
31854 @item -a[@var{address}]
31855 @cindex @option{-a} (@code{gnatdll})
31856 Build a non-relocatable DLL at @var{address}. If @var{address} is not
31857 specified the default address @var{0x11000000} will be used. By default,
31858 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
31859 advise the reader to build relocatable DLL.
31861 @item -b @var{address}
31862 @cindex @option{-b} (@code{gnatdll})
31863 Set the relocatable DLL base address. By default the address is
31866 @item -bargs @var{opts}
31867 @cindex @option{-bargs} (@code{gnatdll})
31868 Binder options. Pass @var{opts} to the binder.
31870 @item -d @var{dllfile}
31871 @cindex @option{-d} (@code{gnatdll})
31872 @var{dllfile} is the name of the DLL. This switch must be present for
31873 @code{gnatdll} to do anything. The name of the generated import library is
31874 obtained algorithmically from @var{dllfile} as shown in the following
31875 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
31876 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
31877 by option @option{-e}) is obtained algorithmically from @var{dllfile}
31878 as shown in the following example:
31879 if @var{dllfile} is @code{xyz.dll}, the definition
31880 file used is @code{xyz.def}.
31882 @item -e @var{deffile}
31883 @cindex @option{-e} (@code{gnatdll})
31884 @var{deffile} is the name of the definition file.
31887 @cindex @option{-g} (@code{gnatdll})
31888 Generate debugging information. This information is stored in the object
31889 file and copied from there to the final DLL file by the linker,
31890 where it can be read by the debugger. You must use the
31891 @option{-g} switch if you plan on using the debugger or the symbolic
31895 @cindex @option{-h} (@code{gnatdll})
31896 Help mode. Displays @code{gnatdll} switch usage information.
31899 @cindex @option{-I} (@code{gnatdll})
31900 Direct @code{gnatdll} to search the @var{dir} directory for source and
31901 object files needed to build the DLL.
31902 (@pxref{Search Paths and the Run-Time Library (RTL)}).
31905 @cindex @option{-k} (@code{gnatdll})
31906 Removes the @code{@@}@i{nn} suffix from the import library's exported
31907 names, but keeps them for the link names. You must specify this
31908 option if you want to use a @code{Stdcall} function in a DLL for which
31909 the @code{@@}@i{nn} suffix has been removed. This is the case for most
31910 of the Windows NT DLL for example. This option has no effect when
31911 @option{-n} option is specified.
31913 @item -l @var{file}
31914 @cindex @option{-l} (@code{gnatdll})
31915 The list of ALI and object files used to build the DLL are listed in
31916 @var{file}, instead of being given in the command line. Each line in
31917 @var{file} contains the name of an ALI or object file.
31920 @cindex @option{-n} (@code{gnatdll})
31921 No Import. Do not create the import library.
31924 @cindex @option{-q} (@code{gnatdll})
31925 Quiet mode. Do not display unnecessary messages.
31928 @cindex @option{-v} (@code{gnatdll})
31929 Verbose mode. Display extra information.
31931 @item -largs @var{opts}
31932 @cindex @option{-largs} (@code{gnatdll})
31933 Linker options. Pass @var{opts} to the linker.
31936 @node gnatdll Example
31937 @subsubsection @code{gnatdll} Example
31940 As an example the command to build a relocatable DLL from @file{api.adb}
31941 once @file{api.adb} has been compiled and @file{api.def} created is
31944 $ gnatdll -d api.dll api.ali
31948 The above command creates two files: @file{libapi.dll.a} (the import
31949 library) and @file{api.dll} (the actual DLL). If you want to create
31950 only the DLL, just type:
31953 $ gnatdll -d api.dll -n api.ali
31957 Alternatively if you want to create just the import library, type:
31960 $ gnatdll -d api.dll
31963 @node gnatdll behind the Scenes
31964 @subsubsection @code{gnatdll} behind the Scenes
31967 This section details the steps involved in creating a DLL. @code{gnatdll}
31968 does these steps for you. Unless you are interested in understanding what
31969 goes on behind the scenes, you should skip this section.
31971 We use the previous example of a DLL containing the Ada package @code{API},
31972 to illustrate the steps necessary to build a DLL. The starting point is a
31973 set of objects that will make up the DLL and the corresponding ALI
31974 files. In the case of this example this means that @file{api.o} and
31975 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
31980 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
31981 the information necessary to generate relocation information for the
31987 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
31992 In addition to the base file, the @command{gnatlink} command generates an
31993 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
31994 asks @command{gnatlink} to generate the routines @code{DllMain} and
31995 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
31996 is loaded into memory.
31999 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
32000 export table (@file{api.exp}). The export table contains the relocation
32001 information in a form which can be used during the final link to ensure
32002 that the Windows loader is able to place the DLL anywhere in memory.
32006 $ dlltool --dllname api.dll --def api.def --base-file api.base \
32007 --output-exp api.exp
32012 @code{gnatdll} builds the base file using the new export table. Note that
32013 @command{gnatbind} must be called once again since the binder generated file
32014 has been deleted during the previous call to @command{gnatlink}.
32019 $ gnatlink api -o api.jnk api.exp -mdll
32020 -Wl,--base-file,api.base
32025 @code{gnatdll} builds the new export table using the new base file and
32026 generates the DLL import library @file{libAPI.dll.a}.
32030 $ dlltool --dllname api.dll --def api.def --base-file api.base \
32031 --output-exp api.exp --output-lib libAPI.a
32036 Finally @code{gnatdll} builds the relocatable DLL using the final export
32042 $ gnatlink api api.exp -o api.dll -mdll
32047 @node Using dlltool
32048 @subsubsection Using @code{dlltool}
32051 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
32052 DLLs and static import libraries. This section summarizes the most
32053 common @code{dlltool} switches. The form of the @code{dlltool} command
32057 $ dlltool [@var{switches}]
32061 @code{dlltool} switches include:
32064 @item --base-file @var{basefile}
32065 @cindex @option{--base-file} (@command{dlltool})
32066 Read the base file @var{basefile} generated by the linker. This switch
32067 is used to create a relocatable DLL.
32069 @item --def @var{deffile}
32070 @cindex @option{--def} (@command{dlltool})
32071 Read the definition file.
32073 @item --dllname @var{name}
32074 @cindex @option{--dllname} (@command{dlltool})
32075 Gives the name of the DLL. This switch is used to embed the name of the
32076 DLL in the static import library generated by @code{dlltool} with switch
32077 @option{--output-lib}.
32080 @cindex @option{-k} (@command{dlltool})
32081 Kill @code{@@}@i{nn} from exported names
32082 (@pxref{Windows Calling Conventions}
32083 for a discussion about @code{Stdcall}-style symbols.
32086 @cindex @option{--help} (@command{dlltool})
32087 Prints the @code{dlltool} switches with a concise description.
32089 @item --output-exp @var{exportfile}
32090 @cindex @option{--output-exp} (@command{dlltool})
32091 Generate an export file @var{exportfile}. The export file contains the
32092 export table (list of symbols in the DLL) and is used to create the DLL.
32094 @item --output-lib @i{libfile}
32095 @cindex @option{--output-lib} (@command{dlltool})
32096 Generate a static import library @var{libfile}.
32099 @cindex @option{-v} (@command{dlltool})
32102 @item --as @i{assembler-name}
32103 @cindex @option{--as} (@command{dlltool})
32104 Use @i{assembler-name} as the assembler. The default is @code{as}.
32107 @node GNAT and Windows Resources
32108 @section GNAT and Windows Resources
32109 @cindex Resources, windows
32112 * Building Resources::
32113 * Compiling Resources::
32114 * Using Resources::
32118 Resources are an easy way to add Windows specific objects to your
32119 application. The objects that can be added as resources include:
32148 This section explains how to build, compile and use resources.
32150 @node Building Resources
32151 @subsection Building Resources
32152 @cindex Resources, building
32155 A resource file is an ASCII file. By convention resource files have an
32156 @file{.rc} extension.
32157 The easiest way to build a resource file is to use Microsoft tools
32158 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
32159 @code{dlgedit.exe} to build dialogs.
32160 It is always possible to build an @file{.rc} file yourself by writing a
32163 It is not our objective to explain how to write a resource file. A
32164 complete description of the resource script language can be found in the
32165 Microsoft documentation.
32167 @node Compiling Resources
32168 @subsection Compiling Resources
32171 @cindex Resources, compiling
32174 This section describes how to build a GNAT-compatible (COFF) object file
32175 containing the resources. This is done using the Resource Compiler
32176 @code{windres} as follows:
32179 $ windres -i myres.rc -o myres.o
32183 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
32184 file. You can specify an alternate preprocessor (usually named
32185 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
32186 parameter. A list of all possible options may be obtained by entering
32187 the command @code{windres} @option{--help}.
32189 It is also possible to use the Microsoft resource compiler @code{rc.exe}
32190 to produce a @file{.res} file (binary resource file). See the
32191 corresponding Microsoft documentation for further details. In this case
32192 you need to use @code{windres} to translate the @file{.res} file to a
32193 GNAT-compatible object file as follows:
32196 $ windres -i myres.res -o myres.o
32199 @node Using Resources
32200 @subsection Using Resources
32201 @cindex Resources, using
32204 To include the resource file in your program just add the
32205 GNAT-compatible object file for the resource(s) to the linker
32206 arguments. With @command{gnatmake} this is done by using the @option{-largs}
32210 $ gnatmake myprog -largs myres.o
32213 @node Debugging a DLL
32214 @section Debugging a DLL
32215 @cindex DLL debugging
32218 * Program and DLL Both Built with GCC/GNAT::
32219 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
32223 Debugging a DLL is similar to debugging a standard program. But
32224 we have to deal with two different executable parts: the DLL and the
32225 program that uses it. We have the following four possibilities:
32229 The program and the DLL are built with @code{GCC/GNAT}.
32231 The program is built with foreign tools and the DLL is built with
32234 The program is built with @code{GCC/GNAT} and the DLL is built with
32240 In this section we address only cases one and two above.
32241 There is no point in trying to debug
32242 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
32243 information in it. To do so you must use a debugger compatible with the
32244 tools suite used to build the DLL.
32246 @node Program and DLL Both Built with GCC/GNAT
32247 @subsection Program and DLL Both Built with GCC/GNAT
32250 This is the simplest case. Both the DLL and the program have @code{GDB}
32251 compatible debugging information. It is then possible to break anywhere in
32252 the process. Let's suppose here that the main procedure is named
32253 @code{ada_main} and that in the DLL there is an entry point named
32257 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
32258 program must have been built with the debugging information (see GNAT -g
32259 switch). Here are the step-by-step instructions for debugging it:
32262 @item Launch @code{GDB} on the main program.
32268 @item Start the program and stop at the beginning of the main procedure
32275 This step is required to be able to set a breakpoint inside the DLL. As long
32276 as the program is not run, the DLL is not loaded. This has the
32277 consequence that the DLL debugging information is also not loaded, so it is not
32278 possible to set a breakpoint in the DLL.
32280 @item Set a breakpoint inside the DLL
32283 (gdb) break ada_dll
32290 At this stage a breakpoint is set inside the DLL. From there on
32291 you can use the standard approach to debug the whole program
32292 (@pxref{Running and Debugging Ada Programs}).
32295 @c This used to work, probably because the DLLs were non-relocatable
32296 @c keep this section around until the problem is sorted out.
32298 To break on the @code{DllMain} routine it is not possible to follow
32299 the procedure above. At the time the program stop on @code{ada_main}
32300 the @code{DllMain} routine as already been called. Either you can use
32301 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
32304 @item Launch @code{GDB} on the main program.
32310 @item Load DLL symbols
32313 (gdb) add-sym api.dll
32316 @item Set a breakpoint inside the DLL
32319 (gdb) break ada_dll.adb:45
32322 Note that at this point it is not possible to break using the routine symbol
32323 directly as the program is not yet running. The solution is to break
32324 on the proper line (break in @file{ada_dll.adb} line 45).
32326 @item Start the program
32335 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
32336 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
32339 * Debugging the DLL Directly::
32340 * Attaching to a Running Process::
32344 In this case things are slightly more complex because it is not possible to
32345 start the main program and then break at the beginning to load the DLL and the
32346 associated DLL debugging information. It is not possible to break at the
32347 beginning of the program because there is no @code{GDB} debugging information,
32348 and therefore there is no direct way of getting initial control. This
32349 section addresses this issue by describing some methods that can be used
32350 to break somewhere in the DLL to debug it.
32353 First suppose that the main procedure is named @code{main} (this is for
32354 example some C code built with Microsoft Visual C) and that there is a
32355 DLL named @code{test.dll} containing an Ada entry point named
32359 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
32360 been built with debugging information (see GNAT -g option).
32362 @node Debugging the DLL Directly
32363 @subsubsection Debugging the DLL Directly
32367 Find out the executable starting address
32370 $ objdump --file-header main.exe
32373 The starting address is reported on the last line. For example:
32376 main.exe: file format pei-i386
32377 architecture: i386, flags 0x0000010a:
32378 EXEC_P, HAS_DEBUG, D_PAGED
32379 start address 0x00401010
32383 Launch the debugger on the executable.
32390 Set a breakpoint at the starting address, and launch the program.
32393 $ (gdb) break *0x00401010
32397 The program will stop at the given address.
32400 Set a breakpoint on a DLL subroutine.
32403 (gdb) break ada_dll.adb:45
32406 Or if you want to break using a symbol on the DLL, you need first to
32407 select the Ada language (language used by the DLL).
32410 (gdb) set language ada
32411 (gdb) break ada_dll
32415 Continue the program.
32422 This will run the program until it reaches the breakpoint that has been
32423 set. From that point you can use the standard way to debug a program
32424 as described in (@pxref{Running and Debugging Ada Programs}).
32429 It is also possible to debug the DLL by attaching to a running process.
32431 @node Attaching to a Running Process
32432 @subsubsection Attaching to a Running Process
32433 @cindex DLL debugging, attach to process
32436 With @code{GDB} it is always possible to debug a running process by
32437 attaching to it. It is possible to debug a DLL this way. The limitation
32438 of this approach is that the DLL must run long enough to perform the
32439 attach operation. It may be useful for instance to insert a time wasting
32440 loop in the code of the DLL to meet this criterion.
32444 @item Launch the main program @file{main.exe}.
32450 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
32451 that the process PID for @file{main.exe} is 208.
32459 @item Attach to the running process to be debugged.
32465 @item Load the process debugging information.
32468 (gdb) symbol-file main.exe
32471 @item Break somewhere in the DLL.
32474 (gdb) break ada_dll
32477 @item Continue process execution.
32486 This last step will resume the process execution, and stop at
32487 the breakpoint we have set. From there you can use the standard
32488 approach to debug a program as described in
32489 (@pxref{Running and Debugging Ada Programs}).
32491 @node Setting Stack Size from gnatlink
32492 @section Setting Stack Size from @command{gnatlink}
32495 It is possible to specify the program stack size at link time. On modern
32496 versions of Windows, starting with XP, this is mostly useful to set the size of
32497 the main stack (environment task). The other task stacks are set with pragma
32498 Storage_Size or with the @command{gnatbind -d} command.
32500 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
32501 reserve size of individual tasks, the link-time stack size applies to all
32502 tasks, and pragma Storage_Size has no effect.
32503 In particular, Stack Overflow checks are made against this
32504 link-time specified size.
32506 This setting can be done with
32507 @command{gnatlink} using either:
32511 @item using @option{-Xlinker} linker option
32514 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
32517 This sets the stack reserve size to 0x10000 bytes and the stack commit
32518 size to 0x1000 bytes.
32520 @item using @option{-Wl} linker option
32523 $ gnatlink hello -Wl,--stack=0x1000000
32526 This sets the stack reserve size to 0x1000000 bytes. Note that with
32527 @option{-Wl} option it is not possible to set the stack commit size
32528 because the coma is a separator for this option.
32532 @node Setting Heap Size from gnatlink
32533 @section Setting Heap Size from @command{gnatlink}
32536 Under Windows systems, it is possible to specify the program heap size from
32537 @command{gnatlink} using either:
32541 @item using @option{-Xlinker} linker option
32544 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
32547 This sets the heap reserve size to 0x10000 bytes and the heap commit
32548 size to 0x1000 bytes.
32550 @item using @option{-Wl} linker option
32553 $ gnatlink hello -Wl,--heap=0x1000000
32556 This sets the heap reserve size to 0x1000000 bytes. Note that with
32557 @option{-Wl} option it is not possible to set the heap commit size
32558 because the coma is a separator for this option.
32564 @c **********************************
32565 @c * GNU Free Documentation License *
32566 @c **********************************
32568 @c GNU Free Documentation License
32570 @node Index,,GNU Free Documentation License, Top
32576 @c Put table of contents at end, otherwise it precedes the "title page" in
32577 @c the .txt version
32578 @c Edit the pdf file to move the contents to the beginning, after the title