1 \input texinfo @c -*-texinfo-*-
3 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c GNAT DOCUMENTATION o
9 @c Copyright (C) 1992-2007, 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
94 @setfilename gnat_ugn_unw.info
99 @set FILE gnat_ugn_unw
103 @set PLATFORM OpenVMS
104 @set FILE gnat_ugn_vms
107 @settitle @value{EDITION} User's Guide @value{PLATFORM}
108 @dircategory GNU Ada tools
110 * @value{EDITION} User's Guide (@value{FILE}) @value{PLATFORM}
113 @include gcc-common.texi
115 @setchapternewpage odd
120 Copyright @copyright{} 1995-2005, 2006, 2007, 2008 Free Software Foundation,
123 Permission is granted to copy, distribute and/or modify this document
124 under the terms of the GNU Free Documentation License, Version 1.2
125 or any later version published by the Free Software Foundation;
126 with the Invariant Sections being ``GNU Free Documentation License'', with the
127 Front-Cover Texts being
128 ``@value{EDITION} User's Guide'',
129 and with no Back-Cover Texts.
130 A copy of the license is included in the section entitled
131 ``GNU Free Documentation License''.
135 @title @value{EDITION} User's Guide
139 @titlefont{@i{@value{PLATFORM}}}
145 @subtitle GNAT, The GNU Ada Compiler
150 @vskip 0pt plus 1filll
157 @node Top, About This Guide, (dir), (dir)
158 @top @value{EDITION} User's Guide
161 @value{EDITION} User's Guide @value{PLATFORM}
164 GNAT, The GNU Ada Compiler@*
165 GCC version @value{version-GCC}@*
172 * Getting Started with GNAT::
173 * The GNAT Compilation Model::
174 * Compiling Using gcc::
175 * Binding Using gnatbind::
176 * Linking Using gnatlink::
177 * The GNAT Make Program gnatmake::
178 * Improving Performance::
179 * Renaming Files Using gnatchop::
180 * Configuration Pragmas::
181 * Handling Arbitrary File Naming Conventions Using gnatname::
182 * GNAT Project Manager::
183 * The Cross-Referencing Tools gnatxref and gnatfind::
184 * The GNAT Pretty-Printer gnatpp::
185 * The GNAT Metric Tool gnatmetric::
186 * File Name Krunching Using gnatkr::
187 * Preprocessing Using gnatprep::
189 * The GNAT Run-Time Library Builder gnatlbr::
191 * The GNAT Library Browser gnatls::
192 * Cleaning Up Using gnatclean::
194 * GNAT and Libraries::
195 * Using the GNU make Utility::
197 * Memory Management Issues::
198 * Stack Related Facilities::
199 * Verifying Properties Using gnatcheck::
200 * Creating Sample Bodies Using gnatstub::
201 * Other Utility Programs::
202 * Running and Debugging Ada Programs::
204 * Compatibility with HP Ada::
206 * Platform-Specific Information for the Run-Time Libraries::
207 * Example of Binder Output File::
208 * Elaboration Order Handling in GNAT::
209 * Conditional Compilation::
211 * Compatibility and Porting Guide::
213 * Microsoft Windows Topics::
215 * GNU Free Documentation License::
218 --- The Detailed Node Listing ---
222 * What This Guide Contains::
223 * What You Should Know before Reading This Guide::
224 * Related Information::
227 Getting Started with GNAT
230 * Running a Simple Ada Program::
231 * Running a Program with Multiple Units::
232 * Using the gnatmake Utility::
234 * Editing with Emacs::
237 * Introduction to GPS::
240 The GNAT Compilation Model
242 * Source Representation::
243 * Foreign Language Representation::
244 * File Naming Rules::
245 * Using Other File Names::
246 * Alternative File Naming Schemes::
247 * Generating Object Files::
248 * Source Dependencies::
249 * The Ada Library Information Files::
250 * Binding an Ada Program::
251 * Mixed Language Programming::
253 * Building Mixed Ada & C++ Programs::
254 * Comparison between GNAT and C/C++ Compilation Models::
256 * Comparison between GNAT and Conventional Ada Library Models::
258 * Placement of temporary files::
261 Foreign Language Representation
264 * Other 8-Bit Codes::
265 * Wide Character Encodings::
267 Compiling Ada Programs With gcc
269 * Compiling Programs::
271 * Search Paths and the Run-Time Library (RTL)::
272 * Order of Compilation Issues::
277 * Output and Error Message Control::
278 * Warning Message Control::
279 * Debugging and Assertion Control::
280 * Validity Checking::
283 * Using gcc for Syntax Checking::
284 * Using gcc for Semantic Checking::
285 * Compiling Different Versions of Ada::
286 * Character Set Control::
287 * File Naming Control::
288 * Subprogram Inlining Control::
289 * Auxiliary Output Control::
290 * Debugging Control::
291 * Exception Handling Control::
292 * Units to Sources Mapping Files::
293 * Integrated Preprocessing::
298 Binding Ada Programs With gnatbind
301 * Switches for gnatbind::
302 * Command-Line Access::
303 * Search Paths for gnatbind::
304 * Examples of gnatbind Usage::
306 Switches for gnatbind
308 * Consistency-Checking Modes::
309 * Binder Error Message Control::
310 * Elaboration Control::
312 * Binding with Non-Ada Main Programs::
313 * Binding Programs with No Main Subprogram::
315 Linking Using gnatlink
318 * Switches for gnatlink::
320 The GNAT Make Program gnatmake
323 * Switches for gnatmake::
324 * Mode Switches for gnatmake::
325 * Notes on the Command Line::
326 * How gnatmake Works::
327 * Examples of gnatmake Usage::
329 Improving Performance
330 * Performance Considerations::
331 * Reducing Size of Ada Executables with gnatelim::
332 * Reducing Size of Executables with unused subprogram/data elimination::
334 Performance Considerations
335 * Controlling Run-Time Checks::
336 * Use of Restrictions::
337 * Optimization Levels::
338 * Debugging Optimized Code::
339 * Inlining of Subprograms::
340 * Other Optimization Switches::
341 * Optimization and Strict Aliasing::
343 * Coverage Analysis::
346 Reducing Size of Ada Executables with gnatelim
349 * Correcting the List of Eliminate Pragmas::
350 * Making Your Executables Smaller::
351 * Summary of the gnatelim Usage Cycle::
353 Reducing Size of Executables with unused subprogram/data elimination
354 * About unused subprogram/data elimination::
355 * Compilation options::
357 Renaming Files Using gnatchop
359 * Handling Files with Multiple Units::
360 * Operating gnatchop in Compilation Mode::
361 * Command Line for gnatchop::
362 * Switches for gnatchop::
363 * Examples of gnatchop Usage::
365 Configuration Pragmas
367 * Handling of Configuration Pragmas::
368 * The Configuration Pragmas Files::
370 Handling Arbitrary File Naming Conventions Using gnatname
372 * Arbitrary File Naming Conventions::
374 * Switches for gnatname::
375 * Examples of gnatname Usage::
380 * Examples of Project Files::
381 * Project File Syntax::
382 * Objects and Sources in Project Files::
383 * Importing Projects::
384 * Project Extension::
385 * Project Hierarchy Extension::
386 * External References in Project Files::
387 * Packages in Project Files::
388 * Variables from Imported Projects::
391 * Stand-alone Library Projects::
392 * Switches Related to Project Files::
393 * Tools Supporting Project Files::
394 * An Extended Example::
395 * Project File Complete Syntax::
397 The Cross-Referencing Tools gnatxref and gnatfind
399 * gnatxref Switches::
400 * gnatfind Switches::
401 * Project Files for gnatxref and gnatfind::
402 * Regular Expressions in gnatfind and gnatxref::
403 * Examples of gnatxref Usage::
404 * Examples of gnatfind Usage::
406 The GNAT Pretty-Printer gnatpp
408 * Switches for gnatpp::
411 The GNAT Metrics Tool gnatmetric
413 * Switches for gnatmetric::
415 File Name Krunching Using gnatkr
420 * Examples of gnatkr Usage::
422 Preprocessing Using gnatprep
424 * Switches for gnatprep::
425 * Form of Definitions File::
426 * Form of Input Text for gnatprep::
429 The GNAT Run-Time Library Builder gnatlbr
432 * Switches for gnatlbr::
433 * Examples of gnatlbr Usage::
436 The GNAT Library Browser gnatls
439 * Switches for gnatls::
440 * Examples of gnatls Usage::
442 Cleaning Up Using gnatclean
444 * Running gnatclean::
445 * Switches for gnatclean::
446 @c * Examples of gnatclean Usage::
452 * Introduction to Libraries in GNAT::
453 * General Ada Libraries::
454 * Stand-alone Ada Libraries::
455 * Rebuilding the GNAT Run-Time Library::
457 Using the GNU make Utility
459 * Using gnatmake in a Makefile::
460 * Automatically Creating a List of Directories::
461 * Generating the Command Line Switches::
462 * Overcoming Command Line Length Limits::
465 Memory Management Issues
467 * Some Useful Memory Pools::
468 * The GNAT Debug Pool Facility::
473 Stack Related Facilities
475 * Stack Overflow Checking::
476 * Static Stack Usage Analysis::
477 * Dynamic Stack Usage Analysis::
479 Some Useful Memory Pools
481 The GNAT Debug Pool Facility
487 * Switches for gnatmem::
488 * Example of gnatmem Usage::
491 Verifying Properties Using gnatcheck
493 * Format of the Report File::
494 * General gnatcheck Switches::
495 * gnatcheck Rule Options::
496 * Adding the Results of Compiler Checks to gnatcheck Output::
497 * Project-Wide Checks::
500 Sample Bodies Using gnatstub
503 * Switches for gnatstub::
505 Other Utility Programs
507 * Using Other Utility Programs with GNAT::
508 * The External Symbol Naming Scheme of GNAT::
509 * Converting Ada Files to html with gnathtml::
511 Running and Debugging Ada Programs
513 * The GNAT Debugger GDB::
515 * Introduction to GDB Commands::
516 * Using Ada Expressions::
517 * Calling User-Defined Subprograms::
518 * Using the Next Command in a Function::
521 * Debugging Generic Units::
522 * GNAT Abnormal Termination or Failure to Terminate::
523 * Naming Conventions for GNAT Source Files::
524 * Getting Internal Debugging Information::
532 Compatibility with HP Ada
534 * Ada Language Compatibility::
535 * Differences in the Definition of Package System::
536 * Language-Related Features::
537 * The Package STANDARD::
538 * The Package SYSTEM::
539 * Tasking and Task-Related Features::
540 * Pragmas and Pragma-Related Features::
541 * Library of Predefined Units::
543 * Main Program Definition::
544 * Implementation-Defined Attributes::
545 * Compiler and Run-Time Interfacing::
546 * Program Compilation and Library Management::
548 * Implementation Limits::
549 * Tools and Utilities::
551 Language-Related Features
553 * Integer Types and Representations::
554 * Floating-Point Types and Representations::
555 * Pragmas Float_Representation and Long_Float::
556 * Fixed-Point Types and Representations::
557 * Record and Array Component Alignment::
559 * Other Representation Clauses::
561 Tasking and Task-Related Features
563 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
564 * Assigning Task IDs::
565 * Task IDs and Delays::
566 * Task-Related Pragmas::
567 * Scheduling and Task Priority::
569 * External Interrupts::
571 Pragmas and Pragma-Related Features
573 * Restrictions on the Pragma INLINE::
574 * Restrictions on the Pragma INTERFACE::
575 * Restrictions on the Pragma SYSTEM_NAME::
577 Library of Predefined Units
579 * Changes to DECLIB::
583 * Shared Libraries and Options Files::
587 Platform-Specific Information for the Run-Time Libraries
589 * Summary of Run-Time Configurations::
590 * Specifying a Run-Time Library::
591 * Choosing the Scheduling Policy::
592 * Solaris-Specific Considerations::
593 * Linux-Specific Considerations::
594 * AIX-Specific Considerations::
596 Example of Binder Output File
598 Elaboration Order Handling in GNAT
601 * Checking the Elaboration Order::
602 * Controlling the Elaboration Order::
603 * Controlling Elaboration in GNAT - Internal Calls::
604 * Controlling Elaboration in GNAT - External Calls::
605 * Default Behavior in GNAT - Ensuring Safety::
606 * Treatment of Pragma Elaborate::
607 * Elaboration Issues for Library Tasks::
608 * Mixing Elaboration Models::
609 * What to Do If the Default Elaboration Behavior Fails::
610 * Elaboration for Access-to-Subprogram Values::
611 * Summary of Procedures for Elaboration Control::
612 * Other Elaboration Order Considerations::
614 Conditional Compilation
615 * Use of Boolean Constants::
616 * Debugging - A Special Case::
617 * Conditionalizing Declarations::
618 * Use of Alternative Implementations::
623 * Basic Assembler Syntax::
624 * A Simple Example of Inline Assembler::
625 * Output Variables in Inline Assembler::
626 * Input Variables in Inline Assembler::
627 * Inlining Inline Assembler Code::
628 * Other Asm Functionality::
630 Compatibility and Porting Guide
632 * Compatibility with Ada 83::
633 * Compatibility between Ada 95 and Ada 2005::
634 * Implementation-dependent characteristics::
636 @c This brief section is only in the non-VMS version
637 @c The complete chapter on HP Ada issues is in the VMS version
638 * Compatibility with HP Ada 83::
640 * Compatibility with Other Ada Systems::
641 * Representation Clauses::
643 * Transitioning to 64-Bit GNAT for OpenVMS::
647 Microsoft Windows Topics
649 * Using GNAT on Windows::
650 * CONSOLE and WINDOWS subsystems::
652 * Mixed-Language Programming on Windows::
653 * Windows Calling Conventions::
654 * Introduction to Dynamic Link Libraries (DLLs)::
655 * Using DLLs with GNAT::
656 * Building DLLs with GNAT::
657 * GNAT and Windows Resources::
659 * Setting Stack Size from gnatlink::
660 * Setting Heap Size from gnatlink::
667 @node About This Guide
668 @unnumbered About This Guide
672 This guide describes the use of @value{EDITION},
673 a compiler and software development toolset for the full Ada
674 programming language, implemented on OpenVMS for HP's Alpha and
675 Integrity server (I64) platforms.
678 This guide describes the use of @value{EDITION},
679 a compiler and software development
680 toolset for the full Ada programming language.
682 It documents the features of the compiler and tools, and explains
683 how to use them to build Ada applications.
685 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
686 Ada 83 compatibility mode.
687 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
688 but you can override with a compiler switch
689 (@pxref{Compiling Different Versions of Ada})
690 to explicitly specify the language version.
691 Throughout this manual, references to ``Ada'' without a year suffix
692 apply to both the Ada 95 and Ada 2005 versions of the language.
696 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
697 ``GNAT'' in the remainder of this document.
704 * What This Guide Contains::
705 * What You Should Know before Reading This Guide::
706 * Related Information::
710 @node What This Guide Contains
711 @unnumberedsec What This Guide Contains
714 This guide contains the following chapters:
718 @ref{Getting Started with GNAT}, describes how to get started compiling
719 and running Ada programs with the GNAT Ada programming environment.
721 @ref{The GNAT Compilation Model}, describes the compilation model used
725 @ref{Compiling Using gcc}, describes how to compile
726 Ada programs with @command{gcc}, the Ada compiler.
729 @ref{Binding Using gnatbind}, describes how to
730 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
734 @ref{Linking Using gnatlink},
735 describes @command{gnatlink}, a
736 program that provides for linking using the GNAT run-time library to
737 construct a program. @command{gnatlink} can also incorporate foreign language
738 object units into the executable.
741 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
742 utility that automatically determines the set of sources
743 needed by an Ada compilation unit, and executes the necessary compilations
747 @ref{Improving Performance}, shows various techniques for making your
748 Ada program run faster or take less space.
749 It discusses the effect of the compiler's optimization switch and
750 also describes the @command{gnatelim} tool and unused subprogram/data
754 @ref{Renaming Files Using gnatchop}, describes
755 @code{gnatchop}, a utility that allows you to preprocess a file that
756 contains Ada source code, and split it into one or more new files, one
757 for each compilation unit.
760 @ref{Configuration Pragmas}, describes the configuration pragmas
764 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
765 shows how to override the default GNAT file naming conventions,
766 either for an individual unit or globally.
769 @ref{GNAT Project Manager}, describes how to use project files
770 to organize large projects.
773 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
774 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
775 way to navigate through sources.
778 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
779 version of an Ada source file with control over casing, indentation,
780 comment placement, and other elements of program presentation style.
783 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
784 metrics for an Ada source file, such as the number of types and subprograms,
785 and assorted complexity measures.
788 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
789 file name krunching utility, used to handle shortened
790 file names on operating systems with a limit on the length of names.
793 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
794 preprocessor utility that allows a single source file to be used to
795 generate multiple or parameterized source files by means of macro
800 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
801 a tool for rebuilding the GNAT run time with user-supplied
802 configuration pragmas.
806 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
807 utility that displays information about compiled units, including dependences
808 on the corresponding sources files, and consistency of compilations.
811 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
812 to delete files that are produced by the compiler, binder and linker.
816 @ref{GNAT and Libraries}, describes the process of creating and using
817 Libraries with GNAT. It also describes how to recompile the GNAT run-time
821 @ref{Using the GNU make Utility}, describes some techniques for using
822 the GNAT toolset in Makefiles.
826 @ref{Memory Management Issues}, describes some useful predefined storage pools
827 and in particular the GNAT Debug Pool facility, which helps detect incorrect
830 It also describes @command{gnatmem}, a utility that monitors dynamic
831 allocation and deallocation and helps detect ``memory leaks''.
835 @ref{Stack Related Facilities}, describes some useful tools associated with
836 stack checking and analysis.
839 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
840 a utility that checks Ada code against a set of rules.
843 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
844 a utility that generates empty but compilable bodies for library units.
847 @ref{Other Utility Programs}, discusses several other GNAT utilities,
848 including @code{gnathtml}.
851 @ref{Running and Debugging Ada Programs}, describes how to run and debug
856 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
857 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
858 developed by Digital Equipment Corporation and currently supported by HP.}
859 for OpenVMS Alpha. This product was formerly known as DEC Ada,
862 historical compatibility reasons, the relevant libraries still use the
867 @ref{Platform-Specific Information for the Run-Time Libraries},
868 describes the various run-time
869 libraries supported by GNAT on various platforms and explains how to
870 choose a particular library.
873 @ref{Example of Binder Output File}, shows the source code for the binder
874 output file for a sample program.
877 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
878 you deal with elaboration order issues.
881 @ref{Conditional Compilation}, describes how to model conditional compilation,
882 both with Ada in general and with GNAT facilities in particular.
885 @ref{Inline Assembler}, shows how to use the inline assembly facility
889 @ref{Compatibility and Porting Guide}, contains sections on compatibility
890 of GNAT with other Ada development environments (including Ada 83 systems),
891 to assist in porting code from those environments.
895 @ref{Microsoft Windows Topics}, presents information relevant to the
896 Microsoft Windows platform.
900 @c *************************************************
901 @node What You Should Know before Reading This Guide
902 @c *************************************************
903 @unnumberedsec What You Should Know before Reading This Guide
905 @cindex Ada 95 Language Reference Manual
906 @cindex Ada 2005 Language Reference Manual
908 This guide assumes a basic familiarity with the Ada 95 language, as
909 described in the International Standard ANSI/ISO/IEC-8652:1995, January
911 It does not require knowledge of the new features introduced by Ada 2005,
912 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
914 Both reference manuals are included in the GNAT documentation
917 @node Related Information
918 @unnumberedsec Related Information
921 For further information about related tools, refer to the following
926 @cite{GNAT Reference Manual}, which contains all reference
927 material for the GNAT implementation of Ada.
931 @cite{Using the GNAT Programming Studio}, which describes the GPS
932 Integrated Development Environment.
935 @cite{GNAT Programming Studio Tutorial}, which introduces the
936 main GPS features through examples.
940 @cite{Ada 95 Reference Manual}, which contains reference
941 material for the Ada 95 programming language.
944 @cite{Ada 2005 Reference Manual}, which contains reference
945 material for the Ada 2005 programming language.
948 @cite{Debugging with GDB}
950 , located in the GNU:[DOCS] directory,
952 contains all details on the use of the GNU source-level debugger.
955 @cite{GNU Emacs Manual}
957 , located in the GNU:[DOCS] directory if the EMACS kit is installed,
959 contains full information on the extensible editor and programming
966 @unnumberedsec Conventions
968 @cindex Typographical conventions
971 Following are examples of the typographical and graphic conventions used
976 @code{Functions}, @code{utility program names}, @code{standard names},
983 @file{File Names}, @file{button names}, and @file{field names}.
992 [optional information or parameters]
995 Examples are described by text
997 and then shown this way.
1002 Commands that are entered by the user are preceded in this manual by the
1003 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1004 uses this sequence as a prompt, then the commands will appear exactly as
1005 you see them in the manual. If your system uses some other prompt, then
1006 the command will appear with the @code{$} replaced by whatever prompt
1007 character you are using.
1010 Full file names are shown with the ``@code{/}'' character
1011 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1012 If you are using GNAT on a Windows platform, please note that
1013 the ``@code{\}'' character should be used instead.
1016 @c ****************************
1017 @node Getting Started with GNAT
1018 @chapter Getting Started with GNAT
1021 This chapter describes some simple ways of using GNAT to build
1022 executable Ada programs.
1024 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1025 show how to use the command line environment.
1026 @ref{Introduction to GPS}, provides a brief
1027 introduction to the GNAT Programming Studio, a visually-oriented
1028 Integrated Development Environment for GNAT.
1029 GPS offers a graphical ``look and feel'', support for development in
1030 other programming languages, comprehensive browsing features, and
1031 many other capabilities.
1032 For information on GPS please refer to
1033 @cite{Using the GNAT Programming Studio}.
1038 * Running a Simple Ada Program::
1039 * Running a Program with Multiple Units::
1040 * Using the gnatmake Utility::
1042 * Editing with Emacs::
1045 * Introduction to GPS::
1050 @section Running GNAT
1053 Three steps are needed to create an executable file from an Ada source
1058 The source file(s) must be compiled.
1060 The file(s) must be bound using the GNAT binder.
1062 All appropriate object files must be linked to produce an executable.
1066 All three steps are most commonly handled by using the @command{gnatmake}
1067 utility program that, given the name of the main program, automatically
1068 performs the necessary compilation, binding and linking steps.
1070 @node Running a Simple Ada Program
1071 @section Running a Simple Ada Program
1074 Any text editor may be used to prepare an Ada program.
1076 used, the optional Ada mode may be helpful in laying out the program.)
1078 program text is a normal text file. We will assume in our initial
1079 example that you have used your editor to prepare the following
1080 standard format text file:
1082 @smallexample @c ada
1084 with Ada.Text_IO; use Ada.Text_IO;
1087 Put_Line ("Hello WORLD!");
1093 This file should be named @file{hello.adb}.
1094 With the normal default file naming conventions, GNAT requires
1096 contain a single compilation unit whose file name is the
1098 with periods replaced by hyphens; the
1099 extension is @file{ads} for a
1100 spec and @file{adb} for a body.
1101 You can override this default file naming convention by use of the
1102 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1103 Alternatively, if you want to rename your files according to this default
1104 convention, which is probably more convenient if you will be using GNAT
1105 for all your compilations, then the @code{gnatchop} utility
1106 can be used to generate correctly-named source files
1107 (@pxref{Renaming Files Using gnatchop}).
1109 You can compile the program using the following command (@code{$} is used
1110 as the command prompt in the examples in this document):
1117 @command{gcc} is the command used to run the compiler. This compiler is
1118 capable of compiling programs in several languages, including Ada and
1119 C. It assumes that you have given it an Ada program if the file extension is
1120 either @file{.ads} or @file{.adb}, and it will then call
1121 the GNAT compiler to compile the specified file.
1124 The @option{-c} switch is required. It tells @command{gcc} to only do a
1125 compilation. (For C programs, @command{gcc} can also do linking, but this
1126 capability is not used directly for Ada programs, so the @option{-c}
1127 switch must always be present.)
1130 This compile command generates a file
1131 @file{hello.o}, which is the object
1132 file corresponding to your Ada program. It also generates
1133 an ``Ada Library Information'' file @file{hello.ali},
1134 which contains additional information used to check
1135 that an Ada program is consistent.
1136 To build an executable file,
1137 use @code{gnatbind} to bind the program
1138 and @command{gnatlink} to link it. The
1139 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1140 @file{ALI} file, but the default extension of @file{.ali} can
1141 be omitted. This means that in the most common case, the argument
1142 is simply the name of the main program:
1150 A simpler method of carrying out these steps is to use
1152 a master program that invokes all the required
1153 compilation, binding and linking tools in the correct order. In particular,
1154 @command{gnatmake} automatically recompiles any sources that have been
1155 modified since they were last compiled, or sources that depend
1156 on such modified sources, so that ``version skew'' is avoided.
1157 @cindex Version skew (avoided by @command{gnatmake})
1160 $ gnatmake hello.adb
1164 The result is an executable program called @file{hello}, which can be
1172 assuming that the current directory is on the search path
1173 for executable programs.
1176 and, if all has gone well, you will see
1183 appear in response to this command.
1185 @c ****************************************
1186 @node Running a Program with Multiple Units
1187 @section Running a Program with Multiple Units
1190 Consider a slightly more complicated example that has three files: a
1191 main program, and the spec and body of a package:
1193 @smallexample @c ada
1196 package Greetings is
1201 with Ada.Text_IO; use Ada.Text_IO;
1202 package body Greetings is
1205 Put_Line ("Hello WORLD!");
1208 procedure Goodbye is
1210 Put_Line ("Goodbye WORLD!");
1227 Following the one-unit-per-file rule, place this program in the
1228 following three separate files:
1232 spec of package @code{Greetings}
1235 body of package @code{Greetings}
1238 body of main program
1242 To build an executable version of
1243 this program, we could use four separate steps to compile, bind, and link
1244 the program, as follows:
1248 $ gcc -c greetings.adb
1254 Note that there is no required order of compilation when using GNAT.
1255 In particular it is perfectly fine to compile the main program first.
1256 Also, it is not necessary to compile package specs in the case where
1257 there is an accompanying body; you only need to compile the body. If you want
1258 to submit these files to the compiler for semantic checking and not code
1259 generation, then use the
1260 @option{-gnatc} switch:
1263 $ gcc -c greetings.ads -gnatc
1267 Although the compilation can be done in separate steps as in the
1268 above example, in practice it is almost always more convenient
1269 to use the @command{gnatmake} tool. All you need to know in this case
1270 is the name of the main program's source file. The effect of the above four
1271 commands can be achieved with a single one:
1274 $ gnatmake gmain.adb
1278 In the next section we discuss the advantages of using @command{gnatmake} in
1281 @c *****************************
1282 @node Using the gnatmake Utility
1283 @section Using the @command{gnatmake} Utility
1286 If you work on a program by compiling single components at a time using
1287 @command{gcc}, you typically keep track of the units you modify. In order to
1288 build a consistent system, you compile not only these units, but also any
1289 units that depend on the units you have modified.
1290 For example, in the preceding case,
1291 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1292 you edit @file{greetings.ads}, you must recompile both
1293 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1294 units that depend on @file{greetings.ads}.
1296 @code{gnatbind} will warn you if you forget one of these compilation
1297 steps, so that it is impossible to generate an inconsistent program as a
1298 result of forgetting to do a compilation. Nevertheless it is tedious and
1299 error-prone to keep track of dependencies among units.
1300 One approach to handle the dependency-bookkeeping is to use a
1301 makefile. However, makefiles present maintenance problems of their own:
1302 if the dependencies change as you change the program, you must make
1303 sure that the makefile is kept up-to-date manually, which is also an
1304 error-prone process.
1306 The @command{gnatmake} utility takes care of these details automatically.
1307 Invoke it using either one of the following forms:
1310 $ gnatmake gmain.adb
1311 $ gnatmake ^gmain^GMAIN^
1315 The argument is the name of the file containing the main program;
1316 you may omit the extension. @command{gnatmake}
1317 examines the environment, automatically recompiles any files that need
1318 recompiling, and binds and links the resulting set of object files,
1319 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1320 In a large program, it
1321 can be extremely helpful to use @command{gnatmake}, because working out by hand
1322 what needs to be recompiled can be difficult.
1324 Note that @command{gnatmake}
1325 takes into account all the Ada rules that
1326 establish dependencies among units. These include dependencies that result
1327 from inlining subprogram bodies, and from
1328 generic instantiation. Unlike some other
1329 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1330 found by the compiler on a previous compilation, which may possibly
1331 be wrong when sources change. @command{gnatmake} determines the exact set of
1332 dependencies from scratch each time it is run.
1335 @node Editing with Emacs
1336 @section Editing with Emacs
1340 Emacs is an extensible self-documenting text editor that is available in a
1341 separate VMSINSTAL kit.
1343 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1344 click on the Emacs Help menu and run the Emacs Tutorial.
1345 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1346 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1348 Documentation on Emacs and other tools is available in Emacs under the
1349 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1350 use the middle mouse button to select a topic (e.g. Emacs).
1352 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1353 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1354 get to the Emacs manual.
1355 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1358 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1359 which is sufficiently extensible to provide for a complete programming
1360 environment and shell for the sophisticated user.
1364 @node Introduction to GPS
1365 @section Introduction to GPS
1366 @cindex GPS (GNAT Programming Studio)
1367 @cindex GNAT Programming Studio (GPS)
1369 Although the command line interface (@command{gnatmake}, etc.) alone
1370 is sufficient, a graphical Interactive Development
1371 Environment can make it easier for you to compose, navigate, and debug
1372 programs. This section describes the main features of GPS
1373 (``GNAT Programming Studio''), the GNAT graphical IDE.
1374 You will see how to use GPS to build and debug an executable, and
1375 you will also learn some of the basics of the GNAT ``project'' facility.
1377 GPS enables you to do much more than is presented here;
1378 e.g., you can produce a call graph, interface to a third-party
1379 Version Control System, and inspect the generated assembly language
1381 Indeed, GPS also supports languages other than Ada.
1382 Such additional information, and an explanation of all of the GPS menu
1383 items. may be found in the on-line help, which includes
1384 a user's guide and a tutorial (these are also accessible from the GNAT
1388 * Building a New Program with GPS::
1389 * Simple Debugging with GPS::
1392 @node Building a New Program with GPS
1393 @subsection Building a New Program with GPS
1395 GPS invokes the GNAT compilation tools using information
1396 contained in a @emph{project} (also known as a @emph{project file}):
1397 a collection of properties such
1398 as source directories, identities of main subprograms, tool switches, etc.,
1399 and their associated values.
1400 See @ref{GNAT Project Manager} for details.
1401 In order to run GPS, you will need to either create a new project
1402 or else open an existing one.
1404 This section will explain how you can use GPS to create a project,
1405 to associate Ada source files with a project, and to build and run
1409 @item @emph{Creating a project}
1411 Invoke GPS, either from the command line or the platform's IDE.
1412 After it starts, GPS will display a ``Welcome'' screen with three
1417 @code{Start with default project in directory}
1420 @code{Create new project with wizard}
1423 @code{Open existing project}
1427 Select @code{Create new project with wizard} and press @code{OK}.
1428 A new window will appear. In the text box labeled with
1429 @code{Enter the name of the project to create}, type @file{sample}
1430 as the project name.
1431 In the next box, browse to choose the directory in which you
1432 would like to create the project file.
1433 After selecting an appropriate directory, press @code{Forward}.
1435 A window will appear with the title
1436 @code{Version Control System Configuration}.
1437 Simply press @code{Forward}.
1439 A window will appear with the title
1440 @code{Please select the source directories for this project}.
1441 The directory that you specified for the project file will be selected
1442 by default as the one to use for sources; simply press @code{Forward}.
1444 A window will appear with the title
1445 @code{Please select the build directory for this project}.
1446 The directory that you specified for the project file will be selected
1447 by default for object files and executables;
1448 simply press @code{Forward}.
1450 A window will appear with the title
1451 @code{Please select the main units for this project}.
1452 You will supply this information later, after creating the source file.
1453 Simply press @code{Forward} for now.
1455 A window will appear with the title
1456 @code{Please select the switches to build the project}.
1457 Press @code{Apply}. This will create a project file named
1458 @file{sample.prj} in the directory that you had specified.
1460 @item @emph{Creating and saving the source file}
1462 After you create the new project, a GPS window will appear, which is
1463 partitioned into two main sections:
1467 A @emph{Workspace area}, initially greyed out, which you will use for
1468 creating and editing source files
1471 Directly below, a @emph{Messages area}, which initially displays a
1472 ``Welcome'' message.
1473 (If the Messages area is not visible, drag its border upward to expand it.)
1477 Select @code{File} on the menu bar, and then the @code{New} command.
1478 The Workspace area will become white, and you can now
1479 enter the source program explicitly.
1480 Type the following text
1482 @smallexample @c ada
1484 with Ada.Text_IO; use Ada.Text_IO;
1487 Put_Line("Hello from GPS!");
1493 Select @code{File}, then @code{Save As}, and enter the source file name
1495 The file will be saved in the same directory you specified as the
1496 location of the default project file.
1498 @item @emph{Updating the project file}
1500 You need to add the new source file to the project.
1502 the @code{Project} menu and then @code{Edit project properties}.
1503 Click the @code{Main files} tab on the left, and then the
1505 Choose @file{hello.adb} from the list, and press @code{Open}.
1506 The project settings window will reflect this action.
1509 @item @emph{Building and running the program}
1511 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1512 and select @file{hello.adb}.
1513 The Messages window will display the resulting invocations of @command{gcc},
1514 @command{gnatbind}, and @command{gnatlink}
1515 (reflecting the default switch settings from the
1516 project file that you created) and then a ``successful compilation/build''
1519 To run the program, choose the @code{Build} menu, then @code{Run}, and
1520 select @command{hello}.
1521 An @emph{Arguments Selection} window will appear.
1522 There are no command line arguments, so just click @code{OK}.
1524 The Messages window will now display the program's output (the string
1525 @code{Hello from GPS}), and at the bottom of the GPS window a status
1526 update is displayed (@code{Run: hello}).
1527 Close the GPS window (or select @code{File}, then @code{Exit}) to
1528 terminate this GPS session.
1531 @node Simple Debugging with GPS
1532 @subsection Simple Debugging with GPS
1534 This section illustrates basic debugging techniques (setting breakpoints,
1535 examining/modifying variables, single stepping).
1538 @item @emph{Opening a project}
1540 Start GPS and select @code{Open existing project}; browse to
1541 specify the project file @file{sample.prj} that you had created in the
1544 @item @emph{Creating a source file}
1546 Select @code{File}, then @code{New}, and type in the following program:
1548 @smallexample @c ada
1550 with Ada.Text_IO; use Ada.Text_IO;
1551 procedure Example is
1552 Line : String (1..80);
1555 Put_Line("Type a line of text at each prompt; an empty line to exit");
1559 Put_Line (Line (1..N) );
1567 Select @code{File}, then @code{Save as}, and enter the file name
1570 @item @emph{Updating the project file}
1572 Add @code{Example} as a new main unit for the project:
1575 Select @code{Project}, then @code{Edit Project Properties}.
1578 Select the @code{Main files} tab, click @code{Add}, then
1579 select the file @file{example.adb} from the list, and
1581 You will see the file name appear in the list of main units
1587 @item @emph{Building/running the executable}
1589 To build the executable
1590 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1592 Run the program to see its effect (in the Messages area).
1593 Each line that you enter is displayed; an empty line will
1594 cause the loop to exit and the program to terminate.
1596 @item @emph{Debugging the program}
1598 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1599 which are required for debugging, are on by default when you create
1601 Thus unless you intentionally remove these settings, you will be able
1602 to debug any program that you develop using GPS.
1605 @item @emph{Initializing}
1607 Select @code{Debug}, then @code{Initialize}, then @file{example}
1609 @item @emph{Setting a breakpoint}
1611 After performing the initialization step, you will observe a small
1612 icon to the right of each line number.
1613 This serves as a toggle for breakpoints; clicking the icon will
1614 set a breakpoint at the corresponding line (the icon will change to
1615 a red circle with an ``x''), and clicking it again
1616 will remove the breakpoint / reset the icon.
1618 For purposes of this example, set a breakpoint at line 10 (the
1619 statement @code{Put_Line@ (Line@ (1..N));}
1621 @item @emph{Starting program execution}
1623 Select @code{Debug}, then @code{Run}. When the
1624 @code{Program Arguments} window appears, click @code{OK}.
1625 A console window will appear; enter some line of text,
1626 e.g. @code{abcde}, at the prompt.
1627 The program will pause execution when it gets to the
1628 breakpoint, and the corresponding line is highlighted.
1630 @item @emph{Examining a variable}
1632 Move the mouse over one of the occurrences of the variable @code{N}.
1633 You will see the value (5) displayed, in ``tool tip'' fashion.
1634 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1635 You will see information about @code{N} appear in the @code{Debugger Data}
1636 pane, showing the value as 5.
1638 @item @emph{Assigning a new value to a variable}
1640 Right click on the @code{N} in the @code{Debugger Data} pane, and
1641 select @code{Set value of N}.
1642 When the input window appears, enter the value @code{4} and click
1644 This value does not automatically appear in the @code{Debugger Data}
1645 pane; to see it, right click again on the @code{N} in the
1646 @code{Debugger Data} pane and select @code{Update value}.
1647 The new value, 4, will appear in red.
1649 @item @emph{Single stepping}
1651 Select @code{Debug}, then @code{Next}.
1652 This will cause the next statement to be executed, in this case the
1653 call of @code{Put_Line} with the string slice.
1654 Notice in the console window that the displayed string is simply
1655 @code{abcd} and not @code{abcde} which you had entered.
1656 This is because the upper bound of the slice is now 4 rather than 5.
1658 @item @emph{Removing a breakpoint}
1660 Toggle the breakpoint icon at line 10.
1662 @item @emph{Resuming execution from a breakpoint}
1664 Select @code{Debug}, then @code{Continue}.
1665 The program will reach the next iteration of the loop, and
1666 wait for input after displaying the prompt.
1667 This time, just hit the @kbd{Enter} key.
1668 The value of @code{N} will be 0, and the program will terminate.
1669 The console window will disappear.
1674 @node The GNAT Compilation Model
1675 @chapter The GNAT Compilation Model
1676 @cindex GNAT compilation model
1677 @cindex Compilation model
1680 * Source Representation::
1681 * Foreign Language Representation::
1682 * File Naming Rules::
1683 * Using Other File Names::
1684 * Alternative File Naming Schemes::
1685 * Generating Object Files::
1686 * Source Dependencies::
1687 * The Ada Library Information Files::
1688 * Binding an Ada Program::
1689 * Mixed Language Programming::
1691 * Building Mixed Ada & C++ Programs::
1692 * Comparison between GNAT and C/C++ Compilation Models::
1694 * Comparison between GNAT and Conventional Ada Library Models::
1696 * Placement of temporary files::
1701 This chapter describes the compilation model used by GNAT. Although
1702 similar to that used by other languages, such as C and C++, this model
1703 is substantially different from the traditional Ada compilation models,
1704 which are based on a library. The model is initially described without
1705 reference to the library-based model. If you have not previously used an
1706 Ada compiler, you need only read the first part of this chapter. The
1707 last section describes and discusses the differences between the GNAT
1708 model and the traditional Ada compiler models. If you have used other
1709 Ada compilers, this section will help you to understand those
1710 differences, and the advantages of the GNAT model.
1712 @node Source Representation
1713 @section Source Representation
1717 Ada source programs are represented in standard text files, using
1718 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1719 7-bit ASCII set, plus additional characters used for
1720 representing foreign languages (@pxref{Foreign Language Representation}
1721 for support of non-USA character sets). The format effector characters
1722 are represented using their standard ASCII encodings, as follows:
1727 Vertical tab, @code{16#0B#}
1731 Horizontal tab, @code{16#09#}
1735 Carriage return, @code{16#0D#}
1739 Line feed, @code{16#0A#}
1743 Form feed, @code{16#0C#}
1747 Source files are in standard text file format. In addition, GNAT will
1748 recognize a wide variety of stream formats, in which the end of
1749 physical lines is marked by any of the following sequences:
1750 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1751 in accommodating files that are imported from other operating systems.
1753 @cindex End of source file
1754 @cindex Source file, end
1756 The end of a source file is normally represented by the physical end of
1757 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1758 recognized as signalling the end of the source file. Again, this is
1759 provided for compatibility with other operating systems where this
1760 code is used to represent the end of file.
1762 Each file contains a single Ada compilation unit, including any pragmas
1763 associated with the unit. For example, this means you must place a
1764 package declaration (a package @dfn{spec}) and the corresponding body in
1765 separate files. An Ada @dfn{compilation} (which is a sequence of
1766 compilation units) is represented using a sequence of files. Similarly,
1767 you will place each subunit or child unit in a separate file.
1769 @node Foreign Language Representation
1770 @section Foreign Language Representation
1773 GNAT supports the standard character sets defined in Ada as well as
1774 several other non-standard character sets for use in localized versions
1775 of the compiler (@pxref{Character Set Control}).
1778 * Other 8-Bit Codes::
1779 * Wide Character Encodings::
1787 The basic character set is Latin-1. This character set is defined by ISO
1788 standard 8859, part 1. The lower half (character codes @code{16#00#}
1789 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1790 is used to represent additional characters. These include extended letters
1791 used by European languages, such as French accents, the vowels with umlauts
1792 used in German, and the extra letter A-ring used in Swedish.
1794 @findex Ada.Characters.Latin_1
1795 For a complete list of Latin-1 codes and their encodings, see the source
1796 file of library unit @code{Ada.Characters.Latin_1} in file
1797 @file{a-chlat1.ads}.
1798 You may use any of these extended characters freely in character or
1799 string literals. In addition, the extended characters that represent
1800 letters can be used in identifiers.
1802 @node Other 8-Bit Codes
1803 @subsection Other 8-Bit Codes
1806 GNAT also supports several other 8-bit coding schemes:
1809 @item ISO 8859-2 (Latin-2)
1812 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1815 @item ISO 8859-3 (Latin-3)
1818 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1821 @item ISO 8859-4 (Latin-4)
1824 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1827 @item ISO 8859-5 (Cyrillic)
1830 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1831 lowercase equivalence.
1833 @item ISO 8859-15 (Latin-9)
1836 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1837 lowercase equivalence
1839 @item IBM PC (code page 437)
1840 @cindex code page 437
1841 This code page is the normal default for PCs in the U.S. It corresponds
1842 to the original IBM PC character set. This set has some, but not all, of
1843 the extended Latin-1 letters, but these letters do not have the same
1844 encoding as Latin-1. In this mode, these letters are allowed in
1845 identifiers with uppercase and lowercase equivalence.
1847 @item IBM PC (code page 850)
1848 @cindex code page 850
1849 This code page is a modification of 437 extended to include all the
1850 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1851 mode, all these letters are allowed in identifiers with uppercase and
1852 lowercase equivalence.
1854 @item Full Upper 8-bit
1855 Any character in the range 80-FF allowed in identifiers, and all are
1856 considered distinct. In other words, there are no uppercase and lowercase
1857 equivalences in this range. This is useful in conjunction with
1858 certain encoding schemes used for some foreign character sets (e.g.
1859 the typical method of representing Chinese characters on the PC).
1862 No upper-half characters in the range 80-FF are allowed in identifiers.
1863 This gives Ada 83 compatibility for identifier names.
1867 For precise data on the encodings permitted, and the uppercase and lowercase
1868 equivalences that are recognized, see the file @file{csets.adb} in
1869 the GNAT compiler sources. You will need to obtain a full source release
1870 of GNAT to obtain this file.
1872 @node Wide Character Encodings
1873 @subsection Wide Character Encodings
1876 GNAT allows wide character codes to appear in character and string
1877 literals, and also optionally in identifiers, by means of the following
1878 possible encoding schemes:
1883 In this encoding, a wide character is represented by the following five
1891 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1892 characters (using uppercase letters) of the wide character code. For
1893 example, ESC A345 is used to represent the wide character with code
1895 This scheme is compatible with use of the full Wide_Character set.
1897 @item Upper-Half Coding
1898 @cindex Upper-Half Coding
1899 The wide character with encoding @code{16#abcd#} where the upper bit is on
1900 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1901 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1902 character, but is not required to be in the upper half. This method can
1903 be also used for shift-JIS or EUC, where the internal coding matches the
1906 @item Shift JIS Coding
1907 @cindex Shift JIS Coding
1908 A wide character is represented by a two-character sequence,
1910 @code{16#cd#}, with the restrictions described for upper-half encoding as
1911 described above. The internal character code is the corresponding JIS
1912 character according to the standard algorithm for Shift-JIS
1913 conversion. Only characters defined in the JIS code set table can be
1914 used with this encoding method.
1918 A wide character is represented by a two-character sequence
1920 @code{16#cd#}, with both characters being in the upper half. The internal
1921 character code is the corresponding JIS character according to the EUC
1922 encoding algorithm. Only characters defined in the JIS code set table
1923 can be used with this encoding method.
1926 A wide character is represented using
1927 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1928 10646-1/Am.2. Depending on the character value, the representation
1929 is a one, two, or three byte sequence:
1934 16#0000#-16#007f#: 2#0xxxxxxx#
1935 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
1936 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
1941 where the xxx bits correspond to the left-padded bits of the
1942 16-bit character value. Note that all lower half ASCII characters
1943 are represented as ASCII bytes and all upper half characters and
1944 other wide characters are represented as sequences of upper-half
1945 (The full UTF-8 scheme allows for encoding 31-bit characters as
1946 6-byte sequences, but in this implementation, all UTF-8 sequences
1947 of four or more bytes length will be treated as illegal).
1948 @item Brackets Coding
1949 In this encoding, a wide character is represented by the following eight
1957 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1958 characters (using uppercase letters) of the wide character code. For
1959 example, [``A345''] is used to represent the wide character with code
1960 @code{16#A345#}. It is also possible (though not required) to use the
1961 Brackets coding for upper half characters. For example, the code
1962 @code{16#A3#} can be represented as @code{[``A3'']}.
1964 This scheme is compatible with use of the full Wide_Character set,
1965 and is also the method used for wide character encoding in the standard
1966 ACVC (Ada Compiler Validation Capability) test suite distributions.
1971 Note: Some of these coding schemes do not permit the full use of the
1972 Ada character set. For example, neither Shift JIS, nor EUC allow the
1973 use of the upper half of the Latin-1 set.
1975 @node File Naming Rules
1976 @section File Naming Rules
1979 The default file name is determined by the name of the unit that the
1980 file contains. The name is formed by taking the full expanded name of
1981 the unit and replacing the separating dots with hyphens and using
1982 ^lowercase^uppercase^ for all letters.
1984 An exception arises if the file name generated by the above rules starts
1985 with one of the characters
1992 and the second character is a
1993 minus. In this case, the character ^tilde^dollar sign^ is used in place
1994 of the minus. The reason for this special rule is to avoid clashes with
1995 the standard names for child units of the packages System, Ada,
1996 Interfaces, and GNAT, which use the prefixes
2005 The file extension is @file{.ads} for a spec and
2006 @file{.adb} for a body. The following list shows some
2007 examples of these rules.
2014 @item arith_functions.ads
2015 Arith_Functions (package spec)
2016 @item arith_functions.adb
2017 Arith_Functions (package body)
2019 Func.Spec (child package spec)
2021 Func.Spec (child package body)
2023 Sub (subunit of Main)
2024 @item ^a~bad.adb^A$BAD.ADB^
2025 A.Bad (child package body)
2029 Following these rules can result in excessively long
2030 file names if corresponding
2031 unit names are long (for example, if child units or subunits are
2032 heavily nested). An option is available to shorten such long file names
2033 (called file name ``krunching''). This may be particularly useful when
2034 programs being developed with GNAT are to be used on operating systems
2035 with limited file name lengths. @xref{Using gnatkr}.
2037 Of course, no file shortening algorithm can guarantee uniqueness over
2038 all possible unit names; if file name krunching is used, it is your
2039 responsibility to ensure no name clashes occur. Alternatively you
2040 can specify the exact file names that you want used, as described
2041 in the next section. Finally, if your Ada programs are migrating from a
2042 compiler with a different naming convention, you can use the gnatchop
2043 utility to produce source files that follow the GNAT naming conventions.
2044 (For details @pxref{Renaming Files Using gnatchop}.)
2046 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2047 systems, case is not significant. So for example on @code{Windows XP}
2048 if the canonical name is @code{main-sub.adb}, you can use the file name
2049 @code{Main-Sub.adb} instead. However, case is significant for other
2050 operating systems, so for example, if you want to use other than
2051 canonically cased file names on a Unix system, you need to follow
2052 the procedures described in the next section.
2054 @node Using Other File Names
2055 @section Using Other File Names
2059 In the previous section, we have described the default rules used by
2060 GNAT to determine the file name in which a given unit resides. It is
2061 often convenient to follow these default rules, and if you follow them,
2062 the compiler knows without being explicitly told where to find all
2065 However, in some cases, particularly when a program is imported from
2066 another Ada compiler environment, it may be more convenient for the
2067 programmer to specify which file names contain which units. GNAT allows
2068 arbitrary file names to be used by means of the Source_File_Name pragma.
2069 The form of this pragma is as shown in the following examples:
2070 @cindex Source_File_Name pragma
2072 @smallexample @c ada
2074 pragma Source_File_Name (My_Utilities.Stacks,
2075 Spec_File_Name => "myutilst_a.ada");
2076 pragma Source_File_name (My_Utilities.Stacks,
2077 Body_File_Name => "myutilst.ada");
2082 As shown in this example, the first argument for the pragma is the unit
2083 name (in this example a child unit). The second argument has the form
2084 of a named association. The identifier
2085 indicates whether the file name is for a spec or a body;
2086 the file name itself is given by a string literal.
2088 The source file name pragma is a configuration pragma, which means that
2089 normally it will be placed in the @file{gnat.adc}
2090 file used to hold configuration
2091 pragmas that apply to a complete compilation environment.
2092 For more details on how the @file{gnat.adc} file is created and used
2093 see @ref{Handling of Configuration Pragmas}.
2094 @cindex @file{gnat.adc}
2097 GNAT allows completely arbitrary file names to be specified using the
2098 source file name pragma. However, if the file name specified has an
2099 extension other than @file{.ads} or @file{.adb} it is necessary to use
2100 a special syntax when compiling the file. The name in this case must be
2101 preceded by the special sequence @option{-x} followed by a space and the name
2102 of the language, here @code{ada}, as in:
2105 $ gcc -c -x ada peculiar_file_name.sim
2110 @command{gnatmake} handles non-standard file names in the usual manner (the
2111 non-standard file name for the main program is simply used as the
2112 argument to gnatmake). Note that if the extension is also non-standard,
2113 then it must be included in the @command{gnatmake} command, it may not
2116 @node Alternative File Naming Schemes
2117 @section Alternative File Naming Schemes
2118 @cindex File naming schemes, alternative
2121 In the previous section, we described the use of the @code{Source_File_Name}
2122 pragma to allow arbitrary names to be assigned to individual source files.
2123 However, this approach requires one pragma for each file, and especially in
2124 large systems can result in very long @file{gnat.adc} files, and also create
2125 a maintenance problem.
2127 GNAT also provides a facility for specifying systematic file naming schemes
2128 other than the standard default naming scheme previously described. An
2129 alternative scheme for naming is specified by the use of
2130 @code{Source_File_Name} pragmas having the following format:
2131 @cindex Source_File_Name pragma
2133 @smallexample @c ada
2134 pragma Source_File_Name (
2135 Spec_File_Name => FILE_NAME_PATTERN
2136 [,Casing => CASING_SPEC]
2137 [,Dot_Replacement => STRING_LITERAL]);
2139 pragma Source_File_Name (
2140 Body_File_Name => FILE_NAME_PATTERN
2141 [,Casing => CASING_SPEC]
2142 [,Dot_Replacement => STRING_LITERAL]);
2144 pragma Source_File_Name (
2145 Subunit_File_Name => FILE_NAME_PATTERN
2146 [,Casing => CASING_SPEC]
2147 [,Dot_Replacement => STRING_LITERAL]);
2149 FILE_NAME_PATTERN ::= STRING_LITERAL
2150 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2154 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2155 It contains a single asterisk character, and the unit name is substituted
2156 systematically for this asterisk. The optional parameter
2157 @code{Casing} indicates
2158 whether the unit name is to be all upper-case letters, all lower-case letters,
2159 or mixed-case. If no
2160 @code{Casing} parameter is used, then the default is all
2161 ^lower-case^upper-case^.
2163 The optional @code{Dot_Replacement} string is used to replace any periods
2164 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2165 argument is used then separating dots appear unchanged in the resulting
2167 Although the above syntax indicates that the
2168 @code{Casing} argument must appear
2169 before the @code{Dot_Replacement} argument, but it
2170 is also permissible to write these arguments in the opposite order.
2172 As indicated, it is possible to specify different naming schemes for
2173 bodies, specs, and subunits. Quite often the rule for subunits is the
2174 same as the rule for bodies, in which case, there is no need to give
2175 a separate @code{Subunit_File_Name} rule, and in this case the
2176 @code{Body_File_name} rule is used for subunits as well.
2178 The separate rule for subunits can also be used to implement the rather
2179 unusual case of a compilation environment (e.g. a single directory) which
2180 contains a subunit and a child unit with the same unit name. Although
2181 both units cannot appear in the same partition, the Ada Reference Manual
2182 allows (but does not require) the possibility of the two units coexisting
2183 in the same environment.
2185 The file name translation works in the following steps:
2190 If there is a specific @code{Source_File_Name} pragma for the given unit,
2191 then this is always used, and any general pattern rules are ignored.
2194 If there is a pattern type @code{Source_File_Name} pragma that applies to
2195 the unit, then the resulting file name will be used if the file exists. If
2196 more than one pattern matches, the latest one will be tried first, and the
2197 first attempt resulting in a reference to a file that exists will be used.
2200 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2201 for which the corresponding file exists, then the standard GNAT default
2202 naming rules are used.
2207 As an example of the use of this mechanism, consider a commonly used scheme
2208 in which file names are all lower case, with separating periods copied
2209 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2210 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2213 @smallexample @c ada
2214 pragma Source_File_Name
2215 (Spec_File_Name => "*.1.ada");
2216 pragma Source_File_Name
2217 (Body_File_Name => "*.2.ada");
2221 The default GNAT scheme is actually implemented by providing the following
2222 default pragmas internally:
2224 @smallexample @c ada
2225 pragma Source_File_Name
2226 (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2227 pragma Source_File_Name
2228 (Body_File_Name => "*.adb", Dot_Replacement => "-");
2232 Our final example implements a scheme typically used with one of the
2233 Ada 83 compilers, where the separator character for subunits was ``__''
2234 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2235 by adding @file{.ADA}, and subunits by
2236 adding @file{.SEP}. All file names were
2237 upper case. Child units were not present of course since this was an
2238 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2239 the same double underscore separator for child units.
2241 @smallexample @c ada
2242 pragma Source_File_Name
2243 (Spec_File_Name => "*_.ADA",
2244 Dot_Replacement => "__",
2245 Casing = Uppercase);
2246 pragma Source_File_Name
2247 (Body_File_Name => "*.ADA",
2248 Dot_Replacement => "__",
2249 Casing = Uppercase);
2250 pragma Source_File_Name
2251 (Subunit_File_Name => "*.SEP",
2252 Dot_Replacement => "__",
2253 Casing = Uppercase);
2256 @node Generating Object Files
2257 @section Generating Object Files
2260 An Ada program consists of a set of source files, and the first step in
2261 compiling the program is to generate the corresponding object files.
2262 These are generated by compiling a subset of these source files.
2263 The files you need to compile are the following:
2267 If a package spec has no body, compile the package spec to produce the
2268 object file for the package.
2271 If a package has both a spec and a body, compile the body to produce the
2272 object file for the package. The source file for the package spec need
2273 not be compiled in this case because there is only one object file, which
2274 contains the code for both the spec and body of the package.
2277 For a subprogram, compile the subprogram body to produce the object file
2278 for the subprogram. The spec, if one is present, is as usual in a
2279 separate file, and need not be compiled.
2283 In the case of subunits, only compile the parent unit. A single object
2284 file is generated for the entire subunit tree, which includes all the
2288 Compile child units independently of their parent units
2289 (though, of course, the spec of all the ancestor unit must be present in order
2290 to compile a child unit).
2294 Compile generic units in the same manner as any other units. The object
2295 files in this case are small dummy files that contain at most the
2296 flag used for elaboration checking. This is because GNAT always handles generic
2297 instantiation by means of macro expansion. However, it is still necessary to
2298 compile generic units, for dependency checking and elaboration purposes.
2302 The preceding rules describe the set of files that must be compiled to
2303 generate the object files for a program. Each object file has the same
2304 name as the corresponding source file, except that the extension is
2307 You may wish to compile other files for the purpose of checking their
2308 syntactic and semantic correctness. For example, in the case where a
2309 package has a separate spec and body, you would not normally compile the
2310 spec. However, it is convenient in practice to compile the spec to make
2311 sure it is error-free before compiling clients of this spec, because such
2312 compilations will fail if there is an error in the spec.
2314 GNAT provides an option for compiling such files purely for the
2315 purposes of checking correctness; such compilations are not required as
2316 part of the process of building a program. To compile a file in this
2317 checking mode, use the @option{-gnatc} switch.
2319 @node Source Dependencies
2320 @section Source Dependencies
2323 A given object file clearly depends on the source file which is compiled
2324 to produce it. Here we are using @dfn{depends} in the sense of a typical
2325 @code{make} utility; in other words, an object file depends on a source
2326 file if changes to the source file require the object file to be
2328 In addition to this basic dependency, a given object may depend on
2329 additional source files as follows:
2333 If a file being compiled @code{with}'s a unit @var{X}, the object file
2334 depends on the file containing the spec of unit @var{X}. This includes
2335 files that are @code{with}'ed implicitly either because they are parents
2336 of @code{with}'ed child units or they are run-time units required by the
2337 language constructs used in a particular unit.
2340 If a file being compiled instantiates a library level generic unit, the
2341 object file depends on both the spec and body files for this generic
2345 If a file being compiled instantiates a generic unit defined within a
2346 package, the object file depends on the body file for the package as
2347 well as the spec file.
2351 @cindex @option{-gnatn} switch
2352 If a file being compiled contains a call to a subprogram for which
2353 pragma @code{Inline} applies and inlining is activated with the
2354 @option{-gnatn} switch, the object file depends on the file containing the
2355 body of this subprogram as well as on the file containing the spec. Note
2356 that for inlining to actually occur as a result of the use of this switch,
2357 it is necessary to compile in optimizing mode.
2359 @cindex @option{-gnatN} switch
2360 The use of @option{-gnatN} activates a more extensive inlining optimization
2361 that is performed by the front end of the compiler. This inlining does
2362 not require that the code generation be optimized. Like @option{-gnatn},
2363 the use of this switch generates additional dependencies.
2365 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
2366 to specify both options.
2369 If an object file @file{O} depends on the proper body of a subunit through
2370 inlining or instantiation, it depends on the parent unit of the subunit.
2371 This means that any modification of the parent unit or one of its subunits
2372 affects the compilation of @file{O}.
2375 The object file for a parent unit depends on all its subunit body files.
2378 The previous two rules meant that for purposes of computing dependencies and
2379 recompilation, a body and all its subunits are treated as an indivisible whole.
2382 These rules are applied transitively: if unit @code{A} @code{with}'s
2383 unit @code{B}, whose elaboration calls an inlined procedure in package
2384 @code{C}, the object file for unit @code{A} will depend on the body of
2385 @code{C}, in file @file{c.adb}.
2387 The set of dependent files described by these rules includes all the
2388 files on which the unit is semantically dependent, as dictated by the
2389 Ada language standard. However, it is a superset of what the
2390 standard describes, because it includes generic, inline, and subunit
2393 An object file must be recreated by recompiling the corresponding source
2394 file if any of the source files on which it depends are modified. For
2395 example, if the @code{make} utility is used to control compilation,
2396 the rule for an Ada object file must mention all the source files on
2397 which the object file depends, according to the above definition.
2398 The determination of the necessary
2399 recompilations is done automatically when one uses @command{gnatmake}.
2402 @node The Ada Library Information Files
2403 @section The Ada Library Information Files
2404 @cindex Ada Library Information files
2405 @cindex @file{ALI} files
2408 Each compilation actually generates two output files. The first of these
2409 is the normal object file that has a @file{.o} extension. The second is a
2410 text file containing full dependency information. It has the same
2411 name as the source file, but an @file{.ali} extension.
2412 This file is known as the Ada Library Information (@file{ALI}) file.
2413 The following information is contained in the @file{ALI} file.
2417 Version information (indicates which version of GNAT was used to compile
2418 the unit(s) in question)
2421 Main program information (including priority and time slice settings,
2422 as well as the wide character encoding used during compilation).
2425 List of arguments used in the @command{gcc} command for the compilation
2428 Attributes of the unit, including configuration pragmas used, an indication
2429 of whether the compilation was successful, exception model used etc.
2432 A list of relevant restrictions applying to the unit (used for consistency)
2436 Categorization information (e.g. use of pragma @code{Pure}).
2439 Information on all @code{with}'ed units, including presence of
2440 @code{Elaborate} or @code{Elaborate_All} pragmas.
2443 Information from any @code{Linker_Options} pragmas used in the unit
2446 Information on the use of @code{Body_Version} or @code{Version}
2447 attributes in the unit.
2450 Dependency information. This is a list of files, together with
2451 time stamp and checksum information. These are files on which
2452 the unit depends in the sense that recompilation is required
2453 if any of these units are modified.
2456 Cross-reference data. Contains information on all entities referenced
2457 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2458 provide cross-reference information.
2463 For a full detailed description of the format of the @file{ALI} file,
2464 see the source of the body of unit @code{Lib.Writ}, contained in file
2465 @file{lib-writ.adb} in the GNAT compiler sources.
2467 @node Binding an Ada Program
2468 @section Binding an Ada Program
2471 When using languages such as C and C++, once the source files have been
2472 compiled the only remaining step in building an executable program
2473 is linking the object modules together. This means that it is possible to
2474 link an inconsistent version of a program, in which two units have
2475 included different versions of the same header.
2477 The rules of Ada do not permit such an inconsistent program to be built.
2478 For example, if two clients have different versions of the same package,
2479 it is illegal to build a program containing these two clients.
2480 These rules are enforced by the GNAT binder, which also determines an
2481 elaboration order consistent with the Ada rules.
2483 The GNAT binder is run after all the object files for a program have
2484 been created. It is given the name of the main program unit, and from
2485 this it determines the set of units required by the program, by reading the
2486 corresponding ALI files. It generates error messages if the program is
2487 inconsistent or if no valid order of elaboration exists.
2489 If no errors are detected, the binder produces a main program, in Ada by
2490 default, that contains calls to the elaboration procedures of those
2491 compilation unit that require them, followed by
2492 a call to the main program. This Ada program is compiled to generate the
2493 object file for the main program. The name of
2494 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2495 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2498 Finally, the linker is used to build the resulting executable program,
2499 using the object from the main program from the bind step as well as the
2500 object files for the Ada units of the program.
2502 @node Mixed Language Programming
2503 @section Mixed Language Programming
2504 @cindex Mixed Language Programming
2507 This section describes how to develop a mixed-language program,
2508 specifically one that comprises units in both Ada and C.
2511 * Interfacing to C::
2512 * Calling Conventions::
2515 @node Interfacing to C
2516 @subsection Interfacing to C
2518 Interfacing Ada with a foreign language such as C involves using
2519 compiler directives to import and/or export entity definitions in each
2520 language---using @code{extern} statements in C, for instance, and the
2521 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2522 A full treatment of these topics is provided in Appendix B, section 1
2523 of the Ada Reference Manual.
2525 There are two ways to build a program using GNAT that contains some Ada
2526 sources and some foreign language sources, depending on whether or not
2527 the main subprogram is written in Ada. Here is a source example with
2528 the main subprogram in Ada:
2534 void print_num (int num)
2536 printf ("num is %d.\n", num);
2542 /* num_from_Ada is declared in my_main.adb */
2543 extern int num_from_Ada;
2547 return num_from_Ada;
2551 @smallexample @c ada
2553 procedure My_Main is
2555 -- Declare then export an Integer entity called num_from_Ada
2556 My_Num : Integer := 10;
2557 pragma Export (C, My_Num, "num_from_Ada");
2559 -- Declare an Ada function spec for Get_Num, then use
2560 -- C function get_num for the implementation.
2561 function Get_Num return Integer;
2562 pragma Import (C, Get_Num, "get_num");
2564 -- Declare an Ada procedure spec for Print_Num, then use
2565 -- C function print_num for the implementation.
2566 procedure Print_Num (Num : Integer);
2567 pragma Import (C, Print_Num, "print_num");
2570 Print_Num (Get_Num);
2576 To build this example, first compile the foreign language files to
2577 generate object files:
2579 ^gcc -c file1.c^gcc -c FILE1.C^
2580 ^gcc -c file2.c^gcc -c FILE2.C^
2584 Then, compile the Ada units to produce a set of object files and ALI
2587 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2591 Run the Ada binder on the Ada main program:
2593 gnatbind my_main.ali
2597 Link the Ada main program, the Ada objects and the other language
2600 gnatlink my_main.ali file1.o file2.o
2604 The last three steps can be grouped in a single command:
2606 gnatmake my_main.adb -largs file1.o file2.o
2609 @cindex Binder output file
2611 If the main program is in a language other than Ada, then you may have
2612 more than one entry point into the Ada subsystem. You must use a special
2613 binder option to generate callable routines that initialize and
2614 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2615 Calls to the initialization and finalization routines must be inserted
2616 in the main program, or some other appropriate point in the code. The
2617 call to initialize the Ada units must occur before the first Ada
2618 subprogram is called, and the call to finalize the Ada units must occur
2619 after the last Ada subprogram returns. The binder will place the
2620 initialization and finalization subprograms into the
2621 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2622 sources. To illustrate, we have the following example:
2626 extern void adainit (void);
2627 extern void adafinal (void);
2628 extern int add (int, int);
2629 extern int sub (int, int);
2631 int main (int argc, char *argv[])
2637 /* Should print "21 + 7 = 28" */
2638 printf ("%d + %d = %d\n", a, b, add (a, b));
2639 /* Should print "21 - 7 = 14" */
2640 printf ("%d - %d = %d\n", a, b, sub (a, b));
2646 @smallexample @c ada
2649 function Add (A, B : Integer) return Integer;
2650 pragma Export (C, Add, "add");
2654 package body Unit1 is
2655 function Add (A, B : Integer) return Integer is
2663 function Sub (A, B : Integer) return Integer;
2664 pragma Export (C, Sub, "sub");
2668 package body Unit2 is
2669 function Sub (A, B : Integer) return Integer is
2678 The build procedure for this application is similar to the last
2679 example's. First, compile the foreign language files to generate object
2682 ^gcc -c main.c^gcc -c main.c^
2686 Next, compile the Ada units to produce a set of object files and ALI
2689 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2690 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2694 Run the Ada binder on every generated ALI file. Make sure to use the
2695 @option{-n} option to specify a foreign main program:
2697 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2701 Link the Ada main program, the Ada objects and the foreign language
2702 objects. You need only list the last ALI file here:
2704 gnatlink unit2.ali main.o -o exec_file
2707 This procedure yields a binary executable called @file{exec_file}.
2711 Depending on the circumstances (for example when your non-Ada main object
2712 does not provide symbol @code{main}), you may also need to instruct the
2713 GNAT linker not to include the standard startup objects by passing the
2714 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2716 @node Calling Conventions
2717 @subsection Calling Conventions
2718 @cindex Foreign Languages
2719 @cindex Calling Conventions
2720 GNAT follows standard calling sequence conventions and will thus interface
2721 to any other language that also follows these conventions. The following
2722 Convention identifiers are recognized by GNAT:
2725 @cindex Interfacing to Ada
2726 @cindex Other Ada compilers
2727 @cindex Convention Ada
2729 This indicates that the standard Ada calling sequence will be
2730 used and all Ada data items may be passed without any limitations in the
2731 case where GNAT is used to generate both the caller and callee. It is also
2732 possible to mix GNAT generated code and code generated by another Ada
2733 compiler. In this case, the data types should be restricted to simple
2734 cases, including primitive types. Whether complex data types can be passed
2735 depends on the situation. Probably it is safe to pass simple arrays, such
2736 as arrays of integers or floats. Records may or may not work, depending
2737 on whether both compilers lay them out identically. Complex structures
2738 involving variant records, access parameters, tasks, or protected types,
2739 are unlikely to be able to be passed.
2741 Note that in the case of GNAT running
2742 on a platform that supports HP Ada 83, a higher degree of compatibility
2743 can be guaranteed, and in particular records are layed out in an identical
2744 manner in the two compilers. Note also that if output from two different
2745 compilers is mixed, the program is responsible for dealing with elaboration
2746 issues. Probably the safest approach is to write the main program in the
2747 version of Ada other than GNAT, so that it takes care of its own elaboration
2748 requirements, and then call the GNAT-generated adainit procedure to ensure
2749 elaboration of the GNAT components. Consult the documentation of the other
2750 Ada compiler for further details on elaboration.
2752 However, it is not possible to mix the tasking run time of GNAT and
2753 HP Ada 83, All the tasking operations must either be entirely within
2754 GNAT compiled sections of the program, or entirely within HP Ada 83
2755 compiled sections of the program.
2757 @cindex Interfacing to Assembly
2758 @cindex Convention Assembler
2760 Specifies assembler as the convention. In practice this has the
2761 same effect as convention Ada (but is not equivalent in the sense of being
2762 considered the same convention).
2764 @cindex Convention Asm
2767 Equivalent to Assembler.
2769 @cindex Interfacing to COBOL
2770 @cindex Convention COBOL
2773 Data will be passed according to the conventions described
2774 in section B.4 of the Ada Reference Manual.
2777 @cindex Interfacing to C
2778 @cindex Convention C
2780 Data will be passed according to the conventions described
2781 in section B.3 of the Ada Reference Manual.
2783 A note on interfacing to a C ``varargs'' function:
2784 @findex C varargs function
2785 @cindex Interfacing to C varargs function
2786 @cindex varargs function interfaces
2790 In C, @code{varargs} allows a function to take a variable number of
2791 arguments. There is no direct equivalent in this to Ada. One
2792 approach that can be used is to create a C wrapper for each
2793 different profile and then interface to this C wrapper. For
2794 example, to print an @code{int} value using @code{printf},
2795 create a C function @code{printfi} that takes two arguments, a
2796 pointer to a string and an int, and calls @code{printf}.
2797 Then in the Ada program, use pragma @code{Import} to
2798 interface to @code{printfi}.
2801 It may work on some platforms to directly interface to
2802 a @code{varargs} function by providing a specific Ada profile
2803 for a particular call. However, this does not work on
2804 all platforms, since there is no guarantee that the
2805 calling sequence for a two argument normal C function
2806 is the same as for calling a @code{varargs} C function with
2807 the same two arguments.
2810 @cindex Convention Default
2815 @cindex Convention External
2822 @cindex Interfacing to C++
2823 @cindex Convention C++
2824 @item C_Plus_Plus (or CPP)
2825 This stands for C++. For most purposes this is identical to C.
2826 See the separate description of the specialized GNAT pragmas relating to
2827 C++ interfacing for further details.
2831 @cindex Interfacing to Fortran
2832 @cindex Convention Fortran
2834 Data will be passed according to the conventions described
2835 in section B.5 of the Ada Reference Manual.
2838 This applies to an intrinsic operation, as defined in the Ada
2839 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2840 this means that the body of the subprogram is provided by the compiler itself,
2841 usually by means of an efficient code sequence, and that the user does not
2842 supply an explicit body for it. In an application program, the pragma can
2843 only be applied to the following two sets of names, which the GNAT compiler
2848 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2849 Shift_Right_Arithmetic. The corresponding subprogram declaration must have
2850 two formal parameters. The
2851 first one must be a signed integer type or a modular type with a binary
2852 modulus, and the second parameter must be of type Natural.
2853 The return type must be the same as the type of the first argument. The size
2854 of this type can only be 8, 16, 32, or 64.
2855 @item binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2856 The corresponding operator declaration must have parameters and result type
2857 that have the same root numeric type (for example, all three are long_float
2858 types). This simplifies the definition of operations that use type checking
2859 to perform dimensional checks:
2861 @smallexample @c ada
2862 type Distance is new Long_Float;
2863 type Time is new Long_Float;
2864 type Velocity is new Long_Float;
2865 function "/" (D : Distance; T : Time)
2867 pragma Import (Intrinsic, "/");
2871 This common idiom is often programmed with a generic definition and an
2872 explicit body. The pragma makes it simpler to introduce such declarations.
2873 It incurs no overhead in compilation time or code size, because it is
2874 implemented as a single machine instruction.
2880 @cindex Convention Stdcall
2882 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2883 and specifies that the @code{Stdcall} calling sequence will be used,
2884 as defined by the NT API. Nevertheless, to ease building
2885 cross-platform bindings this convention will be handled as a @code{C} calling
2886 convention on non Windows platforms.
2889 @cindex Convention DLL
2891 This is equivalent to @code{Stdcall}.
2894 @cindex Convention Win32
2896 This is equivalent to @code{Stdcall}.
2900 @cindex Convention Stubbed
2902 This is a special convention that indicates that the compiler
2903 should provide a stub body that raises @code{Program_Error}.
2907 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2908 that can be used to parametrize conventions and allow additional synonyms
2909 to be specified. For example if you have legacy code in which the convention
2910 identifier Fortran77 was used for Fortran, you can use the configuration
2913 @smallexample @c ada
2914 pragma Convention_Identifier (Fortran77, Fortran);
2918 And from now on the identifier Fortran77 may be used as a convention
2919 identifier (for example in an @code{Import} pragma) with the same
2923 @node Building Mixed Ada & C++ Programs
2924 @section Building Mixed Ada and C++ Programs
2927 A programmer inexperienced with mixed-language development may find that
2928 building an application containing both Ada and C++ code can be a
2929 challenge. This section gives a few
2930 hints that should make this task easier. The first section addresses
2931 the differences between interfacing with C and interfacing with C++.
2933 looks into the delicate problem of linking the complete application from
2934 its Ada and C++ parts. The last section gives some hints on how the GNAT
2935 run-time library can be adapted in order to allow inter-language dispatching
2936 with a new C++ compiler.
2939 * Interfacing to C++::
2940 * Linking a Mixed C++ & Ada Program::
2941 * A Simple Example::
2942 * Interfacing with C++ at the Class Level::
2945 @node Interfacing to C++
2946 @subsection Interfacing to C++
2949 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2950 generating code that is compatible with the G++ Application Binary
2951 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2954 Interfacing can be done at 3 levels: simple data, subprograms, and
2955 classes. In the first two cases, GNAT offers a specific @code{Convention
2956 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2957 Usually, C++ mangles the names of subprograms, and currently, GNAT does
2958 not provide any help to solve the demangling problem. This problem can be
2959 addressed in two ways:
2962 by modifying the C++ code in order to force a C convention using
2963 the @code{extern "C"} syntax.
2966 by figuring out the mangled name and use it as the Link_Name argument of
2971 Interfacing at the class level can be achieved by using the GNAT specific
2972 pragmas such as @code{CPP_Constructor}. See the GNAT Reference Manual for
2973 additional information.
2975 @node Linking a Mixed C++ & Ada Program
2976 @subsection Linking a Mixed C++ & Ada Program
2979 Usually the linker of the C++ development system must be used to link
2980 mixed applications because most C++ systems will resolve elaboration
2981 issues (such as calling constructors on global class instances)
2982 transparently during the link phase. GNAT has been adapted to ease the
2983 use of a foreign linker for the last phase. Three cases can be
2988 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
2989 The C++ linker can simply be called by using the C++ specific driver
2990 called @code{c++}. Note that this setup is not very common because it
2991 may involve recompiling the whole GCC tree from sources, which makes it
2992 harder to upgrade the compilation system for one language without
2993 destabilizing the other.
2998 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
3002 Using GNAT and G++ from two different GCC installations: If both
3003 compilers are on the PATH, the previous method may be used. It is
3004 important to note that environment variables such as C_INCLUDE_PATH,
3005 GCC_EXEC_PREFIX, BINUTILS_ROOT, and GCC_ROOT will affect both compilers
3006 at the same time and may make one of the two compilers operate
3007 improperly if set during invocation of the wrong compiler. It is also
3008 very important that the linker uses the proper @file{libgcc.a} GCC
3009 library -- that is, the one from the C++ compiler installation. The
3010 implicit link command as suggested in the @command{gnatmake} command
3011 from the former example can be replaced by an explicit link command with
3012 the full-verbosity option in order to verify which library is used:
3015 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3017 If there is a problem due to interfering environment variables, it can
3018 be worked around by using an intermediate script. The following example
3019 shows the proper script to use when GNAT has not been installed at its
3020 default location and g++ has been installed at its default location:
3028 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3032 Using a non-GNU C++ compiler: The commands previously described can be
3033 used to insure that the C++ linker is used. Nonetheless, you need to add
3034 a few more parameters to the link command line, depending on the exception
3037 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3038 to the libgcc libraries are required:
3043 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3044 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3047 Where CC is the name of the non-GNU C++ compiler.
3049 If the @code{zero cost} exception mechanism is used, and the platform
3050 supports automatic registration of exception tables (e.g. Solaris or IRIX),
3051 paths to more objects are required:
3056 CC `gcc -print-file-name=crtbegin.o` $* \
3057 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3058 `gcc -print-file-name=crtend.o`
3059 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3062 If the @code{zero cost} exception mechanism is used, and the platform
3063 doesn't support automatic registration of exception tables (e.g. HP-UX,
3064 Tru64 or AIX), the simple approach described above will not work and
3065 a pre-linking phase using GNAT will be necessary.
3069 @node A Simple Example
3070 @subsection A Simple Example
3072 The following example, provided as part of the GNAT examples, shows how
3073 to achieve procedural interfacing between Ada and C++ in both
3074 directions. The C++ class A has two methods. The first method is exported
3075 to Ada by the means of an extern C wrapper function. The second method
3076 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3077 a limited record with a layout comparable to the C++ class. The Ada
3078 subprogram, in turn, calls the C++ method. So, starting from the C++
3079 main program, the process passes back and forth between the two
3083 Here are the compilation commands:
3085 $ gnatmake -c simple_cpp_interface
3088 $ gnatbind -n simple_cpp_interface
3089 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3090 -lstdc++ ex7.o cpp_main.o
3094 Here are the corresponding sources:
3102 void adainit (void);
3103 void adafinal (void);
3104 void method1 (A *t);
3126 class A : public Origin @{
3128 void method1 (void);
3129 void method2 (int v);
3139 extern "C" @{ void ada_method2 (A *t, int v);@}
3141 void A::method1 (void)
3144 printf ("in A::method1, a_value = %d \n",a_value);
3148 void A::method2 (int v)
3150 ada_method2 (this, v);
3151 printf ("in A::method2, a_value = %d \n",a_value);
3158 printf ("in A::A, a_value = %d \n",a_value);
3162 @smallexample @c ada
3164 package body Simple_Cpp_Interface is
3166 procedure Ada_Method2 (This : in out A; V : Integer) is
3172 end Simple_Cpp_Interface;
3175 package Simple_Cpp_Interface is
3178 Vptr : System.Address;
3182 pragma Convention (C, A);
3184 procedure Method1 (This : in out A);
3185 pragma Import (C, Method1);
3187 procedure Ada_Method2 (This : in out A; V : Integer);
3188 pragma Export (C, Ada_Method2);
3190 end Simple_Cpp_Interface;
3193 @node Interfacing with C++ at the Class Level
3194 @subsection Interfacing with C++ at the Class Level
3196 In this section we demonstrate the GNAT features for interfacing with
3197 C++ by means of an example making use of Ada 2005 abstract interface
3198 types. This example consists of a classification of animals; classes
3199 have been used to model our main classification of animals, and
3200 interfaces provide support for the management of secondary
3201 classifications. We first demonstrate a case in which the types and
3202 constructors are defined on the C++ side and imported from the Ada
3203 side, and latter the reverse case.
3205 The root of our derivation will be the @code{Animal} class, with a
3206 single private attribute (the @code{Age} of the animal) and two public
3207 primitives to set and get the value of this attribute.
3212 @b{virtual} void Set_Age (int New_Age);
3213 @b{virtual} int Age ();
3219 Abstract interface types are defined in C++ by means of classes with pure
3220 virtual functions and no data members. In our example we will use two
3221 interfaces that provide support for the common management of @code{Carnivore}
3222 and @code{Domestic} animals:
3225 @b{class} Carnivore @{
3227 @b{virtual} int Number_Of_Teeth () = 0;
3230 @b{class} Domestic @{
3232 @b{virtual void} Set_Owner (char* Name) = 0;
3236 Using these declarations, we can now say that a @code{Dog} is an animal that is
3237 both Carnivore and Domestic, that is:
3240 @b{class} Dog : Animal, Carnivore, Domestic @{
3242 @b{virtual} int Number_Of_Teeth ();
3243 @b{virtual} void Set_Owner (char* Name);
3245 Dog(); // Constructor
3252 In the following examples we will assume that the previous declarations are
3253 located in a file named @code{animals.h}. The following package demonstrates
3254 how to import these C++ declarations from the Ada side:
3256 @smallexample @c ada
3257 with Interfaces.C.Strings; use Interfaces.C.Strings;
3259 type Carnivore is interface;
3260 pragma Convention (C_Plus_Plus, Carnivore);
3261 function Number_Of_Teeth (X : Carnivore)
3262 return Natural is abstract;
3264 type Domestic is interface;
3265 pragma Convention (C_Plus_Plus, Set_Owner);
3267 (X : in out Domestic;
3268 Name : Chars_Ptr) is abstract;
3270 type Animal is tagged record
3273 pragma Import (C_Plus_Plus, Animal);
3275 procedure Set_Age (X : in out Animal; Age : Integer);
3276 pragma Import (C_Plus_Plus, Set_Age);
3278 function Age (X : Animal) return Integer;
3279 pragma Import (C_Plus_Plus, Age);
3281 type Dog is new Animal and Carnivore and Domestic with record
3282 Tooth_Count : Natural;
3283 Owner : String (1 .. 30);
3285 pragma Import (C_Plus_Plus, Dog);
3287 function Number_Of_Teeth (A : Dog) return Integer;
3288 pragma Import (C_Plus_Plus, Number_Of_Teeth);
3290 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3291 pragma Import (C_Plus_Plus, Set_Owner);
3293 function New_Dog return Dog'Class;
3294 pragma CPP_Constructor (New_Dog);
3295 pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3299 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3300 interfacing with these C++ classes is easy. The only requirement is that all
3301 the primitives and components must be declared exactly in the same order in
3304 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3305 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3306 the arguments to the called primitives will be the same as for C++. For the
3307 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3308 to indicate that they have been defined on the C++ side; this is required
3309 because the dispatch table associated with these tagged types will be built
3310 in the C++ side and therefore will not contain the predefined Ada primitives
3311 which Ada would otherwise expect.
3313 As the reader can see there is no need to indicate the C++ mangled names
3314 associated with each subprogram because it is assumed that all the calls to
3315 these primitives will be dispatching calls. The only exception is the
3316 constructor, which must be registered with the compiler by means of
3317 @code{pragma CPP_Constructor} and needs to provide its associated C++
3318 mangled name because the Ada compiler generates direct calls to it.
3320 With the above packages we can now declare objects of type Dog on the Ada side
3321 and dispatch calls to the corresponding subprograms on the C++ side. We can
3322 also extend the tagged type Dog with further fields and primitives, and
3323 override some of its C++ primitives on the Ada side. For example, here we have
3324 a type derivation defined on the Ada side that inherits all the dispatching
3325 primitives of the ancestor from the C++ side.
3328 @b{with} Animals; @b{use} Animals;
3329 @b{package} Vaccinated_Animals @b{is}
3330 @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3331 @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3332 @b{end} Vaccinated_Animals;
3335 It is important to note that, because of the ABI compatibility, the programmer
3336 does not need to add any further information to indicate either the object
3337 layout or the dispatch table entry associated with each dispatching operation.
3339 Now let us define all the types and constructors on the Ada side and export
3340 them to C++, using the same hierarchy of our previous example:
3342 @smallexample @c ada
3343 with Interfaces.C.Strings;
3344 use Interfaces.C.Strings;
3346 type Carnivore is interface;
3347 pragma Convention (C_Plus_Plus, Carnivore);
3348 function Number_Of_Teeth (X : Carnivore)
3349 return Natural is abstract;
3351 type Domestic is interface;
3352 pragma Convention (C_Plus_Plus, Set_Owner);
3354 (X : in out Domestic;
3355 Name : Chars_Ptr) is abstract;
3357 type Animal is tagged record
3360 pragma Convention (C_Plus_Plus, Animal);
3362 procedure Set_Age (X : in out Animal; Age : Integer);
3363 pragma Export (C_Plus_Plus, Set_Age);
3365 function Age (X : Animal) return Integer;
3366 pragma Export (C_Plus_Plus, Age);
3368 type Dog is new Animal and Carnivore and Domestic with record
3369 Tooth_Count : Natural;
3370 Owner : String (1 .. 30);
3372 pragma Convention (C_Plus_Plus, Dog);
3374 function Number_Of_Teeth (A : Dog) return Integer;
3375 pragma Export (C_Plus_Plus, Number_Of_Teeth);
3377 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3378 pragma Export (C_Plus_Plus, Set_Owner);
3380 function New_Dog return Dog'Class;
3381 pragma Export (C_Plus_Plus, New_Dog);
3385 Compared with our previous example the only difference is the use of
3386 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3387 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3388 nothing else to be done; as explained above, the only requirement is that all
3389 the primitives and components are declared in exactly the same order.
3391 For completeness, let us see a brief C++ main program that uses the
3392 declarations available in @code{animals.h} (presented in our first example) to
3393 import and use the declarations from the Ada side, properly initializing and
3394 finalizing the Ada run-time system along the way:
3397 @b{#include} "animals.h"
3398 @b{#include} <iostream>
3399 @b{using namespace} std;
3401 void Check_Carnivore (Carnivore *obj) @{ ... @}
3402 void Check_Domestic (Domestic *obj) @{ ... @}
3403 void Check_Animal (Animal *obj) @{ ... @}
3404 void Check_Dog (Dog *obj) @{ ... @}
3407 void adainit (void);
3408 void adafinal (void);
3414 Dog *obj = new_dog(); // Ada constructor
3415 Check_Carnivore (obj); // Check secondary DT
3416 Check_Domestic (obj); // Check secondary DT
3417 Check_Animal (obj); // Check primary DT
3418 Check_Dog (obj); // Check primary DT
3423 adainit (); test(); adafinal ();
3428 @node Comparison between GNAT and C/C++ Compilation Models
3429 @section Comparison between GNAT and C/C++ Compilation Models
3432 The GNAT model of compilation is close to the C and C++ models. You can
3433 think of Ada specs as corresponding to header files in C. As in C, you
3434 don't need to compile specs; they are compiled when they are used. The
3435 Ada @code{with} is similar in effect to the @code{#include} of a C
3438 One notable difference is that, in Ada, you may compile specs separately
3439 to check them for semantic and syntactic accuracy. This is not always
3440 possible with C headers because they are fragments of programs that have
3441 less specific syntactic or semantic rules.
3443 The other major difference is the requirement for running the binder,
3444 which performs two important functions. First, it checks for
3445 consistency. In C or C++, the only defense against assembling
3446 inconsistent programs lies outside the compiler, in a makefile, for
3447 example. The binder satisfies the Ada requirement that it be impossible
3448 to construct an inconsistent program when the compiler is used in normal
3451 @cindex Elaboration order control
3452 The other important function of the binder is to deal with elaboration
3453 issues. There are also elaboration issues in C++ that are handled
3454 automatically. This automatic handling has the advantage of being
3455 simpler to use, but the C++ programmer has no control over elaboration.
3456 Where @code{gnatbind} might complain there was no valid order of
3457 elaboration, a C++ compiler would simply construct a program that
3458 malfunctioned at run time.
3461 @node Comparison between GNAT and Conventional Ada Library Models
3462 @section Comparison between GNAT and Conventional Ada Library Models
3465 This section is intended for Ada programmers who have
3466 used an Ada compiler implementing the traditional Ada library
3467 model, as described in the Ada Reference Manual.
3469 @cindex GNAT library
3470 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3471 source files themselves acts as the library. Compiling Ada programs does
3472 not generate any centralized information, but rather an object file and
3473 a ALI file, which are of interest only to the binder and linker.
3474 In a traditional system, the compiler reads information not only from
3475 the source file being compiled, but also from the centralized library.
3476 This means that the effect of a compilation depends on what has been
3477 previously compiled. In particular:
3481 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3482 to the version of the unit most recently compiled into the library.
3485 Inlining is effective only if the necessary body has already been
3486 compiled into the library.
3489 Compiling a unit may obsolete other units in the library.
3493 In GNAT, compiling one unit never affects the compilation of any other
3494 units because the compiler reads only source files. Only changes to source
3495 files can affect the results of a compilation. In particular:
3499 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3500 to the source version of the unit that is currently accessible to the
3505 Inlining requires the appropriate source files for the package or
3506 subprogram bodies to be available to the compiler. Inlining is always
3507 effective, independent of the order in which units are complied.
3510 Compiling a unit never affects any other compilations. The editing of
3511 sources may cause previous compilations to be out of date if they
3512 depended on the source file being modified.
3516 The most important result of these differences is that order of compilation
3517 is never significant in GNAT. There is no situation in which one is
3518 required to do one compilation before another. What shows up as order of
3519 compilation requirements in the traditional Ada library becomes, in
3520 GNAT, simple source dependencies; in other words, there is only a set
3521 of rules saying what source files must be present when a file is
3525 @node Placement of temporary files
3526 @section Placement of temporary files
3527 @cindex Temporary files (user control over placement)
3530 GNAT creates temporary files in the directory designated by the environment
3531 variable @env{TMPDIR}.
3532 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3533 for detailed information on how environment variables are resolved.
3534 For most users the easiest way to make use of this feature is to simply
3535 define @env{TMPDIR} as a job level logical name).
3536 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3537 for compiler temporary files, then you can include something like the
3538 following command in your @file{LOGIN.COM} file:
3541 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3545 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3546 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3547 designated by @env{TEMP}.
3548 If none of these environment variables are defined then GNAT uses the
3549 directory designated by the logical name @code{SYS$SCRATCH:}
3550 (by default the user's home directory). If all else fails
3551 GNAT uses the current directory for temporary files.
3554 @c *************************
3555 @node Compiling Using gcc
3556 @chapter Compiling Using @command{gcc}
3559 This chapter discusses how to compile Ada programs using the @command{gcc}
3560 command. It also describes the set of switches
3561 that can be used to control the behavior of the compiler.
3563 * Compiling Programs::
3564 * Switches for gcc::
3565 * Search Paths and the Run-Time Library (RTL)::
3566 * Order of Compilation Issues::
3570 @node Compiling Programs
3571 @section Compiling Programs
3574 The first step in creating an executable program is to compile the units
3575 of the program using the @command{gcc} command. You must compile the
3580 the body file (@file{.adb}) for a library level subprogram or generic
3584 the spec file (@file{.ads}) for a library level package or generic
3585 package that has no body
3588 the body file (@file{.adb}) for a library level package
3589 or generic package that has a body
3594 You need @emph{not} compile the following files
3599 the spec of a library unit which has a body
3606 because they are compiled as part of compiling related units. GNAT
3608 when the corresponding body is compiled, and subunits when the parent is
3611 @cindex cannot generate code
3612 If you attempt to compile any of these files, you will get one of the
3613 following error messages (where fff is the name of the file you compiled):
3616 cannot generate code for file @var{fff} (package spec)
3617 to check package spec, use -gnatc
3619 cannot generate code for file @var{fff} (missing subunits)
3620 to check parent unit, use -gnatc
3622 cannot generate code for file @var{fff} (subprogram spec)
3623 to check subprogram spec, use -gnatc
3625 cannot generate code for file @var{fff} (subunit)
3626 to check subunit, use -gnatc
3630 As indicated by the above error messages, if you want to submit
3631 one of these files to the compiler to check for correct semantics
3632 without generating code, then use the @option{-gnatc} switch.
3634 The basic command for compiling a file containing an Ada unit is
3637 $ gcc -c [@var{switches}] @file{file name}
3641 where @var{file name} is the name of the Ada file (usually
3643 @file{.ads} for a spec or @file{.adb} for a body).
3646 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3648 The result of a successful compilation is an object file, which has the
3649 same name as the source file but an extension of @file{.o} and an Ada
3650 Library Information (ALI) file, which also has the same name as the
3651 source file, but with @file{.ali} as the extension. GNAT creates these
3652 two output files in the current directory, but you may specify a source
3653 file in any directory using an absolute or relative path specification
3654 containing the directory information.
3657 @command{gcc} is actually a driver program that looks at the extensions of
3658 the file arguments and loads the appropriate compiler. For example, the
3659 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3660 These programs are in directories known to the driver program (in some
3661 configurations via environment variables you set), but need not be in
3662 your path. The @command{gcc} driver also calls the assembler and any other
3663 utilities needed to complete the generation of the required object
3666 It is possible to supply several file names on the same @command{gcc}
3667 command. This causes @command{gcc} to call the appropriate compiler for
3668 each file. For example, the following command lists three separate
3669 files to be compiled:
3672 $ gcc -c x.adb y.adb z.c
3676 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3677 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3678 The compiler generates three object files @file{x.o}, @file{y.o} and
3679 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3680 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3683 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3686 @node Switches for gcc
3687 @section Switches for @command{gcc}
3690 The @command{gcc} command accepts switches that control the
3691 compilation process. These switches are fully described in this section.
3692 First we briefly list all the switches, in alphabetical order, then we
3693 describe the switches in more detail in functionally grouped sections.
3695 More switches exist for GCC than those documented here, especially
3696 for specific targets. However, their use is not recommended as
3697 they may change code generation in ways that are incompatible with
3698 the Ada run-time library, or can cause inconsistencies between
3702 * Output and Error Message Control::
3703 * Warning Message Control::
3704 * Debugging and Assertion Control::
3705 * Validity Checking::
3708 * Using gcc for Syntax Checking::
3709 * Using gcc for Semantic Checking::
3710 * Compiling Different Versions of Ada::
3711 * Character Set Control::
3712 * File Naming Control::
3713 * Subprogram Inlining Control::
3714 * Auxiliary Output Control::
3715 * Debugging Control::
3716 * Exception Handling Control::
3717 * Units to Sources Mapping Files::
3718 * Integrated Preprocessing::
3719 * Code Generation Control::
3728 @cindex @option{-b} (@command{gcc})
3729 @item -b @var{target}
3730 Compile your program to run on @var{target}, which is the name of a
3731 system configuration. You must have a GNAT cross-compiler built if
3732 @var{target} is not the same as your host system.
3735 @cindex @option{-B} (@command{gcc})
3736 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3737 from @var{dir} instead of the default location. Only use this switch
3738 when multiple versions of the GNAT compiler are available. See the
3739 @command{gcc} manual page for further details. You would normally use the
3740 @option{-b} or @option{-V} switch instead.
3743 @cindex @option{-c} (@command{gcc})
3744 Compile. Always use this switch when compiling Ada programs.
3746 Note: for some other languages when using @command{gcc}, notably in
3747 the case of C and C++, it is possible to use
3748 use @command{gcc} without a @option{-c} switch to
3749 compile and link in one step. In the case of GNAT, you
3750 cannot use this approach, because the binder must be run
3751 and @command{gcc} cannot be used to run the GNAT binder.
3755 @cindex @option{-fno-inline} (@command{gcc})
3756 Suppresses all back-end inlining, even if other optimization or inlining
3758 This includes suppression of inlining that results
3759 from the use of the pragma @code{Inline_Always}.
3760 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3761 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3762 effect if this switch is present.
3764 @item -fno-strict-aliasing
3765 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3766 Causes the compiler to avoid assumptions regarding non-aliasing
3767 of objects of different types. See
3768 @ref{Optimization and Strict Aliasing} for details.
3771 @cindex @option{-fstack-check} (@command{gcc})
3772 Activates stack checking.
3773 See @ref{Stack Overflow Checking} for details.
3776 @cindex @option{-fstack-usage} (@command{gcc})
3777 Makes the compiler output stack usage information for the program, on a
3778 per-function basis. See @ref{Static Stack Usage Analysis} for details.
3780 @item -fcallgraph-info[=su]
3781 @cindex @option{-fcallgraph-info} (@command{gcc})
3782 Makes the compiler output callgraph information for the program, on a
3783 per-file basis. The information is generated in the VCG format. It can
3784 be decorated with stack-usage per-node information.
3787 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3788 Generate debugging information. This information is stored in the object
3789 file and copied from there to the final executable file by the linker,
3790 where it can be read by the debugger. You must use the
3791 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3794 @cindex @option{-gnat83} (@command{gcc})
3795 Enforce Ada 83 restrictions.
3798 @cindex @option{-gnat95} (@command{gcc})
3799 Enforce Ada 95 restrictions.
3802 @cindex @option{-gnat05} (@command{gcc})
3803 Allow full Ada 2005 features.
3806 @cindex @option{-gnata} (@command{gcc})
3807 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3808 activated. Note that these pragmas can also be controlled using the
3809 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3812 @cindex @option{-gnatA} (@command{gcc})
3813 Avoid processing @file{gnat.adc}. If a gnat.adc file is present,
3817 @cindex @option{-gnatb} (@command{gcc})
3818 Generate brief messages to @file{stderr} even if verbose mode set.
3821 @cindex @option{-gnatc} (@command{gcc})
3822 Check syntax and semantics only (no code generation attempted).
3825 @cindex @option{-gnatd} (@command{gcc})
3826 Specify debug options for the compiler. The string of characters after
3827 the @option{-gnatd} specify the specific debug options. The possible
3828 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3829 compiler source file @file{debug.adb} for details of the implemented
3830 debug options. Certain debug options are relevant to applications
3831 programmers, and these are documented at appropriate points in this
3835 @cindex @option{-gnatD} (@command{gcc})
3836 Create expanded source files for source level debugging. This switch
3837 also suppress generation of cross-reference information
3838 (see @option{-gnatx}).
3840 @item -gnatec=@var{path}
3841 @cindex @option{-gnatec} (@command{gcc})
3842 Specify a configuration pragma file
3844 (the equal sign is optional)
3846 (@pxref{The Configuration Pragmas Files}).
3848 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
3849 @cindex @option{-gnateD} (@command{gcc})
3850 Defines a symbol, associated with value, for preprocessing.
3851 (@pxref{Integrated Preprocessing}).
3854 @cindex @option{-gnatef} (@command{gcc})
3855 Display full source path name in brief error messages.
3857 @item -gnatem=@var{path}
3858 @cindex @option{-gnatem} (@command{gcc})
3859 Specify a mapping file
3861 (the equal sign is optional)
3863 (@pxref{Units to Sources Mapping Files}).
3865 @item -gnatep=@var{file}
3866 @cindex @option{-gnatep} (@command{gcc})
3867 Specify a preprocessing data file
3869 (the equal sign is optional)
3871 (@pxref{Integrated Preprocessing}).
3874 @cindex @option{-gnatE} (@command{gcc})
3875 Full dynamic elaboration checks.
3878 @cindex @option{-gnatf} (@command{gcc})
3879 Full errors. Multiple errors per line, all undefined references, do not
3880 attempt to suppress cascaded errors.
3883 @cindex @option{-gnatF} (@command{gcc})
3884 Externals names are folded to all uppercase.
3886 @item ^-gnatg^/GNAT_INTERNAL^
3887 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
3888 Internal GNAT implementation mode. This should not be used for
3889 applications programs, it is intended only for use by the compiler
3890 and its run-time library. For documentation, see the GNAT sources.
3891 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
3892 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
3893 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
3894 so that all standard warnings and all standard style options are turned on.
3895 All warnings and style error messages are treated as errors.
3898 @cindex @option{-gnatG} (@command{gcc})
3899 List generated expanded code in source form.
3901 @item ^-gnath^/HELP^
3902 @cindex @option{^-gnath^/HELP^} (@command{gcc})
3903 Output usage information. The output is written to @file{stdout}.
3905 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3906 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
3907 Identifier character set
3909 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3911 For details of the possible selections for @var{c},
3912 see @ref{Character Set Control}.
3914 @item ^-gnatI^/IGNORE_REP_CLAUSES^
3915 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
3916 Ignore representation clauses. When this switch is used, all
3917 representation clauses are treated as comments. This is useful
3918 when initially porting code where you want to ignore rep clause
3919 problems, and also for compiling foreign code (particularly
3923 @cindex @option{-gnatjnn} (@command{gcc})
3924 Reformat error messages to fit on nn character lines
3926 @item -gnatk=@var{n}
3927 @cindex @option{-gnatk} (@command{gcc})
3928 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3931 @cindex @option{-gnatl} (@command{gcc})
3932 Output full source listing with embedded error messages.
3935 @cindex @option{-gnatL} (@command{gcc})
3936 Used in conjunction with -gnatG or -gnatD to intersperse original
3937 source lines (as comment lines with line numbers) in the expanded
3940 @item -gnatm=@var{n}
3941 @cindex @option{-gnatm} (@command{gcc})
3942 Limit number of detected error or warning messages to @var{n}
3943 where @var{n} is in the range 1..999_999. The default setting if
3944 no switch is given is 9999. Compilation is terminated if this
3945 limit is exceeded. The equal sign here is optional.
3948 @cindex @option{-gnatn} (@command{gcc})
3949 Activate inlining for subprograms for which
3950 pragma @code{inline} is specified. This inlining is performed
3951 by the GCC back-end.
3954 @cindex @option{-gnatN} (@command{gcc})
3955 Activate front end inlining for subprograms for which
3956 pragma @code{Inline} is specified. This inlining is performed
3957 by the front end and will be visible in the
3958 @option{-gnatG} output.
3959 In some cases, this has proved more effective than the back end
3960 inlining resulting from the use of
3963 @option{-gnatN} automatically implies
3964 @option{-gnatn} so it is not necessary
3965 to specify both options. There are a few cases that the back-end inlining
3966 catches that cannot be dealt with in the front-end.
3969 @cindex @option{-gnato} (@command{gcc})
3970 Enable numeric overflow checking (which is not normally enabled by
3971 default). Not that division by zero is a separate check that is not
3972 controlled by this switch (division by zero checking is on by default).
3975 @cindex @option{-gnatp} (@command{gcc})
3976 Suppress all checks.
3979 @cindex @option{-gnatP} (@command{gcc})
3980 Enable polling. This is required on some systems (notably Windows NT) to
3981 obtain asynchronous abort and asynchronous transfer of control capability.
3982 See the description of pragma Polling in the GNAT Reference Manual for
3986 @cindex @option{-gnatq} (@command{gcc})
3987 Don't quit; try semantics, even if parse errors.
3990 @cindex @option{-gnatQ} (@command{gcc})
3991 Don't quit; generate @file{ALI} and tree files even if illegalities.
3993 @item ^-gnatR[0/1/2/3[s]]^/REPRESENTATION_INFO^
3994 @cindex @option{-gnatR} (@command{gcc})
3995 Output representation information for declared types and objects.
3998 @cindex @option{-gnats} (@command{gcc})
4002 @cindex @option{-gnatS} (@command{gcc})
4003 Print package Standard.
4006 @cindex @option{-gnatt} (@command{gcc})
4007 Generate tree output file.
4009 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4010 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4011 All compiler tables start at @var{nnn} times usual starting size.
4014 @cindex @option{-gnatu} (@command{gcc})
4015 List units for this compilation.
4018 @cindex @option{-gnatU} (@command{gcc})
4019 Tag all error messages with the unique string ``error:''
4022 @cindex @option{-gnatv} (@command{gcc})
4023 Verbose mode. Full error output with source lines to @file{stdout}.
4026 @cindex @option{-gnatV} (@command{gcc})
4027 Control level of validity checking. See separate section describing
4030 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}[,...])^
4031 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4033 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4034 the exact warnings that
4035 are enabled or disabled (@pxref{Warning Message Control}).
4037 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4038 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4039 Wide character encoding method
4041 (@var{e}=n/h/u/s/e/8).
4044 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4048 @cindex @option{-gnatx} (@command{gcc})
4049 Suppress generation of cross-reference information.
4051 @item ^-gnaty^/STYLE_CHECKS=(option,option..)^
4052 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4053 Enable built-in style checks (@pxref{Style Checking}).
4055 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4056 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4057 Distribution stub generation and compilation
4059 (@var{m}=r/c for receiver/caller stubs).
4062 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4063 to be generated and compiled).
4066 @item ^-I^/SEARCH=^@var{dir}
4067 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4069 Direct GNAT to search the @var{dir} directory for source files needed by
4070 the current compilation
4071 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4073 @item ^-I-^/NOCURRENT_DIRECTORY^
4074 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4076 Except for the source file named in the command line, do not look for source
4077 files in the directory containing the source file named in the command line
4078 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4082 @cindex @option{-mbig-switch} (@command{gcc})
4083 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4084 This standard gcc switch causes the compiler to use larger offsets in its
4085 jump table representation for @code{case} statements.
4086 This may result in less efficient code, but is sometimes necessary
4087 (for example on HP-UX targets)
4088 @cindex HP-UX and @option{-mbig-switch} option
4089 in order to compile large and/or nested @code{case} statements.
4092 @cindex @option{-o} (@command{gcc})
4093 This switch is used in @command{gcc} to redirect the generated object file
4094 and its associated ALI file. Beware of this switch with GNAT, because it may
4095 cause the object file and ALI file to have different names which in turn
4096 may confuse the binder and the linker.
4100 @cindex @option{-nostdinc} (@command{gcc})
4101 Inhibit the search of the default location for the GNAT Run Time
4102 Library (RTL) source files.
4105 @cindex @option{-nostdlib} (@command{gcc})
4106 Inhibit the search of the default location for the GNAT Run Time
4107 Library (RTL) ALI files.
4111 @cindex @option{-O} (@command{gcc})
4112 @var{n} controls the optimization level.
4116 No optimization, the default setting if no @option{-O} appears
4119 Normal optimization, the default if you specify @option{-O} without
4120 an operand. A good compromise between code quality and compilation
4124 Extensive optimization, may improve execution time, possibly at the cost of
4125 substantially increased compilation time.
4128 Same as @option{-O2}, and also includes inline expansion for small subprograms
4132 Optimize space usage
4136 See also @ref{Optimization Levels}.
4141 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4142 Equivalent to @option{/OPTIMIZE=NONE}.
4143 This is the default behavior in the absence of an @option{/OPTIMIZE}
4146 @item /OPTIMIZE[=(keyword[,...])]
4147 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4148 Selects the level of optimization for your program. The supported
4149 keywords are as follows:
4152 Perform most optimizations, including those that
4154 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4155 without keyword options.
4158 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4161 Perform some optimizations, but omit ones that are costly.
4164 Same as @code{SOME}.
4167 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4168 automatic inlining of small subprograms within a unit
4171 Try to unroll loops. This keyword may be specified together with
4172 any keyword above other than @code{NONE}. Loop unrolling
4173 usually, but not always, improves the performance of programs.
4176 Optimize space usage
4180 See also @ref{Optimization Levels}.
4184 @item -pass-exit-codes
4185 @cindex @option{-pass-exit-codes} (@command{gcc})
4186 Catch exit codes from the compiler and use the most meaningful as
4190 @item --RTS=@var{rts-path}
4191 @cindex @option{--RTS} (@command{gcc})
4192 Specifies the default location of the runtime library. Same meaning as the
4193 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4196 @cindex @option{^-S^/ASM^} (@command{gcc})
4197 ^Used in place of @option{-c} to^Used to^
4198 cause the assembler source file to be
4199 generated, using @file{^.s^.S^} as the extension,
4200 instead of the object file.
4201 This may be useful if you need to examine the generated assembly code.
4203 @item ^-fverbose-asm^/VERBOSE_ASM^
4204 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4205 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4206 to cause the generated assembly code file to be annotated with variable
4207 names, making it significantly easier to follow.
4210 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4211 Show commands generated by the @command{gcc} driver. Normally used only for
4212 debugging purposes or if you need to be sure what version of the
4213 compiler you are executing.
4217 @cindex @option{-V} (@command{gcc})
4218 Execute @var{ver} version of the compiler. This is the @command{gcc}
4219 version, not the GNAT version.
4222 @item ^-w^/NO_BACK_END_WARNINGS^
4223 @cindex @option{-w} (@command{gcc})
4224 Turn off warnings generated by the back end of the compiler. Use of
4225 this switch also causes the default for front end warnings to be set
4226 to suppress (as though @option{-gnatws} had appeared at the start of
4232 @c Combining qualifiers does not work on VMS
4233 You may combine a sequence of GNAT switches into a single switch. For
4234 example, the combined switch
4236 @cindex Combining GNAT switches
4242 is equivalent to specifying the following sequence of switches:
4245 -gnato -gnatf -gnati3
4250 The following restrictions apply to the combination of switches
4255 The switch @option{-gnatc} if combined with other switches must come
4256 first in the string.
4259 The switch @option{-gnats} if combined with other switches must come
4260 first in the string.
4264 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4265 may not be combined with any other switches.
4269 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4270 switch), then all further characters in the switch are interpreted
4271 as style modifiers (see description of @option{-gnaty}).
4274 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4275 switch), then all further characters in the switch are interpreted
4276 as debug flags (see description of @option{-gnatd}).
4279 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4280 switch), then all further characters in the switch are interpreted
4281 as warning mode modifiers (see description of @option{-gnatw}).
4284 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4285 switch), then all further characters in the switch are interpreted
4286 as validity checking options (see description of @option{-gnatV}).
4290 @node Output and Error Message Control
4291 @subsection Output and Error Message Control
4295 The standard default format for error messages is called ``brief format''.
4296 Brief format messages are written to @file{stderr} (the standard error
4297 file) and have the following form:
4300 e.adb:3:04: Incorrect spelling of keyword "function"
4301 e.adb:4:20: ";" should be "is"
4305 The first integer after the file name is the line number in the file,
4306 and the second integer is the column number within the line.
4308 @code{GPS} can parse the error messages
4309 and point to the referenced character.
4311 The following switches provide control over the error message
4317 @cindex @option{-gnatv} (@command{gcc})
4320 The v stands for verbose.
4322 The effect of this setting is to write long-format error
4323 messages to @file{stdout} (the standard output file.
4324 The same program compiled with the
4325 @option{-gnatv} switch would generate:
4329 3. funcion X (Q : Integer)
4331 >>> Incorrect spelling of keyword "function"
4334 >>> ";" should be "is"
4339 The vertical bar indicates the location of the error, and the @samp{>>>}
4340 prefix can be used to search for error messages. When this switch is
4341 used the only source lines output are those with errors.
4344 @cindex @option{-gnatl} (@command{gcc})
4346 The @code{l} stands for list.
4348 This switch causes a full listing of
4349 the file to be generated. In the case where a body is
4350 compiled, the corresponding spec is also listed, along
4351 with any subunits. Typical output from compiling a package
4352 body @file{p.adb} might look like:
4354 @smallexample @c ada
4358 1. package body p is
4360 3. procedure a is separate;
4371 2. pragma Elaborate_Body
4395 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4396 standard output is redirected, a brief summary is written to
4397 @file{stderr} (standard error) giving the number of error messages and
4398 warning messages generated.
4400 @item -^gnatl^OUTPUT_FILE^=file
4401 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4402 This has the same effect as @option{-gnatl} except that the output is
4403 written to a file instead of to standard output. If the given name
4404 @file{fname} does not start with a period, then it is the full name
4405 of the file to be written. If @file{fname} is an extension, it is
4406 appended to the name of the file being compiled. For example, if
4407 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4408 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4411 @cindex @option{-gnatU} (@command{gcc})
4412 This switch forces all error messages to be preceded by the unique
4413 string ``error:''. This means that error messages take a few more
4414 characters in space, but allows easy searching for and identification
4418 @cindex @option{-gnatb} (@command{gcc})
4420 The @code{b} stands for brief.
4422 This switch causes GNAT to generate the
4423 brief format error messages to @file{stderr} (the standard error
4424 file) as well as the verbose
4425 format message or full listing (which as usual is written to
4426 @file{stdout} (the standard output file).
4428 @item -gnatm=@var{n}
4429 @cindex @option{-gnatm} (@command{gcc})
4431 The @code{m} stands for maximum.
4433 @var{n} is a decimal integer in the
4434 range of 1 to 999 and limits the number of error messages to be
4435 generated. For example, using @option{-gnatm2} might yield
4438 e.adb:3:04: Incorrect spelling of keyword "function"
4439 e.adb:5:35: missing ".."
4440 fatal error: maximum errors reached
4441 compilation abandoned
4445 Note that the equal sign is optional, so the switches
4446 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4449 @cindex @option{-gnatf} (@command{gcc})
4450 @cindex Error messages, suppressing
4452 The @code{f} stands for full.
4454 Normally, the compiler suppresses error messages that are likely to be
4455 redundant. This switch causes all error
4456 messages to be generated. In particular, in the case of
4457 references to undefined variables. If a given variable is referenced
4458 several times, the normal format of messages is
4460 e.adb:7:07: "V" is undefined (more references follow)
4464 where the parenthetical comment warns that there are additional
4465 references to the variable @code{V}. Compiling the same program with the
4466 @option{-gnatf} switch yields
4469 e.adb:7:07: "V" is undefined
4470 e.adb:8:07: "V" is undefined
4471 e.adb:8:12: "V" is undefined
4472 e.adb:8:16: "V" is undefined
4473 e.adb:9:07: "V" is undefined
4474 e.adb:9:12: "V" is undefined
4478 The @option{-gnatf} switch also generates additional information for
4479 some error messages. Some examples are:
4483 Full details on entities not available in high integrity mode
4485 Details on possibly non-portable unchecked conversion
4487 List possible interpretations for ambiguous calls
4489 Additional details on incorrect parameters
4493 @cindex @option{-gnatjnn} (@command{gcc})
4494 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4495 with continuation lines are treated as though the continuation lines were
4496 separate messages (and so a warning with two continuation lines counts as
4497 three warnings, and is listed as three separate messages).
4499 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4500 messages are output in a different manner. A message and all its continuation
4501 lines are treated as a unit, and count as only one warning or message in the
4502 statistics totals. Furthermore, the message is reformatted so that no line
4503 is longer than nn characters.
4506 @cindex @option{-gnatq} (@command{gcc})
4508 The @code{q} stands for quit (really ``don't quit'').
4510 In normal operation mode, the compiler first parses the program and
4511 determines if there are any syntax errors. If there are, appropriate
4512 error messages are generated and compilation is immediately terminated.
4514 GNAT to continue with semantic analysis even if syntax errors have been
4515 found. This may enable the detection of more errors in a single run. On
4516 the other hand, the semantic analyzer is more likely to encounter some
4517 internal fatal error when given a syntactically invalid tree.
4520 @cindex @option{-gnatQ} (@command{gcc})
4521 In normal operation mode, the @file{ALI} file is not generated if any
4522 illegalities are detected in the program. The use of @option{-gnatQ} forces
4523 generation of the @file{ALI} file. This file is marked as being in
4524 error, so it cannot be used for binding purposes, but it does contain
4525 reasonably complete cross-reference information, and thus may be useful
4526 for use by tools (e.g. semantic browsing tools or integrated development
4527 environments) that are driven from the @file{ALI} file. This switch
4528 implies @option{-gnatq}, since the semantic phase must be run to get a
4529 meaningful ALI file.
4531 In addition, if @option{-gnatt} is also specified, then the tree file is
4532 generated even if there are illegalities. It may be useful in this case
4533 to also specify @option{-gnatq} to ensure that full semantic processing
4534 occurs. The resulting tree file can be processed by ASIS, for the purpose
4535 of providing partial information about illegal units, but if the error
4536 causes the tree to be badly malformed, then ASIS may crash during the
4539 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4540 being in error, @command{gnatmake} will attempt to recompile the source when it
4541 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4543 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4544 since ALI files are never generated if @option{-gnats} is set.
4548 @node Warning Message Control
4549 @subsection Warning Message Control
4550 @cindex Warning messages
4552 In addition to error messages, which correspond to illegalities as defined
4553 in the Ada Reference Manual, the compiler detects two kinds of warning
4556 First, the compiler considers some constructs suspicious and generates a
4557 warning message to alert you to a possible error. Second, if the
4558 compiler detects a situation that is sure to raise an exception at
4559 run time, it generates a warning message. The following shows an example
4560 of warning messages:
4562 e.adb:4:24: warning: creation of object may raise Storage_Error
4563 e.adb:10:17: warning: static value out of range
4564 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4568 GNAT considers a large number of situations as appropriate
4569 for the generation of warning messages. As always, warnings are not
4570 definite indications of errors. For example, if you do an out-of-range
4571 assignment with the deliberate intention of raising a
4572 @code{Constraint_Error} exception, then the warning that may be
4573 issued does not indicate an error. Some of the situations for which GNAT
4574 issues warnings (at least some of the time) are given in the following
4575 list. This list is not complete, and new warnings are often added to
4576 subsequent versions of GNAT. The list is intended to give a general idea
4577 of the kinds of warnings that are generated.
4581 Possible infinitely recursive calls
4584 Out-of-range values being assigned
4587 Possible order of elaboration problems
4590 Assertions (pragma Assert) that are sure to fail
4596 Address clauses with possibly unaligned values, or where an attempt is
4597 made to overlay a smaller variable with a larger one.
4600 Fixed-point type declarations with a null range
4603 Direct_IO or Sequential_IO instantiated with a type that has access values
4606 Variables that are never assigned a value
4609 Variables that are referenced before being initialized
4612 Task entries with no corresponding @code{accept} statement
4615 Duplicate accepts for the same task entry in a @code{select}
4618 Objects that take too much storage
4621 Unchecked conversion between types of differing sizes
4624 Missing @code{return} statement along some execution path in a function
4627 Incorrect (unrecognized) pragmas
4630 Incorrect external names
4633 Allocation from empty storage pool
4636 Potentially blocking operation in protected type
4639 Suspicious parenthesization of expressions
4642 Mismatching bounds in an aggregate
4645 Attempt to return local value by reference
4648 Premature instantiation of a generic body
4651 Attempt to pack aliased components
4654 Out of bounds array subscripts
4657 Wrong length on string assignment
4660 Violations of style rules if style checking is enabled
4663 Unused @code{with} clauses
4666 @code{Bit_Order} usage that does not have any effect
4669 @code{Standard.Duration} used to resolve universal fixed expression
4672 Dereference of possibly null value
4675 Declaration that is likely to cause storage error
4678 Internal GNAT unit @code{with}'ed by application unit
4681 Values known to be out of range at compile time
4684 Unreferenced labels and variables
4687 Address overlays that could clobber memory
4690 Unexpected initialization when address clause present
4693 Bad alignment for address clause
4696 Useless type conversions
4699 Redundant assignment statements and other redundant constructs
4702 Useless exception handlers
4705 Accidental hiding of name by child unit
4708 Access before elaboration detected at compile time
4711 A range in a @code{for} loop that is known to be null or might be null
4716 The following section lists compiler switches that are available
4717 to control the handling of warning messages. It is also possible
4718 to exercise much finer control over what warnings are issued and
4719 suppressed using the GNAT pragma Warnings, which is documented
4720 in the GNAT Reference manual.
4725 @emph{Activate all optional errors.}
4726 @cindex @option{-gnatwa} (@command{gcc})
4727 This switch activates most optional warning messages, see remaining list
4728 in this section for details on optional warning messages that can be
4729 individually controlled. The warnings that are not turned on by this
4731 @option{-gnatwd} (implicit dereferencing),
4732 @option{-gnatwh} (hiding),
4733 @option{-gnatwl} (elaboration warnings),
4734 @option{-gnatw.o} (warn on values set by out parameters ignored)
4735 and @option{-gnatwt} (tracking of deleted conditional code).
4736 All other optional warnings are turned on.
4739 @emph{Suppress all optional errors.}
4740 @cindex @option{-gnatwA} (@command{gcc})
4741 This switch suppresses all optional warning messages, see remaining list
4742 in this section for details on optional warning messages that can be
4743 individually controlled.
4746 @emph{Activate warnings on failing assertions.}
4747 @cindex @option{-gnatw.a} (@command{gcc})
4748 @cindex Assert failures
4749 This switch activates warnings for assertions where the compiler can tell at
4750 compile time that the assertion will fail. Note that this warning is given
4751 even if assertions are disabled. The default is that such warnings are
4755 @emph{Suppress warnings on failing assertions.}
4756 @cindex @option{-gnatw.A} (@command{gcc})
4757 @cindex Assert failures
4758 This switch suppresses warnings for assertions where the compiler can tell at
4759 compile time that the assertion will fail.
4762 @emph{Activate warnings on bad fixed values.}
4763 @cindex @option{-gnatwb} (@command{gcc})
4764 @cindex Bad fixed values
4765 @cindex Fixed-point Small value
4767 This switch activates warnings for static fixed-point expressions whose
4768 value is not an exact multiple of Small. Such values are implementation
4769 dependent, since an implementation is free to choose either of the multiples
4770 that surround the value. GNAT always chooses the closer one, but this is not
4771 required behavior, and it is better to specify a value that is an exact
4772 multiple, ensuring predictable execution. The default is that such warnings
4776 @emph{Suppress warnings on bad fixed values.}
4777 @cindex @option{-gnatwB} (@command{gcc})
4778 This switch suppresses warnings for static fixed-point expressions whose
4779 value is not an exact multiple of Small.
4782 @emph{Activate warnings on conditionals.}
4783 @cindex @option{-gnatwc} (@command{gcc})
4784 @cindex Conditionals, constant
4785 This switch activates warnings for conditional expressions used in
4786 tests that are known to be True or False at compile time. The default
4787 is that such warnings are not generated.
4788 Note that this warning does
4789 not get issued for the use of boolean variables or constants whose
4790 values are known at compile time, since this is a standard technique
4791 for conditional compilation in Ada, and this would generate too many
4792 false positive warnings.
4794 This warning option also activates a special test for comparisons using
4795 the operators ``>='' and`` <=''.
4796 If the compiler can tell that only the equality condition is possible,
4797 then it will warn that the ``>'' or ``<'' part of the test
4798 is useless and that the operator could be replaced by ``=''.
4799 An example would be comparing a @code{Natural} variable <= 0.
4801 This warning option also generates warnings if
4802 one or both tests is optimized away in a membership test for integer
4803 values if the result can be determined at compile time. Range tests on
4804 enumeration types are not included, since it is common for such tests
4805 to include an end point.
4807 This warning can also be turned on using @option{-gnatwa}.
4810 @emph{Suppress warnings on conditionals.}
4811 @cindex @option{-gnatwC} (@command{gcc})
4812 This switch suppresses warnings for conditional expressions used in
4813 tests that are known to be True or False at compile time.
4816 @emph{Activate warnings on missing component clauses.}
4817 @cindex @option{-gnatw.c} (@command{gcc})
4818 @cindex Component clause, missing
4819 This switch activates warnings for record components where a record
4820 representation clause is present and has component clauses for the
4821 majority, but not all, of the components. A warning is given for each
4822 component for which no component clause is present.
4824 This warning can also be turned on using @option{-gnatwa}.
4827 @emph{Suppress warnings on missing component clauses.}
4828 @cindex @option{-gnatwC} (@command{gcc})
4829 This switch suppresses warnings for record components that are
4830 missing a component clause in the situation described above.
4833 @emph{Activate warnings on implicit dereferencing.}
4834 @cindex @option{-gnatwd} (@command{gcc})
4835 If this switch is set, then the use of a prefix of an access type
4836 in an indexed component, slice, or selected component without an
4837 explicit @code{.all} will generate a warning. With this warning
4838 enabled, access checks occur only at points where an explicit
4839 @code{.all} appears in the source code (assuming no warnings are
4840 generated as a result of this switch). The default is that such
4841 warnings are not generated.
4842 Note that @option{-gnatwa} does not affect the setting of
4843 this warning option.
4846 @emph{Suppress warnings on implicit dereferencing.}
4847 @cindex @option{-gnatwD} (@command{gcc})
4848 @cindex Implicit dereferencing
4849 @cindex Dereferencing, implicit
4850 This switch suppresses warnings for implicit dereferences in
4851 indexed components, slices, and selected components.
4854 @emph{Treat warnings as errors.}
4855 @cindex @option{-gnatwe} (@command{gcc})
4856 @cindex Warnings, treat as error
4857 This switch causes warning messages to be treated as errors.
4858 The warning string still appears, but the warning messages are counted
4859 as errors, and prevent the generation of an object file.
4862 @emph{Activate warnings on unreferenced formals.}
4863 @cindex @option{-gnatwf} (@command{gcc})
4864 @cindex Formals, unreferenced
4865 This switch causes a warning to be generated if a formal parameter
4866 is not referenced in the body of the subprogram. This warning can
4867 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
4868 default is that these warnings are not generated.
4871 @emph{Suppress warnings on unreferenced formals.}
4872 @cindex @option{-gnatwF} (@command{gcc})
4873 This switch suppresses warnings for unreferenced formal
4874 parameters. Note that the
4875 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4876 effect of warning on unreferenced entities other than subprogram
4880 @emph{Activate warnings on unrecognized pragmas.}
4881 @cindex @option{-gnatwg} (@command{gcc})
4882 @cindex Pragmas, unrecognized
4883 This switch causes a warning to be generated if an unrecognized
4884 pragma is encountered. Apart from issuing this warning, the
4885 pragma is ignored and has no effect. This warning can
4886 also be turned on using @option{-gnatwa}. The default
4887 is that such warnings are issued (satisfying the Ada Reference
4888 Manual requirement that such warnings appear).
4891 @emph{Suppress warnings on unrecognized pragmas.}
4892 @cindex @option{-gnatwG} (@command{gcc})
4893 This switch suppresses warnings for unrecognized pragmas.
4896 @emph{Activate warnings on hiding.}
4897 @cindex @option{-gnatwh} (@command{gcc})
4898 @cindex Hiding of Declarations
4899 This switch activates warnings on hiding declarations.
4900 A declaration is considered hiding
4901 if it is for a non-overloadable entity, and it declares an entity with the
4902 same name as some other entity that is directly or use-visible. The default
4903 is that such warnings are not generated.
4904 Note that @option{-gnatwa} does not affect the setting of this warning option.
4907 @emph{Suppress warnings on hiding.}
4908 @cindex @option{-gnatwH} (@command{gcc})
4909 This switch suppresses warnings on hiding declarations.
4912 @emph{Activate warnings on implementation units.}
4913 @cindex @option{-gnatwi} (@command{gcc})
4914 This switch activates warnings for a @code{with} of an internal GNAT
4915 implementation unit, defined as any unit from the @code{Ada},
4916 @code{Interfaces}, @code{GNAT},
4917 ^^@code{DEC},^ or @code{System}
4918 hierarchies that is not
4919 documented in either the Ada Reference Manual or the GNAT
4920 Programmer's Reference Manual. Such units are intended only
4921 for internal implementation purposes and should not be @code{with}'ed
4922 by user programs. The default is that such warnings are generated
4923 This warning can also be turned on using @option{-gnatwa}.
4926 @emph{Disable warnings on implementation units.}
4927 @cindex @option{-gnatwI} (@command{gcc})
4928 This switch disables warnings for a @code{with} of an internal GNAT
4929 implementation unit.
4932 @emph{Activate warnings on obsolescent features (Annex J).}
4933 @cindex @option{-gnatwj} (@command{gcc})
4934 @cindex Features, obsolescent
4935 @cindex Obsolescent features
4936 If this warning option is activated, then warnings are generated for
4937 calls to subprograms marked with @code{pragma Obsolescent} and
4938 for use of features in Annex J of the Ada Reference Manual. In the
4939 case of Annex J, not all features are flagged. In particular use
4940 of the renamed packages (like @code{Text_IO}) and use of package
4941 @code{ASCII} are not flagged, since these are very common and
4942 would generate many annoying positive warnings. The default is that
4943 such warnings are not generated. This warning is also turned on by
4944 the use of @option{-gnatwa}.
4946 In addition to the above cases, warnings are also generated for
4947 GNAT features that have been provided in past versions but which
4948 have been superseded (typically by features in the new Ada standard).
4949 For example, @code{pragma Ravenscar} will be flagged since its
4950 function is replaced by @code{pragma Profile(Ravenscar)}.
4952 Note that this warning option functions differently from the
4953 restriction @code{No_Obsolescent_Features} in two respects.
4954 First, the restriction applies only to annex J features.
4955 Second, the restriction does flag uses of package @code{ASCII}.
4958 @emph{Suppress warnings on obsolescent features (Annex J).}
4959 @cindex @option{-gnatwJ} (@command{gcc})
4960 This switch disables warnings on use of obsolescent features.
4963 @emph{Activate warnings on variables that could be constants.}
4964 @cindex @option{-gnatwk} (@command{gcc})
4965 This switch activates warnings for variables that are initialized but
4966 never modified, and then could be declared constants. The default is that
4967 such warnings are not given.
4968 This warning can also be turned on using @option{-gnatwa}.
4971 @emph{Suppress warnings on variables that could be constants.}
4972 @cindex @option{-gnatwK} (@command{gcc})
4973 This switch disables warnings on variables that could be declared constants.
4976 @emph{Activate warnings for missing elaboration pragmas.}
4977 @cindex @option{-gnatwl} (@command{gcc})
4978 @cindex Elaboration, warnings
4979 This switch activates warnings on missing
4980 @code{Elaborate_All} and @code{Elaborate} pragmas.
4981 See the section in this guide on elaboration checking for details on
4982 when such pragmas should be used. Warnings are also generated if you
4983 are using the static mode of elaboration, and a @code{pragma Elaborate}
4984 is encountered. The default is that such warnings
4986 This warning is not automatically turned on by the use of @option{-gnatwa}.
4989 @emph{Suppress warnings for missing elaboration pragmas.}
4990 @cindex @option{-gnatwL} (@command{gcc})
4991 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
4992 See the section in this guide on elaboration checking for details on
4993 when such pragmas should be used.
4996 @emph{Activate warnings on modified but unreferenced variables.}
4997 @cindex @option{-gnatwm} (@command{gcc})
4998 This switch activates warnings for variables that are assigned (using
4999 an initialization value or with one or more assignment statements) but
5000 whose value is never read. The warning is suppressed for volatile
5001 variables and also for variables that are renamings of other variables
5002 or for which an address clause is given.
5003 This warning can also be turned on using @option{-gnatwa}.
5004 The default is that these warnings are not given.
5007 @emph{Disable warnings on modified but unreferenced variables.}
5008 @cindex @option{-gnatwM} (@command{gcc})
5009 This switch disables warnings for variables that are assigned or
5010 initialized, but never read.
5013 @emph{Set normal warnings mode.}
5014 @cindex @option{-gnatwn} (@command{gcc})
5015 This switch sets normal warning mode, in which enabled warnings are
5016 issued and treated as warnings rather than errors. This is the default
5017 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5018 an explicit @option{-gnatws} or
5019 @option{-gnatwe}. It also cancels the effect of the
5020 implicit @option{-gnatwe} that is activated by the
5021 use of @option{-gnatg}.
5024 @emph{Activate warnings on address clause overlays.}
5025 @cindex @option{-gnatwo} (@command{gcc})
5026 @cindex Address Clauses, warnings
5027 This switch activates warnings for possibly unintended initialization
5028 effects of defining address clauses that cause one variable to overlap
5029 another. The default is that such warnings are generated.
5030 This warning can also be turned on using @option{-gnatwa}.
5033 @emph{Suppress warnings on address clause overlays.}
5034 @cindex @option{-gnatwO} (@command{gcc})
5035 This switch suppresses warnings on possibly unintended initialization
5036 effects of defining address clauses that cause one variable to overlap
5040 @emph{Activate warnings on modified but unreferenced out parameters.}
5041 @cindex @option{-gnatw.o} (@command{gcc})
5042 This switch activates warnings for variables that are modified by using
5043 them as actuals for a call to a procedure with an out mode formal, where
5044 the resulting assigned value is never read. It is applicable in the case
5045 where there is more than one out mode formal. If there is only one out
5046 mode formal, the warning is issued by default (controlled by -gnatwu).
5047 The warning is suppressed for volatile
5048 variables and also for variables that are renamings of other variables
5049 or for which an address clause is given.
5050 The default is that these warnings are not given. Note that this warning
5051 is not included in -gnatwa, it must be activated explicitly.
5054 @emph{Disable warnings on modified but unreferenced out parameters.}
5055 @cindex @option{-gnatw.O} (@command{gcc})
5056 This switch suppresses warnings for variables that are modified by using
5057 them as actuals for a call to a procedure with an out mode formal, where
5058 the resulting assigned value is never read.
5061 @emph{Activate warnings on ineffective pragma Inlines.}
5062 @cindex @option{-gnatwp} (@command{gcc})
5063 @cindex Inlining, warnings
5064 This switch activates warnings for failure of front end inlining
5065 (activated by @option{-gnatN}) to inline a particular call. There are
5066 many reasons for not being able to inline a call, including most
5067 commonly that the call is too complex to inline. The default is
5068 that such warnings are not given.
5069 This warning can also be turned on using @option{-gnatwa}.
5070 Warnings on ineffective inlining by the gcc back-end can be activated
5071 separately, using the gcc switch -Winline.
5074 @emph{Suppress warnings on ineffective pragma Inlines.}
5075 @cindex @option{-gnatwP} (@command{gcc})
5076 This switch suppresses warnings on ineffective pragma Inlines. If the
5077 inlining mechanism cannot inline a call, it will simply ignore the
5081 @emph{Activate warnings on questionable missing parentheses.}
5082 @cindex @option{-gnatwq} (@command{gcc})
5083 @cindex Parentheses, warnings
5084 This switch activates warnings for cases where parentheses are not used and
5085 the result is potential ambiguity from a readers point of view. For example
5086 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5087 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5088 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5089 follow the rule of always parenthesizing to make the association clear, and
5090 this warning switch warns if such parentheses are not present. The default
5091 is that these warnings are given.
5092 This warning can also be turned on using @option{-gnatwa}.
5095 @emph{Suppress warnings on questionable missing parentheses.}
5096 @cindex @option{-gnatwQ} (@command{gcc})
5097 This switch suppresses warnings for cases where the association is not
5098 clear and the use of parentheses is preferred.
5101 @emph{Activate warnings on redundant constructs.}
5102 @cindex @option{-gnatwr} (@command{gcc})
5103 This switch activates warnings for redundant constructs. The following
5104 is the current list of constructs regarded as redundant:
5108 Assignment of an item to itself.
5110 Type conversion that converts an expression to its own type.
5112 Use of the attribute @code{Base} where @code{typ'Base} is the same
5115 Use of pragma @code{Pack} when all components are placed by a record
5116 representation clause.
5118 Exception handler containing only a reraise statement (raise with no
5119 operand) which has no effect.
5121 Use of the operator abs on an operand that is known at compile time
5124 Comparison of boolean expressions to an explicit True value.
5127 This warning can also be turned on using @option{-gnatwa}.
5128 The default is that warnings for redundant constructs are not given.
5131 @emph{Suppress warnings on redundant constructs.}
5132 @cindex @option{-gnatwR} (@command{gcc})
5133 This switch suppresses warnings for redundant constructs.
5136 @emph{Suppress all warnings.}
5137 @cindex @option{-gnatws} (@command{gcc})
5138 This switch completely suppresses the
5139 output of all warning messages from the GNAT front end.
5140 Note that it does not suppress warnings from the @command{gcc} back end.
5141 To suppress these back end warnings as well, use the switch @option{-w}
5142 in addition to @option{-gnatws}.
5145 @emph{Activate warnings for tracking of deleted conditional code.}
5146 @cindex @option{-gnatwt} (@command{gcc})
5147 @cindex Deactivated code, warnings
5148 @cindex Deleted code, warnings
5149 This switch activates warnings for tracking of code in conditionals (IF and
5150 CASE statements) that is detected to be dead code which cannot be executed, and
5151 which is removed by the front end. This warning is off by default, and is not
5152 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5153 useful for detecting deactivated code in certified applications.
5156 @emph{Suppress warnings for tracking of deleted conditional code.}
5157 @cindex @option{-gnatwT} (@command{gcc})
5158 This switch suppresses warnings for tracking of deleted conditional code.
5161 @emph{Activate warnings on unused entities.}
5162 @cindex @option{-gnatwu} (@command{gcc})
5163 This switch activates warnings to be generated for entities that
5164 are declared but not referenced, and for units that are @code{with}'ed
5166 referenced. In the case of packages, a warning is also generated if
5167 no entities in the package are referenced. This means that if the package
5168 is referenced but the only references are in @code{use}
5169 clauses or @code{renames}
5170 declarations, a warning is still generated. A warning is also generated
5171 for a generic package that is @code{with}'ed but never instantiated.
5172 In the case where a package or subprogram body is compiled, and there
5173 is a @code{with} on the corresponding spec
5174 that is only referenced in the body,
5175 a warning is also generated, noting that the
5176 @code{with} can be moved to the body. The default is that
5177 such warnings are not generated.
5178 This switch also activates warnings on unreferenced formals
5179 (it includes the effect of @option{-gnatwf}).
5180 This warning can also be turned on using @option{-gnatwa}.
5183 @emph{Suppress warnings on unused entities.}
5184 @cindex @option{-gnatwU} (@command{gcc})
5185 This switch suppresses warnings for unused entities and packages.
5186 It also turns off warnings on unreferenced formals (and thus includes
5187 the effect of @option{-gnatwF}).
5190 @emph{Activate warnings on unassigned variables.}
5191 @cindex @option{-gnatwv} (@command{gcc})
5192 @cindex Unassigned variable warnings
5193 This switch activates warnings for access to variables which
5194 may not be properly initialized. The default is that
5195 such warnings are generated.
5196 This warning can also be turned on using @option{-gnatwa}.
5199 @emph{Suppress warnings on unassigned variables.}
5200 @cindex @option{-gnatwV} (@command{gcc})
5201 This switch suppresses warnings for access to variables which
5202 may not be properly initialized.
5203 For variables of a composite type, the warning can also be suppressed in
5204 Ada 2005 by using a default initialization with a box. For example, if
5205 Table is an array of records whose components are only partially uninitialized,
5206 then the following code:
5208 @smallexample @c ada
5209 Tab : Table := (others => <>);
5212 will suppress warnings on subsequent statements that access components
5216 @emph{Activate warnings on wrong low bound assumption.}
5217 @cindex @option{-gnatww} (@command{gcc})
5218 @cindex String indexing warnings
5219 This switch activates warnings for indexing an unconstrained string parameter
5220 with a literal or S'Length. This is a case where the code is assuming that the
5221 low bound is one, which is in general not true (for example when a slice is
5222 passed). The default is that such warnings are generated.
5223 This warning can also be turned on using @option{-gnatwa}.
5226 @emph{Suppress warnings on wrong low bound assumption.}
5227 @cindex @option{-gnatwW} (@command{gcc})
5228 This switch activates warnings for indexing an unconstrained string parameter
5229 with a literal or S'Length. This warning can also be suppressed by providing
5230 an Assert pragma that checks the low bound, for example:
5232 @smallexample @c ada
5233 procedure K (S : String) is
5234 pragma Assert (S'First = 1);
5239 @emph{Activate warnings on Export/Import pragmas.}
5240 @cindex @option{-gnatwx} (@command{gcc})
5241 @cindex Export/Import pragma warnings
5242 This switch activates warnings on Export/Import pragmas when
5243 the compiler detects a possible conflict between the Ada and
5244 foreign language calling sequences. For example, the use of
5245 default parameters in a convention C procedure is dubious
5246 because the C compiler cannot supply the proper default, so
5247 a warning is issued. The default is that such warnings are
5249 This warning can also be turned on using @option{-gnatwa}.
5252 @emph{Suppress warnings on Export/Import pragmas.}
5253 @cindex @option{-gnatwX} (@command{gcc})
5254 This switch suppresses warnings on Export/Import pragmas.
5255 The sense of this is that you are telling the compiler that
5256 you know what you are doing in writing the pragma, and it
5257 should not complain at you.
5260 @emph{Activate warnings for No_Exception_Propagation mode.}
5261 @cindex @option{-gnatwm} (@command{gcc})
5262 This switch activates warnings for exception usage when pragma Restrictions
5263 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5264 explicit exception raises which are not covered by a local handler, and for
5265 exception handlers which do not cover a local raise. The default is that these
5266 warnings are not given.
5269 @emph{Disable warnings for No_Exception_Propagation mode.}
5270 This switch disables warnings for exception usage when pragma Restrictions
5271 (No_Exception_Propagation) is in effect.
5274 @emph{Activate warnings for Ada 2005 compatibility issues.}
5275 @cindex @option{-gnatwy} (@command{gcc})
5276 @cindex Ada 2005 compatibility issues warnings
5277 For the most part Ada 2005 is upwards compatible with Ada 95,
5278 but there are some exceptions (for example the fact that
5279 @code{interface} is now a reserved word in Ada 2005). This
5280 switch activates several warnings to help in identifying
5281 and correcting such incompatibilities. The default is that
5282 these warnings are generated. Note that at one point Ada 2005
5283 was called Ada 0Y, hence the choice of character.
5284 This warning can also be turned on using @option{-gnatwa}.
5287 @emph{Disable warnings for Ada 2005 compatibility issues.}
5288 @cindex @option{-gnatwY} (@command{gcc})
5289 @cindex Ada 2005 compatibility issues warnings
5290 This switch suppresses several warnings intended to help in identifying
5291 incompatibilities between Ada 95 and Ada 2005.
5294 @emph{Activate warnings on unchecked conversions.}
5295 @cindex @option{-gnatwz} (@command{gcc})
5296 @cindex Unchecked_Conversion warnings
5297 This switch activates warnings for unchecked conversions
5298 where the types are known at compile time to have different
5300 is that such warnings are generated.
5301 This warning can also be turned on using @option{-gnatwa}.
5304 @emph{Suppress warnings on unchecked conversions.}
5305 @cindex @option{-gnatwZ} (@command{gcc})
5306 This switch suppresses warnings for unchecked conversions
5307 where the types are known at compile time to have different
5310 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5311 @cindex @option{-Wuninitialized}
5312 The warnings controlled by the @option{-gnatw} switch are generated by the
5313 front end of the compiler. In some cases, the @option{^gcc^GCC^} back end
5314 can provide additional warnings. One such useful warning is provided by
5315 @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^}. This must be used in
5316 conjunction with turning on optimization mode. This causes the flow
5317 analysis circuits of the back end optimizer to output additional
5318 warnings about uninitialized variables.
5320 @item ^-w^/NO_BACK_END_WARNINGS^
5322 This switch suppresses warnings from the @option{^gcc^GCC^} back end. The
5323 code generator detects a number of warning situations that are missed
5324 by the @option{GNAT} front end, and this switch can be used to suppress them.
5325 The use of this switch also sets the default front end warning mode to
5326 @option{-gnatws}, that is, front end warnings suppressed as well.
5332 A string of warning parameters can be used in the same parameter. For example:
5339 will turn on all optional warnings except for elaboration pragma warnings,
5340 and also specify that warnings should be treated as errors.
5342 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5367 @node Debugging and Assertion Control
5368 @subsection Debugging and Assertion Control
5372 @cindex @option{-gnata} (@command{gcc})
5378 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5379 are ignored. This switch, where @samp{a} stands for assert, causes
5380 @code{Assert} and @code{Debug} pragmas to be activated.
5382 The pragmas have the form:
5386 @b{pragma} Assert (@var{Boolean-expression} [,
5387 @var{static-string-expression}])
5388 @b{pragma} Debug (@var{procedure call})
5393 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5394 If the result is @code{True}, the pragma has no effect (other than
5395 possible side effects from evaluating the expression). If the result is
5396 @code{False}, the exception @code{Assert_Failure} declared in the package
5397 @code{System.Assertions} is
5398 raised (passing @var{static-string-expression}, if present, as the
5399 message associated with the exception). If no string expression is
5400 given the default is a string giving the file name and line number
5403 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5404 @code{pragma Debug} may appear within a declaration sequence, allowing
5405 debugging procedures to be called between declarations.
5408 @item /DEBUG[=debug-level]
5410 Specifies how much debugging information is to be included in
5411 the resulting object file where 'debug-level' is one of the following:
5414 Include both debugger symbol records and traceback
5416 This is the default setting.
5418 Include both debugger symbol records and traceback in
5421 Excludes both debugger symbol records and traceback
5422 the object file. Same as /NODEBUG.
5424 Includes only debugger symbol records in the object
5425 file. Note that this doesn't include traceback information.
5430 @node Validity Checking
5431 @subsection Validity Checking
5432 @findex Validity Checking
5435 The Ada Reference Manual has specific requirements for checking
5436 for invalid values. In particular, RM 13.9.1 requires that the
5437 evaluation of invalid values (for example from unchecked conversions),
5438 not result in erroneous execution. In GNAT, the result of such an
5439 evaluation in normal default mode is to either use the value
5440 unmodified, or to raise Constraint_Error in those cases where use
5441 of the unmodified value would cause erroneous execution. The cases
5442 where unmodified values might lead to erroneous execution are case
5443 statements (where a wild jump might result from an invalid value),
5444 and subscripts on the left hand side (where memory corruption could
5445 occur as a result of an invalid value).
5447 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5450 The @code{x} argument is a string of letters that
5451 indicate validity checks that are performed or not performed in addition
5452 to the default checks described above.
5455 The options allowed for this qualifier
5456 indicate validity checks that are performed or not performed in addition
5457 to the default checks described above.
5463 @emph{All validity checks.}
5464 @cindex @option{-gnatVa} (@command{gcc})
5465 All validity checks are turned on.
5467 That is, @option{-gnatVa} is
5468 equivalent to @option{gnatVcdfimorst}.
5472 @emph{Validity checks for copies.}
5473 @cindex @option{-gnatVc} (@command{gcc})
5474 The right hand side of assignments, and the initializing values of
5475 object declarations are validity checked.
5478 @emph{Default (RM) validity checks.}
5479 @cindex @option{-gnatVd} (@command{gcc})
5480 Some validity checks are done by default following normal Ada semantics
5482 A check is done in case statements that the expression is within the range
5483 of the subtype. If it is not, Constraint_Error is raised.
5484 For assignments to array components, a check is done that the expression used
5485 as index is within the range. If it is not, Constraint_Error is raised.
5486 Both these validity checks may be turned off using switch @option{-gnatVD}.
5487 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5488 switch @option{-gnatVd} will leave the checks turned on.
5489 Switch @option{-gnatVD} should be used only if you are sure that all such
5490 expressions have valid values. If you use this switch and invalid values
5491 are present, then the program is erroneous, and wild jumps or memory
5492 overwriting may occur.
5495 @emph{Validity checks for elementary components.}
5496 @cindex @option{-gnatVe} (@command{gcc})
5497 In the absence of this switch, assignments to record or array components are
5498 not validity checked, even if validity checks for assignments generally
5499 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5500 require valid data, but assignment of individual components does. So for
5501 example, there is a difference between copying the elements of an array with a
5502 slice assignment, compared to assigning element by element in a loop. This
5503 switch allows you to turn off validity checking for components, even when they
5504 are assigned component by component.
5507 @emph{Validity checks for floating-point values.}
5508 @cindex @option{-gnatVf} (@command{gcc})
5509 In the absence of this switch, validity checking occurs only for discrete
5510 values. If @option{-gnatVf} is specified, then validity checking also applies
5511 for floating-point values, and NaNs and infinities are considered invalid,
5512 as well as out of range values for constrained types. Note that this means
5513 that standard IEEE infinity mode is not allowed. The exact contexts
5514 in which floating-point values are checked depends on the setting of other
5515 options. For example,
5516 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5517 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5518 (the order does not matter) specifies that floating-point parameters of mode
5519 @code{in} should be validity checked.
5522 @emph{Validity checks for @code{in} mode parameters}
5523 @cindex @option{-gnatVi} (@command{gcc})
5524 Arguments for parameters of mode @code{in} are validity checked in function
5525 and procedure calls at the point of call.
5528 @emph{Validity checks for @code{in out} mode parameters.}
5529 @cindex @option{-gnatVm} (@command{gcc})
5530 Arguments for parameters of mode @code{in out} are validity checked in
5531 procedure calls at the point of call. The @code{'m'} here stands for
5532 modify, since this concerns parameters that can be modified by the call.
5533 Note that there is no specific option to test @code{out} parameters,
5534 but any reference within the subprogram will be tested in the usual
5535 manner, and if an invalid value is copied back, any reference to it
5536 will be subject to validity checking.
5539 @emph{No validity checks.}
5540 @cindex @option{-gnatVn} (@command{gcc})
5541 This switch turns off all validity checking, including the default checking
5542 for case statements and left hand side subscripts. Note that the use of
5543 the switch @option{-gnatp} suppresses all run-time checks, including
5544 validity checks, and thus implies @option{-gnatVn}. When this switch
5545 is used, it cancels any other @option{-gnatV} previously issued.
5548 @emph{Validity checks for operator and attribute operands.}
5549 @cindex @option{-gnatVo} (@command{gcc})
5550 Arguments for predefined operators and attributes are validity checked.
5551 This includes all operators in package @code{Standard},
5552 the shift operators defined as intrinsic in package @code{Interfaces}
5553 and operands for attributes such as @code{Pos}. Checks are also made
5554 on individual component values for composite comparisons, and on the
5555 expressions in type conversions and qualified expressions. Checks are
5556 also made on explicit ranges using .. (e.g. slices, loops etc).
5559 @emph{Validity checks for parameters.}
5560 @cindex @option{-gnatVp} (@command{gcc})
5561 This controls the treatment of parameters within a subprogram (as opposed
5562 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5563 of parameters on a call. If either of these call options is used, then
5564 normally an assumption is made within a subprogram that the input arguments
5565 have been validity checking at the point of call, and do not need checking
5566 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5567 is not made, and parameters are not assumed to be valid, so their validity
5568 will be checked (or rechecked) within the subprogram.
5571 @emph{Validity checks for function returns.}
5572 @cindex @option{-gnatVr} (@command{gcc})
5573 The expression in @code{return} statements in functions is validity
5577 @emph{Validity checks for subscripts.}
5578 @cindex @option{-gnatVs} (@command{gcc})
5579 All subscripts expressions are checked for validity, whether they appear
5580 on the right side or left side (in default mode only left side subscripts
5581 are validity checked).
5584 @emph{Validity checks for tests.}
5585 @cindex @option{-gnatVt} (@command{gcc})
5586 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5587 statements are checked, as well as guard expressions in entry calls.
5592 The @option{-gnatV} switch may be followed by
5593 ^a string of letters^a list of options^
5594 to turn on a series of validity checking options.
5596 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5597 specifies that in addition to the default validity checking, copies and
5598 function return expressions are to be validity checked.
5599 In order to make it easier
5600 to specify the desired combination of effects,
5602 the upper case letters @code{CDFIMORST} may
5603 be used to turn off the corresponding lower case option.
5606 the prefix @code{NO} on an option turns off the corresponding validity
5609 @item @code{NOCOPIES}
5610 @item @code{NODEFAULT}
5611 @item @code{NOFLOATS}
5612 @item @code{NOIN_PARAMS}
5613 @item @code{NOMOD_PARAMS}
5614 @item @code{NOOPERANDS}
5615 @item @code{NORETURNS}
5616 @item @code{NOSUBSCRIPTS}
5617 @item @code{NOTESTS}
5621 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5622 turns on all validity checking options except for
5623 checking of @code{@b{in out}} procedure arguments.
5625 The specification of additional validity checking generates extra code (and
5626 in the case of @option{-gnatVa} the code expansion can be substantial.
5627 However, these additional checks can be very useful in detecting
5628 uninitialized variables, incorrect use of unchecked conversion, and other
5629 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5630 is useful in conjunction with the extra validity checking, since this
5631 ensures that wherever possible uninitialized variables have invalid values.
5633 See also the pragma @code{Validity_Checks} which allows modification of
5634 the validity checking mode at the program source level, and also allows for
5635 temporary disabling of validity checks.
5637 @node Style Checking
5638 @subsection Style Checking
5639 @findex Style checking
5642 The @option{-gnaty^x^(option,option,...)^} switch
5643 @cindex @option{-gnaty} (@command{gcc})
5644 causes the compiler to
5645 enforce specified style rules. A limited set of style rules has been used
5646 in writing the GNAT sources themselves. This switch allows user programs
5647 to activate all or some of these checks. If the source program fails a
5648 specified style check, an appropriate warning message is given, preceded by
5649 the character sequence ``(style)''.
5651 @code{(option,option,...)} is a sequence of keywords
5654 The string @var{x} is a sequence of letters or digits
5656 indicating the particular style
5657 checks to be performed. The following checks are defined:
5662 @emph{Specify indentation level.}
5663 If a digit from 1-9 appears
5664 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5665 then proper indentation is checked, with the digit indicating the
5666 indentation level required.
5667 The general style of required indentation is as specified by
5668 the examples in the Ada Reference Manual. Full line comments must be
5669 aligned with the @code{--} starting on a column that is a multiple of
5670 the alignment level, or they may be aligned the same way as the following
5671 non-blank line (this is useful when full line comments appear in the middle
5675 @emph{Check attribute casing.}
5676 If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty}
5677 then attribute names, including the case of keywords such as @code{digits}
5678 used as attributes names, must be written in mixed case, that is, the
5679 initial letter and any letter following an underscore must be uppercase.
5680 All other letters must be lowercase.
5682 @item ^A^ARRAY_INDEXES^
5683 @emph{Use of array index numbers in array attributes.}
5684 If the ^letter A^word ARRAY_INDEXES^ appears in the string after
5685 @option{-gnaty} then when using the array attributes First, Last, Range,
5686 or Length, the index number must be omitted for one-dimensional arrays
5687 and is required for multi-dimensional arrays.
5690 @emph{Blanks not allowed at statement end.}
5691 If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then
5692 trailing blanks are not allowed at the end of statements. The purpose of this
5693 rule, together with h (no horizontal tabs), is to enforce a canonical format
5694 for the use of blanks to separate source tokens.
5697 @emph{Check comments.}
5698 If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty}
5699 then comments must meet the following set of rules:
5704 The ``@code{--}'' that starts the column must either start in column one,
5705 or else at least one blank must precede this sequence.
5708 Comments that follow other tokens on a line must have at least one blank
5709 following the ``@code{--}'' at the start of the comment.
5712 Full line comments must have two blanks following the ``@code{--}'' that
5713 starts the comment, with the following exceptions.
5716 A line consisting only of the ``@code{--}'' characters, possibly preceded
5717 by blanks is permitted.
5720 A comment starting with ``@code{--x}'' where @code{x} is a special character
5722 This allows proper processing of the output generated by specialized tools
5723 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5725 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5726 special character is defined as being in one of the ASCII ranges
5727 @code{16#21#..16#2F#} or @code{16#3A#..16#3F#}.
5728 Note that this usage is not permitted
5729 in GNAT implementation units (i.e. when @option{-gnatg} is used).
5732 A line consisting entirely of minus signs, possibly preceded by blanks, is
5733 permitted. This allows the construction of box comments where lines of minus
5734 signs are used to form the top and bottom of the box.
5737 A comment that starts and ends with ``@code{--}'' is permitted as long as at
5738 least one blank follows the initial ``@code{--}''. Together with the preceding
5739 rule, this allows the construction of box comments, as shown in the following
5742 ---------------------------
5743 -- This is a box comment --
5744 -- with two text lines. --
5745 ---------------------------
5749 @item ^d^DOS_LINE_ENDINGS^
5750 @emph{Check no DOS line terminators present.}
5751 If the ^letter d^word DOS_LINE_ENDINGS^ appears in the string after
5752 @option{-gnaty} then all lines must be terminated by a single ASCII.LF
5753 character (in particular the DOS line terminator sequence CR/LF is not
5757 @emph{Check end/exit labels.}
5758 If the ^letter e^word END^ appears in the string after @option{-gnaty} then
5759 optional labels on @code{end} statements ending subprograms and on
5760 @code{exit} statements exiting named loops, are required to be present.
5763 @emph{No form feeds or vertical tabs.}
5764 If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then
5765 neither form feeds nor vertical tab characters are permitted
5769 @emph{GNAT style mode}
5770 If the ^letter g^word GNAT^ appears in the string after @option{-gnaty} then
5771 the set of style check switches is set to match that used by the GNAT sources.
5772 This may be useful when developing code that is eventually intended to be
5773 incorporated into GNAT. For further details, see GNAT sources.
5776 @emph{No horizontal tabs.}
5777 If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then
5778 horizontal tab characters are not permitted in the source text.
5779 Together with the b (no blanks at end of line) check, this
5780 enforces a canonical form for the use of blanks to separate
5784 @emph{Check if-then layout.}
5785 If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty},
5786 then the keyword @code{then} must appear either on the same
5787 line as corresponding @code{if}, or on a line on its own, lined
5788 up under the @code{if} with at least one non-blank line in between
5789 containing all or part of the condition to be tested.
5792 @emph{check mode IN keywords}
5793 If the ^letter I (upper case)^word IN_MODE^ appears in the string
5794 after @option{-gnaty} then mode @code{in} (the default mode) is not
5795 allowed to be given explicitly. @code{in out} is fine,
5796 but not @code{in} on its own.
5799 @emph{Check keyword casing.}
5800 If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then
5801 all keywords must be in lower case (with the exception of keywords
5802 such as @code{digits} used as attribute names to which this check
5806 @emph{Check layout.}
5807 If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then
5808 layout of statement and declaration constructs must follow the
5809 recommendations in the Ada Reference Manual, as indicated by the
5810 form of the syntax rules. For example an @code{else} keyword must
5811 be lined up with the corresponding @code{if} keyword.
5813 There are two respects in which the style rule enforced by this check
5814 option are more liberal than those in the Ada Reference Manual. First
5815 in the case of record declarations, it is permissible to put the
5816 @code{record} keyword on the same line as the @code{type} keyword, and
5817 then the @code{end} in @code{end record} must line up under @code{type}.
5818 This is also permitted when the type declaration is split on two lines.
5819 For example, any of the following three layouts is acceptable:
5821 @smallexample @c ada
5844 Second, in the case of a block statement, a permitted alternative
5845 is to put the block label on the same line as the @code{declare} or
5846 @code{begin} keyword, and then line the @code{end} keyword up under
5847 the block label. For example both the following are permitted:
5849 @smallexample @c ada
5867 The same alternative format is allowed for loops. For example, both of
5868 the following are permitted:
5870 @smallexample @c ada
5872 Clear : while J < 10 loop
5883 @item ^Lnnn^MAX_NESTING=nnn^
5884 @emph{Set maximum nesting level}
5885 If the sequence ^Lnnn^MAX_NESTING=nnn^, where nnn is a decimal number in
5886 the range 0-999, appears in the string after @option{-gnaty} then the
5887 maximum level of nesting of constructs (including subprograms, loops,
5888 blocks, packages, and conditionals) may not exceed the given value. A
5889 value of zero disconnects this style check.
5891 @item ^m^LINE_LENGTH^
5892 @emph{Check maximum line length.}
5893 If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty}
5894 then the length of source lines must not exceed 79 characters, including
5895 any trailing blanks. The value of 79 allows convenient display on an
5896 80 character wide device or window, allowing for possible special
5897 treatment of 80 character lines. Note that this count is of
5898 characters in the source text. This means that a tab character counts
5899 as one character in this count but a wide character sequence counts as
5900 a single character (however many bytes are needed in the encoding).
5902 @item ^Mnnn^MAX_LENGTH=nnn^
5903 @emph{Set maximum line length.}
5904 If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in
5905 the string after @option{-gnaty} then the length of lines must not exceed the
5906 given value. The maximum value that can be specified is 32767.
5908 @item ^n^STANDARD_CASING^
5909 @emph{Check casing of entities in Standard.}
5910 If the ^letter n^word STANDARD_CASING^ appears in the string
5911 after @option{-gnaty} then any identifier from Standard must be cased
5912 to match the presentation in the Ada Reference Manual (for example,
5913 @code{Integer} and @code{ASCII.NUL}).
5915 @item ^o^ORDERED_SUBPROGRAMS^
5916 @emph{Check order of subprogram bodies.}
5917 If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string
5918 after @option{-gnaty} then all subprogram bodies in a given scope
5919 (e.g. a package body) must be in alphabetical order. The ordering
5920 rule uses normal Ada rules for comparing strings, ignoring casing
5921 of letters, except that if there is a trailing numeric suffix, then
5922 the value of this suffix is used in the ordering (e.g. Junk2 comes
5926 @emph{Check pragma casing.}
5927 If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then
5928 pragma names must be written in mixed case, that is, the
5929 initial letter and any letter following an underscore must be uppercase.
5930 All other letters must be lowercase.
5932 @item ^r^REFERENCES^
5933 @emph{Check references.}
5934 If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty}
5935 then all identifier references must be cased in the same way as the
5936 corresponding declaration. No specific casing style is imposed on
5937 identifiers. The only requirement is for consistency of references
5940 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
5941 @emph{Check no statements after THEN/ELSE.}
5942 If the ^letter S^word STATEMENTS_AFTER_THEN_ELSE^ appears in the
5943 string after @option{-gnaty} then it is not permitted to write any
5944 statements on the same line as a THEN OR ELSE keyword following the
5945 keyword in an IF statement. OR ELSE and AND THEN are not affected,
5946 and a special exception allows a pragma to appear after ELSE.
5949 @emph{Check separate specs.}
5950 If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then
5951 separate declarations (``specs'') are required for subprograms (a
5952 body is not allowed to serve as its own declaration). The only
5953 exception is that parameterless library level procedures are
5954 not required to have a separate declaration. This exception covers
5955 the most frequent form of main program procedures.
5958 @emph{Check token spacing.}
5959 If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then
5960 the following token spacing rules are enforced:
5965 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
5968 The token @code{=>} must be surrounded by spaces.
5971 The token @code{<>} must be preceded by a space or a left parenthesis.
5974 Binary operators other than @code{**} must be surrounded by spaces.
5975 There is no restriction on the layout of the @code{**} binary operator.
5978 Colon must be surrounded by spaces.
5981 Colon-equal (assignment, initialization) must be surrounded by spaces.
5984 Comma must be the first non-blank character on the line, or be
5985 immediately preceded by a non-blank character, and must be followed
5989 If the token preceding a left parenthesis ends with a letter or digit, then
5990 a space must separate the two tokens.
5993 A right parenthesis must either be the first non-blank character on
5994 a line, or it must be preceded by a non-blank character.
5997 A semicolon must not be preceded by a space, and must not be followed by
5998 a non-blank character.
6001 A unary plus or minus may not be followed by a space.
6004 A vertical bar must be surrounded by spaces.
6007 @item ^u^UNNECESSARY_BLANK_LINES^
6008 @emph{Check unnecessary blank lines.}
6009 Check for unnecessary blank lines. A blank line is considered
6010 unnecessary if it appears at the end of the file, or if more than
6011 one blank line occurs in sequence.
6013 @item ^x^XTRA_PARENS^
6014 @emph{Check extra parentheses.}
6015 Check for the use of an unnecessary extra level of parentheses (C-style)
6016 around conditions in @code{if} statements, @code{while} statements and
6017 @code{exit} statements.
6022 In the above rules, appearing in column one is always permitted, that is,
6023 counts as meeting either a requirement for a required preceding space,
6024 or as meeting a requirement for no preceding space.
6026 Appearing at the end of a line is also always permitted, that is, counts
6027 as meeting either a requirement for a following space, or as meeting
6028 a requirement for no following space.
6031 If any of these style rules is violated, a message is generated giving
6032 details on the violation. The initial characters of such messages are
6033 always ``@code{(style)}''. Note that these messages are treated as warning
6034 messages, so they normally do not prevent the generation of an object
6035 file. The @option{-gnatwe} switch can be used to treat warning messages,
6036 including style messages, as fatal errors.
6040 @option{-gnaty} on its own (that is not
6041 followed by any letters or digits),
6042 is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6043 options enabled with the exception of @option{-gnatyo},
6044 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6047 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6048 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6049 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6051 an indentation level of 3 is set. This is similar to the standard
6052 checking option that is used for the GNAT sources.
6061 clears any previously set style checks.
6063 @node Run-Time Checks
6064 @subsection Run-Time Checks
6065 @cindex Division by zero
6066 @cindex Access before elaboration
6067 @cindex Checks, division by zero
6068 @cindex Checks, access before elaboration
6069 @cindex Checks, stack overflow checking
6072 If you compile with the default options, GNAT will insert many run-time
6073 checks into the compiled code, including code that performs range
6074 checking against constraints, but not arithmetic overflow checking for
6075 integer operations (including division by zero), checks for access
6076 before elaboration on subprogram calls, or stack overflow checking. All
6077 other run-time checks, as required by the Ada Reference Manual, are
6078 generated by default. The following @command{gcc} switches refine this
6084 @cindex @option{-gnatp} (@command{gcc})
6085 @cindex Suppressing checks
6086 @cindex Checks, suppressing
6088 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
6089 had been present in the source. Validity checks are also suppressed (in
6090 other words @option{-gnatp} also implies @option{-gnatVn}.
6091 Use this switch to improve the performance
6092 of the code at the expense of safety in the presence of invalid data or
6096 @cindex @option{-gnato} (@command{gcc})
6097 @cindex Overflow checks
6098 @cindex Check, overflow
6099 Enables overflow checking for integer operations.
6100 This causes GNAT to generate slower and larger executable
6101 programs by adding code to check for overflow (resulting in raising
6102 @code{Constraint_Error} as required by standard Ada
6103 semantics). These overflow checks correspond to situations in which
6104 the true value of the result of an operation may be outside the base
6105 range of the result type. The following example shows the distinction:
6107 @smallexample @c ada
6108 X1 : Integer := Integer'Last;
6109 X2 : Integer range 1 .. 5 := 5;
6110 X3 : Integer := Integer'Last;
6111 X4 : Integer range 1 .. 5 := 5;
6112 F : Float := 2.0E+20;
6121 Here the first addition results in a value that is outside the base range
6122 of Integer, and hence requires an overflow check for detection of the
6123 constraint error. Thus the first assignment to @code{X1} raises a
6124 @code{Constraint_Error} exception only if @option{-gnato} is set.
6126 The second increment operation results in a violation
6127 of the explicit range constraint, and such range checks are always
6128 performed (unless specifically suppressed with a pragma @code{suppress}
6129 or the use of @option{-gnatp}).
6131 The two conversions of @code{F} both result in values that are outside
6132 the base range of type @code{Integer} and thus will raise
6133 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6134 The fact that the result of the second conversion is assigned to
6135 variable @code{X4} with a restricted range is irrelevant, since the problem
6136 is in the conversion, not the assignment.
6138 Basically the rule is that in the default mode (@option{-gnato} not
6139 used), the generated code assures that all integer variables stay
6140 within their declared ranges, or within the base range if there is
6141 no declared range. This prevents any serious problems like indexes
6142 out of range for array operations.
6144 What is not checked in default mode is an overflow that results in
6145 an in-range, but incorrect value. In the above example, the assignments
6146 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6147 range of the target variable, but the result is wrong in the sense that
6148 it is too large to be represented correctly. Typically the assignment
6149 to @code{X1} will result in wrap around to the largest negative number.
6150 The conversions of @code{F} will result in some @code{Integer} value
6151 and if that integer value is out of the @code{X4} range then the
6152 subsequent assignment would generate an exception.
6154 @findex Machine_Overflows
6155 Note that the @option{-gnato} switch does not affect the code generated
6156 for any floating-point operations; it applies only to integer
6158 For floating-point, GNAT has the @code{Machine_Overflows}
6159 attribute set to @code{False} and the normal mode of operation is to
6160 generate IEEE NaN and infinite values on overflow or invalid operations
6161 (such as dividing 0.0 by 0.0).
6163 The reason that we distinguish overflow checking from other kinds of
6164 range constraint checking is that a failure of an overflow check can
6165 generate an incorrect value, but cannot cause erroneous behavior. This
6166 is unlike the situation with a constraint check on an array subscript,
6167 where failure to perform the check can result in random memory description,
6168 or the range check on a case statement, where failure to perform the check
6169 can cause a wild jump.
6171 Note again that @option{-gnato} is off by default, so overflow checking is
6172 not performed in default mode. This means that out of the box, with the
6173 default settings, GNAT does not do all the checks expected from the
6174 language description in the Ada Reference Manual. If you want all constraint
6175 checks to be performed, as described in this Manual, then you must
6176 explicitly use the -gnato switch either on the @command{gnatmake} or
6177 @command{gcc} command.
6180 @cindex @option{-gnatE} (@command{gcc})
6181 @cindex Elaboration checks
6182 @cindex Check, elaboration
6183 Enables dynamic checks for access-before-elaboration
6184 on subprogram calls and generic instantiations.
6185 For full details of the effect and use of this switch,
6186 @xref{Compiling Using gcc}.
6189 @cindex @option{-fstack-check} (@command{gcc})
6190 @cindex Stack Overflow Checking
6191 @cindex Checks, stack overflow checking
6192 Activates stack overflow checking. For full details of the effect and use of
6193 this switch see @ref{Stack Overflow Checking}.
6198 The setting of these switches only controls the default setting of the
6199 checks. You may modify them using either @code{Suppress} (to remove
6200 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6203 @node Using gcc for Syntax Checking
6204 @subsection Using @command{gcc} for Syntax Checking
6207 @cindex @option{-gnats} (@command{gcc})
6211 The @code{s} stands for ``syntax''.
6214 Run GNAT in syntax checking only mode. For
6215 example, the command
6218 $ gcc -c -gnats x.adb
6222 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6223 series of files in a single command
6225 , and can use wild cards to specify such a group of files.
6226 Note that you must specify the @option{-c} (compile
6227 only) flag in addition to the @option{-gnats} flag.
6230 You may use other switches in conjunction with @option{-gnats}. In
6231 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6232 format of any generated error messages.
6234 When the source file is empty or contains only empty lines and/or comments,
6235 the output is a warning:
6238 $ gcc -c -gnats -x ada toto.txt
6239 toto.txt:1:01: warning: empty file, contains no compilation units
6243 Otherwise, the output is simply the error messages, if any. No object file or
6244 ALI file is generated by a syntax-only compilation. Also, no units other
6245 than the one specified are accessed. For example, if a unit @code{X}
6246 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6247 check only mode does not access the source file containing unit
6250 @cindex Multiple units, syntax checking
6251 Normally, GNAT allows only a single unit in a source file. However, this
6252 restriction does not apply in syntax-check-only mode, and it is possible
6253 to check a file containing multiple compilation units concatenated
6254 together. This is primarily used by the @code{gnatchop} utility
6255 (@pxref{Renaming Files Using gnatchop}).
6258 @node Using gcc for Semantic Checking
6259 @subsection Using @command{gcc} for Semantic Checking
6262 @cindex @option{-gnatc} (@command{gcc})
6266 The @code{c} stands for ``check''.
6268 Causes the compiler to operate in semantic check mode,
6269 with full checking for all illegalities specified in the
6270 Ada Reference Manual, but without generation of any object code
6271 (no object file is generated).
6273 Because dependent files must be accessed, you must follow the GNAT
6274 semantic restrictions on file structuring to operate in this mode:
6278 The needed source files must be accessible
6279 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6282 Each file must contain only one compilation unit.
6285 The file name and unit name must match (@pxref{File Naming Rules}).
6288 The output consists of error messages as appropriate. No object file is
6289 generated. An @file{ALI} file is generated for use in the context of
6290 cross-reference tools, but this file is marked as not being suitable
6291 for binding (since no object file is generated).
6292 The checking corresponds exactly to the notion of
6293 legality in the Ada Reference Manual.
6295 Any unit can be compiled in semantics-checking-only mode, including
6296 units that would not normally be compiled (subunits,
6297 and specifications where a separate body is present).
6300 @node Compiling Different Versions of Ada
6301 @subsection Compiling Different Versions of Ada
6304 The switches described in this section allow you to explicitly specify
6305 the version of the Ada language that your programs are written in.
6306 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6307 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6308 indicate Ada 83 compatibility mode.
6311 @cindex Compatibility with Ada 83
6313 @item -gnat83 (Ada 83 Compatibility Mode)
6314 @cindex @option{-gnat83} (@command{gcc})
6315 @cindex ACVC, Ada 83 tests
6319 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6320 specifies that the program is to be compiled in Ada 83 mode. With
6321 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6322 semantics where this can be done easily.
6323 It is not possible to guarantee this switch does a perfect
6324 job; some subtle tests, such as are
6325 found in earlier ACVC tests (and that have been removed from the ACATS suite
6326 for Ada 95), might not compile correctly.
6327 Nevertheless, this switch may be useful in some circumstances, for example
6328 where, due to contractual reasons, existing code needs to be maintained
6329 using only Ada 83 features.
6331 With few exceptions (most notably the need to use @code{<>} on
6332 @cindex Generic formal parameters
6333 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6334 reserved words, and the use of packages
6335 with optional bodies), it is not necessary to specify the
6336 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6337 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6338 a correct Ada 83 program is usually also a correct program
6339 in these later versions of the language standard.
6340 For further information, please refer to @ref{Compatibility and Porting Guide}.
6342 @item -gnat95 (Ada 95 mode)
6343 @cindex @option{-gnat95} (@command{gcc})
6347 This switch directs the compiler to implement the Ada 95 version of the
6349 Since Ada 95 is almost completely upwards
6350 compatible with Ada 83, Ada 83 programs may generally be compiled using
6351 this switch (see the description of the @option{-gnat83} switch for further
6352 information about Ada 83 mode).
6353 If an Ada 2005 program is compiled in Ada 95 mode,
6354 uses of the new Ada 2005 features will cause error
6355 messages or warnings.
6357 This switch also can be used to cancel the effect of a previous
6358 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6360 @item -gnat05 (Ada 2005 mode)
6361 @cindex @option{-gnat05} (@command{gcc})
6362 @cindex Ada 2005 mode
6365 This switch directs the compiler to implement the Ada 2005 version of the
6367 Since Ada 2005 is almost completely upwards
6368 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6369 may generally be compiled using this switch (see the description of the
6370 @option{-gnat83} and @option{-gnat95} switches for further
6373 For information about the approved ``Ada Issues'' that have been incorporated
6374 into Ada 2005, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6375 Included with GNAT releases is a file @file{features-ada0y} that describes
6376 the set of implemented Ada 2005 features.
6380 @node Character Set Control
6381 @subsection Character Set Control
6383 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6384 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6387 Normally GNAT recognizes the Latin-1 character set in source program
6388 identifiers, as described in the Ada Reference Manual.
6390 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6391 single character ^^or word^ indicating the character set, as follows:
6395 ISO 8859-1 (Latin-1) identifiers
6398 ISO 8859-2 (Latin-2) letters allowed in identifiers
6401 ISO 8859-3 (Latin-3) letters allowed in identifiers
6404 ISO 8859-4 (Latin-4) letters allowed in identifiers
6407 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6410 ISO 8859-15 (Latin-9) letters allowed in identifiers
6413 IBM PC letters (code page 437) allowed in identifiers
6416 IBM PC letters (code page 850) allowed in identifiers
6418 @item ^f^FULL_UPPER^
6419 Full upper-half codes allowed in identifiers
6422 No upper-half codes allowed in identifiers
6425 Wide-character codes (that is, codes greater than 255)
6426 allowed in identifiers
6429 @xref{Foreign Language Representation}, for full details on the
6430 implementation of these character sets.
6432 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6433 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6434 Specify the method of encoding for wide characters.
6435 @var{e} is one of the following:
6440 Hex encoding (brackets coding also recognized)
6443 Upper half encoding (brackets encoding also recognized)
6446 Shift/JIS encoding (brackets encoding also recognized)
6449 EUC encoding (brackets encoding also recognized)
6452 UTF-8 encoding (brackets encoding also recognized)
6455 Brackets encoding only (default value)
6457 For full details on these encoding
6458 methods see @ref{Wide Character Encodings}.
6459 Note that brackets coding is always accepted, even if one of the other
6460 options is specified, so for example @option{-gnatW8} specifies that both
6461 brackets and UTF-8 encodings will be recognized. The units that are
6462 with'ed directly or indirectly will be scanned using the specified
6463 representation scheme, and so if one of the non-brackets scheme is
6464 used, it must be used consistently throughout the program. However,
6465 since brackets encoding is always recognized, it may be conveniently
6466 used in standard libraries, allowing these libraries to be used with
6467 any of the available coding schemes.
6470 If no @option{-gnatW?} parameter is present, then the default
6471 representation is normally Brackets encoding only. However, if the
6472 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6473 byte order mark or BOM for UTF-8), then these three characters are
6474 skipped and the default representation for the file is set to UTF-8.
6476 Note that the wide character representation that is specified (explicitly
6477 or by default) for the main program also acts as the default encoding used
6478 for Wide_Text_IO files if not specifically overridden by a WCEM form
6482 @node File Naming Control
6483 @subsection File Naming Control
6486 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6487 @cindex @option{-gnatk} (@command{gcc})
6488 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6489 1-999, indicates the maximum allowable length of a file name (not
6490 including the @file{.ads} or @file{.adb} extension). The default is not
6491 to enable file name krunching.
6493 For the source file naming rules, @xref{File Naming Rules}.
6496 @node Subprogram Inlining Control
6497 @subsection Subprogram Inlining Control
6502 @cindex @option{-gnatn} (@command{gcc})
6504 The @code{n} here is intended to suggest the first syllable of the
6507 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6508 inlining to actually occur, optimization must be enabled. To enable
6509 inlining of subprograms specified by pragma @code{Inline},
6510 you must also specify this switch.
6511 In the absence of this switch, GNAT does not attempt
6512 inlining and does not need to access the bodies of
6513 subprograms for which @code{pragma Inline} is specified if they are not
6514 in the current unit.
6516 If you specify this switch the compiler will access these bodies,
6517 creating an extra source dependency for the resulting object file, and
6518 where possible, the call will be inlined.
6519 For further details on when inlining is possible
6520 see @ref{Inlining of Subprograms}.
6523 @cindex @option{-gnatN} (@command{gcc})
6524 The front end inlining activated by this switch is generally more extensive,
6525 and quite often more effective than the standard @option{-gnatn} inlining mode.
6526 It will also generate additional dependencies.
6528 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
6529 to specify both options.
6532 @node Auxiliary Output Control
6533 @subsection Auxiliary Output Control
6537 @cindex @option{-gnatt} (@command{gcc})
6538 @cindex Writing internal trees
6539 @cindex Internal trees, writing to file
6540 Causes GNAT to write the internal tree for a unit to a file (with the
6541 extension @file{.adt}.
6542 This not normally required, but is used by separate analysis tools.
6544 these tools do the necessary compilations automatically, so you should
6545 not have to specify this switch in normal operation.
6548 @cindex @option{-gnatu} (@command{gcc})
6549 Print a list of units required by this compilation on @file{stdout}.
6550 The listing includes all units on which the unit being compiled depends
6551 either directly or indirectly.
6554 @item -pass-exit-codes
6555 @cindex @option{-pass-exit-codes} (@command{gcc})
6556 If this switch is not used, the exit code returned by @command{gcc} when
6557 compiling multiple files indicates whether all source files have
6558 been successfully used to generate object files or not.
6560 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
6561 exit status and allows an integrated development environment to better
6562 react to a compilation failure. Those exit status are:
6566 There was an error in at least one source file.
6568 At least one source file did not generate an object file.
6570 The compiler died unexpectedly (internal error for example).
6572 An object file has been generated for every source file.
6577 @node Debugging Control
6578 @subsection Debugging Control
6582 @cindex Debugging options
6585 @cindex @option{-gnatd} (@command{gcc})
6586 Activate internal debugging switches. @var{x} is a letter or digit, or
6587 string of letters or digits, which specifies the type of debugging
6588 outputs desired. Normally these are used only for internal development
6589 or system debugging purposes. You can find full documentation for these
6590 switches in the body of the @code{Debug} unit in the compiler source
6591 file @file{debug.adb}.
6595 @cindex @option{-gnatG} (@command{gcc})
6596 This switch causes the compiler to generate auxiliary output containing
6597 a pseudo-source listing of the generated expanded code. Like most Ada
6598 compilers, GNAT works by first transforming the high level Ada code into
6599 lower level constructs. For example, tasking operations are transformed
6600 into calls to the tasking run-time routines. A unique capability of GNAT
6601 is to list this expanded code in a form very close to normal Ada source.
6602 This is very useful in understanding the implications of various Ada
6603 usage on the efficiency of the generated code. There are many cases in
6604 Ada (e.g. the use of controlled types), where simple Ada statements can
6605 generate a lot of run-time code. By using @option{-gnatG} you can identify
6606 these cases, and consider whether it may be desirable to modify the coding
6607 approach to improve efficiency.
6609 The format of the output is very similar to standard Ada source, and is
6610 easily understood by an Ada programmer. The following special syntactic
6611 additions correspond to low level features used in the generated code that
6612 do not have any exact analogies in pure Ada source form. The following
6613 is a partial list of these special constructions. See the specification
6614 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6616 If the switch @option{-gnatL} is used in conjunction with
6617 @cindex @option{-gnatL} (@command{gcc})
6618 @option{-gnatG}, then the original source lines are interspersed
6619 in the expanded source (as comment lines with the original line number).
6622 @item new @var{xxx} [storage_pool = @var{yyy}]
6623 Shows the storage pool being used for an allocator.
6625 @item at end @var{procedure-name};
6626 Shows the finalization (cleanup) procedure for a scope.
6628 @item (if @var{expr} then @var{expr} else @var{expr})
6629 Conditional expression equivalent to the @code{x?y:z} construction in C.
6631 @item @var{target}^^^(@var{source})
6632 A conversion with floating-point truncation instead of rounding.
6634 @item @var{target}?(@var{source})
6635 A conversion that bypasses normal Ada semantic checking. In particular
6636 enumeration types and fixed-point types are treated simply as integers.
6638 @item @var{target}?^^^(@var{source})
6639 Combines the above two cases.
6641 @item @var{x} #/ @var{y}
6642 @itemx @var{x} #mod @var{y}
6643 @itemx @var{x} #* @var{y}
6644 @itemx @var{x} #rem @var{y}
6645 A division or multiplication of fixed-point values which are treated as
6646 integers without any kind of scaling.
6648 @item free @var{expr} [storage_pool = @var{xxx}]
6649 Shows the storage pool associated with a @code{free} statement.
6651 @item [subtype or type declaration]
6652 Used to list an equivalent declaration for an internally generated
6653 type that is referenced elsewhere in the listing.
6655 @item freeze @var{type-name} [@var{actions}]
6656 Shows the point at which @var{type-name} is frozen, with possible
6657 associated actions to be performed at the freeze point.
6659 @item reference @var{itype}
6660 Reference (and hence definition) to internal type @var{itype}.
6662 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6663 Intrinsic function call.
6665 @item @var{label-name} : label
6666 Declaration of label @var{labelname}.
6668 @item #$ @var{subprogram-name}
6669 An implicit call to a run-time support routine
6670 (to meet the requirement of H.3.1(9) in a
6673 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
6674 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6675 @var{expr}, but handled more efficiently).
6677 @item [constraint_error]
6678 Raise the @code{Constraint_Error} exception.
6680 @item @var{expression}'reference
6681 A pointer to the result of evaluating @var{expression}.
6683 @item @var{target-type}!(@var{source-expression})
6684 An unchecked conversion of @var{source-expression} to @var{target-type}.
6686 @item [@var{numerator}/@var{denominator}]
6687 Used to represent internal real literals (that) have no exact
6688 representation in base 2-16 (for example, the result of compile time
6689 evaluation of the expression 1.0/27.0).
6693 @cindex @option{-gnatD} (@command{gcc})
6694 When used in conjunction with @option{-gnatG}, this switch causes
6695 the expanded source, as described above for
6696 @option{-gnatG} to be written to files with names
6697 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6698 instead of to the standard output file. For
6699 example, if the source file name is @file{hello.adb}, then a file
6700 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written. The debugging
6701 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
6702 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6703 you to do source level debugging using the generated code which is
6704 sometimes useful for complex code, for example to find out exactly
6705 which part of a complex construction raised an exception. This switch
6706 also suppress generation of cross-reference information (see
6707 @option{-gnatx}) since otherwise the cross-reference information
6708 would refer to the @file{^.dg^.DG^} file, which would cause
6709 confusion since this is not the original source file.
6711 Note that @option{-gnatD} actually implies @option{-gnatG}
6712 automatically, so it is not necessary to give both options.
6713 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6715 If the switch @option{-gnatL} is used in conjunction with
6716 @cindex @option{-gnatL} (@command{gcc})
6717 @option{-gnatDG}, then the original source lines are interspersed
6718 in the expanded source (as comment lines with the original line number).
6721 @item -gnatR[0|1|2|3[s]]
6722 @cindex @option{-gnatR} (@command{gcc})
6723 This switch controls output from the compiler of a listing showing
6724 representation information for declared types and objects. For
6725 @option{-gnatR0}, no information is output (equivalent to omitting
6726 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6727 so @option{-gnatR} with no parameter has the same effect), size and alignment
6728 information is listed for declared array and record types. For
6729 @option{-gnatR2}, size and alignment information is listed for all
6730 declared types and objects. Finally @option{-gnatR3} includes symbolic
6731 expressions for values that are computed at run time for
6732 variant records. These symbolic expressions have a mostly obvious
6733 format with #n being used to represent the value of the n'th
6734 discriminant. See source files @file{repinfo.ads/adb} in the
6735 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6736 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
6737 the output is to a file with the name @file{^file.rep^file_REP^} where
6738 file is the name of the corresponding source file.
6741 @item /REPRESENTATION_INFO
6742 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
6743 This qualifier controls output from the compiler of a listing showing
6744 representation information for declared types and objects. For
6745 @option{/REPRESENTATION_INFO=NONE}, no information is output
6746 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6747 @option{/REPRESENTATION_INFO} without option is equivalent to
6748 @option{/REPRESENTATION_INFO=ARRAYS}.
6749 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6750 information is listed for declared array and record types. For
6751 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6752 is listed for all expression information for values that are computed
6753 at run time for variant records. These symbolic expressions have a mostly
6754 obvious format with #n being used to represent the value of the n'th
6755 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6756 @code{GNAT} sources for full details on the format of
6757 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6758 If _FILE is added at the end of an option
6759 (e.g. @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6760 then the output is to a file with the name @file{file_REP} where
6761 file is the name of the corresponding source file.
6763 Note that it is possible for record components to have zero size. In
6764 this case, the component clause uses an obvious extension of permitted
6765 Ada syntax, for example @code{at 0 range 0 .. -1}.
6767 Representation information requires that code be generated (since it is the
6768 code generator that lays out complex data structures). If an attempt is made
6769 to output representation information when no code is generated, for example
6770 when a subunit is compiled on its own, then no information can be generated
6771 and the compiler outputs a message to this effect.
6774 @cindex @option{-gnatS} (@command{gcc})
6775 The use of the switch @option{-gnatS} for an
6776 Ada compilation will cause the compiler to output a
6777 representation of package Standard in a form very
6778 close to standard Ada. It is not quite possible to
6779 do this entirely in standard Ada (since new
6780 numeric base types cannot be created in standard
6781 Ada), but the output is easily
6782 readable to any Ada programmer, and is useful to
6783 determine the characteristics of target dependent
6784 types in package Standard.
6787 @cindex @option{-gnatx} (@command{gcc})
6788 Normally the compiler generates full cross-referencing information in
6789 the @file{ALI} file. This information is used by a number of tools,
6790 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
6791 suppresses this information. This saves some space and may slightly
6792 speed up compilation, but means that these tools cannot be used.
6795 @node Exception Handling Control
6796 @subsection Exception Handling Control
6799 GNAT uses two methods for handling exceptions at run-time. The
6800 @code{setjmp/longjmp} method saves the context when entering
6801 a frame with an exception handler. Then when an exception is
6802 raised, the context can be restored immediately, without the
6803 need for tracing stack frames. This method provides very fast
6804 exception propagation, but introduces significant overhead for
6805 the use of exception handlers, even if no exception is raised.
6807 The other approach is called ``zero cost'' exception handling.
6808 With this method, the compiler builds static tables to describe
6809 the exception ranges. No dynamic code is required when entering
6810 a frame containing an exception handler. When an exception is
6811 raised, the tables are used to control a back trace of the
6812 subprogram invocation stack to locate the required exception
6813 handler. This method has considerably poorer performance for
6814 the propagation of exceptions, but there is no overhead for
6815 exception handlers if no exception is raised. Note that in this
6816 mode and in the context of mixed Ada and C/C++ programming,
6817 to propagate an exception through a C/C++ code, the C/C++ code
6818 must be compiled with the @option{-funwind-tables} GCC's
6821 The following switches may be used to control which of the
6822 two exception handling methods is used.
6828 @cindex @option{--RTS=sjlj} (@command{gnatmake})
6829 This switch causes the setjmp/longjmp run-time (when available) to be used
6830 for exception handling. If the default
6831 mechanism for the target is zero cost exceptions, then
6832 this switch can be used to modify this default, and must be
6833 used for all units in the partition.
6834 This option is rarely used. One case in which it may be
6835 advantageous is if you have an application where exception
6836 raising is common and the overall performance of the
6837 application is improved by favoring exception propagation.
6840 @cindex @option{--RTS=zcx} (@command{gnatmake})
6841 @cindex Zero Cost Exceptions
6842 This switch causes the zero cost approach to be used
6843 for exception handling. If this is the default mechanism for the
6844 target (see below), then this switch is unneeded. If the default
6845 mechanism for the target is setjmp/longjmp exceptions, then
6846 this switch can be used to modify this default, and must be
6847 used for all units in the partition.
6848 This option can only be used if the zero cost approach
6849 is available for the target in use, otherwise it will generate an error.
6853 The same option @option{--RTS} must be used both for @command{gcc}
6854 and @command{gnatbind}. Passing this option to @command{gnatmake}
6855 (@pxref{Switches for gnatmake}) will ensure the required consistency
6856 through the compilation and binding steps.
6858 @node Units to Sources Mapping Files
6859 @subsection Units to Sources Mapping Files
6863 @item -gnatem^^=^@var{path}
6864 @cindex @option{-gnatem} (@command{gcc})
6865 A mapping file is a way to communicate to the compiler two mappings:
6866 from unit names to file names (without any directory information) and from
6867 file names to path names (with full directory information). These mappings
6868 are used by the compiler to short-circuit the path search.
6870 The use of mapping files is not required for correct operation of the
6871 compiler, but mapping files can improve efficiency, particularly when
6872 sources are read over a slow network connection. In normal operation,
6873 you need not be concerned with the format or use of mapping files,
6874 and the @option{-gnatem} switch is not a switch that you would use
6875 explicitly. it is intended only for use by automatic tools such as
6876 @command{gnatmake} running under the project file facility. The
6877 description here of the format of mapping files is provided
6878 for completeness and for possible use by other tools.
6880 A mapping file is a sequence of sets of three lines. In each set,
6881 the first line is the unit name, in lower case, with ``@code{%s}''
6883 specifications and ``@code{%b}'' appended for bodies; the second line is the
6884 file name; and the third line is the path name.
6890 /gnat/project1/sources/main.2.ada
6893 When the switch @option{-gnatem} is specified, the compiler will create
6894 in memory the two mappings from the specified file. If there is any problem
6895 (non existent file, truncated file or duplicate entries), no mapping
6898 Several @option{-gnatem} switches may be specified; however, only the last
6899 one on the command line will be taken into account.
6901 When using a project file, @command{gnatmake} create a temporary mapping file
6902 and communicates it to the compiler using this switch.
6906 @node Integrated Preprocessing
6907 @subsection Integrated Preprocessing
6910 GNAT sources may be preprocessed immediately before compilation.
6911 In this case, the actual
6912 text of the source is not the text of the source file, but is derived from it
6913 through a process called preprocessing. Integrated preprocessing is specified
6914 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
6915 indicates, through a text file, the preprocessing data to be used.
6916 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
6919 Note that when integrated preprocessing is used, the output from the
6920 preprocessor is not written to any external file. Instead it is passed
6921 internally to the compiler. If you need to preserve the result of
6922 preprocessing in a file, then you should use @command{gnatprep}
6923 to perform the desired preprocessing in stand-alone mode.
6926 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
6927 used when Integrated Preprocessing is used. The reason is that preprocessing
6928 with another Preprocessing Data file without changing the sources will
6929 not trigger recompilation without this switch.
6932 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
6933 always trigger recompilation for sources that are preprocessed,
6934 because @command{gnatmake} cannot compute the checksum of the source after
6938 The actual preprocessing function is described in details in section
6939 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
6940 preprocessing is triggered and parameterized.
6944 @item -gnatep=@var{file}
6945 @cindex @option{-gnatep} (@command{gcc})
6946 This switch indicates to the compiler the file name (without directory
6947 information) of the preprocessor data file to use. The preprocessor data file
6948 should be found in the source directories.
6951 A preprocessing data file is a text file with significant lines indicating
6952 how should be preprocessed either a specific source or all sources not
6953 mentioned in other lines. A significant line is a non empty, non comment line.
6954 Comments are similar to Ada comments.
6957 Each significant line starts with either a literal string or the character '*'.
6958 A literal string is the file name (without directory information) of the source
6959 to preprocess. A character '*' indicates the preprocessing for all the sources
6960 that are not specified explicitly on other lines (order of the lines is not
6961 significant). It is an error to have two lines with the same file name or two
6962 lines starting with the character '*'.
6965 After the file name or the character '*', another optional literal string
6966 indicating the file name of the definition file to be used for preprocessing
6967 (@pxref{Form of Definitions File}). The definition files are found by the
6968 compiler in one of the source directories. In some cases, when compiling
6969 a source in a directory other than the current directory, if the definition
6970 file is in the current directory, it may be necessary to add the current
6971 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
6972 the compiler would not find the definition file.
6975 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
6976 be found. Those ^switches^switches^ are:
6981 Causes both preprocessor lines and the lines deleted by
6982 preprocessing to be replaced by blank lines, preserving the line number.
6983 This ^switch^switch^ is always implied; however, if specified after @option{-c}
6984 it cancels the effect of @option{-c}.
6987 Causes both preprocessor lines and the lines deleted
6988 by preprocessing to be retained as comments marked
6989 with the special string ``@code{--! }''.
6991 @item -Dsymbol=value
6992 Define or redefine a symbol, associated with value. A symbol is an Ada
6993 identifier, or an Ada reserved word, with the exception of @code{if},
6994 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6995 @code{value} is either a literal string, an Ada identifier or any Ada reserved
6996 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
6997 same name defined in a definition file.
7000 Causes a sorted list of symbol names and values to be
7001 listed on the standard output file.
7004 Causes undefined symbols to be treated as having the value @code{FALSE}
7006 of a preprocessor test. In the absence of this option, an undefined symbol in
7007 a @code{#if} or @code{#elsif} test will be treated as an error.
7012 Examples of valid lines in a preprocessor data file:
7015 "toto.adb" "prep.def" -u
7016 -- preprocess "toto.adb", using definition file "prep.def",
7017 -- undefined symbol are False.
7020 -- preprocess all other sources without a definition file;
7021 -- suppressed lined are commented; symbol VERSION has the value V101.
7023 "titi.adb" "prep2.def" -s
7024 -- preprocess "titi.adb", using definition file "prep2.def";
7025 -- list all symbols with their values.
7028 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
7029 @cindex @option{-gnateD} (@command{gcc})
7030 Define or redefine a preprocessing symbol, associated with value. If no value
7031 is given on the command line, then the value of the symbol is @code{True}.
7032 A symbol is an identifier, following normal Ada (case-insensitive)
7033 rules for its syntax, and value is any sequence (including an empty sequence)
7034 of characters from the set (letters, digits, period, underline).
7035 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7036 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7039 A symbol declared with this ^switch^switch^ on the command line replaces a
7040 symbol with the same name either in a definition file or specified with a
7041 ^switch^switch^ -D in the preprocessor data file.
7044 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7048 @node Code Generation Control
7049 @subsection Code Generation Control
7053 The GCC technology provides a wide range of target dependent
7054 @option{-m} switches for controlling
7055 details of code generation with respect to different versions of
7056 architectures. This includes variations in instruction sets (e.g.
7057 different members of the power pc family), and different requirements
7058 for optimal arrangement of instructions (e.g. different members of
7059 the x86 family). The list of available @option{-m} switches may be
7060 found in the GCC documentation.
7062 Use of these @option{-m} switches may in some cases result in improved
7065 The GNAT Pro technology is tested and qualified without any
7066 @option{-m} switches,
7067 so generally the most reliable approach is to avoid the use of these
7068 switches. However, we generally expect most of these switches to work
7069 successfully with GNAT Pro, and many customers have reported successful
7070 use of these options.
7072 Our general advice is to avoid the use of @option{-m} switches unless
7073 special needs lead to requirements in this area. In particular,
7074 there is no point in using @option{-m} switches to improve performance
7075 unless you actually see a performance improvement.
7079 @subsection Return Codes
7080 @cindex Return Codes
7081 @cindex @option{/RETURN_CODES=VMS}
7084 On VMS, GNAT compiled programs return POSIX-style codes by default,
7085 e.g. @option{/RETURN_CODES=POSIX}.
7087 To enable VMS style return codes, use GNAT BIND and LINK with the option
7088 @option{/RETURN_CODES=VMS}. For example:
7091 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7092 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7096 Programs built with /RETURN_CODES=VMS are suitable to be called in
7097 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7098 are suitable for spawning with appropriate GNAT RTL routines.
7102 @node Search Paths and the Run-Time Library (RTL)
7103 @section Search Paths and the Run-Time Library (RTL)
7106 With the GNAT source-based library system, the compiler must be able to
7107 find source files for units that are needed by the unit being compiled.
7108 Search paths are used to guide this process.
7110 The compiler compiles one source file whose name must be given
7111 explicitly on the command line. In other words, no searching is done
7112 for this file. To find all other source files that are needed (the most
7113 common being the specs of units), the compiler examines the following
7114 directories, in the following order:
7118 The directory containing the source file of the main unit being compiled
7119 (the file name on the command line).
7122 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7123 @command{gcc} command line, in the order given.
7126 @findex ADA_PRJ_INCLUDE_FILE
7127 Each of the directories listed in the text file whose name is given
7128 by the @code{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7131 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7132 driver when project files are used. It should not normally be set
7136 @findex ADA_INCLUDE_PATH
7137 Each of the directories listed in the value of the
7138 @code{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7140 Construct this value
7141 exactly as the @code{PATH} environment variable: a list of directory
7142 names separated by colons (semicolons when working with the NT version).
7145 Normally, define this value as a logical name containing a comma separated
7146 list of directory names.
7148 This variable can also be defined by means of an environment string
7149 (an argument to the HP C exec* set of functions).
7153 DEFINE ANOTHER_PATH FOO:[BAG]
7154 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7157 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7158 first, followed by the standard Ada
7159 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7160 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7161 (Text_IO, Sequential_IO, etc)
7162 instead of the standard Ada packages. Thus, in order to get the standard Ada
7163 packages by default, ADA_INCLUDE_PATH must be redefined.
7167 The content of the @file{ada_source_path} file which is part of the GNAT
7168 installation tree and is used to store standard libraries such as the
7169 GNAT Run Time Library (RTL) source files.
7171 @ref{Installing a library}
7176 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7177 inhibits the use of the directory
7178 containing the source file named in the command line. You can still
7179 have this directory on your search path, but in this case it must be
7180 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7182 Specifying the switch @option{-nostdinc}
7183 inhibits the search of the default location for the GNAT Run Time
7184 Library (RTL) source files.
7186 The compiler outputs its object files and ALI files in the current
7189 Caution: The object file can be redirected with the @option{-o} switch;
7190 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7191 so the @file{ALI} file will not go to the right place. Therefore, you should
7192 avoid using the @option{-o} switch.
7196 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7197 children make up the GNAT RTL, together with the simple @code{System.IO}
7198 package used in the @code{"Hello World"} example. The sources for these units
7199 are needed by the compiler and are kept together in one directory. Not
7200 all of the bodies are needed, but all of the sources are kept together
7201 anyway. In a normal installation, you need not specify these directory
7202 names when compiling or binding. Either the environment variables or
7203 the built-in defaults cause these files to be found.
7205 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7206 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7207 consisting of child units of @code{GNAT}. This is a collection of generally
7208 useful types, subprograms, etc. See the @cite{GNAT Reference Manual} for
7211 Besides simplifying access to the RTL, a major use of search paths is
7212 in compiling sources from multiple directories. This can make
7213 development environments much more flexible.
7215 @node Order of Compilation Issues
7216 @section Order of Compilation Issues
7219 If, in our earlier example, there was a spec for the @code{hello}
7220 procedure, it would be contained in the file @file{hello.ads}; yet this
7221 file would not have to be explicitly compiled. This is the result of the
7222 model we chose to implement library management. Some of the consequences
7223 of this model are as follows:
7227 There is no point in compiling specs (except for package
7228 specs with no bodies) because these are compiled as needed by clients. If
7229 you attempt a useless compilation, you will receive an error message.
7230 It is also useless to compile subunits because they are compiled as needed
7234 There are no order of compilation requirements: performing a
7235 compilation never obsoletes anything. The only way you can obsolete
7236 something and require recompilations is to modify one of the
7237 source files on which it depends.
7240 There is no library as such, apart from the ALI files
7241 (@pxref{The Ada Library Information Files}, for information on the format
7242 of these files). For now we find it convenient to create separate ALI files,
7243 but eventually the information therein may be incorporated into the object
7247 When you compile a unit, the source files for the specs of all units
7248 that it @code{with}'s, all its subunits, and the bodies of any generics it
7249 instantiates must be available (reachable by the search-paths mechanism
7250 described above), or you will receive a fatal error message.
7257 The following are some typical Ada compilation command line examples:
7260 @item $ gcc -c xyz.adb
7261 Compile body in file @file{xyz.adb} with all default options.
7264 @item $ gcc -c -O2 -gnata xyz-def.adb
7267 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7270 Compile the child unit package in file @file{xyz-def.adb} with extensive
7271 optimizations, and pragma @code{Assert}/@code{Debug} statements
7274 @item $ gcc -c -gnatc abc-def.adb
7275 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7279 @node Binding Using gnatbind
7280 @chapter Binding Using @code{gnatbind}
7284 * Running gnatbind::
7285 * Switches for gnatbind::
7286 * Command-Line Access::
7287 * Search Paths for gnatbind::
7288 * Examples of gnatbind Usage::
7292 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7293 to bind compiled GNAT objects.
7295 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7296 driver (see @ref{The GNAT Driver and Project Files}).
7298 The @code{gnatbind} program performs four separate functions:
7302 Checks that a program is consistent, in accordance with the rules in
7303 Chapter 10 of the Ada Reference Manual. In particular, error
7304 messages are generated if a program uses inconsistent versions of a
7308 Checks that an acceptable order of elaboration exists for the program
7309 and issues an error message if it cannot find an order of elaboration
7310 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7313 Generates a main program incorporating the given elaboration order.
7314 This program is a small Ada package (body and spec) that
7315 must be subsequently compiled
7316 using the GNAT compiler. The necessary compilation step is usually
7317 performed automatically by @command{gnatlink}. The two most important
7318 functions of this program
7319 are to call the elaboration routines of units in an appropriate order
7320 and to call the main program.
7323 Determines the set of object files required by the given main program.
7324 This information is output in the forms of comments in the generated program,
7325 to be read by the @command{gnatlink} utility used to link the Ada application.
7328 @node Running gnatbind
7329 @section Running @code{gnatbind}
7332 The form of the @code{gnatbind} command is
7335 $ gnatbind [@i{switches}] @i{mainprog}[.ali] [@i{switches}]
7339 where @file{@i{mainprog}.adb} is the Ada file containing the main program
7340 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
7341 package in two files whose names are
7342 @file{b~@i{mainprog}.ads}, and @file{b~@i{mainprog}.adb}.
7343 For example, if given the
7344 parameter @file{hello.ali}, for a main program contained in file
7345 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7346 and @file{b~hello.adb}.
7348 When doing consistency checking, the binder takes into consideration
7349 any source files it can locate. For example, if the binder determines
7350 that the given main program requires the package @code{Pack}, whose
7352 file is @file{pack.ali} and whose corresponding source spec file is
7353 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7354 (using the same search path conventions as previously described for the
7355 @command{gcc} command). If it can locate this source file, it checks that
7357 or source checksums of the source and its references to in @file{ALI} files
7358 match. In other words, any @file{ALI} files that mentions this spec must have
7359 resulted from compiling this version of the source file (or in the case
7360 where the source checksums match, a version close enough that the
7361 difference does not matter).
7363 @cindex Source files, use by binder
7364 The effect of this consistency checking, which includes source files, is
7365 that the binder ensures that the program is consistent with the latest
7366 version of the source files that can be located at bind time. Editing a
7367 source file without compiling files that depend on the source file cause
7368 error messages to be generated by the binder.
7370 For example, suppose you have a main program @file{hello.adb} and a
7371 package @code{P}, from file @file{p.ads} and you perform the following
7376 Enter @code{gcc -c hello.adb} to compile the main program.
7379 Enter @code{gcc -c p.ads} to compile package @code{P}.
7382 Edit file @file{p.ads}.
7385 Enter @code{gnatbind hello}.
7389 At this point, the file @file{p.ali} contains an out-of-date time stamp
7390 because the file @file{p.ads} has been edited. The attempt at binding
7391 fails, and the binder generates the following error messages:
7394 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7395 error: "p.ads" has been modified and must be recompiled
7399 Now both files must be recompiled as indicated, and then the bind can
7400 succeed, generating a main program. You need not normally be concerned
7401 with the contents of this file, but for reference purposes a sample
7402 binder output file is given in @ref{Example of Binder Output File}.
7404 In most normal usage, the default mode of @command{gnatbind} which is to
7405 generate the main package in Ada, as described in the previous section.
7406 In particular, this means that any Ada programmer can read and understand
7407 the generated main program. It can also be debugged just like any other
7408 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7409 @command{gnatbind} and @command{gnatlink}.
7411 However for some purposes it may be convenient to generate the main
7412 program in C rather than Ada. This may for example be helpful when you
7413 are generating a mixed language program with the main program in C. The
7414 GNAT compiler itself is an example.
7415 The use of the @option{^-C^/BIND_FILE=C^} switch
7416 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7417 be generated in C (and compiled using the gnu C compiler).
7419 @node Switches for gnatbind
7420 @section Switches for @command{gnatbind}
7423 The following switches are available with @code{gnatbind}; details will
7424 be presented in subsequent sections.
7427 * Consistency-Checking Modes::
7428 * Binder Error Message Control::
7429 * Elaboration Control::
7431 * Binding with Non-Ada Main Programs::
7432 * Binding Programs with No Main Subprogram::
7439 @cindex @option{--version} @command{gnatbind}
7440 Display Copyright and version, then exit disregarding all other options.
7443 @cindex @option{--help} @command{gnatbind}
7444 If @option{--version} was not used, display usage, then exit disregarding
7448 @cindex @option{-a} @command{gnatbind}
7449 Indicates that, if supported by the platform, the adainit procedure should
7450 be treated as an initialisation routine by the linker (a constructor). This
7451 is intended to be used by the Project Manager to automatically initialize
7452 shared Stand-Alone Libraries.
7454 @item ^-aO^/OBJECT_SEARCH^
7455 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7456 Specify directory to be searched for ALI files.
7458 @item ^-aI^/SOURCE_SEARCH^
7459 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7460 Specify directory to be searched for source file.
7462 @item ^-A^/BIND_FILE=ADA^
7463 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
7464 Generate binder program in Ada (default)
7466 @item ^-b^/REPORT_ERRORS=BRIEF^
7467 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
7468 Generate brief messages to @file{stderr} even if verbose mode set.
7470 @item ^-c^/NOOUTPUT^
7471 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
7472 Check only, no generation of binder output file.
7474 @item ^-C^/BIND_FILE=C^
7475 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
7476 Generate binder program in C
7478 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}[k|m]
7479 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}[k|m]} (@command{gnatbind})
7480 This switch can be used to change the default task stack size value
7481 to a specified size @var{nn}, which is expressed in bytes by default, or
7482 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7484 In the absence of a [k|m] suffix, this switch is equivalent, in effect,
7485 to completing all task specs with
7486 @smallexample @c ada
7487 pragma Storage_Size (nn);
7489 When they do not already have such a pragma.
7491 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}[k|m]
7492 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
7493 This switch can be used to change the default secondary stack size value
7494 to a specified size @var{nn}, which is expressed in bytes by default, or
7495 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7498 The secondary stack is used to deal with functions that return a variable
7499 sized result, for example a function returning an unconstrained
7500 String. There are two ways in which this secondary stack is allocated.
7502 For most targets, the secondary stack is growing on demand and is allocated
7503 as a chain of blocks in the heap. The -D option is not very
7504 relevant. It only give some control over the size of the allocated
7505 blocks (whose size is the minimum of the default secondary stack size value,
7506 and the actual size needed for the current allocation request).
7508 For certain targets, notably VxWorks 653,
7509 the secondary stack is allocated by carving off a fixed ratio chunk of the
7510 primary task stack. The -D option is used to define the
7511 size of the environment task's secondary stack.
7513 @item ^-e^/ELABORATION_DEPENDENCIES^
7514 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
7515 Output complete list of elaboration-order dependencies.
7517 @item ^-E^/STORE_TRACEBACKS^
7518 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
7519 Store tracebacks in exception occurrences when the target supports it.
7520 This is the default with the zero cost exception mechanism.
7522 @c The following may get moved to an appendix
7523 This option is currently supported on the following targets:
7524 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
7526 See also the packages @code{GNAT.Traceback} and
7527 @code{GNAT.Traceback.Symbolic} for more information.
7529 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
7530 @command{gcc} option.
7533 @item ^-F^/FORCE_ELABS_FLAGS^
7534 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
7535 Force the checks of elaboration flags. @command{gnatbind} does not normally
7536 generate checks of elaboration flags for the main executable, except when
7537 a Stand-Alone Library is used. However, there are cases when this cannot be
7538 detected by gnatbind. An example is importing an interface of a Stand-Alone
7539 Library through a pragma Import and only specifying through a linker switch
7540 this Stand-Alone Library. This switch is used to guarantee that elaboration
7541 flag checks are generated.
7544 @cindex @option{^-h^/HELP^} (@command{gnatbind})
7545 Output usage (help) information
7548 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7549 Specify directory to be searched for source and ALI files.
7551 @item ^-I-^/NOCURRENT_DIRECTORY^
7552 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
7553 Do not look for sources in the current directory where @code{gnatbind} was
7554 invoked, and do not look for ALI files in the directory containing the
7555 ALI file named in the @code{gnatbind} command line.
7557 @item ^-l^/ORDER_OF_ELABORATION^
7558 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
7559 Output chosen elaboration order.
7561 @item ^-Lxxx^/BUILD_LIBRARY=xxx^
7562 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
7563 Bind the units for library building. In this case the adainit and
7564 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
7565 are renamed to ^xxxinit^XXXINIT^ and
7566 ^xxxfinal^XXXFINAL^.
7567 Implies ^-n^/NOCOMPILE^.
7569 (@xref{GNAT and Libraries}, for more details.)
7572 On OpenVMS, these init and final procedures are exported in uppercase
7573 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
7574 the init procedure will be "TOTOINIT" and the exported name of the final
7575 procedure will be "TOTOFINAL".
7578 @item ^-Mxyz^/RENAME_MAIN=xyz^
7579 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
7580 Rename generated main program from main to xyz. This option is
7581 supported on cross environments only.
7583 @item ^-m^/ERROR_LIMIT=^@var{n}
7584 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
7585 Limit number of detected errors to @var{n}, where @var{n} is
7586 in the range 1..999_999. The default value if no switch is
7587 given is 9999. Binding is terminated if the limit is exceeded.
7589 Furthermore, under Windows, the sources pointed to by the libraries path
7590 set in the registry are not searched for.
7594 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7598 @cindex @option{-nostdinc} (@command{gnatbind})
7599 Do not look for sources in the system default directory.
7602 @cindex @option{-nostdlib} (@command{gnatbind})
7603 Do not look for library files in the system default directory.
7605 @item --RTS=@var{rts-path}
7606 @cindex @option{--RTS} (@code{gnatbind})
7607 Specifies the default location of the runtime library. Same meaning as the
7608 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
7610 @item ^-o ^/OUTPUT=^@var{file}
7611 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7612 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7613 Note that if this option is used, then linking must be done manually,
7614 gnatlink cannot be used.
7616 @item ^-O^/OBJECT_LIST^
7617 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7620 @item ^-p^/PESSIMISTIC_ELABORATION^
7621 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7622 Pessimistic (worst-case) elaboration order
7625 @cindex @option{^-R^-R^} (@command{gnatbind})
7626 Output closure source list.
7628 @item ^-s^/READ_SOURCES=ALL^
7629 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7630 Require all source files to be present.
7632 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7633 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7634 Specifies the value to be used when detecting uninitialized scalar
7635 objects with pragma Initialize_Scalars.
7636 The @var{xxx} ^string specified with the switch^option^ may be either
7638 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7639 @item ``@option{^lo^LOW^}'' for the lowest possible value
7640 @item ``@option{^hi^HIGH^}'' for the highest possible value
7641 @item ``@option{xx}'' for a value consisting of repeated bytes with the
7642 value 16#xx# (i.e. xx is a string of two hexadecimal digits).
7645 In addition, you can specify @option{-Sev} to indicate that the value is
7646 to be set at run time. In this case, the program will look for an environment
7647 @cindex GNAT_INIT_SCALARS
7648 variable of the form @code{GNAT_INIT_SCALARS=xx}, where xx is one
7649 of @option{in/lo/hi/xx} with the same meanings as above.
7650 If no environment variable is found, or if it does not have a valid value,
7651 then the default is @option{in} (invalid values).
7655 @cindex @option{-static} (@code{gnatbind})
7656 Link against a static GNAT run time.
7659 @cindex @option{-shared} (@code{gnatbind})
7660 Link against a shared GNAT run time when available.
7663 @item ^-t^/NOTIME_STAMP_CHECK^
7664 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7665 Tolerate time stamp and other consistency errors
7667 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7668 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7669 Set the time slice value to @var{n} milliseconds. If the system supports
7670 the specification of a specific time slice value, then the indicated value
7671 is used. If the system does not support specific time slice values, but
7672 does support some general notion of round-robin scheduling, then any
7673 nonzero value will activate round-robin scheduling.
7675 A value of zero is treated specially. It turns off time
7676 slicing, and in addition, indicates to the tasking run time that the
7677 semantics should match as closely as possible the Annex D
7678 requirements of the Ada RM, and in particular sets the default
7679 scheduling policy to @code{FIFO_Within_Priorities}.
7681 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
7682 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
7683 Enable dynamic stack usage, with @var{n} results stored and displayed
7684 at program termination. A result is generated when a task
7685 terminates. Results that can't be stored are displayed on the fly, at
7686 task termination. This option is currently not supported on Itanium
7687 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
7689 @item ^-v^/REPORT_ERRORS=VERBOSE^
7690 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7691 Verbose mode. Write error messages, header, summary output to
7696 @cindex @option{-w} (@code{gnatbind})
7697 Warning mode (@var{x}=s/e for suppress/treat as error)
7701 @item /WARNINGS=NORMAL
7702 @cindex @option{/WARNINGS} (@code{gnatbind})
7703 Normal warnings mode. Warnings are issued but ignored
7705 @item /WARNINGS=SUPPRESS
7706 @cindex @option{/WARNINGS} (@code{gnatbind})
7707 All warning messages are suppressed
7709 @item /WARNINGS=ERROR
7710 @cindex @option{/WARNINGS} (@code{gnatbind})
7711 Warning messages are treated as fatal errors
7714 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
7715 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
7716 Override default wide character encoding for standard Text_IO files.
7718 @item ^-x^/READ_SOURCES=NONE^
7719 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7720 Exclude source files (check object consistency only).
7723 @item /READ_SOURCES=AVAILABLE
7724 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7725 Default mode, in which sources are checked for consistency only if
7729 @item ^-y^/ENABLE_LEAP_SECONDS^
7730 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
7731 Enable leap seconds support in @code{Ada.Calendar} and its children.
7733 @item ^-z^/ZERO_MAIN^
7734 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7740 You may obtain this listing of switches by running @code{gnatbind} with
7744 @node Consistency-Checking Modes
7745 @subsection Consistency-Checking Modes
7748 As described earlier, by default @code{gnatbind} checks
7749 that object files are consistent with one another and are consistent
7750 with any source files it can locate. The following switches control binder
7755 @item ^-s^/READ_SOURCES=ALL^
7756 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
7757 Require source files to be present. In this mode, the binder must be
7758 able to locate all source files that are referenced, in order to check
7759 their consistency. In normal mode, if a source file cannot be located it
7760 is simply ignored. If you specify this switch, a missing source
7763 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
7764 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
7765 Override default wide character encoding for standard Text_IO files.
7766 Normally the default wide character encoding method used for standard
7767 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
7768 the main source input (see description of switch
7769 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
7770 use of this switch for the binder (which has the same set of
7771 possible arguments) overrides this default as specified.
7773 @item ^-x^/READ_SOURCES=NONE^
7774 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
7775 Exclude source files. In this mode, the binder only checks that ALI
7776 files are consistent with one another. Source files are not accessed.
7777 The binder runs faster in this mode, and there is still a guarantee that
7778 the resulting program is self-consistent.
7779 If a source file has been edited since it was last compiled, and you
7780 specify this switch, the binder will not detect that the object
7781 file is out of date with respect to the source file. Note that this is the
7782 mode that is automatically used by @command{gnatmake} because in this
7783 case the checking against sources has already been performed by
7784 @command{gnatmake} in the course of compilation (i.e. before binding).
7787 @item /READ_SOURCES=AVAILABLE
7788 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
7789 This is the default mode in which source files are checked if they are
7790 available, and ignored if they are not available.
7794 @node Binder Error Message Control
7795 @subsection Binder Error Message Control
7798 The following switches provide control over the generation of error
7799 messages from the binder:
7803 @item ^-v^/REPORT_ERRORS=VERBOSE^
7804 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7805 Verbose mode. In the normal mode, brief error messages are generated to
7806 @file{stderr}. If this switch is present, a header is written
7807 to @file{stdout} and any error messages are directed to @file{stdout}.
7808 All that is written to @file{stderr} is a brief summary message.
7810 @item ^-b^/REPORT_ERRORS=BRIEF^
7811 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
7812 Generate brief error messages to @file{stderr} even if verbose mode is
7813 specified. This is relevant only when used with the
7814 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
7818 @cindex @option{-m} (@code{gnatbind})
7819 Limits the number of error messages to @var{n}, a decimal integer in the
7820 range 1-999. The binder terminates immediately if this limit is reached.
7823 @cindex @option{-M} (@code{gnatbind})
7824 Renames the generated main program from @code{main} to @code{xxx}.
7825 This is useful in the case of some cross-building environments, where
7826 the actual main program is separate from the one generated
7830 @item ^-ws^/WARNINGS=SUPPRESS^
7831 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
7833 Suppress all warning messages.
7835 @item ^-we^/WARNINGS=ERROR^
7836 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
7837 Treat any warning messages as fatal errors.
7840 @item /WARNINGS=NORMAL
7841 Standard mode with warnings generated, but warnings do not get treated
7845 @item ^-t^/NOTIME_STAMP_CHECK^
7846 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7847 @cindex Time stamp checks, in binder
7848 @cindex Binder consistency checks
7849 @cindex Consistency checks, in binder
7850 The binder performs a number of consistency checks including:
7854 Check that time stamps of a given source unit are consistent
7856 Check that checksums of a given source unit are consistent
7858 Check that consistent versions of @code{GNAT} were used for compilation
7860 Check consistency of configuration pragmas as required
7864 Normally failure of such checks, in accordance with the consistency
7865 requirements of the Ada Reference Manual, causes error messages to be
7866 generated which abort the binder and prevent the output of a binder
7867 file and subsequent link to obtain an executable.
7869 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
7870 into warnings, so that
7871 binding and linking can continue to completion even in the presence of such
7872 errors. The result may be a failed link (due to missing symbols), or a
7873 non-functional executable which has undefined semantics.
7874 @emph{This means that
7875 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
7879 @node Elaboration Control
7880 @subsection Elaboration Control
7883 The following switches provide additional control over the elaboration
7884 order. For full details see @ref{Elaboration Order Handling in GNAT}.
7887 @item ^-p^/PESSIMISTIC_ELABORATION^
7888 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
7889 Normally the binder attempts to choose an elaboration order that is
7890 likely to minimize the likelihood of an elaboration order error resulting
7891 in raising a @code{Program_Error} exception. This switch reverses the
7892 action of the binder, and requests that it deliberately choose an order
7893 that is likely to maximize the likelihood of an elaboration error.
7894 This is useful in ensuring portability and avoiding dependence on
7895 accidental fortuitous elaboration ordering.
7897 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
7899 elaboration checking is used (@option{-gnatE} switch used for compilation).
7900 This is because in the default static elaboration mode, all necessary
7901 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
7902 These implicit pragmas are still respected by the binder in
7903 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
7904 safe elaboration order is assured.
7907 @node Output Control
7908 @subsection Output Control
7911 The following switches allow additional control over the output
7912 generated by the binder.
7917 @item ^-A^/BIND_FILE=ADA^
7918 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
7919 Generate binder program in Ada (default). The binder program is named
7920 @file{b~@var{mainprog}.adb} by default. This can be changed with
7921 @option{^-o^/OUTPUT^} @code{gnatbind} option.
7923 @item ^-c^/NOOUTPUT^
7924 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
7925 Check only. Do not generate the binder output file. In this mode the
7926 binder performs all error checks but does not generate an output file.
7928 @item ^-C^/BIND_FILE=C^
7929 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
7930 Generate binder program in C. The binder program is named
7931 @file{b_@var{mainprog}.c}.
7932 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
7935 @item ^-e^/ELABORATION_DEPENDENCIES^
7936 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
7937 Output complete list of elaboration-order dependencies, showing the
7938 reason for each dependency. This output can be rather extensive but may
7939 be useful in diagnosing problems with elaboration order. The output is
7940 written to @file{stdout}.
7943 @cindex @option{^-h^/HELP^} (@code{gnatbind})
7944 Output usage information. The output is written to @file{stdout}.
7946 @item ^-K^/LINKER_OPTION_LIST^
7947 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
7948 Output linker options to @file{stdout}. Includes library search paths,
7949 contents of pragmas Ident and Linker_Options, and libraries added
7952 @item ^-l^/ORDER_OF_ELABORATION^
7953 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
7954 Output chosen elaboration order. The output is written to @file{stdout}.
7956 @item ^-O^/OBJECT_LIST^
7957 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
7958 Output full names of all the object files that must be linked to provide
7959 the Ada component of the program. The output is written to @file{stdout}.
7960 This list includes the files explicitly supplied and referenced by the user
7961 as well as implicitly referenced run-time unit files. The latter are
7962 omitted if the corresponding units reside in shared libraries. The
7963 directory names for the run-time units depend on the system configuration.
7965 @item ^-o ^/OUTPUT=^@var{file}
7966 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
7967 Set name of output file to @var{file} instead of the normal
7968 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
7969 binder generated body filename. In C mode you would normally give
7970 @var{file} an extension of @file{.c} because it will be a C source program.
7971 Note that if this option is used, then linking must be done manually.
7972 It is not possible to use gnatlink in this case, since it cannot locate
7975 @item ^-r^/RESTRICTION_LIST^
7976 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
7977 Generate list of @code{pragma Restrictions} that could be applied to
7978 the current unit. This is useful for code audit purposes, and also may
7979 be used to improve code generation in some cases.
7983 @node Binding with Non-Ada Main Programs
7984 @subsection Binding with Non-Ada Main Programs
7987 In our description so far we have assumed that the main
7988 program is in Ada, and that the task of the binder is to generate a
7989 corresponding function @code{main} that invokes this Ada main
7990 program. GNAT also supports the building of executable programs where
7991 the main program is not in Ada, but some of the called routines are
7992 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
7993 The following switch is used in this situation:
7997 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
7998 No main program. The main program is not in Ada.
8002 In this case, most of the functions of the binder are still required,
8003 but instead of generating a main program, the binder generates a file
8004 containing the following callable routines:
8009 You must call this routine to initialize the Ada part of the program by
8010 calling the necessary elaboration routines. A call to @code{adainit} is
8011 required before the first call to an Ada subprogram.
8013 Note that it is assumed that the basic execution environment must be setup
8014 to be appropriate for Ada execution at the point where the first Ada
8015 subprogram is called. In particular, if the Ada code will do any
8016 floating-point operations, then the FPU must be setup in an appropriate
8017 manner. For the case of the x86, for example, full precision mode is
8018 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8019 that the FPU is in the right state.
8023 You must call this routine to perform any library-level finalization
8024 required by the Ada subprograms. A call to @code{adafinal} is required
8025 after the last call to an Ada subprogram, and before the program
8030 If the @option{^-n^/NOMAIN^} switch
8031 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8032 @cindex Binder, multiple input files
8033 is given, more than one ALI file may appear on
8034 the command line for @code{gnatbind}. The normal @dfn{closure}
8035 calculation is performed for each of the specified units. Calculating
8036 the closure means finding out the set of units involved by tracing
8037 @code{with} references. The reason it is necessary to be able to
8038 specify more than one ALI file is that a given program may invoke two or
8039 more quite separate groups of Ada units.
8041 The binder takes the name of its output file from the last specified ALI
8042 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8043 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8044 The output is an Ada unit in source form that can
8045 be compiled with GNAT unless the -C switch is used in which case the
8046 output is a C source file, which must be compiled using the C compiler.
8047 This compilation occurs automatically as part of the @command{gnatlink}
8050 Currently the GNAT run time requires a FPU using 80 bits mode
8051 precision. Under targets where this is not the default it is required to
8052 call GNAT.Float_Control.Reset before using floating point numbers (this
8053 include float computation, float input and output) in the Ada code. A
8054 side effect is that this could be the wrong mode for the foreign code
8055 where floating point computation could be broken after this call.
8057 @node Binding Programs with No Main Subprogram
8058 @subsection Binding Programs with No Main Subprogram
8061 It is possible to have an Ada program which does not have a main
8062 subprogram. This program will call the elaboration routines of all the
8063 packages, then the finalization routines.
8065 The following switch is used to bind programs organized in this manner:
8068 @item ^-z^/ZERO_MAIN^
8069 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8070 Normally the binder checks that the unit name given on the command line
8071 corresponds to a suitable main subprogram. When this switch is used,
8072 a list of ALI files can be given, and the execution of the program
8073 consists of elaboration of these units in an appropriate order. Note
8074 that the default wide character encoding method for standard Text_IO
8075 files is always set to Brackets if this switch is set (you can use
8077 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8080 @node Command-Line Access
8081 @section Command-Line Access
8084 The package @code{Ada.Command_Line} provides access to the command-line
8085 arguments and program name. In order for this interface to operate
8086 correctly, the two variables
8098 are declared in one of the GNAT library routines. These variables must
8099 be set from the actual @code{argc} and @code{argv} values passed to the
8100 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8101 generates the C main program to automatically set these variables.
8102 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8103 set these variables. If they are not set, the procedures in
8104 @code{Ada.Command_Line} will not be available, and any attempt to use
8105 them will raise @code{Constraint_Error}. If command line access is
8106 required, your main program must set @code{gnat_argc} and
8107 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8110 @node Search Paths for gnatbind
8111 @section Search Paths for @code{gnatbind}
8114 The binder takes the name of an ALI file as its argument and needs to
8115 locate source files as well as other ALI files to verify object consistency.
8117 For source files, it follows exactly the same search rules as @command{gcc}
8118 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8119 directories searched are:
8123 The directory containing the ALI file named in the command line, unless
8124 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8127 All directories specified by @option{^-I^/SEARCH^}
8128 switches on the @code{gnatbind}
8129 command line, in the order given.
8132 @findex ADA_PRJ_OBJECTS_FILE
8133 Each of the directories listed in the text file whose name is given
8134 by the @code{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8137 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8138 driver when project files are used. It should not normally be set
8142 @findex ADA_OBJECTS_PATH
8143 Each of the directories listed in the value of the
8144 @code{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8146 Construct this value
8147 exactly as the @code{PATH} environment variable: a list of directory
8148 names separated by colons (semicolons when working with the NT version
8152 Normally, define this value as a logical name containing a comma separated
8153 list of directory names.
8155 This variable can also be defined by means of an environment string
8156 (an argument to the HP C exec* set of functions).
8160 DEFINE ANOTHER_PATH FOO:[BAG]
8161 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8164 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8165 first, followed by the standard Ada
8166 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8167 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8168 (Text_IO, Sequential_IO, etc)
8169 instead of the standard Ada packages. Thus, in order to get the standard Ada
8170 packages by default, ADA_OBJECTS_PATH must be redefined.
8174 The content of the @file{ada_object_path} file which is part of the GNAT
8175 installation tree and is used to store standard libraries such as the
8176 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8179 @ref{Installing a library}
8184 In the binder the switch @option{^-I^/SEARCH^}
8185 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8186 is used to specify both source and
8187 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8188 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8189 instead if you want to specify
8190 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8191 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8192 if you want to specify library paths
8193 only. This means that for the binder
8194 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8195 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8196 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8197 The binder generates the bind file (a C language source file) in the
8198 current working directory.
8204 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8205 children make up the GNAT Run-Time Library, together with the package
8206 GNAT and its children, which contain a set of useful additional
8207 library functions provided by GNAT. The sources for these units are
8208 needed by the compiler and are kept together in one directory. The ALI
8209 files and object files generated by compiling the RTL are needed by the
8210 binder and the linker and are kept together in one directory, typically
8211 different from the directory containing the sources. In a normal
8212 installation, you need not specify these directory names when compiling
8213 or binding. Either the environment variables or the built-in defaults
8214 cause these files to be found.
8216 Besides simplifying access to the RTL, a major use of search paths is
8217 in compiling sources from multiple directories. This can make
8218 development environments much more flexible.
8220 @node Examples of gnatbind Usage
8221 @section Examples of @code{gnatbind} Usage
8224 This section contains a number of examples of using the GNAT binding
8225 utility @code{gnatbind}.
8228 @item gnatbind hello
8229 The main program @code{Hello} (source program in @file{hello.adb}) is
8230 bound using the standard switch settings. The generated main program is
8231 @file{b~hello.adb}. This is the normal, default use of the binder.
8234 @item gnatbind hello -o mainprog.adb
8237 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8239 The main program @code{Hello} (source program in @file{hello.adb}) is
8240 bound using the standard switch settings. The generated main program is
8241 @file{mainprog.adb} with the associated spec in
8242 @file{mainprog.ads}. Note that you must specify the body here not the
8243 spec, in the case where the output is in Ada. Note that if this option
8244 is used, then linking must be done manually, since gnatlink will not
8245 be able to find the generated file.
8248 @item gnatbind main -C -o mainprog.c -x
8251 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
8253 The main program @code{Main} (source program in
8254 @file{main.adb}) is bound, excluding source files from the
8255 consistency checking, generating
8256 the file @file{mainprog.c}.
8259 @item gnatbind -x main_program -C -o mainprog.c
8260 This command is exactly the same as the previous example. Switches may
8261 appear anywhere in the command line, and single letter switches may be
8262 combined into a single switch.
8266 @item gnatbind -n math dbase -C -o ada-control.c
8269 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
8271 The main program is in a language other than Ada, but calls to
8272 subprograms in packages @code{Math} and @code{Dbase} appear. This call
8273 to @code{gnatbind} generates the file @file{ada-control.c} containing
8274 the @code{adainit} and @code{adafinal} routines to be called before and
8275 after accessing the Ada units.
8278 @c ------------------------------------
8279 @node Linking Using gnatlink
8280 @chapter Linking Using @command{gnatlink}
8281 @c ------------------------------------
8285 This chapter discusses @command{gnatlink}, a tool that links
8286 an Ada program and builds an executable file. This utility
8287 invokes the system linker ^(via the @command{gcc} command)^^
8288 with a correct list of object files and library references.
8289 @command{gnatlink} automatically determines the list of files and
8290 references for the Ada part of a program. It uses the binder file
8291 generated by the @command{gnatbind} to determine this list.
8293 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8294 driver (see @ref{The GNAT Driver and Project Files}).
8297 * Running gnatlink::
8298 * Switches for gnatlink::
8301 @node Running gnatlink
8302 @section Running @command{gnatlink}
8305 The form of the @command{gnatlink} command is
8308 $ gnatlink [@var{switches}] @var{mainprog}[.ali]
8309 [@var{non-Ada objects}] [@var{linker options}]
8313 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8315 or linker options) may be in any order, provided that no non-Ada object may
8316 be mistaken for a main @file{ALI} file.
8317 Any file name @file{F} without the @file{.ali}
8318 extension will be taken as the main @file{ALI} file if a file exists
8319 whose name is the concatenation of @file{F} and @file{.ali}.
8322 @file{@var{mainprog}.ali} references the ALI file of the main program.
8323 The @file{.ali} extension of this file can be omitted. From this
8324 reference, @command{gnatlink} locates the corresponding binder file
8325 @file{b~@var{mainprog}.adb} and, using the information in this file along
8326 with the list of non-Ada objects and linker options, constructs a
8327 linker command file to create the executable.
8329 The arguments other than the @command{gnatlink} switches and the main
8330 @file{ALI} file are passed to the linker uninterpreted.
8331 They typically include the names of
8332 object files for units written in other languages than Ada and any library
8333 references required to resolve references in any of these foreign language
8334 units, or in @code{Import} pragmas in any Ada units.
8336 @var{linker options} is an optional list of linker specific
8338 The default linker called by gnatlink is @command{gcc} which in
8339 turn calls the appropriate system linker.
8340 Standard options for the linker such as @option{-lmy_lib} or
8341 @option{-Ldir} can be added as is.
8342 For options that are not recognized by
8343 @command{gcc} as linker options, use the @command{gcc} switches
8344 @option{-Xlinker} or @option{-Wl,}.
8345 Refer to the GCC documentation for
8346 details. Here is an example showing how to generate a linker map:
8349 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8352 Using @var{linker options} it is possible to set the program stack and
8355 See @ref{Setting Stack Size from gnatlink} and
8356 @ref{Setting Heap Size from gnatlink}.
8359 @command{gnatlink} determines the list of objects required by the Ada
8360 program and prepends them to the list of objects passed to the linker.
8361 @command{gnatlink} also gathers any arguments set by the use of
8362 @code{pragma Linker_Options} and adds them to the list of arguments
8363 presented to the linker.
8366 @command{gnatlink} accepts the following types of extra files on the command
8367 line: objects (.OBJ), libraries (.OLB), sharable images (.EXE), and
8368 options files (.OPT). These are recognized and handled according to their
8372 @node Switches for gnatlink
8373 @section Switches for @command{gnatlink}
8376 The following switches are available with the @command{gnatlink} utility:
8382 @cindex @option{--version} @command{gnatlink}
8383 Display Copyright and version, then exit disregarding all other options.
8386 @cindex @option{--help} @command{gnatlink}
8387 If @option{--version} was not used, display usage, then exit disregarding
8390 @item ^-A^/BIND_FILE=ADA^
8391 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
8392 The binder has generated code in Ada. This is the default.
8394 @item ^-C^/BIND_FILE=C^
8395 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
8396 If instead of generating a file in Ada, the binder has generated one in
8397 C, then the linker needs to know about it. Use this switch to signal
8398 to @command{gnatlink} that the binder has generated C code rather than
8401 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8402 @cindex Command line length
8403 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8404 On some targets, the command line length is limited, and @command{gnatlink}
8405 will generate a separate file for the linker if the list of object files
8407 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8408 to be generated even if
8409 the limit is not exceeded. This is useful in some cases to deal with
8410 special situations where the command line length is exceeded.
8413 @cindex Debugging information, including
8414 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8415 The option to include debugging information causes the Ada bind file (in
8416 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8417 @option{^-g^/DEBUG^}.
8418 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8419 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8420 Without @option{^-g^/DEBUG^}, the binder removes these files by
8421 default. The same procedure apply if a C bind file was generated using
8422 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8423 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8425 @item ^-n^/NOCOMPILE^
8426 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8427 Do not compile the file generated by the binder. This may be used when
8428 a link is rerun with different options, but there is no need to recompile
8432 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8433 Causes additional information to be output, including a full list of the
8434 included object files. This switch option is most useful when you want
8435 to see what set of object files are being used in the link step.
8437 @item ^-v -v^/VERBOSE/VERBOSE^
8438 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8439 Very verbose mode. Requests that the compiler operate in verbose mode when
8440 it compiles the binder file, and that the system linker run in verbose mode.
8442 @item ^-o ^/EXECUTABLE=^@var{exec-name}
8443 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
8444 @var{exec-name} specifies an alternate name for the generated
8445 executable program. If this switch is omitted, the executable has the same
8446 name as the main unit. For example, @code{gnatlink try.ali} creates
8447 an executable called @file{^try^TRY.EXE^}.
8450 @item -b @var{target}
8451 @cindex @option{-b} (@command{gnatlink})
8452 Compile your program to run on @var{target}, which is the name of a
8453 system configuration. You must have a GNAT cross-compiler built if
8454 @var{target} is not the same as your host system.
8457 @cindex @option{-B} (@command{gnatlink})
8458 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8459 from @var{dir} instead of the default location. Only use this switch
8460 when multiple versions of the GNAT compiler are available. See the
8461 @command{gcc} manual page for further details. You would normally use the
8462 @option{-b} or @option{-V} switch instead.
8464 @item --GCC=@var{compiler_name}
8465 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8466 Program used for compiling the binder file. The default is
8467 @command{gcc}. You need to use quotes around @var{compiler_name} if
8468 @code{compiler_name} contains spaces or other separator characters.
8469 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8470 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8471 inserted after your command name. Thus in the above example the compiler
8472 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8473 A limitation of this syntax is that the name and path name of the executable
8474 itself must not include any embedded spaces. If several
8475 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
8476 is taken into account. However, all the additional switches are also taken
8478 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8479 @option{--GCC="bar -x -y -z -t"}.
8481 @item --LINK=@var{name}
8482 @cindex @option{--LINK=} (@command{gnatlink})
8483 @var{name} is the name of the linker to be invoked. This is especially
8484 useful in mixed language programs since languages such as C++ require
8485 their own linker to be used. When this switch is omitted, the default
8486 name for the linker is @command{gcc}. When this switch is used, the
8487 specified linker is called instead of @command{gcc} with exactly the same
8488 parameters that would have been passed to @command{gcc} so if the desired
8489 linker requires different parameters it is necessary to use a wrapper
8490 script that massages the parameters before invoking the real linker. It
8491 may be useful to control the exact invocation by using the verbose
8497 @item /DEBUG=TRACEBACK
8498 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
8499 This qualifier causes sufficient information to be included in the
8500 executable file to allow a traceback, but does not include the full
8501 symbol information needed by the debugger.
8503 @item /IDENTIFICATION="<string>"
8504 @code{"<string>"} specifies the string to be stored in the image file
8505 identification field in the image header.
8506 It overrides any pragma @code{Ident} specified string.
8508 @item /NOINHIBIT-EXEC
8509 Generate the executable file even if there are linker warnings.
8511 @item /NOSTART_FILES
8512 Don't link in the object file containing the ``main'' transfer address.
8513 Used when linking with a foreign language main program compiled with an
8517 Prefer linking with object libraries over sharable images, even without
8523 @node The GNAT Make Program gnatmake
8524 @chapter The GNAT Make Program @command{gnatmake}
8528 * Running gnatmake::
8529 * Switches for gnatmake::
8530 * Mode Switches for gnatmake::
8531 * Notes on the Command Line::
8532 * How gnatmake Works::
8533 * Examples of gnatmake Usage::
8536 A typical development cycle when working on an Ada program consists of
8537 the following steps:
8541 Edit some sources to fix bugs.
8547 Compile all sources affected.
8557 The third step can be tricky, because not only do the modified files
8558 @cindex Dependency rules
8559 have to be compiled, but any files depending on these files must also be
8560 recompiled. The dependency rules in Ada can be quite complex, especially
8561 in the presence of overloading, @code{use} clauses, generics and inlined
8564 @command{gnatmake} automatically takes care of the third and fourth steps
8565 of this process. It determines which sources need to be compiled,
8566 compiles them, and binds and links the resulting object files.
8568 Unlike some other Ada make programs, the dependencies are always
8569 accurately recomputed from the new sources. The source based approach of
8570 the GNAT compilation model makes this possible. This means that if
8571 changes to the source program cause corresponding changes in
8572 dependencies, they will always be tracked exactly correctly by
8575 @node Running gnatmake
8576 @section Running @command{gnatmake}
8579 The usual form of the @command{gnatmake} command is
8582 $ gnatmake [@var{switches}] @var{file_name}
8583 [@var{file_names}] [@var{mode_switches}]
8587 The only required argument is one @var{file_name}, which specifies
8588 a compilation unit that is a main program. Several @var{file_names} can be
8589 specified: this will result in several executables being built.
8590 If @code{switches} are present, they can be placed before the first
8591 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8592 If @var{mode_switches} are present, they must always be placed after
8593 the last @var{file_name} and all @code{switches}.
8595 If you are using standard file extensions (.adb and .ads), then the
8596 extension may be omitted from the @var{file_name} arguments. However, if
8597 you are using non-standard extensions, then it is required that the
8598 extension be given. A relative or absolute directory path can be
8599 specified in a @var{file_name}, in which case, the input source file will
8600 be searched for in the specified directory only. Otherwise, the input
8601 source file will first be searched in the directory where
8602 @command{gnatmake} was invoked and if it is not found, it will be search on
8603 the source path of the compiler as described in
8604 @ref{Search Paths and the Run-Time Library (RTL)}.
8606 All @command{gnatmake} output (except when you specify
8607 @option{^-M^/DEPENDENCIES_LIST^}) is to
8608 @file{stderr}. The output produced by the
8609 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8612 @node Switches for gnatmake
8613 @section Switches for @command{gnatmake}
8616 You may specify any of the following switches to @command{gnatmake}:
8622 @cindex @option{--version} @command{gnatmake}
8623 Display Copyright and version, then exit disregarding all other options.
8626 @cindex @option{--help} @command{gnatmake}
8627 If @option{--version} was not used, display usage, then exit disregarding
8631 @item --GCC=@var{compiler_name}
8632 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
8633 Program used for compiling. The default is `@command{gcc}'. You need to use
8634 quotes around @var{compiler_name} if @code{compiler_name} contains
8635 spaces or other separator characters. As an example @option{--GCC="foo -x
8636 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
8637 compiler. A limitation of this syntax is that the name and path name of
8638 the executable itself must not include any embedded spaces. Note that
8639 switch @option{-c} is always inserted after your command name. Thus in the
8640 above example the compiler command that will be used by @command{gnatmake}
8641 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
8642 used, only the last @var{compiler_name} is taken into account. However,
8643 all the additional switches are also taken into account. Thus,
8644 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8645 @option{--GCC="bar -x -y -z -t"}.
8647 @item --GNATBIND=@var{binder_name}
8648 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
8649 Program used for binding. The default is `@code{gnatbind}'. You need to
8650 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8651 or other separator characters. As an example @option{--GNATBIND="bar -x
8652 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
8653 binder. Binder switches that are normally appended by @command{gnatmake}
8654 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8655 A limitation of this syntax is that the name and path name of the executable
8656 itself must not include any embedded spaces.
8658 @item --GNATLINK=@var{linker_name}
8659 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
8660 Program used for linking. The default is `@command{gnatlink}'. You need to
8661 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8662 or other separator characters. As an example @option{--GNATLINK="lan -x
8663 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
8664 linker. Linker switches that are normally appended by @command{gnatmake} to
8665 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
8666 A limitation of this syntax is that the name and path name of the executable
8667 itself must not include any embedded spaces.
8671 @item ^-a^/ALL_FILES^
8672 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
8673 Consider all files in the make process, even the GNAT internal system
8674 files (for example, the predefined Ada library files), as well as any
8675 locked files. Locked files are files whose ALI file is write-protected.
8677 @command{gnatmake} does not check these files,
8678 because the assumption is that the GNAT internal files are properly up
8679 to date, and also that any write protected ALI files have been properly
8680 installed. Note that if there is an installation problem, such that one
8681 of these files is not up to date, it will be properly caught by the
8683 You may have to specify this switch if you are working on GNAT
8684 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8685 in conjunction with @option{^-f^/FORCE_COMPILE^}
8686 if you need to recompile an entire application,
8687 including run-time files, using special configuration pragmas,
8688 such as a @code{Normalize_Scalars} pragma.
8691 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8694 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8697 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8700 @item ^-b^/ACTIONS=BIND^
8701 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
8702 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8703 compilation and binding, but no link.
8704 Can be combined with @option{^-l^/ACTIONS=LINK^}
8705 to do binding and linking. When not combined with
8706 @option{^-c^/ACTIONS=COMPILE^}
8707 all the units in the closure of the main program must have been previously
8708 compiled and must be up to date. The root unit specified by @var{file_name}
8709 may be given without extension, with the source extension or, if no GNAT
8710 Project File is specified, with the ALI file extension.
8712 @item ^-c^/ACTIONS=COMPILE^
8713 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
8714 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8715 is also specified. Do not perform linking, except if both
8716 @option{^-b^/ACTIONS=BIND^} and
8717 @option{^-l^/ACTIONS=LINK^} are also specified.
8718 If the root unit specified by @var{file_name} is not a main unit, this is the
8719 default. Otherwise @command{gnatmake} will attempt binding and linking
8720 unless all objects are up to date and the executable is more recent than
8724 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
8725 Use a temporary mapping file. A mapping file is a way to communicate to the
8726 compiler two mappings: from unit names to file names (without any directory
8727 information) and from file names to path names (with full directory
8728 information). These mappings are used by the compiler to short-circuit the path
8729 search. When @command{gnatmake} is invoked with this switch, it will create
8730 a temporary mapping file, initially populated by the project manager,
8731 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8732 Each invocation of the compiler will add the newly accessed sources to the
8733 mapping file. This will improve the source search during the next invocation
8736 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8737 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
8738 Use a specific mapping file. The file, specified as a path name (absolute or
8739 relative) by this switch, should already exist, otherwise the switch is
8740 ineffective. The specified mapping file will be communicated to the compiler.
8741 This switch is not compatible with a project file
8742 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8743 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8745 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
8746 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
8747 Put all object files and ALI file in directory @var{dir}.
8748 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
8749 and ALI files go in the current working directory.
8751 This switch cannot be used when using a project file.
8755 @cindex @option{-eL} (@command{gnatmake})
8756 Follow all symbolic links when processing project files.
8759 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
8760 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
8761 Output the commands for the compiler, the binder and the linker
8762 on ^standard output^SYS$OUTPUT^,
8763 instead of ^standard error^SYS$ERROR^.
8765 @item ^-f^/FORCE_COMPILE^
8766 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
8767 Force recompilations. Recompile all sources, even though some object
8768 files may be up to date, but don't recompile predefined or GNAT internal
8769 files or locked files (files with a write-protected ALI file),
8770 unless the @option{^-a^/ALL_FILES^} switch is also specified.
8772 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
8773 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
8774 When using project files, if some errors or warnings are detected during
8775 parsing and verbose mode is not in effect (no use of switch
8776 ^-v^/VERBOSE^), then error lines start with the full path name of the project
8777 file, rather than its simple file name.
8780 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
8781 Enable debugging. This switch is simply passed to the compiler and to the
8784 @item ^-i^/IN_PLACE^
8785 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
8786 In normal mode, @command{gnatmake} compiles all object files and ALI files
8787 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
8788 then instead object files and ALI files that already exist are overwritten
8789 in place. This means that once a large project is organized into separate
8790 directories in the desired manner, then @command{gnatmake} will automatically
8791 maintain and update this organization. If no ALI files are found on the
8792 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
8793 the new object and ALI files are created in the
8794 directory containing the source being compiled. If another organization
8795 is desired, where objects and sources are kept in different directories,
8796 a useful technique is to create dummy ALI files in the desired directories.
8797 When detecting such a dummy file, @command{gnatmake} will be forced to
8798 recompile the corresponding source file, and it will be put the resulting
8799 object and ALI files in the directory where it found the dummy file.
8801 @item ^-j^/PROCESSES=^@var{n}
8802 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
8803 @cindex Parallel make
8804 Use @var{n} processes to carry out the (re)compilations. On a
8805 multiprocessor machine compilations will occur in parallel. In the
8806 event of compilation errors, messages from various compilations might
8807 get interspersed (but @command{gnatmake} will give you the full ordered
8808 list of failing compiles at the end). If this is problematic, rerun
8809 the make process with n set to 1 to get a clean list of messages.
8811 @item ^-k^/CONTINUE_ON_ERROR^
8812 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
8813 Keep going. Continue as much as possible after a compilation error. To
8814 ease the programmer's task in case of compilation errors, the list of
8815 sources for which the compile fails is given when @command{gnatmake}
8818 If @command{gnatmake} is invoked with several @file{file_names} and with this
8819 switch, if there are compilation errors when building an executable,
8820 @command{gnatmake} will not attempt to build the following executables.
8822 @item ^-l^/ACTIONS=LINK^
8823 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
8824 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
8825 and linking. Linking will not be performed if combined with
8826 @option{^-c^/ACTIONS=COMPILE^}
8827 but not with @option{^-b^/ACTIONS=BIND^}.
8828 When not combined with @option{^-b^/ACTIONS=BIND^}
8829 all the units in the closure of the main program must have been previously
8830 compiled and must be up to date, and the main program needs to have been bound.
8831 The root unit specified by @var{file_name}
8832 may be given without extension, with the source extension or, if no GNAT
8833 Project File is specified, with the ALI file extension.
8835 @item ^-m^/MINIMAL_RECOMPILATION^
8836 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
8837 Specify that the minimum necessary amount of recompilations
8838 be performed. In this mode @command{gnatmake} ignores time
8839 stamp differences when the only
8840 modifications to a source file consist in adding/removing comments,
8841 empty lines, spaces or tabs. This means that if you have changed the
8842 comments in a source file or have simply reformatted it, using this
8843 switch will tell @command{gnatmake} not to recompile files that depend on it
8844 (provided other sources on which these files depend have undergone no
8845 semantic modifications). Note that the debugging information may be
8846 out of date with respect to the sources if the @option{-m} switch causes
8847 a compilation to be switched, so the use of this switch represents a
8848 trade-off between compilation time and accurate debugging information.
8850 @item ^-M^/DEPENDENCIES_LIST^
8851 @cindex Dependencies, producing list
8852 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
8853 Check if all objects are up to date. If they are, output the object
8854 dependences to @file{stdout} in a form that can be directly exploited in
8855 a @file{Makefile}. By default, each source file is prefixed with its
8856 (relative or absolute) directory name. This name is whatever you
8857 specified in the various @option{^-aI^/SOURCE_SEARCH^}
8858 and @option{^-I^/SEARCH^} switches. If you use
8859 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
8860 @option{^-q^/QUIET^}
8861 (see below), only the source file names,
8862 without relative paths, are output. If you just specify the
8863 @option{^-M^/DEPENDENCIES_LIST^}
8864 switch, dependencies of the GNAT internal system files are omitted. This
8865 is typically what you want. If you also specify
8866 the @option{^-a^/ALL_FILES^} switch,
8867 dependencies of the GNAT internal files are also listed. Note that
8868 dependencies of the objects in external Ada libraries (see switch
8869 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
8872 @item ^-n^/DO_OBJECT_CHECK^
8873 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
8874 Don't compile, bind, or link. Checks if all objects are up to date.
8875 If they are not, the full name of the first file that needs to be
8876 recompiled is printed.
8877 Repeated use of this option, followed by compiling the indicated source
8878 file, will eventually result in recompiling all required units.
8880 @item ^-o ^/EXECUTABLE=^@var{exec_name}
8881 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
8882 Output executable name. The name of the final executable program will be
8883 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
8884 name for the executable will be the name of the input file in appropriate form
8885 for an executable file on the host system.
8887 This switch cannot be used when invoking @command{gnatmake} with several
8890 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
8891 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
8892 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
8893 automatically missing object directories, library directories and exec
8896 @item ^-P^/PROJECT_FILE=^@var{project}
8897 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
8898 Use project file @var{project}. Only one such switch can be used.
8899 @xref{gnatmake and Project Files}.
8902 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
8903 Quiet. When this flag is not set, the commands carried out by
8904 @command{gnatmake} are displayed.
8906 @item ^-s^/SWITCH_CHECK/^
8907 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
8908 Recompile if compiler switches have changed since last compilation.
8909 All compiler switches but -I and -o are taken into account in the
8911 orders between different ``first letter'' switches are ignored, but
8912 orders between same switches are taken into account. For example,
8913 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
8914 is equivalent to @option{-O -g}.
8916 This switch is recommended when Integrated Preprocessing is used.
8919 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
8920 Unique. Recompile at most the main files. It implies -c. Combined with
8921 -f, it is equivalent to calling the compiler directly. Note that using
8922 ^-u^/UNIQUE^ with a project file and no main has a special meaning
8923 (@pxref{Project Files and Main Subprograms}).
8925 @item ^-U^/ALL_PROJECTS^
8926 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
8927 When used without a project file or with one or several mains on the command
8928 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
8929 on the command line, all sources of all project files are checked and compiled
8930 if not up to date, and libraries are rebuilt, if necessary.
8933 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
8934 Verbose. Display the reason for all recompilations @command{gnatmake}
8935 decides are necessary, with the highest verbosity level.
8937 @item ^-vl^/LOW_VERBOSITY^
8938 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
8939 Verbosity level Low. Display fewer lines than in verbosity Medium.
8941 @item ^-vm^/MEDIUM_VERBOSITY^
8942 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
8943 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
8945 @item ^-vh^/HIGH_VERBOSITY^
8946 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
8947 Verbosity level High. Equivalent to ^-v^/REASONS^.
8949 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
8950 Indicate the verbosity of the parsing of GNAT project files.
8951 @xref{Switches Related to Project Files}.
8953 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
8954 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
8955 Indicate that sources that are not part of any Project File may be compiled.
8956 Normally, when using Project Files, only sources that are part of a Project
8957 File may be compile. When this switch is used, a source outside of all Project
8958 Files may be compiled. The ALI file and the object file will be put in the
8959 object directory of the main Project. The compilation switches used will only
8960 be those specified on the command line.
8962 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
8963 Indicate that external variable @var{name} has the value @var{value}.
8964 The Project Manager will use this value for occurrences of
8965 @code{external(name)} when parsing the project file.
8966 @xref{Switches Related to Project Files}.
8969 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
8970 No main subprogram. Bind and link the program even if the unit name
8971 given on the command line is a package name. The resulting executable
8972 will execute the elaboration routines of the package and its closure,
8973 then the finalization routines.
8978 @item @command{gcc} @asis{switches}
8980 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
8981 is passed to @command{gcc} (e.g. @option{-O}, @option{-gnato,} etc.)
8984 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
8985 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
8986 automatically treated as a compiler switch, and passed on to all
8987 compilations that are carried out.
8992 Source and library search path switches:
8996 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
8997 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
8998 When looking for source files also look in directory @var{dir}.
8999 The order in which source files search is undertaken is
9000 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9002 @item ^-aL^/SKIP_MISSING=^@var{dir}
9003 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9004 Consider @var{dir} as being an externally provided Ada library.
9005 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9006 files have been located in directory @var{dir}. This allows you to have
9007 missing bodies for the units in @var{dir} and to ignore out of date bodies
9008 for the same units. You still need to specify
9009 the location of the specs for these units by using the switches
9010 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9011 or @option{^-I^/SEARCH=^@var{dir}}.
9012 Note: this switch is provided for compatibility with previous versions
9013 of @command{gnatmake}. The easier method of causing standard libraries
9014 to be excluded from consideration is to write-protect the corresponding
9017 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9018 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9019 When searching for library and object files, look in directory
9020 @var{dir}. The order in which library files are searched is described in
9021 @ref{Search Paths for gnatbind}.
9023 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9024 @cindex Search paths, for @command{gnatmake}
9025 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9026 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9027 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9029 @item ^-I^/SEARCH=^@var{dir}
9030 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9031 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9032 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9034 @item ^-I-^/NOCURRENT_DIRECTORY^
9035 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9036 @cindex Source files, suppressing search
9037 Do not look for source files in the directory containing the source
9038 file named in the command line.
9039 Do not look for ALI or object files in the directory
9040 where @command{gnatmake} was invoked.
9042 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9043 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9044 @cindex Linker libraries
9045 Add directory @var{dir} to the list of directories in which the linker
9046 will search for libraries. This is equivalent to
9047 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9049 Furthermore, under Windows, the sources pointed to by the libraries path
9050 set in the registry are not searched for.
9054 @cindex @option{-nostdinc} (@command{gnatmake})
9055 Do not look for source files in the system default directory.
9058 @cindex @option{-nostdlib} (@command{gnatmake})
9059 Do not look for library files in the system default directory.
9061 @item --RTS=@var{rts-path}
9062 @cindex @option{--RTS} (@command{gnatmake})
9063 Specifies the default location of the runtime library. GNAT looks for the
9065 in the following directories, and stops as soon as a valid runtime is found
9066 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9067 @file{ada_object_path} present):
9070 @item <current directory>/$rts_path
9072 @item <default-search-dir>/$rts_path
9074 @item <default-search-dir>/rts-$rts_path
9078 The selected path is handled like a normal RTS path.
9082 @node Mode Switches for gnatmake
9083 @section Mode Switches for @command{gnatmake}
9086 The mode switches (referred to as @code{mode_switches}) allow the
9087 inclusion of switches that are to be passed to the compiler itself, the
9088 binder or the linker. The effect of a mode switch is to cause all
9089 subsequent switches up to the end of the switch list, or up to the next
9090 mode switch, to be interpreted as switches to be passed on to the
9091 designated component of GNAT.
9095 @item -cargs @var{switches}
9096 @cindex @option{-cargs} (@command{gnatmake})
9097 Compiler switches. Here @var{switches} is a list of switches
9098 that are valid switches for @command{gcc}. They will be passed on to
9099 all compile steps performed by @command{gnatmake}.
9101 @item -bargs @var{switches}
9102 @cindex @option{-bargs} (@command{gnatmake})
9103 Binder switches. Here @var{switches} is a list of switches
9104 that are valid switches for @code{gnatbind}. They will be passed on to
9105 all bind steps performed by @command{gnatmake}.
9107 @item -largs @var{switches}
9108 @cindex @option{-largs} (@command{gnatmake})
9109 Linker switches. Here @var{switches} is a list of switches
9110 that are valid switches for @command{gnatlink}. They will be passed on to
9111 all link steps performed by @command{gnatmake}.
9113 @item -margs @var{switches}
9114 @cindex @option{-margs} (@command{gnatmake})
9115 Make switches. The switches are directly interpreted by @command{gnatmake},
9116 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9120 @node Notes on the Command Line
9121 @section Notes on the Command Line
9124 This section contains some additional useful notes on the operation
9125 of the @command{gnatmake} command.
9129 @cindex Recompilation, by @command{gnatmake}
9130 If @command{gnatmake} finds no ALI files, it recompiles the main program
9131 and all other units required by the main program.
9132 This means that @command{gnatmake}
9133 can be used for the initial compile, as well as during subsequent steps of
9134 the development cycle.
9137 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9138 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9139 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9143 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9144 is used to specify both source and
9145 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9146 instead if you just want to specify
9147 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9148 if you want to specify library paths
9152 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9153 This may conveniently be used to exclude standard libraries from
9154 consideration and in particular it means that the use of the
9155 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9156 unless @option{^-a^/ALL_FILES^} is also specified.
9159 @command{gnatmake} has been designed to make the use of Ada libraries
9160 particularly convenient. Assume you have an Ada library organized
9161 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9162 of your Ada compilation units,
9163 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9164 specs of these units, but no bodies. Then to compile a unit
9165 stored in @code{main.adb}, which uses this Ada library you would just type
9169 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
9172 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9173 /SKIP_MISSING=@i{[OBJ_DIR]} main
9178 Using @command{gnatmake} along with the
9179 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9180 switch provides a mechanism for avoiding unnecessary recompilations. Using
9182 you can update the comments/format of your
9183 source files without having to recompile everything. Note, however, that
9184 adding or deleting lines in a source files may render its debugging
9185 info obsolete. If the file in question is a spec, the impact is rather
9186 limited, as that debugging info will only be useful during the
9187 elaboration phase of your program. For bodies the impact can be more
9188 significant. In all events, your debugger will warn you if a source file
9189 is more recent than the corresponding object, and alert you to the fact
9190 that the debugging information may be out of date.
9193 @node How gnatmake Works
9194 @section How @command{gnatmake} Works
9197 Generally @command{gnatmake} automatically performs all necessary
9198 recompilations and you don't need to worry about how it works. However,
9199 it may be useful to have some basic understanding of the @command{gnatmake}
9200 approach and in particular to understand how it uses the results of
9201 previous compilations without incorrectly depending on them.
9203 First a definition: an object file is considered @dfn{up to date} if the
9204 corresponding ALI file exists and if all the source files listed in the
9205 dependency section of this ALI file have time stamps matching those in
9206 the ALI file. This means that neither the source file itself nor any
9207 files that it depends on have been modified, and hence there is no need
9208 to recompile this file.
9210 @command{gnatmake} works by first checking if the specified main unit is up
9211 to date. If so, no compilations are required for the main unit. If not,
9212 @command{gnatmake} compiles the main program to build a new ALI file that
9213 reflects the latest sources. Then the ALI file of the main unit is
9214 examined to find all the source files on which the main program depends,
9215 and @command{gnatmake} recursively applies the above procedure on all these
9218 This process ensures that @command{gnatmake} only trusts the dependencies
9219 in an existing ALI file if they are known to be correct. Otherwise it
9220 always recompiles to determine a new, guaranteed accurate set of
9221 dependencies. As a result the program is compiled ``upside down'' from what may
9222 be more familiar as the required order of compilation in some other Ada
9223 systems. In particular, clients are compiled before the units on which
9224 they depend. The ability of GNAT to compile in any order is critical in
9225 allowing an order of compilation to be chosen that guarantees that
9226 @command{gnatmake} will recompute a correct set of new dependencies if
9229 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9230 imported by several of the executables, it will be recompiled at most once.
9232 Note: when using non-standard naming conventions
9233 (@pxref{Using Other File Names}), changing through a configuration pragmas
9234 file the version of a source and invoking @command{gnatmake} to recompile may
9235 have no effect, if the previous version of the source is still accessible
9236 by @command{gnatmake}. It may be necessary to use the switch
9237 ^-f^/FORCE_COMPILE^.
9239 @node Examples of gnatmake Usage
9240 @section Examples of @command{gnatmake} Usage
9243 @item gnatmake hello.adb
9244 Compile all files necessary to bind and link the main program
9245 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9246 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9248 @item gnatmake main1 main2 main3
9249 Compile all files necessary to bind and link the main programs
9250 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9251 (containing unit @code{Main2}) and @file{main3.adb}
9252 (containing unit @code{Main3}) and bind and link the resulting object files
9253 to generate three executable files @file{^main1^MAIN1.EXE^},
9254 @file{^main2^MAIN2.EXE^}
9255 and @file{^main3^MAIN3.EXE^}.
9258 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9262 @item gnatmake Main_Unit /QUIET
9263 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9264 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9266 Compile all files necessary to bind and link the main program unit
9267 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9268 be done with optimization level 2 and the order of elaboration will be
9269 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9270 displaying commands it is executing.
9273 @c *************************
9274 @node Improving Performance
9275 @chapter Improving Performance
9276 @cindex Improving performance
9279 This chapter presents several topics related to program performance.
9280 It first describes some of the tradeoffs that need to be considered
9281 and some of the techniques for making your program run faster.
9282 It then documents the @command{gnatelim} tool and unused subprogram/data
9283 elimination feature, which can reduce the size of program executables.
9285 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9286 driver (see @ref{The GNAT Driver and Project Files}).
9290 * Performance Considerations::
9291 * Reducing Size of Ada Executables with gnatelim::
9292 * Reducing Size of Executables with unused subprogram/data elimination::
9296 @c *****************************
9297 @node Performance Considerations
9298 @section Performance Considerations
9301 The GNAT system provides a number of options that allow a trade-off
9306 performance of the generated code
9309 speed of compilation
9312 minimization of dependences and recompilation
9315 the degree of run-time checking.
9319 The defaults (if no options are selected) aim at improving the speed
9320 of compilation and minimizing dependences, at the expense of performance
9321 of the generated code:
9328 no inlining of subprogram calls
9331 all run-time checks enabled except overflow and elaboration checks
9335 These options are suitable for most program development purposes. This
9336 chapter describes how you can modify these choices, and also provides
9337 some guidelines on debugging optimized code.
9340 * Controlling Run-Time Checks::
9341 * Use of Restrictions::
9342 * Optimization Levels::
9343 * Debugging Optimized Code::
9344 * Inlining of Subprograms::
9345 * Other Optimization Switches::
9346 * Optimization and Strict Aliasing::
9349 * Coverage Analysis::
9353 @node Controlling Run-Time Checks
9354 @subsection Controlling Run-Time Checks
9357 By default, GNAT generates all run-time checks, except arithmetic overflow
9358 checking for integer operations and checks for access before elaboration on
9359 subprogram calls. The latter are not required in default mode, because all
9360 necessary checking is done at compile time.
9361 @cindex @option{-gnatp} (@command{gcc})
9362 @cindex @option{-gnato} (@command{gcc})
9363 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9364 be modified. @xref{Run-Time Checks}.
9366 Our experience is that the default is suitable for most development
9369 We treat integer overflow specially because these
9370 are quite expensive and in our experience are not as important as other
9371 run-time checks in the development process. Note that division by zero
9372 is not considered an overflow check, and divide by zero checks are
9373 generated where required by default.
9375 Elaboration checks are off by default, and also not needed by default, since
9376 GNAT uses a static elaboration analysis approach that avoids the need for
9377 run-time checking. This manual contains a full chapter discussing the issue
9378 of elaboration checks, and if the default is not satisfactory for your use,
9379 you should read this chapter.
9381 For validity checks, the minimal checks required by the Ada Reference
9382 Manual (for case statements and assignments to array elements) are on
9383 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9384 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9385 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9386 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9387 are also suppressed entirely if @option{-gnatp} is used.
9389 @cindex Overflow checks
9390 @cindex Checks, overflow
9393 @cindex pragma Suppress
9394 @cindex pragma Unsuppress
9395 Note that the setting of the switches controls the default setting of
9396 the checks. They may be modified using either @code{pragma Suppress} (to
9397 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9398 checks) in the program source.
9400 @node Use of Restrictions
9401 @subsection Use of Restrictions
9404 The use of pragma Restrictions allows you to control which features are
9405 permitted in your program. Apart from the obvious point that if you avoid
9406 relatively expensive features like finalization (enforceable by the use
9407 of pragma Restrictions (No_Finalization), the use of this pragma does not
9408 affect the generated code in most cases.
9410 One notable exception to this rule is that the possibility of task abort
9411 results in some distributed overhead, particularly if finalization or
9412 exception handlers are used. The reason is that certain sections of code
9413 have to be marked as non-abortable.
9415 If you use neither the @code{abort} statement, nor asynchronous transfer
9416 of control (@code{select .. then abort}), then this distributed overhead
9417 is removed, which may have a general positive effect in improving
9418 overall performance. Especially code involving frequent use of tasking
9419 constructs and controlled types will show much improved performance.
9420 The relevant restrictions pragmas are
9422 @smallexample @c ada
9423 pragma Restrictions (No_Abort_Statements);
9424 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
9428 It is recommended that these restriction pragmas be used if possible. Note
9429 that this also means that you can write code without worrying about the
9430 possibility of an immediate abort at any point.
9432 @node Optimization Levels
9433 @subsection Optimization Levels
9434 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
9437 The default is optimization off. This results in the fastest compile
9438 times, but GNAT makes absolutely no attempt to optimize, and the
9439 generated programs are considerably larger and slower than when
9440 optimization is enabled. You can use the
9442 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
9443 @option{-O2}, @option{-O3}, and @option{-Os})
9446 @code{OPTIMIZE} qualifier
9448 to @command{gcc} to control the optimization level:
9451 @item ^-O0^/OPTIMIZE=NONE^
9452 No optimization (the default);
9453 generates unoptimized code but has
9454 the fastest compilation time.
9456 Note that many other compilers do fairly extensive optimization
9457 even if "no optimization" is specified. When using gcc, it is
9458 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
9459 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
9460 really does mean no optimization at all. This difference between
9461 gcc and other compilers should be kept in mind when doing
9462 performance comparisons.
9464 @item ^-O1^/OPTIMIZE=SOME^
9465 Moderate optimization;
9466 optimizes reasonably well but does not
9467 degrade compilation time significantly.
9469 @item ^-O2^/OPTIMIZE=ALL^
9471 @itemx /OPTIMIZE=DEVELOPMENT
9474 generates highly optimized code and has
9475 the slowest compilation time.
9477 @item ^-O3^/OPTIMIZE=INLINING^
9478 Full optimization as in @option{-O2},
9479 and also attempts automatic inlining of small
9480 subprograms within a unit (@pxref{Inlining of Subprograms}).
9482 @item ^-Os^/OPTIMIZE=SPACE^
9483 Optimize space usage of resulting program.
9487 Higher optimization levels perform more global transformations on the
9488 program and apply more expensive analysis algorithms in order to generate
9489 faster and more compact code. The price in compilation time, and the
9490 resulting improvement in execution time,
9491 both depend on the particular application and the hardware environment.
9492 You should experiment to find the best level for your application.
9494 The @option{^-Os^/OPTIMIZE=SPACE^} switch is independent of the time
9495 optimizations, so you can specify both @option{^-Os^/OPTIMIZE=SPACE^}
9496 and a time optimization on the same compile command.
9498 Since the precise set of optimizations done at each level will vary from
9499 release to release (and sometime from target to target), it is best to think
9500 of the optimization settings in general terms.
9501 The @cite{Using GNU GCC} manual contains details about
9502 ^the @option{-O} settings and a number of @option{-f} options that^how to^
9503 individually enable or disable specific optimizations.
9505 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
9506 been tested extensively at all optimization levels. There are some bugs
9507 which appear only with optimization turned on, but there have also been
9508 bugs which show up only in @emph{unoptimized} code. Selecting a lower
9509 level of optimization does not improve the reliability of the code
9510 generator, which in practice is highly reliable at all optimization
9513 Note regarding the use of @option{-O3}: The use of this optimization level
9514 is generally discouraged with GNAT, since it often results in larger
9515 executables which run more slowly. See further discussion of this point
9516 in @ref{Inlining of Subprograms}.
9518 @node Debugging Optimized Code
9519 @subsection Debugging Optimized Code
9520 @cindex Debugging optimized code
9521 @cindex Optimization and debugging
9524 Although it is possible to do a reasonable amount of debugging at
9526 nonzero optimization levels,
9527 the higher the level the more likely that
9530 @option{/OPTIMIZE} settings other than @code{NONE},
9531 such settings will make it more likely that
9533 source-level constructs will have been eliminated by optimization.
9534 For example, if a loop is strength-reduced, the loop
9535 control variable may be completely eliminated and thus cannot be
9536 displayed in the debugger.
9537 This can only happen at @option{-O2} or @option{-O3}.
9538 Explicit temporary variables that you code might be eliminated at
9539 ^level^setting^ @option{-O1} or higher.
9541 The use of the @option{^-g^/DEBUG^} switch,
9542 @cindex @option{^-g^/DEBUG^} (@command{gcc})
9543 which is needed for source-level debugging,
9544 affects the size of the program executable on disk,
9545 and indeed the debugging information can be quite large.
9546 However, it has no effect on the generated code (and thus does not
9547 degrade performance)
9549 Since the compiler generates debugging tables for a compilation unit before
9550 it performs optimizations, the optimizing transformations may invalidate some
9551 of the debugging data. You therefore need to anticipate certain
9552 anomalous situations that may arise while debugging optimized code.
9553 These are the most common cases:
9557 @i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next}
9559 the PC bouncing back and forth in the code. This may result from any of
9560 the following optimizations:
9564 @i{Common subexpression elimination:} using a single instance of code for a
9565 quantity that the source computes several times. As a result you
9566 may not be able to stop on what looks like a statement.
9569 @i{Invariant code motion:} moving an expression that does not change within a
9570 loop, to the beginning of the loop.
9573 @i{Instruction scheduling:} moving instructions so as to
9574 overlap loads and stores (typically) with other code, or in
9575 general to move computations of values closer to their uses. Often
9576 this causes you to pass an assignment statement without the assignment
9577 happening and then later bounce back to the statement when the
9578 value is actually needed. Placing a breakpoint on a line of code
9579 and then stepping over it may, therefore, not always cause all the
9580 expected side-effects.
9584 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
9585 two identical pieces of code are merged and the program counter suddenly
9586 jumps to a statement that is not supposed to be executed, simply because
9587 it (and the code following) translates to the same thing as the code
9588 that @emph{was} supposed to be executed. This effect is typically seen in
9589 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
9590 a @code{break} in a C @code{^switch^switch^} statement.
9593 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
9594 There are various reasons for this effect:
9598 In a subprogram prologue, a parameter may not yet have been moved to its
9602 A variable may be dead, and its register re-used. This is
9603 probably the most common cause.
9606 As mentioned above, the assignment of a value to a variable may
9610 A variable may be eliminated entirely by value propagation or
9611 other means. In this case, GCC may incorrectly generate debugging
9612 information for the variable
9616 In general, when an unexpected value appears for a local variable or parameter
9617 you should first ascertain if that value was actually computed by
9618 your program, as opposed to being incorrectly reported by the debugger.
9620 array elements in an object designated by an access value
9621 are generally less of a problem, once you have ascertained that the access
9623 Typically, this means checking variables in the preceding code and in the
9624 calling subprogram to verify that the value observed is explainable from other
9625 values (one must apply the procedure recursively to those
9626 other values); or re-running the code and stopping a little earlier
9627 (perhaps before the call) and stepping to better see how the variable obtained
9628 the value in question; or continuing to step @emph{from} the point of the
9629 strange value to see if code motion had simply moved the variable's
9634 In light of such anomalies, a recommended technique is to use @option{-O0}
9635 early in the software development cycle, when extensive debugging capabilities
9636 are most needed, and then move to @option{-O1} and later @option{-O2} as
9637 the debugger becomes less critical.
9638 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
9639 a release management issue.
9641 Note that if you use @option{-g} you can then use the @command{strip} program
9642 on the resulting executable,
9643 which removes both debugging information and global symbols.
9646 @node Inlining of Subprograms
9647 @subsection Inlining of Subprograms
9650 A call to a subprogram in the current unit is inlined if all the
9651 following conditions are met:
9655 The optimization level is at least @option{-O1}.
9658 The called subprogram is suitable for inlining: It must be small enough
9659 and not contain nested subprograms or anything else that @command{gcc}
9660 cannot support in inlined subprograms.
9663 The call occurs after the definition of the body of the subprogram.
9666 @cindex pragma Inline
9668 Either @code{pragma Inline} applies to the subprogram or it is
9669 small and automatic inlining (optimization level @option{-O3}) is
9674 Calls to subprograms in @code{with}'ed units are normally not inlined.
9675 To achieve actual inlining (that is, replacement of the call by the code
9676 in the body of the subprogram), the following conditions must all be true.
9680 The optimization level is at least @option{-O1}.
9683 The called subprogram is suitable for inlining: It must be small enough
9684 and not contain nested subprograms or anything else @command{gcc} cannot
9685 support in inlined subprograms.
9688 The call appears in a body (not in a package spec).
9691 There is a @code{pragma Inline} for the subprogram.
9694 @cindex @option{-gnatn} (@command{gcc})
9695 The @option{^-gnatn^/INLINE^} switch
9696 is used in the @command{gcc} command line
9699 Even if all these conditions are met, it may not be possible for
9700 the compiler to inline the call, due to the length of the body,
9701 or features in the body that make it impossible for the compiler
9704 Note that specifying the @option{-gnatn} switch causes additional
9705 compilation dependencies. Consider the following:
9707 @smallexample @c ada
9727 With the default behavior (no @option{-gnatn} switch specified), the
9728 compilation of the @code{Main} procedure depends only on its own source,
9729 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
9730 means that editing the body of @code{R} does not require recompiling
9733 On the other hand, the call @code{R.Q} is not inlined under these
9734 circumstances. If the @option{-gnatn} switch is present when @code{Main}
9735 is compiled, the call will be inlined if the body of @code{Q} is small
9736 enough, but now @code{Main} depends on the body of @code{R} in
9737 @file{r.adb} as well as on the spec. This means that if this body is edited,
9738 the main program must be recompiled. Note that this extra dependency
9739 occurs whether or not the call is in fact inlined by @command{gcc}.
9741 The use of front end inlining with @option{-gnatN} generates similar
9742 additional dependencies.
9744 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
9745 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
9746 can be used to prevent
9747 all inlining. This switch overrides all other conditions and ensures
9748 that no inlining occurs. The extra dependences resulting from
9749 @option{-gnatn} will still be active, even if
9750 this switch is used to suppress the resulting inlining actions.
9752 Note regarding the use of @option{-O3}: There is no difference in inlining
9753 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
9754 pragma @code{Inline} assuming the use of @option{-gnatn}
9755 or @option{-gnatN} (the switches that activate inlining). If you have used
9756 pragma @code{Inline} in appropriate cases, then it is usually much better
9757 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
9758 in this case only has the effect of inlining subprograms you did not
9759 think should be inlined. We often find that the use of @option{-O3} slows
9760 down code by performing excessive inlining, leading to increased instruction
9761 cache pressure from the increased code size. So the bottom line here is
9762 that you should not automatically assume that @option{-O3} is better than
9763 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
9764 it actually improves performance.
9766 @node Other Optimization Switches
9767 @subsection Other Optimization Switches
9768 @cindex Optimization Switches
9770 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
9771 @command{gcc} optimization switches are potentially usable. These switches
9772 have not been extensively tested with GNAT but can generally be expected
9773 to work. Examples of switches in this category are
9774 @option{-funroll-loops} and
9775 the various target-specific @option{-m} options (in particular, it has been
9776 observed that @option{-march=pentium4} can significantly improve performance
9777 on appropriate machines). For full details of these switches, see the
9778 @command{gcc} manual.
9780 @node Optimization and Strict Aliasing
9781 @subsection Optimization and Strict Aliasing
9783 @cindex Strict Aliasing
9784 @cindex No_Strict_Aliasing
9787 The strong typing capabilities of Ada allow an optimizer to generate
9788 efficient code in situations where other languages would be forced to
9789 make worst case assumptions preventing such optimizations. Consider
9790 the following example:
9792 @smallexample @c ada
9795 type Int1 is new Integer;
9796 type Int2 is new Integer;
9797 type Int1A is access Int1;
9798 type Int2A is access Int2;
9805 for J in Data'Range loop
9806 if Data (J) = Int1V.all then
9807 Int2V.all := Int2V.all + 1;
9816 In this example, since the variable @code{Int1V} can only access objects
9817 of type @code{Int1}, and @code{Int2V} can only access objects of type
9818 @code{Int2}, there is no possibility that the assignment to
9819 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
9820 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
9821 for all iterations of the loop and avoid the extra memory reference
9822 required to dereference it each time through the loop.
9824 This kind of optimization, called strict aliasing analysis, is
9825 triggered by specifying an optimization level of @option{-O2} or
9826 higher and allows @code{GNAT} to generate more efficient code
9827 when access values are involved.
9829 However, although this optimization is always correct in terms of
9830 the formal semantics of the Ada Reference Manual, difficulties can
9831 arise if features like @code{Unchecked_Conversion} are used to break
9832 the typing system. Consider the following complete program example:
9834 @smallexample @c ada
9837 type int1 is new integer;
9838 type int2 is new integer;
9839 type a1 is access int1;
9840 type a2 is access int2;
9845 function to_a2 (Input : a1) return a2;
9848 with Unchecked_Conversion;
9850 function to_a2 (Input : a1) return a2 is
9852 new Unchecked_Conversion (a1, a2);
9854 return to_a2u (Input);
9860 with Text_IO; use Text_IO;
9862 v1 : a1 := new int1;
9863 v2 : a2 := to_a2 (v1);
9867 put_line (int1'image (v1.all));
9873 This program prints out 0 in @option{-O0} or @option{-O1}
9874 mode, but it prints out 1 in @option{-O2} mode. That's
9875 because in strict aliasing mode, the compiler can and
9876 does assume that the assignment to @code{v2.all} could not
9877 affect the value of @code{v1.all}, since different types
9880 This behavior is not a case of non-conformance with the standard, since
9881 the Ada RM specifies that an unchecked conversion where the resulting
9882 bit pattern is not a correct value of the target type can result in an
9883 abnormal value and attempting to reference an abnormal value makes the
9884 execution of a program erroneous. That's the case here since the result
9885 does not point to an object of type @code{int2}. This means that the
9886 effect is entirely unpredictable.
9888 However, although that explanation may satisfy a language
9889 lawyer, in practice an applications programmer expects an
9890 unchecked conversion involving pointers to create true
9891 aliases and the behavior of printing 1 seems plain wrong.
9892 In this case, the strict aliasing optimization is unwelcome.
9894 Indeed the compiler recognizes this possibility, and the
9895 unchecked conversion generates a warning:
9898 p2.adb:5:07: warning: possible aliasing problem with type "a2"
9899 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
9900 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
9904 Unfortunately the problem is recognized when compiling the body of
9905 package @code{p2}, but the actual "bad" code is generated while
9906 compiling the body of @code{m} and this latter compilation does not see
9907 the suspicious @code{Unchecked_Conversion}.
9909 As implied by the warning message, there are approaches you can use to
9910 avoid the unwanted strict aliasing optimization in a case like this.
9912 One possibility is to simply avoid the use of @option{-O2}, but
9913 that is a bit drastic, since it throws away a number of useful
9914 optimizations that do not involve strict aliasing assumptions.
9916 A less drastic approach is to compile the program using the
9917 option @option{-fno-strict-aliasing}. Actually it is only the
9918 unit containing the dereferencing of the suspicious pointer
9919 that needs to be compiled. So in this case, if we compile
9920 unit @code{m} with this switch, then we get the expected
9921 value of zero printed. Analyzing which units might need
9922 the switch can be painful, so a more reasonable approach
9923 is to compile the entire program with options @option{-O2}
9924 and @option{-fno-strict-aliasing}. If the performance is
9925 satisfactory with this combination of options, then the
9926 advantage is that the entire issue of possible "wrong"
9927 optimization due to strict aliasing is avoided.
9929 To avoid the use of compiler switches, the configuration
9930 pragma @code{No_Strict_Aliasing} with no parameters may be
9931 used to specify that for all access types, the strict
9932 aliasing optimization should be suppressed.
9934 However, these approaches are still overkill, in that they causes
9935 all manipulations of all access values to be deoptimized. A more
9936 refined approach is to concentrate attention on the specific
9937 access type identified as problematic.
9939 First, if a careful analysis of uses of the pointer shows
9940 that there are no possible problematic references, then
9941 the warning can be suppressed by bracketing the
9942 instantiation of @code{Unchecked_Conversion} to turn
9945 @smallexample @c ada
9946 pragma Warnings (Off);
9948 new Unchecked_Conversion (a1, a2);
9949 pragma Warnings (On);
9953 Of course that approach is not appropriate for this particular
9954 example, since indeed there is a problematic reference. In this
9955 case we can take one of two other approaches.
9957 The first possibility is to move the instantiation of unchecked
9958 conversion to the unit in which the type is declared. In
9959 this example, we would move the instantiation of
9960 @code{Unchecked_Conversion} from the body of package
9961 @code{p2} to the spec of package @code{p1}. Now the
9962 warning disappears. That's because any use of the
9963 access type knows there is a suspicious unchecked
9964 conversion, and the strict aliasing optimization
9965 is automatically suppressed for the type.
9967 If it is not practical to move the unchecked conversion to the same unit
9968 in which the destination access type is declared (perhaps because the
9969 source type is not visible in that unit), you may use pragma
9970 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
9971 same declarative sequence as the declaration of the access type:
9973 @smallexample @c ada
9974 type a2 is access int2;
9975 pragma No_Strict_Aliasing (a2);
9979 Here again, the compiler now knows that the strict aliasing optimization
9980 should be suppressed for any reference to type @code{a2} and the
9981 expected behavior is obtained.
9983 Finally, note that although the compiler can generate warnings for
9984 simple cases of unchecked conversions, there are tricker and more
9985 indirect ways of creating type incorrect aliases which the compiler
9986 cannot detect. Examples are the use of address overlays and unchecked
9987 conversions involving composite types containing access types as
9988 components. In such cases, no warnings are generated, but there can
9989 still be aliasing problems. One safe coding practice is to forbid the
9990 use of address clauses for type overlaying, and to allow unchecked
9991 conversion only for primitive types. This is not really a significant
9992 restriction since any possible desired effect can be achieved by
9993 unchecked conversion of access values.
9996 @node Coverage Analysis
9997 @subsection Coverage Analysis
10000 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10001 the user to determine the distribution of execution time across a program,
10002 @pxref{Profiling} for details of usage.
10005 @node Reducing Size of Ada Executables with gnatelim
10006 @section Reducing Size of Ada Executables with @code{gnatelim}
10010 This section describes @command{gnatelim}, a tool which detects unused
10011 subprograms and helps the compiler to create a smaller executable for your
10016 * Running gnatelim::
10017 * Correcting the List of Eliminate Pragmas::
10018 * Making Your Executables Smaller::
10019 * Summary of the gnatelim Usage Cycle::
10022 @node About gnatelim
10023 @subsection About @code{gnatelim}
10026 When a program shares a set of Ada
10027 packages with other programs, it may happen that this program uses
10028 only a fraction of the subprograms defined in these packages. The code
10029 created for these unused subprograms increases the size of the executable.
10031 @code{gnatelim} tracks unused subprograms in an Ada program and
10032 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10033 subprograms that are declared but never called. By placing the list of
10034 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10035 recompiling your program, you may decrease the size of its executable,
10036 because the compiler will not generate the code for 'eliminated' subprograms.
10037 See GNAT Reference Manual for more information about this pragma.
10039 @code{gnatelim} needs as its input data the name of the main subprogram
10040 and a bind file for a main subprogram.
10042 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
10043 the main subprogram. @code{gnatelim} can work with both Ada and C
10044 bind files; when both are present, it uses the Ada bind file.
10045 The following commands will build the program and create the bind file:
10048 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10049 $ gnatbind main_prog
10052 Note that @code{gnatelim} needs neither object nor ALI files.
10054 @node Running gnatelim
10055 @subsection Running @code{gnatelim}
10058 @code{gnatelim} has the following command-line interface:
10061 $ gnatelim [options] name
10065 @code{name} should be a name of a source file that contains the main subprogram
10066 of a program (partition).
10068 @code{gnatelim} has the following switches:
10073 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10074 Quiet mode: by default @code{gnatelim} outputs to the standard error
10075 stream the number of program units left to be processed. This option turns
10078 @item ^-v^/VERBOSE^
10079 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10080 Verbose mode: @code{gnatelim} version information is printed as Ada
10081 comments to the standard output stream. Also, in addition to the number of
10082 program units left @code{gnatelim} will output the name of the current unit
10086 @cindex @option{^-a^/ALL^} (@command{gnatelim})
10087 Also look for subprograms from the GNAT run time that can be eliminated. Note
10088 that when @file{gnat.adc} is produced using this switch, the entire program
10089 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
10091 @item ^-I^/INCLUDE_DIRS=^@var{dir}
10092 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
10093 When looking for source files also look in directory @var{dir}. Specifying
10094 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
10095 sources in the current directory.
10097 @item ^-b^/BIND_FILE=^@var{bind_file}
10098 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
10099 Specifies @var{bind_file} as the bind file to process. If not set, the name
10100 of the bind file is computed from the full expanded Ada name
10101 of a main subprogram.
10103 @item ^-C^/CONFIG_FILE=^@var{config_file}
10104 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
10105 Specifies a file @var{config_file} that contains configuration pragmas. The
10106 file must be specified with full path.
10108 @item ^--GCC^/COMPILER^=@var{compiler_name}
10109 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
10110 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
10111 available on the path.
10113 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
10114 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
10115 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
10116 available on the path.
10120 @code{gnatelim} sends its output to the standard output stream, and all the
10121 tracing and debug information is sent to the standard error stream.
10122 In order to produce a proper GNAT configuration file
10123 @file{gnat.adc}, redirection must be used:
10127 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
10130 $ gnatelim main_prog.adb > gnat.adc
10139 $ gnatelim main_prog.adb >> gnat.adc
10143 in order to append the @code{gnatelim} output to the existing contents of
10147 @node Correcting the List of Eliminate Pragmas
10148 @subsection Correcting the List of Eliminate Pragmas
10151 In some rare cases @code{gnatelim} may try to eliminate
10152 subprograms that are actually called in the program. In this case, the
10153 compiler will generate an error message of the form:
10156 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
10160 You will need to manually remove the wrong @code{Eliminate} pragmas from
10161 the @file{gnat.adc} file. You should recompile your program
10162 from scratch after that, because you need a consistent @file{gnat.adc} file
10163 during the entire compilation.
10165 @node Making Your Executables Smaller
10166 @subsection Making Your Executables Smaller
10169 In order to get a smaller executable for your program you now have to
10170 recompile the program completely with the new @file{gnat.adc} file
10171 created by @code{gnatelim} in your current directory:
10174 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10178 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10179 recompile everything
10180 with the set of pragmas @code{Eliminate} that you have obtained with
10181 @command{gnatelim}).
10183 Be aware that the set of @code{Eliminate} pragmas is specific to each
10184 program. It is not recommended to merge sets of @code{Eliminate}
10185 pragmas created for different programs in one @file{gnat.adc} file.
10187 @node Summary of the gnatelim Usage Cycle
10188 @subsection Summary of the gnatelim Usage Cycle
10191 Here is a quick summary of the steps to be taken in order to reduce
10192 the size of your executables with @code{gnatelim}. You may use
10193 other GNAT options to control the optimization level,
10194 to produce the debugging information, to set search path, etc.
10198 Produce a bind file
10201 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10202 $ gnatbind main_prog
10206 Generate a list of @code{Eliminate} pragmas
10209 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10212 $ gnatelim main_prog >[>] gnat.adc
10217 Recompile the application
10220 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10225 @node Reducing Size of Executables with unused subprogram/data elimination
10226 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10227 @findex unused subprogram/data elimination
10230 This section describes how you can eliminate unused subprograms and data from
10231 your executable just by setting options at compilation time.
10234 * About unused subprogram/data elimination::
10235 * Compilation options::
10236 * Example of unused subprogram/data elimination::
10239 @node About unused subprogram/data elimination
10240 @subsection About unused subprogram/data elimination
10243 By default, an executable contains all code and data of its composing objects
10244 (directly linked or coming from statically linked libraries), even data or code
10245 never used by this executable.
10247 This feature will allow you to eliminate such unused code from your
10248 executable, making it smaller (in disk and in memory).
10250 This functionality is available on all Linux platforms except for the IA-64
10251 architecture and on all cross platforms using the ELF binary file format.
10252 In both cases GNU binutils version 2.16 or later are required to enable it.
10254 @node Compilation options
10255 @subsection Compilation options
10258 The operation of eliminating the unused code and data from the final executable
10259 is directly performed by the linker.
10261 In order to do this, it has to work with objects compiled with the
10263 @option{-ffunction-sections} @option{-fdata-sections}.
10264 @cindex @option{-ffunction-sections} (@command{gcc})
10265 @cindex @option{-fdata-sections} (@command{gcc})
10266 These options are usable with C and Ada files.
10267 They will place respectively each
10268 function or data in a separate section in the resulting object file.
10270 Once the objects and static libraries are created with these options, the
10271 linker can perform the dead code elimination. You can do this by setting
10272 the @option{-Wl,--gc-sections} option to gcc command or in the
10273 @option{-largs} section of @command{gnatmake}. This will perform a
10274 garbage collection of code and data never referenced.
10276 If the linker performs a partial link (@option{-r} ld linker option), then you
10277 will need to provide one or several entry point using the
10278 @option{-e} / @option{--entry} ld option.
10280 Note that objects compiled without the @option{-ffunction-sections} and
10281 @option{-fdata-sections} options can still be linked with the executable.
10282 However, no dead code elimination will be performed on those objects (they will
10285 The GNAT static library is now compiled with -ffunction-sections and
10286 -fdata-sections on some platforms. This allows you to eliminate the unused code
10287 and data of the GNAT library from your executable.
10289 @node Example of unused subprogram/data elimination
10290 @subsection Example of unused subprogram/data elimination
10293 Here is a simple example:
10295 @smallexample @c ada
10304 Used_Data : Integer;
10305 Unused_Data : Integer;
10307 procedure Used (Data : Integer);
10308 procedure Unused (Data : Integer);
10311 package body Aux is
10312 procedure Used (Data : Integer) is
10317 procedure Unused (Data : Integer) is
10319 Unused_Data := Data;
10325 @code{Unused} and @code{Unused_Data} are never referenced in this code
10326 excerpt, and hence they may be safely removed from the final executable.
10331 $ nm test | grep used
10332 020015f0 T aux__unused
10333 02005d88 B aux__unused_data
10334 020015cc T aux__used
10335 02005d84 B aux__used_data
10337 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10338 -largs -Wl,--gc-sections
10340 $ nm test | grep used
10341 02005350 T aux__used
10342 0201ffe0 B aux__used_data
10346 It can be observed that the procedure @code{Unused} and the object
10347 @code{Unused_Data} are removed by the linker when using the
10348 appropriate options.
10350 @c ********************************
10351 @node Renaming Files Using gnatchop
10352 @chapter Renaming Files Using @code{gnatchop}
10356 This chapter discusses how to handle files with multiple units by using
10357 the @code{gnatchop} utility. This utility is also useful in renaming
10358 files to meet the standard GNAT default file naming conventions.
10361 * Handling Files with Multiple Units::
10362 * Operating gnatchop in Compilation Mode::
10363 * Command Line for gnatchop::
10364 * Switches for gnatchop::
10365 * Examples of gnatchop Usage::
10368 @node Handling Files with Multiple Units
10369 @section Handling Files with Multiple Units
10372 The basic compilation model of GNAT requires that a file submitted to the
10373 compiler have only one unit and there be a strict correspondence
10374 between the file name and the unit name.
10376 The @code{gnatchop} utility allows both of these rules to be relaxed,
10377 allowing GNAT to process files which contain multiple compilation units
10378 and files with arbitrary file names. @code{gnatchop}
10379 reads the specified file and generates one or more output files,
10380 containing one unit per file. The unit and the file name correspond,
10381 as required by GNAT.
10383 If you want to permanently restructure a set of ``foreign'' files so that
10384 they match the GNAT rules, and do the remaining development using the
10385 GNAT structure, you can simply use @command{gnatchop} once, generate the
10386 new set of files and work with them from that point on.
10388 Alternatively, if you want to keep your files in the ``foreign'' format,
10389 perhaps to maintain compatibility with some other Ada compilation
10390 system, you can set up a procedure where you use @command{gnatchop} each
10391 time you compile, regarding the source files that it writes as temporary
10392 files that you throw away.
10394 @node Operating gnatchop in Compilation Mode
10395 @section Operating gnatchop in Compilation Mode
10398 The basic function of @code{gnatchop} is to take a file with multiple units
10399 and split it into separate files. The boundary between files is reasonably
10400 clear, except for the issue of comments and pragmas. In default mode, the
10401 rule is that any pragmas between units belong to the previous unit, except
10402 that configuration pragmas always belong to the following unit. Any comments
10403 belong to the following unit. These rules
10404 almost always result in the right choice of
10405 the split point without needing to mark it explicitly and most users will
10406 find this default to be what they want. In this default mode it is incorrect to
10407 submit a file containing only configuration pragmas, or one that ends in
10408 configuration pragmas, to @code{gnatchop}.
10410 However, using a special option to activate ``compilation mode'',
10412 can perform another function, which is to provide exactly the semantics
10413 required by the RM for handling of configuration pragmas in a compilation.
10414 In the absence of configuration pragmas (at the main file level), this
10415 option has no effect, but it causes such configuration pragmas to be handled
10416 in a quite different manner.
10418 First, in compilation mode, if @code{gnatchop} is given a file that consists of
10419 only configuration pragmas, then this file is appended to the
10420 @file{gnat.adc} file in the current directory. This behavior provides
10421 the required behavior described in the RM for the actions to be taken
10422 on submitting such a file to the compiler, namely that these pragmas
10423 should apply to all subsequent compilations in the same compilation
10424 environment. Using GNAT, the current directory, possibly containing a
10425 @file{gnat.adc} file is the representation
10426 of a compilation environment. For more information on the
10427 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
10429 Second, in compilation mode, if @code{gnatchop}
10430 is given a file that starts with
10431 configuration pragmas, and contains one or more units, then these
10432 configuration pragmas are prepended to each of the chopped files. This
10433 behavior provides the required behavior described in the RM for the
10434 actions to be taken on compiling such a file, namely that the pragmas
10435 apply to all units in the compilation, but not to subsequently compiled
10438 Finally, if configuration pragmas appear between units, they are appended
10439 to the previous unit. This results in the previous unit being illegal,
10440 since the compiler does not accept configuration pragmas that follow
10441 a unit. This provides the required RM behavior that forbids configuration
10442 pragmas other than those preceding the first compilation unit of a
10445 For most purposes, @code{gnatchop} will be used in default mode. The
10446 compilation mode described above is used only if you need exactly
10447 accurate behavior with respect to compilations, and you have files
10448 that contain multiple units and configuration pragmas. In this
10449 circumstance the use of @code{gnatchop} with the compilation mode
10450 switch provides the required behavior, and is for example the mode
10451 in which GNAT processes the ACVC tests.
10453 @node Command Line for gnatchop
10454 @section Command Line for @code{gnatchop}
10457 The @code{gnatchop} command has the form:
10460 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
10465 The only required argument is the file name of the file to be chopped.
10466 There are no restrictions on the form of this file name. The file itself
10467 contains one or more Ada units, in normal GNAT format, concatenated
10468 together. As shown, more than one file may be presented to be chopped.
10470 When run in default mode, @code{gnatchop} generates one output file in
10471 the current directory for each unit in each of the files.
10473 @var{directory}, if specified, gives the name of the directory to which
10474 the output files will be written. If it is not specified, all files are
10475 written to the current directory.
10477 For example, given a
10478 file called @file{hellofiles} containing
10480 @smallexample @c ada
10485 with Text_IO; use Text_IO;
10488 Put_Line ("Hello");
10498 $ gnatchop ^hellofiles^HELLOFILES.^
10502 generates two files in the current directory, one called
10503 @file{hello.ads} containing the single line that is the procedure spec,
10504 and the other called @file{hello.adb} containing the remaining text. The
10505 original file is not affected. The generated files can be compiled in
10509 When gnatchop is invoked on a file that is empty or that contains only empty
10510 lines and/or comments, gnatchop will not fail, but will not produce any
10513 For example, given a
10514 file called @file{toto.txt} containing
10516 @smallexample @c ada
10528 $ gnatchop ^toto.txt^TOT.TXT^
10532 will not produce any new file and will result in the following warnings:
10535 toto.txt:1:01: warning: empty file, contains no compilation units
10536 no compilation units found
10537 no source files written
10540 @node Switches for gnatchop
10541 @section Switches for @code{gnatchop}
10544 @command{gnatchop} recognizes the following switches:
10550 @cindex @option{--version} @command{gnatchop}
10551 Display Copyright and version, then exit disregarding all other options.
10554 @cindex @option{--help} @command{gnatchop}
10555 If @option{--version} was not used, display usage, then exit disregarding
10558 @item ^-c^/COMPILATION^
10559 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
10560 Causes @code{gnatchop} to operate in compilation mode, in which
10561 configuration pragmas are handled according to strict RM rules. See
10562 previous section for a full description of this mode.
10566 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
10567 used to parse the given file. Not all @code{xxx} options make sense,
10568 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
10569 process a source file that uses Latin-2 coding for identifiers.
10573 Causes @code{gnatchop} to generate a brief help summary to the standard
10574 output file showing usage information.
10576 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
10577 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
10578 Limit generated file names to the specified number @code{mm}
10580 This is useful if the
10581 resulting set of files is required to be interoperable with systems
10582 which limit the length of file names.
10584 If no value is given, or
10585 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
10586 a default of 39, suitable for OpenVMS Alpha
10587 Systems, is assumed
10590 No space is allowed between the @option{-k} and the numeric value. The numeric
10591 value may be omitted in which case a default of @option{-k8},
10593 with DOS-like file systems, is used. If no @option{-k} switch
10595 there is no limit on the length of file names.
10598 @item ^-p^/PRESERVE^
10599 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
10600 Causes the file ^modification^creation^ time stamp of the input file to be
10601 preserved and used for the time stamp of the output file(s). This may be
10602 useful for preserving coherency of time stamps in an environment where
10603 @code{gnatchop} is used as part of a standard build process.
10606 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
10607 Causes output of informational messages indicating the set of generated
10608 files to be suppressed. Warnings and error messages are unaffected.
10610 @item ^-r^/REFERENCE^
10611 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
10612 @findex Source_Reference
10613 Generate @code{Source_Reference} pragmas. Use this switch if the output
10614 files are regarded as temporary and development is to be done in terms
10615 of the original unchopped file. This switch causes
10616 @code{Source_Reference} pragmas to be inserted into each of the
10617 generated files to refers back to the original file name and line number.
10618 The result is that all error messages refer back to the original
10620 In addition, the debugging information placed into the object file (when
10621 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
10623 also refers back to this original file so that tools like profilers and
10624 debuggers will give information in terms of the original unchopped file.
10626 If the original file to be chopped itself contains
10627 a @code{Source_Reference}
10628 pragma referencing a third file, then gnatchop respects
10629 this pragma, and the generated @code{Source_Reference} pragmas
10630 in the chopped file refer to the original file, with appropriate
10631 line numbers. This is particularly useful when @code{gnatchop}
10632 is used in conjunction with @code{gnatprep} to compile files that
10633 contain preprocessing statements and multiple units.
10635 @item ^-v^/VERBOSE^
10636 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
10637 Causes @code{gnatchop} to operate in verbose mode. The version
10638 number and copyright notice are output, as well as exact copies of
10639 the gnat1 commands spawned to obtain the chop control information.
10641 @item ^-w^/OVERWRITE^
10642 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
10643 Overwrite existing file names. Normally @code{gnatchop} regards it as a
10644 fatal error if there is already a file with the same name as a
10645 file it would otherwise output, in other words if the files to be
10646 chopped contain duplicated units. This switch bypasses this
10647 check, and causes all but the last instance of such duplicated
10648 units to be skipped.
10652 @cindex @option{--GCC=} (@code{gnatchop})
10653 Specify the path of the GNAT parser to be used. When this switch is used,
10654 no attempt is made to add the prefix to the GNAT parser executable.
10658 @node Examples of gnatchop Usage
10659 @section Examples of @code{gnatchop} Usage
10663 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
10666 @item gnatchop -w hello_s.ada prerelease/files
10669 Chops the source file @file{hello_s.ada}. The output files will be
10670 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
10672 files with matching names in that directory (no files in the current
10673 directory are modified).
10675 @item gnatchop ^archive^ARCHIVE.^
10676 Chops the source file @file{^archive^ARCHIVE.^}
10677 into the current directory. One
10678 useful application of @code{gnatchop} is in sending sets of sources
10679 around, for example in email messages. The required sources are simply
10680 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
10682 @command{gnatchop} is used at the other end to reconstitute the original
10685 @item gnatchop file1 file2 file3 direc
10686 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
10687 the resulting files in the directory @file{direc}. Note that if any units
10688 occur more than once anywhere within this set of files, an error message
10689 is generated, and no files are written. To override this check, use the
10690 @option{^-w^/OVERWRITE^} switch,
10691 in which case the last occurrence in the last file will
10692 be the one that is output, and earlier duplicate occurrences for a given
10693 unit will be skipped.
10696 @node Configuration Pragmas
10697 @chapter Configuration Pragmas
10698 @cindex Configuration pragmas
10699 @cindex Pragmas, configuration
10702 Configuration pragmas include those pragmas described as
10703 such in the Ada Reference Manual, as well as
10704 implementation-dependent pragmas that are configuration pragmas. See the
10705 individual descriptions of pragmas in the @cite{GNAT Reference Manual} for
10706 details on these additional GNAT-specific configuration pragmas. Most
10707 notably, the pragma @code{Source_File_Name}, which allows
10708 specifying non-default names for source files, is a configuration
10709 pragma. The following is a complete list of configuration pragmas
10710 recognized by GNAT:
10717 Component_Alignment
10723 External_Name_Casing
10724 Float_Representation
10735 Propagate_Exceptions
10738 Restricted_Run_Time
10740 Restrictions_Warnings
10745 Task_Dispatching_Policy
10754 * Handling of Configuration Pragmas::
10755 * The Configuration Pragmas Files::
10758 @node Handling of Configuration Pragmas
10759 @section Handling of Configuration Pragmas
10761 Configuration pragmas may either appear at the start of a compilation
10762 unit, in which case they apply only to that unit, or they may apply to
10763 all compilations performed in a given compilation environment.
10765 GNAT also provides the @code{gnatchop} utility to provide an automatic
10766 way to handle configuration pragmas following the semantics for
10767 compilations (that is, files with multiple units), described in the RM.
10768 See @ref{Operating gnatchop in Compilation Mode} for details.
10769 However, for most purposes, it will be more convenient to edit the
10770 @file{gnat.adc} file that contains configuration pragmas directly,
10771 as described in the following section.
10773 @node The Configuration Pragmas Files
10774 @section The Configuration Pragmas Files
10775 @cindex @file{gnat.adc}
10778 In GNAT a compilation environment is defined by the current
10779 directory at the time that a compile command is given. This current
10780 directory is searched for a file whose name is @file{gnat.adc}. If
10781 this file is present, it is expected to contain one or more
10782 configuration pragmas that will be applied to the current compilation.
10783 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
10786 Configuration pragmas may be entered into the @file{gnat.adc} file
10787 either by running @code{gnatchop} on a source file that consists only of
10788 configuration pragmas, or more conveniently by
10789 direct editing of the @file{gnat.adc} file, which is a standard format
10792 In addition to @file{gnat.adc}, additional files containing configuration
10793 pragmas may be applied to the current compilation using the switch
10794 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
10795 contains only configuration pragmas. These configuration pragmas are
10796 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
10797 is present and switch @option{-gnatA} is not used).
10799 It is allowed to specify several switches @option{-gnatec}, all of which
10800 will be taken into account.
10802 If you are using project file, a separate mechanism is provided using
10803 project attributes, see @ref{Specifying Configuration Pragmas} for more
10807 Of special interest to GNAT OpenVMS Alpha is the following
10808 configuration pragma:
10810 @smallexample @c ada
10812 pragma Extend_System (Aux_DEC);
10817 In the presence of this pragma, GNAT adds to the definition of the
10818 predefined package SYSTEM all the additional types and subprograms that are
10819 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
10822 @node Handling Arbitrary File Naming Conventions Using gnatname
10823 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
10824 @cindex Arbitrary File Naming Conventions
10827 * Arbitrary File Naming Conventions::
10828 * Running gnatname::
10829 * Switches for gnatname::
10830 * Examples of gnatname Usage::
10833 @node Arbitrary File Naming Conventions
10834 @section Arbitrary File Naming Conventions
10837 The GNAT compiler must be able to know the source file name of a compilation
10838 unit. When using the standard GNAT default file naming conventions
10839 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
10840 does not need additional information.
10843 When the source file names do not follow the standard GNAT default file naming
10844 conventions, the GNAT compiler must be given additional information through
10845 a configuration pragmas file (@pxref{Configuration Pragmas})
10847 When the non standard file naming conventions are well-defined,
10848 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
10849 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
10850 if the file naming conventions are irregular or arbitrary, a number
10851 of pragma @code{Source_File_Name} for individual compilation units
10853 To help maintain the correspondence between compilation unit names and
10854 source file names within the compiler,
10855 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
10858 @node Running gnatname
10859 @section Running @code{gnatname}
10862 The usual form of the @code{gnatname} command is
10865 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
10869 All of the arguments are optional. If invoked without any argument,
10870 @code{gnatname} will display its usage.
10873 When used with at least one naming pattern, @code{gnatname} will attempt to
10874 find all the compilation units in files that follow at least one of the
10875 naming patterns. To find these compilation units,
10876 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
10880 One or several Naming Patterns may be given as arguments to @code{gnatname}.
10881 Each Naming Pattern is enclosed between double quotes.
10882 A Naming Pattern is a regular expression similar to the wildcard patterns
10883 used in file names by the Unix shells or the DOS prompt.
10886 Examples of Naming Patterns are
10895 For a more complete description of the syntax of Naming Patterns,
10896 see the second kind of regular expressions described in @file{g-regexp.ads}
10897 (the ``Glob'' regular expressions).
10900 When invoked with no switches, @code{gnatname} will create a configuration
10901 pragmas file @file{gnat.adc} in the current working directory, with pragmas
10902 @code{Source_File_Name} for each file that contains a valid Ada unit.
10904 @node Switches for gnatname
10905 @section Switches for @code{gnatname}
10908 Switches for @code{gnatname} must precede any specified Naming Pattern.
10911 You may specify any of the following switches to @code{gnatname}:
10917 @cindex @option{--version} @command{gnatname}
10918 Display Copyright and version, then exit disregarding all other options.
10921 @cindex @option{--help} @command{gnatname}
10922 If @option{--version} was not used, display usage, then exit disregarding
10925 @item ^-c^/CONFIG_FILE=^@file{file}
10926 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
10927 Create a configuration pragmas file @file{file} (instead of the default
10930 There may be zero, one or more space between @option{-c} and
10933 @file{file} may include directory information. @file{file} must be
10934 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
10935 When a switch @option{^-c^/CONFIG_FILE^} is
10936 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
10938 @item ^-d^/SOURCE_DIRS=^@file{dir}
10939 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
10940 Look for source files in directory @file{dir}. There may be zero, one or more
10941 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
10942 When a switch @option{^-d^/SOURCE_DIRS^}
10943 is specified, the current working directory will not be searched for source
10944 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
10945 or @option{^-D^/DIR_FILES^} switch.
10946 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
10947 If @file{dir} is a relative path, it is relative to the directory of
10948 the configuration pragmas file specified with switch
10949 @option{^-c^/CONFIG_FILE^},
10950 or to the directory of the project file specified with switch
10951 @option{^-P^/PROJECT_FILE^} or,
10952 if neither switch @option{^-c^/CONFIG_FILE^}
10953 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
10954 current working directory. The directory
10955 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
10957 @item ^-D^/DIRS_FILE=^@file{file}
10958 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
10959 Look for source files in all directories listed in text file @file{file}.
10960 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
10962 @file{file} must be an existing, readable text file.
10963 Each non empty line in @file{file} must be a directory.
10964 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
10965 switches @option{^-d^/SOURCE_DIRS^} as there are non empty lines in
10968 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
10969 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
10970 Foreign patterns. Using this switch, it is possible to add sources of languages
10971 other than Ada to the list of sources of a project file.
10972 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
10975 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
10978 will look for Ada units in all files with the @file{.ada} extension,
10979 and will add to the list of file for project @file{prj.gpr} the C files
10980 with extension ".^c^C^".
10983 @cindex @option{^-h^/HELP^} (@code{gnatname})
10984 Output usage (help) information. The output is written to @file{stdout}.
10986 @item ^-P^/PROJECT_FILE=^@file{proj}
10987 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
10988 Create or update project file @file{proj}. There may be zero, one or more space
10989 between @option{-P} and @file{proj}. @file{proj} may include directory
10990 information. @file{proj} must be writable.
10991 There may be only one switch @option{^-P^/PROJECT_FILE^}.
10992 When a switch @option{^-P^/PROJECT_FILE^} is specified,
10993 no switch @option{^-c^/CONFIG_FILE^} may be specified.
10995 @item ^-v^/VERBOSE^
10996 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
10997 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
10998 This includes name of the file written, the name of the directories to search
10999 and, for each file in those directories whose name matches at least one of
11000 the Naming Patterns, an indication of whether the file contains a unit,
11001 and if so the name of the unit.
11003 @item ^-v -v^/VERBOSE /VERBOSE^
11004 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11005 Very Verbose mode. In addition to the output produced in verbose mode,
11006 for each file in the searched directories whose name matches none of
11007 the Naming Patterns, an indication is given that there is no match.
11009 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11010 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11011 Excluded patterns. Using this switch, it is possible to exclude some files
11012 that would match the name patterns. For example,
11014 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11017 will look for Ada units in all files with the @file{.ada} extension,
11018 except those whose names end with @file{_nt.ada}.
11022 @node Examples of gnatname Usage
11023 @section Examples of @code{gnatname} Usage
11027 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11033 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11038 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11039 and be writable. In addition, the directory
11040 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11041 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11044 Note the optional spaces after @option{-c} and @option{-d}.
11049 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11050 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11053 $ gnatname /PROJECT_FILE=[HOME.ME]PROJ
11054 /EXCLUDED_PATTERN=*_nt_body.ada
11055 /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11056 /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11060 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11061 even in conjunction with one or several switches
11062 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11063 are used in this example.
11065 @c *****************************************
11066 @c * G N A T P r o j e c t M a n a g e r *
11067 @c *****************************************
11068 @node GNAT Project Manager
11069 @chapter GNAT Project Manager
11073 * Examples of Project Files::
11074 * Project File Syntax::
11075 * Objects and Sources in Project Files::
11076 * Importing Projects::
11077 * Project Extension::
11078 * Project Hierarchy Extension::
11079 * External References in Project Files::
11080 * Packages in Project Files::
11081 * Variables from Imported Projects::
11083 * Library Projects::
11084 * Stand-alone Library Projects::
11085 * Switches Related to Project Files::
11086 * Tools Supporting Project Files::
11087 * An Extended Example::
11088 * Project File Complete Syntax::
11091 @c ****************
11092 @c * Introduction *
11093 @c ****************
11096 @section Introduction
11099 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
11100 you to manage complex builds involving a number of source files, directories,
11101 and compilation options for different system configurations. In particular,
11102 project files allow you to specify:
11105 The directory or set of directories containing the source files, and/or the
11106 names of the specific source files themselves
11108 The directory in which the compiler's output
11109 (@file{ALI} files, object files, tree files) is to be placed
11111 The directory in which the executable programs is to be placed
11113 ^Switch^Switch^ settings for any of the project-enabled tools
11114 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
11115 @code{gnatfind}); you can apply these settings either globally or to individual
11118 The source files containing the main subprogram(s) to be built
11120 The source programming language(s) (currently Ada and/or C)
11122 Source file naming conventions; you can specify these either globally or for
11123 individual compilation units
11130 @node Project Files
11131 @subsection Project Files
11134 Project files are written in a syntax close to that of Ada, using familiar
11135 notions such as packages, context clauses, declarations, default values,
11136 assignments, and inheritance. Finally, project files can be built
11137 hierarchically from other project files, simplifying complex system
11138 integration and project reuse.
11140 A @dfn{project} is a specific set of values for various compilation properties.
11141 The settings for a given project are described by means of
11142 a @dfn{project file}, which is a text file written in an Ada-like syntax.
11143 Property values in project files are either strings or lists of strings.
11144 Properties that are not explicitly set receive default values. A project
11145 file may interrogate the values of @dfn{external variables} (user-defined
11146 command-line switches or environment variables), and it may specify property
11147 settings conditionally, based on the value of such variables.
11149 In simple cases, a project's source files depend only on other source files
11150 in the same project, or on the predefined libraries. (@emph{Dependence} is
11152 the Ada technical sense; as in one Ada unit @code{with}ing another.) However,
11153 the Project Manager also allows more sophisticated arrangements,
11154 where the source files in one project depend on source files in other
11158 One project can @emph{import} other projects containing needed source files.
11160 You can organize GNAT projects in a hierarchy: a @emph{child} project
11161 can extend a @emph{parent} project, inheriting the parent's source files and
11162 optionally overriding any of them with alternative versions
11166 More generally, the Project Manager lets you structure large development
11167 efforts into hierarchical subsystems, where build decisions are delegated
11168 to the subsystem level, and thus different compilation environments
11169 (^switch^switch^ settings) used for different subsystems.
11171 The Project Manager is invoked through the
11172 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
11173 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
11175 There may be zero, one or more spaces between @option{-P} and
11176 @option{@emph{projectfile}}.
11178 If you want to define (on the command line) an external variable that is
11179 queried by the project file, you must use the
11180 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
11181 The Project Manager parses and interprets the project file, and drives the
11182 invoked tool based on the project settings.
11184 The Project Manager supports a wide range of development strategies,
11185 for systems of all sizes. Here are some typical practices that are
11189 Using a common set of source files, but generating object files in different
11190 directories via different ^switch^switch^ settings
11192 Using a mostly-shared set of source files, but with different versions of
11197 The destination of an executable can be controlled inside a project file
11198 using the @option{^-o^-o^}
11200 In the absence of such a ^switch^switch^ either inside
11201 the project file or on the command line, any executable files generated by
11202 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
11203 in the project file. If no @code{Exec_Dir} is specified, they will be placed
11204 in the object directory of the project.
11206 You can use project files to achieve some of the effects of a source
11207 versioning system (for example, defining separate projects for
11208 the different sets of sources that comprise different releases) but the
11209 Project Manager is independent of any source configuration management tools
11210 that might be used by the developers.
11212 The next section introduces the main features of GNAT's project facility
11213 through a sequence of examples; subsequent sections will present the syntax
11214 and semantics in more detail. A more formal description of the project
11215 facility appears in the GNAT Reference Manual.
11217 @c *****************************
11218 @c * Examples of Project Files *
11219 @c *****************************
11221 @node Examples of Project Files
11222 @section Examples of Project Files
11224 This section illustrates some of the typical uses of project files and
11225 explains their basic structure and behavior.
11228 * Common Sources with Different ^Switches^Switches^ and Directories::
11229 * Using External Variables::
11230 * Importing Other Projects::
11231 * Extending a Project::
11234 @node Common Sources with Different ^Switches^Switches^ and Directories
11235 @subsection Common Sources with Different ^Switches^Switches^ and Directories
11239 * Specifying the Object Directory::
11240 * Specifying the Exec Directory::
11241 * Project File Packages::
11242 * Specifying ^Switch^Switch^ Settings::
11243 * Main Subprograms::
11244 * Executable File Names::
11245 * Source File Naming Conventions::
11246 * Source Language(s)::
11250 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
11251 @file{proc.adb} are in the @file{/common} directory. The file
11252 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
11253 package @code{Pack}. We want to compile these source files under two sets
11254 of ^switches^switches^:
11257 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
11258 and the @option{^-gnata^-gnata^},
11259 @option{^-gnato^-gnato^},
11260 and @option{^-gnatE^-gnatE^} switches to the
11261 compiler; the compiler's output is to appear in @file{/common/debug}
11263 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
11264 to the compiler; the compiler's output is to appear in @file{/common/release}
11268 The GNAT project files shown below, respectively @file{debug.gpr} and
11269 @file{release.gpr} in the @file{/common} directory, achieve these effects.
11282 ^/common/debug^[COMMON.DEBUG]^
11287 ^/common/release^[COMMON.RELEASE]^
11292 Here are the corresponding project files:
11294 @smallexample @c projectfile
11297 for Object_Dir use "debug";
11298 for Main use ("proc");
11301 for ^Default_Switches^Default_Switches^ ("Ada")
11303 for Executable ("proc.adb") use "proc1";
11308 package Compiler is
11309 for ^Default_Switches^Default_Switches^ ("Ada")
11310 use ("-fstack-check",
11313 "^-gnatE^-gnatE^");
11319 @smallexample @c projectfile
11322 for Object_Dir use "release";
11323 for Exec_Dir use ".";
11324 for Main use ("proc");
11326 package Compiler is
11327 for ^Default_Switches^Default_Switches^ ("Ada")
11335 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
11336 insensitive), and analogously the project defined by @file{release.gpr} is
11337 @code{"Release"}. For consistency the file should have the same name as the
11338 project, and the project file's extension should be @code{"gpr"}. These
11339 conventions are not required, but a warning is issued if they are not followed.
11341 If the current directory is @file{^/temp^[TEMP]^}, then the command
11343 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
11347 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
11348 as well as the @code{^proc1^PROC1.EXE^} executable,
11349 using the ^switch^switch^ settings defined in the project file.
11351 Likewise, the command
11353 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
11357 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
11358 and the @code{^proc^PROC.EXE^}
11359 executable in @file{^/common^[COMMON]^},
11360 using the ^switch^switch^ settings from the project file.
11363 @unnumberedsubsubsec Source Files
11366 If a project file does not explicitly specify a set of source directories or
11367 a set of source files, then by default the project's source files are the
11368 Ada source files in the project file directory. Thus @file{pack.ads},
11369 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
11371 @node Specifying the Object Directory
11372 @unnumberedsubsubsec Specifying the Object Directory
11375 Several project properties are modeled by Ada-style @emph{attributes};
11376 a property is defined by supplying the equivalent of an Ada attribute
11377 definition clause in the project file.
11378 A project's object directory is another such a property; the corresponding
11379 attribute is @code{Object_Dir}, and its value is also a string expression,
11380 specified either as absolute or relative. In the later case,
11381 it is relative to the project file directory. Thus the compiler's
11382 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
11383 (for the @code{Debug} project)
11384 and to @file{^/common/release^[COMMON.RELEASE]^}
11385 (for the @code{Release} project).
11386 If @code{Object_Dir} is not specified, then the default is the project file
11389 @node Specifying the Exec Directory
11390 @unnumberedsubsubsec Specifying the Exec Directory
11393 A project's exec directory is another property; the corresponding
11394 attribute is @code{Exec_Dir}, and its value is also a string expression,
11395 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
11396 then the default is the object directory (which may also be the project file
11397 directory if attribute @code{Object_Dir} is not specified). Thus the executable
11398 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
11399 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
11400 and in @file{^/common^[COMMON]^} for the @code{Release} project.
11402 @node Project File Packages
11403 @unnumberedsubsubsec Project File Packages
11406 A GNAT tool that is integrated with the Project Manager is modeled by a
11407 corresponding package in the project file. In the example above,
11408 The @code{Debug} project defines the packages @code{Builder}
11409 (for @command{gnatmake}) and @code{Compiler};
11410 the @code{Release} project defines only the @code{Compiler} package.
11412 The Ada-like package syntax is not to be taken literally. Although packages in
11413 project files bear a surface resemblance to packages in Ada source code, the
11414 notation is simply a way to convey a grouping of properties for a named
11415 entity. Indeed, the package names permitted in project files are restricted
11416 to a predefined set, corresponding to the project-aware tools, and the contents
11417 of packages are limited to a small set of constructs.
11418 The packages in the example above contain attribute definitions.
11420 @node Specifying ^Switch^Switch^ Settings
11421 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
11424 ^Switch^Switch^ settings for a project-aware tool can be specified through
11425 attributes in the package that corresponds to the tool.
11426 The example above illustrates one of the relevant attributes,
11427 @code{^Default_Switches^Default_Switches^}, which is defined in packages
11428 in both project files.
11429 Unlike simple attributes like @code{Source_Dirs},
11430 @code{^Default_Switches^Default_Switches^} is
11431 known as an @emph{associative array}. When you define this attribute, you must
11432 supply an ``index'' (a literal string), and the effect of the attribute
11433 definition is to set the value of the array at the specified index.
11434 For the @code{^Default_Switches^Default_Switches^} attribute,
11435 the index is a programming language (in our case, Ada),
11436 and the value specified (after @code{use}) must be a list
11437 of string expressions.
11439 The attributes permitted in project files are restricted to a predefined set.
11440 Some may appear at project level, others in packages.
11441 For any attribute that is an associative array, the index must always be a
11442 literal string, but the restrictions on this string (e.g., a file name or a
11443 language name) depend on the individual attribute.
11444 Also depending on the attribute, its specified value will need to be either a
11445 string or a string list.
11447 In the @code{Debug} project, we set the switches for two tools,
11448 @command{gnatmake} and the compiler, and thus we include the two corresponding
11449 packages; each package defines the @code{^Default_Switches^Default_Switches^}
11450 attribute with index @code{"Ada"}.
11451 Note that the package corresponding to
11452 @command{gnatmake} is named @code{Builder}. The @code{Release} project is
11453 similar, but only includes the @code{Compiler} package.
11455 In project @code{Debug} above, the ^switches^switches^ starting with
11456 @option{-gnat} that are specified in package @code{Compiler}
11457 could have been placed in package @code{Builder}, since @command{gnatmake}
11458 transmits all such ^switches^switches^ to the compiler.
11460 @node Main Subprograms
11461 @unnumberedsubsubsec Main Subprograms
11464 One of the specifiable properties of a project is a list of files that contain
11465 main subprograms. This property is captured in the @code{Main} attribute,
11466 whose value is a list of strings. If a project defines the @code{Main}
11467 attribute, it is not necessary to identify the main subprogram(s) when
11468 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
11470 @node Executable File Names
11471 @unnumberedsubsubsec Executable File Names
11474 By default, the executable file name corresponding to a main source is
11475 deduced from the main source file name. Through the attributes
11476 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
11477 it is possible to change this default.
11478 In project @code{Debug} above, the executable file name
11479 for main source @file{^proc.adb^PROC.ADB^} is
11480 @file{^proc1^PROC1.EXE^}.
11481 Attribute @code{Executable_Suffix}, when specified, may change the suffix
11482 of the executable files, when no attribute @code{Executable} applies:
11483 its value replace the platform-specific executable suffix.
11484 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
11485 specify a non default executable file name when several mains are built at once
11486 in a single @command{gnatmake} command.
11488 @node Source File Naming Conventions
11489 @unnumberedsubsubsec Source File Naming Conventions
11492 Since the project files above do not specify any source file naming
11493 conventions, the GNAT defaults are used. The mechanism for defining source
11494 file naming conventions -- a package named @code{Naming} --
11495 is described below (@pxref{Naming Schemes}).
11497 @node Source Language(s)
11498 @unnumberedsubsubsec Source Language(s)
11501 Since the project files do not specify a @code{Languages} attribute, by
11502 default the GNAT tools assume that the language of the project file is Ada.
11503 More generally, a project can comprise source files
11504 in Ada, C, and/or other languages.
11506 @node Using External Variables
11507 @subsection Using External Variables
11510 Instead of supplying different project files for debug and release, we can
11511 define a single project file that queries an external variable (set either
11512 on the command line or via an ^environment variable^logical name^) in order to
11513 conditionally define the appropriate settings. Again, assume that the
11514 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
11515 located in directory @file{^/common^[COMMON]^}. The following project file,
11516 @file{build.gpr}, queries the external variable named @code{STYLE} and
11517 defines an object directory and ^switch^switch^ settings based on whether
11518 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
11519 the default is @code{"deb"}.
11521 @smallexample @c projectfile
11524 for Main use ("proc");
11526 type Style_Type is ("deb", "rel");
11527 Style : Style_Type := external ("STYLE", "deb");
11531 for Object_Dir use "debug";
11534 for Object_Dir use "release";
11535 for Exec_Dir use ".";
11544 for ^Default_Switches^Default_Switches^ ("Ada")
11546 for Executable ("proc") use "proc1";
11555 package Compiler is
11559 for ^Default_Switches^Default_Switches^ ("Ada")
11560 use ("^-gnata^-gnata^",
11562 "^-gnatE^-gnatE^");
11565 for ^Default_Switches^Default_Switches^ ("Ada")
11576 @code{Style_Type} is an example of a @emph{string type}, which is the project
11577 file analog of an Ada enumeration type but whose components are string literals
11578 rather than identifiers. @code{Style} is declared as a variable of this type.
11580 The form @code{external("STYLE", "deb")} is known as an
11581 @emph{external reference}; its first argument is the name of an
11582 @emph{external variable}, and the second argument is a default value to be
11583 used if the external variable doesn't exist. You can define an external
11584 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
11585 or you can use ^an environment variable^a logical name^
11586 as an external variable.
11588 Each @code{case} construct is expanded by the Project Manager based on the
11589 value of @code{Style}. Thus the command
11592 gnatmake -P/common/build.gpr -XSTYLE=deb
11598 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
11603 is equivalent to the @command{gnatmake} invocation using the project file
11604 @file{debug.gpr} in the earlier example. So is the command
11606 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
11610 since @code{"deb"} is the default for @code{STYLE}.
11616 gnatmake -P/common/build.gpr -XSTYLE=rel
11622 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
11627 is equivalent to the @command{gnatmake} invocation using the project file
11628 @file{release.gpr} in the earlier example.
11630 @node Importing Other Projects
11631 @subsection Importing Other Projects
11632 @cindex @code{ADA_PROJECT_PATH}
11635 A compilation unit in a source file in one project may depend on compilation
11636 units in source files in other projects. To compile this unit under
11637 control of a project file, the
11638 dependent project must @emph{import} the projects containing the needed source
11640 This effect is obtained using syntax similar to an Ada @code{with} clause,
11641 but where @code{with}ed entities are strings that denote project files.
11643 As an example, suppose that the two projects @code{GUI_Proj} and
11644 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
11645 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
11646 and @file{^/comm^[COMM]^}, respectively.
11647 Suppose that the source files for @code{GUI_Proj} are
11648 @file{gui.ads} and @file{gui.adb}, and that the source files for
11649 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
11650 files is located in its respective project file directory. Schematically:
11669 We want to develop an application in directory @file{^/app^[APP]^} that
11670 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
11671 the corresponding project files (e.g. the ^switch^switch^ settings
11672 and object directory).
11673 Skeletal code for a main procedure might be something like the following:
11675 @smallexample @c ada
11678 procedure App_Main is
11687 Here is a project file, @file{app_proj.gpr}, that achieves the desired
11690 @smallexample @c projectfile
11692 with "/gui/gui_proj", "/comm/comm_proj";
11693 project App_Proj is
11694 for Main use ("app_main");
11700 Building an executable is achieved through the command:
11702 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
11705 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
11706 in the directory where @file{app_proj.gpr} resides.
11708 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
11709 (as illustrated above) the @code{with} clause can omit the extension.
11711 Our example specified an absolute path for each imported project file.
11712 Alternatively, the directory name of an imported object can be omitted
11716 The imported project file is in the same directory as the importing project
11719 You have defined ^an environment variable^a logical name^
11720 that includes the directory containing
11721 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
11722 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
11723 directory names separated by colons (semicolons on Windows).
11727 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
11728 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
11731 @smallexample @c projectfile
11733 with "gui_proj", "comm_proj";
11734 project App_Proj is
11735 for Main use ("app_main");
11741 Importing other projects can create ambiguities.
11742 For example, the same unit might be present in different imported projects, or
11743 it might be present in both the importing project and in an imported project.
11744 Both of these conditions are errors. Note that in the current version of
11745 the Project Manager, it is illegal to have an ambiguous unit even if the
11746 unit is never referenced by the importing project. This restriction may be
11747 relaxed in a future release.
11749 @node Extending a Project
11750 @subsection Extending a Project
11753 In large software systems it is common to have multiple
11754 implementations of a common interface; in Ada terms, multiple versions of a
11755 package body for the same specification. For example, one implementation
11756 might be safe for use in tasking programs, while another might only be used
11757 in sequential applications. This can be modeled in GNAT using the concept
11758 of @emph{project extension}. If one project (the ``child'') @emph{extends}
11759 another project (the ``parent'') then by default all source files of the
11760 parent project are inherited by the child, but the child project can
11761 override any of the parent's source files with new versions, and can also
11762 add new files. This facility is the project analog of a type extension in
11763 Object-Oriented Programming. Project hierarchies are permitted (a child
11764 project may be the parent of yet another project), and a project that
11765 inherits one project can also import other projects.
11767 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
11768 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
11769 @file{pack.adb}, and @file{proc.adb}:
11782 Note that the project file can simply be empty (that is, no attribute or
11783 package is defined):
11785 @smallexample @c projectfile
11787 project Seq_Proj is
11793 implying that its source files are all the Ada source files in the project
11796 Suppose we want to supply an alternate version of @file{pack.adb}, in
11797 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
11798 @file{pack.ads} and @file{proc.adb}. We can define a project
11799 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
11803 ^/tasking^[TASKING]^
11809 project Tasking_Proj extends "/seq/seq_proj" is
11815 The version of @file{pack.adb} used in a build depends on which project file
11818 Note that we could have obtained the desired behavior using project import
11819 rather than project inheritance; a @code{base} project would contain the
11820 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
11821 import @code{base} and add @file{pack.adb}, and likewise a tasking project
11822 would import @code{base} and add a different version of @file{pack.adb}. The
11823 choice depends on whether other sources in the original project need to be
11824 overridden. If they do, then project extension is necessary, otherwise,
11825 importing is sufficient.
11828 In a project file that extends another project file, it is possible to
11829 indicate that an inherited source is not part of the sources of the extending
11830 project. This is necessary sometimes when a package spec has been overloaded
11831 and no longer requires a body: in this case, it is necessary to indicate that
11832 the inherited body is not part of the sources of the project, otherwise there
11833 will be a compilation error when compiling the spec.
11835 For that purpose, the attribute @code{Excluded_Source_Files} is used.
11836 Its value is a string list: a list of file names.
11838 @smallexample @c @projectfile
11839 project B extends "a" is
11840 for Source_Files use ("pkg.ads");
11841 -- New spec of Pkg does not need a completion
11842 for Excluded_Source_Files use ("pkg.adb");
11846 Attribute @code{Excluded_Source_Files} may also be used to check if a source
11847 is still needed: if it is possible to build using @command{gnatmake} when such
11848 a source is put in attribute @code{Excluded_Source_Files} of a project P, then
11849 it is possible to remove the source completely from a system that includes
11852 @c ***********************
11853 @c * Project File Syntax *
11854 @c ***********************
11856 @node Project File Syntax
11857 @section Project File Syntax
11866 * Associative Array Attributes::
11867 * case Constructions::
11871 This section describes the structure of project files.
11873 A project may be an @emph{independent project}, entirely defined by a single
11874 project file. Any Ada source file in an independent project depends only
11875 on the predefined library and other Ada source files in the same project.
11878 A project may also @dfn{depend on} other projects, in either or both of
11879 the following ways:
11881 @item It may import any number of projects
11882 @item It may extend at most one other project
11886 The dependence relation is a directed acyclic graph (the subgraph reflecting
11887 the ``extends'' relation is a tree).
11889 A project's @dfn{immediate sources} are the source files directly defined by
11890 that project, either implicitly by residing in the project file's directory,
11891 or explicitly through any of the source-related attributes described below.
11892 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
11893 of @var{proj} together with the immediate sources (unless overridden) of any
11894 project on which @var{proj} depends (either directly or indirectly).
11897 @subsection Basic Syntax
11900 As seen in the earlier examples, project files have an Ada-like syntax.
11901 The minimal project file is:
11902 @smallexample @c projectfile
11911 The identifier @code{Empty} is the name of the project.
11912 This project name must be present after the reserved
11913 word @code{end} at the end of the project file, followed by a semi-colon.
11915 Any name in a project file, such as the project name or a variable name,
11916 has the same syntax as an Ada identifier.
11918 The reserved words of project files are the Ada reserved words plus
11919 @code{extends}, @code{external}, and @code{project}. Note that the only Ada
11920 reserved words currently used in project file syntax are:
11948 Comments in project files have the same syntax as in Ada, two consecutive
11949 hyphens through the end of the line.
11952 @subsection Packages
11955 A project file may contain @emph{packages}. The name of a package must be one
11956 of the identifiers from the following list. A package
11957 with a given name may only appear once in a project file. Package names are
11958 case insensitive. The following package names are legal:
11974 @code{Cross_Reference}
11978 @code{Pretty_Printer}
11988 @code{Language_Processing}
11992 In its simplest form, a package may be empty:
11994 @smallexample @c projectfile
12004 A package may contain @emph{attribute declarations},
12005 @emph{variable declarations} and @emph{case constructions}, as will be
12008 When there is ambiguity between a project name and a package name,
12009 the name always designates the project. To avoid possible confusion, it is
12010 always a good idea to avoid naming a project with one of the
12011 names allowed for packages or any name that starts with @code{gnat}.
12014 @subsection Expressions
12017 An @emph{expression} is either a @emph{string expression} or a
12018 @emph{string list expression}.
12020 A @emph{string expression} is either a @emph{simple string expression} or a
12021 @emph{compound string expression}.
12023 A @emph{simple string expression} is one of the following:
12025 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
12026 @item A string-valued variable reference (@pxref{Variables})
12027 @item A string-valued attribute reference (@pxref{Attributes})
12028 @item An external reference (@pxref{External References in Project Files})
12032 A @emph{compound string expression} is a concatenation of string expressions,
12033 using the operator @code{"&"}
12035 Path & "/" & File_Name & ".ads"
12039 A @emph{string list expression} is either a
12040 @emph{simple string list expression} or a
12041 @emph{compound string list expression}.
12043 A @emph{simple string list expression} is one of the following:
12045 @item A parenthesized list of zero or more string expressions,
12046 separated by commas
12048 File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
12051 @item A string list-valued variable reference
12052 @item A string list-valued attribute reference
12056 A @emph{compound string list expression} is the concatenation (using
12057 @code{"&"}) of a simple string list expression and an expression. Note that
12058 each term in a compound string list expression, except the first, may be
12059 either a string expression or a string list expression.
12061 @smallexample @c projectfile
12063 File_Name_List := () & File_Name; -- One string in this list
12064 Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
12066 Big_List := File_Name_List & Extended_File_Name_List;
12067 -- Concatenation of two string lists: three strings
12068 Illegal_List := "gnat.adc" & Extended_File_Name_List;
12069 -- Illegal: must start with a string list
12074 @subsection String Types
12077 A @emph{string type declaration} introduces a discrete set of string literals.
12078 If a string variable is declared to have this type, its value
12079 is restricted to the given set of literals.
12081 Here is an example of a string type declaration:
12083 @smallexample @c projectfile
12084 type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
12088 Variables of a string type are called @emph{typed variables}; all other
12089 variables are called @emph{untyped variables}. Typed variables are
12090 particularly useful in @code{case} constructions, to support conditional
12091 attribute declarations.
12092 (@pxref{case Constructions}).
12094 The string literals in the list are case sensitive and must all be different.
12095 They may include any graphic characters allowed in Ada, including spaces.
12097 A string type may only be declared at the project level, not inside a package.
12099 A string type may be referenced by its name if it has been declared in the same
12100 project file, or by an expanded name whose prefix is the name of the project
12101 in which it is declared.
12104 @subsection Variables
12107 A variable may be declared at the project file level, or within a package.
12108 Here are some examples of variable declarations:
12110 @smallexample @c projectfile
12112 This_OS : OS := external ("OS"); -- a typed variable declaration
12113 That_OS := "GNU/Linux"; -- an untyped variable declaration
12118 The syntax of a @emph{typed variable declaration} is identical to the Ada
12119 syntax for an object declaration. By contrast, the syntax of an untyped
12120 variable declaration is identical to an Ada assignment statement. In fact,
12121 variable declarations in project files have some of the characteristics of
12122 an assignment, in that successive declarations for the same variable are
12123 allowed. Untyped variable declarations do establish the expected kind of the
12124 variable (string or string list), and successive declarations for it must
12125 respect the initial kind.
12128 A string variable declaration (typed or untyped) declares a variable
12129 whose value is a string. This variable may be used as a string expression.
12130 @smallexample @c projectfile
12131 File_Name := "readme.txt";
12132 Saved_File_Name := File_Name & ".saved";
12136 A string list variable declaration declares a variable whose value is a list
12137 of strings. The list may contain any number (zero or more) of strings.
12139 @smallexample @c projectfile
12141 List_With_One_Element := ("^-gnaty^-gnaty^");
12142 List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
12143 Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
12144 "pack2.ada", "util_.ada", "util.ada");
12148 The same typed variable may not be declared more than once at project level,
12149 and it may not be declared more than once in any package; it is in effect
12152 The same untyped variable may be declared several times. Declarations are
12153 elaborated in the order in which they appear, so the new value replaces
12154 the old one, and any subsequent reference to the variable uses the new value.
12155 However, as noted above, if a variable has been declared as a string, all
12157 declarations must give it a string value. Similarly, if a variable has
12158 been declared as a string list, all subsequent declarations
12159 must give it a string list value.
12161 A @emph{variable reference} may take several forms:
12164 @item The simple variable name, for a variable in the current package (if any)
12165 or in the current project
12166 @item An expanded name, whose prefix is a context name.
12170 A @emph{context} may be one of the following:
12173 @item The name of an existing package in the current project
12174 @item The name of an imported project of the current project
12175 @item The name of an ancestor project (i.e., a project extended by the current
12176 project, either directly or indirectly)
12177 @item An expanded name whose prefix is an imported/parent project name, and
12178 whose selector is a package name in that project.
12182 A variable reference may be used in an expression.
12185 @subsection Attributes
12188 A project (and its packages) may have @emph{attributes} that define
12189 the project's properties. Some attributes have values that are strings;
12190 others have values that are string lists.
12192 There are two categories of attributes: @emph{simple attributes}
12193 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
12195 Legal project attribute names, and attribute names for each legal package are
12196 listed below. Attributes names are case-insensitive.
12198 The following attributes are defined on projects (all are simple attributes):
12200 @multitable @columnfractions .4 .3
12201 @item @emph{Attribute Name}
12203 @item @code{Source_Files}
12205 @item @code{Source_Dirs}
12207 @item @code{Source_List_File}
12209 @item @code{Object_Dir}
12211 @item @code{Exec_Dir}
12213 @item @code{Excluded_Source_Dirs}
12215 @item @code{Excluded_Source_Files}
12217 @item @code{Languages}
12221 @item @code{Library_Dir}
12223 @item @code{Library_Name}
12225 @item @code{Library_Kind}
12227 @item @code{Library_Version}
12229 @item @code{Library_Interface}
12231 @item @code{Library_Auto_Init}
12233 @item @code{Library_Options}
12235 @item @code{Library_Src_Dir}
12237 @item @code{Library_ALI_Dir}
12239 @item @code{Library_GCC}
12241 @item @code{Library_Symbol_File}
12243 @item @code{Library_Symbol_Policy}
12245 @item @code{Library_Reference_Symbol_File}
12247 @item @code{Externally_Built}
12252 The following attributes are defined for package @code{Naming}
12253 (@pxref{Naming Schemes}):
12255 @multitable @columnfractions .4 .2 .2 .2
12256 @item Attribute Name @tab Category @tab Index @tab Value
12257 @item @code{Spec_Suffix}
12258 @tab associative array
12261 @item @code{Body_Suffix}
12262 @tab associative array
12265 @item @code{Separate_Suffix}
12266 @tab simple attribute
12269 @item @code{Casing}
12270 @tab simple attribute
12273 @item @code{Dot_Replacement}
12274 @tab simple attribute
12278 @tab associative array
12282 @tab associative array
12285 @item @code{Specification_Exceptions}
12286 @tab associative array
12289 @item @code{Implementation_Exceptions}
12290 @tab associative array
12296 The following attributes are defined for packages @code{Builder},
12297 @code{Compiler}, @code{Binder},
12298 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
12299 (@pxref{^Switches^Switches^ and Project Files}).
12301 @multitable @columnfractions .4 .2 .2 .2
12302 @item Attribute Name @tab Category @tab Index @tab Value
12303 @item @code{^Default_Switches^Default_Switches^}
12304 @tab associative array
12307 @item @code{^Switches^Switches^}
12308 @tab associative array
12314 In addition, package @code{Compiler} has a single string attribute
12315 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
12316 string attribute @code{Global_Configuration_Pragmas}.
12319 Each simple attribute has a default value: the empty string (for string-valued
12320 attributes) and the empty list (for string list-valued attributes).
12322 An attribute declaration defines a new value for an attribute.
12324 Examples of simple attribute declarations:
12326 @smallexample @c projectfile
12327 for Object_Dir use "objects";
12328 for Source_Dirs use ("units", "test/drivers");
12332 The syntax of a @dfn{simple attribute declaration} is similar to that of an
12333 attribute definition clause in Ada.
12335 Attributes references may be appear in expressions.
12336 The general form for such a reference is @code{<entity>'<attribute>}:
12337 Associative array attributes are functions. Associative
12338 array attribute references must have an argument that is a string literal.
12342 @smallexample @c projectfile
12344 Naming'Dot_Replacement
12345 Imported_Project'Source_Dirs
12346 Imported_Project.Naming'Casing
12347 Builder'^Default_Switches^Default_Switches^("Ada")
12351 The prefix of an attribute may be:
12353 @item @code{project} for an attribute of the current project
12354 @item The name of an existing package of the current project
12355 @item The name of an imported project
12356 @item The name of a parent project that is extended by the current project
12357 @item An expanded name whose prefix is imported/parent project name,
12358 and whose selector is a package name
12363 @smallexample @c projectfile
12366 for Source_Dirs use project'Source_Dirs & "units";
12367 for Source_Dirs use project'Source_Dirs & "test/drivers"
12373 In the first attribute declaration, initially the attribute @code{Source_Dirs}
12374 has the default value: an empty string list. After this declaration,
12375 @code{Source_Dirs} is a string list of one element: @code{"units"}.
12376 After the second attribute declaration @code{Source_Dirs} is a string list of
12377 two elements: @code{"units"} and @code{"test/drivers"}.
12379 Note: this example is for illustration only. In practice,
12380 the project file would contain only one attribute declaration:
12382 @smallexample @c projectfile
12383 for Source_Dirs use ("units", "test/drivers");
12386 @node Associative Array Attributes
12387 @subsection Associative Array Attributes
12390 Some attributes are defined as @emph{associative arrays}. An associative
12391 array may be regarded as a function that takes a string as a parameter
12392 and delivers a string or string list value as its result.
12394 Here are some examples of single associative array attribute associations:
12396 @smallexample @c projectfile
12397 for Body ("main") use "Main.ada";
12398 for ^Switches^Switches^ ("main.ada")
12400 "^-gnatv^-gnatv^");
12401 for ^Switches^Switches^ ("main.ada")
12402 use Builder'^Switches^Switches^ ("main.ada")
12407 Like untyped variables and simple attributes, associative array attributes
12408 may be declared several times. Each declaration supplies a new value for the
12409 attribute, and replaces the previous setting.
12412 An associative array attribute may be declared as a full associative array
12413 declaration, with the value of the same attribute in an imported or extended
12416 @smallexample @c projectfile
12418 for Default_Switches use Default.Builder'Default_Switches;
12423 In this example, @code{Default} must be either a project imported by the
12424 current project, or the project that the current project extends. If the
12425 attribute is in a package (in this case, in package @code{Builder}), the same
12426 package needs to be specified.
12429 A full associative array declaration replaces any other declaration for the
12430 attribute, including other full associative array declaration. Single
12431 associative array associations may be declare after a full associative
12432 declaration, modifying the value for a single association of the attribute.
12434 @node case Constructions
12435 @subsection @code{case} Constructions
12438 A @code{case} construction is used in a project file to effect conditional
12440 Here is a typical example:
12442 @smallexample @c projectfile
12445 type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
12447 OS : OS_Type := external ("OS", "GNU/Linux");
12451 package Compiler is
12453 when "GNU/Linux" | "Unix" =>
12454 for ^Default_Switches^Default_Switches^ ("Ada")
12455 use ("^-gnath^-gnath^");
12457 for ^Default_Switches^Default_Switches^ ("Ada")
12458 use ("^-gnatP^-gnatP^");
12467 The syntax of a @code{case} construction is based on the Ada case statement
12468 (although there is no @code{null} construction for empty alternatives).
12470 The case expression must be a typed string variable.
12471 Each alternative comprises the reserved word @code{when}, either a list of
12472 literal strings separated by the @code{"|"} character or the reserved word
12473 @code{others}, and the @code{"=>"} token.
12474 Each literal string must belong to the string type that is the type of the
12476 An @code{others} alternative, if present, must occur last.
12478 After each @code{=>}, there are zero or more constructions. The only
12479 constructions allowed in a case construction are other case constructions,
12480 attribute declarations and variable declarations. String type declarations and
12481 package declarations are not allowed. Variable declarations are restricted to
12482 variables that have already been declared before the case construction.
12484 The value of the case variable is often given by an external reference
12485 (@pxref{External References in Project Files}).
12487 @c ****************************************
12488 @c * Objects and Sources in Project Files *
12489 @c ****************************************
12491 @node Objects and Sources in Project Files
12492 @section Objects and Sources in Project Files
12495 * Object Directory::
12497 * Source Directories::
12498 * Source File Names::
12502 Each project has exactly one object directory and one or more source
12503 directories. The source directories must contain at least one source file,
12504 unless the project file explicitly specifies that no source files are present
12505 (@pxref{Source File Names}).
12507 @node Object Directory
12508 @subsection Object Directory
12511 The object directory for a project is the directory containing the compiler's
12512 output (such as @file{ALI} files and object files) for the project's immediate
12515 The object directory is given by the value of the attribute @code{Object_Dir}
12516 in the project file.
12518 @smallexample @c projectfile
12519 for Object_Dir use "objects";
12523 The attribute @code{Object_Dir} has a string value, the path name of the object
12524 directory. The path name may be absolute or relative to the directory of the
12525 project file. This directory must already exist, and be readable and writable.
12527 By default, when the attribute @code{Object_Dir} is not given an explicit value
12528 or when its value is the empty string, the object directory is the same as the
12529 directory containing the project file.
12531 @node Exec Directory
12532 @subsection Exec Directory
12535 The exec directory for a project is the directory containing the executables
12536 for the project's main subprograms.
12538 The exec directory is given by the value of the attribute @code{Exec_Dir}
12539 in the project file.
12541 @smallexample @c projectfile
12542 for Exec_Dir use "executables";
12546 The attribute @code{Exec_Dir} has a string value, the path name of the exec
12547 directory. The path name may be absolute or relative to the directory of the
12548 project file. This directory must already exist, and be writable.
12550 By default, when the attribute @code{Exec_Dir} is not given an explicit value
12551 or when its value is the empty string, the exec directory is the same as the
12552 object directory of the project file.
12554 @node Source Directories
12555 @subsection Source Directories
12558 The source directories of a project are specified by the project file
12559 attribute @code{Source_Dirs}.
12561 This attribute's value is a string list. If the attribute is not given an
12562 explicit value, then there is only one source directory, the one where the
12563 project file resides.
12565 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
12568 @smallexample @c projectfile
12569 for Source_Dirs use ();
12573 indicates that the project contains no source files.
12575 Otherwise, each string in the string list designates one or more
12576 source directories.
12578 @smallexample @c projectfile
12579 for Source_Dirs use ("sources", "test/drivers");
12583 If a string in the list ends with @code{"/**"}, then the directory whose path
12584 name precedes the two asterisks, as well as all its subdirectories
12585 (recursively), are source directories.
12587 @smallexample @c projectfile
12588 for Source_Dirs use ("/system/sources/**");
12592 Here the directory @code{/system/sources} and all of its subdirectories
12593 (recursively) are source directories.
12595 To specify that the source directories are the directory of the project file
12596 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
12597 @smallexample @c projectfile
12598 for Source_Dirs use ("./**");
12602 Each of the source directories must exist and be readable.
12604 @node Source File Names
12605 @subsection Source File Names
12608 In a project that contains source files, their names may be specified by the
12609 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
12610 (a string). Source file names never include any directory information.
12612 If the attribute @code{Source_Files} is given an explicit value, then each
12613 element of the list is a source file name.
12615 @smallexample @c projectfile
12616 for Source_Files use ("main.adb");
12617 for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
12621 If the attribute @code{Source_Files} is not given an explicit value,
12622 but the attribute @code{Source_List_File} is given a string value,
12623 then the source file names are contained in the text file whose path name
12624 (absolute or relative to the directory of the project file) is the
12625 value of the attribute @code{Source_List_File}.
12627 Each line in the file that is not empty or is not a comment
12628 contains a source file name.
12630 @smallexample @c projectfile
12631 for Source_List_File use "source_list.txt";
12635 By default, if neither the attribute @code{Source_Files} nor the attribute
12636 @code{Source_List_File} is given an explicit value, then each file in the
12637 source directories that conforms to the project's naming scheme
12638 (@pxref{Naming Schemes}) is an immediate source of the project.
12640 A warning is issued if both attributes @code{Source_Files} and
12641 @code{Source_List_File} are given explicit values. In this case, the attribute
12642 @code{Source_Files} prevails.
12644 Each source file name must be the name of one existing source file
12645 in one of the source directories.
12647 A @code{Source_Files} attribute whose value is an empty list
12648 indicates that there are no source files in the project.
12650 If the order of the source directories is known statically, that is if
12651 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
12652 be several files with the same source file name. In this case, only the file
12653 in the first directory is considered as an immediate source of the project
12654 file. If the order of the source directories is not known statically, it is
12655 an error to have several files with the same source file name.
12657 Projects can be specified to have no Ada source
12658 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
12659 list, or the @code{"Ada"} may be absent from @code{Languages}:
12661 @smallexample @c projectfile
12662 for Source_Dirs use ();
12663 for Source_Files use ();
12664 for Languages use ("C", "C++");
12668 Otherwise, a project must contain at least one immediate source.
12670 Projects with no source files are useful as template packages
12671 (@pxref{Packages in Project Files}) for other projects; in particular to
12672 define a package @code{Naming} (@pxref{Naming Schemes}).
12674 @c ****************************
12675 @c * Importing Projects *
12676 @c ****************************
12678 @node Importing Projects
12679 @section Importing Projects
12680 @cindex @code{ADA_PROJECT_PATH}
12683 An immediate source of a project P may depend on source files that
12684 are neither immediate sources of P nor in the predefined library.
12685 To get this effect, P must @emph{import} the projects that contain the needed
12688 @smallexample @c projectfile
12690 with "project1", "utilities.gpr";
12691 with "/namings/apex.gpr";
12698 As can be seen in this example, the syntax for importing projects is similar
12699 to the syntax for importing compilation units in Ada. However, project files
12700 use literal strings instead of names, and the @code{with} clause identifies
12701 project files rather than packages.
12703 Each literal string is the file name or path name (absolute or relative) of a
12704 project file. If a string corresponds to a file name, with no path or a
12705 relative path, then its location is determined by the @emph{project path}. The
12706 latter can be queried using @code{gnatls -v}. It contains:
12710 In first position, the directory containing the current project file.
12712 In last position, the default project directory. This default project directory
12713 is part of the GNAT installation and is the standard place to install project
12714 files giving access to standard support libraries.
12716 @ref{Installing a library}
12720 In between, all the directories referenced in the
12721 ^environment variable^logical name^ @env{ADA_PROJECT_PATH} if it exists.
12725 If a relative pathname is used, as in
12727 @smallexample @c projectfile
12732 then the full path for the project is constructed by concatenating this
12733 relative path to those in the project path, in order, until a matching file is
12734 found. Any symbolic link will be fully resolved in the directory of the
12735 importing project file before the imported project file is examined.
12737 If the @code{with}'ed project file name does not have an extension,
12738 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
12739 then the file name as specified in the @code{with} clause (no extension) will
12740 be used. In the above example, if a file @code{project1.gpr} is found, then it
12741 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
12742 then it will be used; if neither file exists, this is an error.
12744 A warning is issued if the name of the project file does not match the
12745 name of the project; this check is case insensitive.
12747 Any source file that is an immediate source of the imported project can be
12748 used by the immediate sources of the importing project, transitively. Thus
12749 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
12750 sources of @code{A} may depend on the immediate sources of @code{C}, even if
12751 @code{A} does not import @code{C} explicitly. However, this is not recommended,
12752 because if and when @code{B} ceases to import @code{C}, some sources in
12753 @code{A} will no longer compile.
12755 A side effect of this capability is that normally cyclic dependencies are not
12756 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
12757 is not allowed to import @code{A}. However, there are cases when cyclic
12758 dependencies would be beneficial. For these cases, another form of import
12759 between projects exists, the @code{limited with}: a project @code{A} that
12760 imports a project @code{B} with a straight @code{with} may also be imported,
12761 directly or indirectly, by @code{B} on the condition that imports from @code{B}
12762 to @code{A} include at least one @code{limited with}.
12764 @smallexample @c 0projectfile
12770 limited with "../a/a.gpr";
12778 limited with "../a/a.gpr";
12784 In the above legal example, there are two project cycles:
12787 @item A -> C -> D -> A
12791 In each of these cycle there is one @code{limited with}: import of @code{A}
12792 from @code{B} and import of @code{A} from @code{D}.
12794 The difference between straight @code{with} and @code{limited with} is that
12795 the name of a project imported with a @code{limited with} cannot be used in the
12796 project that imports it. In particular, its packages cannot be renamed and
12797 its variables cannot be referred to.
12799 An exception to the above rules for @code{limited with} is that for the main
12800 project specified to @command{gnatmake} or to the @command{GNAT} driver a
12801 @code{limited with} is equivalent to a straight @code{with}. For example,
12802 in the example above, projects @code{B} and @code{D} could not be main
12803 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
12804 each have a @code{limited with} that is the only one in a cycle of importing
12807 @c *********************
12808 @c * Project Extension *
12809 @c *********************
12811 @node Project Extension
12812 @section Project Extension
12815 During development of a large system, it is sometimes necessary to use
12816 modified versions of some of the source files, without changing the original
12817 sources. This can be achieved through the @emph{project extension} facility.
12819 @smallexample @c projectfile
12820 project Modified_Utilities extends "/baseline/utilities.gpr" is ...
12824 A project extension declaration introduces an extending project
12825 (the @emph{child}) and a project being extended (the @emph{parent}).
12827 By default, a child project inherits all the sources of its parent.
12828 However, inherited sources can be overridden: a unit in a parent is hidden
12829 by a unit of the same name in the child.
12831 Inherited sources are considered to be sources (but not immediate sources)
12832 of the child project; see @ref{Project File Syntax}.
12834 An inherited source file retains any switches specified in the parent project.
12836 For example if the project @code{Utilities} contains the specification and the
12837 body of an Ada package @code{Util_IO}, then the project
12838 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
12839 The original body of @code{Util_IO} will not be considered in program builds.
12840 However, the package specification will still be found in the project
12843 A child project can have only one parent but it may import any number of other
12846 A project is not allowed to import directly or indirectly at the same time a
12847 child project and any of its ancestors.
12849 @c *******************************
12850 @c * Project Hierarchy Extension *
12851 @c *******************************
12853 @node Project Hierarchy Extension
12854 @section Project Hierarchy Extension
12857 When extending a large system spanning multiple projects, it is often
12858 inconvenient to extend every project in the hierarchy that is impacted by a
12859 small change introduced. In such cases, it is possible to create a virtual
12860 extension of entire hierarchy using @code{extends all} relationship.
12862 When the project is extended using @code{extends all} inheritance, all projects
12863 that are imported by it, both directly and indirectly, are considered virtually
12864 extended. That is, the Project Manager creates "virtual projects"
12865 that extend every project in the hierarchy; all these virtual projects have
12866 no sources of their own and have as object directory the object directory of
12867 the root of "extending all" project.
12869 It is possible to explicitly extend one or more projects in the hierarchy
12870 in order to modify the sources. These extending projects must be imported by
12871 the "extending all" project, which will replace the corresponding virtual
12872 projects with the explicit ones.
12874 When building such a project hierarchy extension, the Project Manager will
12875 ensure that both modified sources and sources in virtual extending projects
12876 that depend on them, are recompiled.
12878 By means of example, consider the following hierarchy of projects.
12882 project A, containing package P1
12884 project B importing A and containing package P2 which depends on P1
12886 project C importing B and containing package P3 which depends on P2
12890 We want to modify packages P1 and P3.
12892 This project hierarchy will need to be extended as follows:
12896 Create project A1 that extends A, placing modified P1 there:
12898 @smallexample @c 0projectfile
12899 project A1 extends "(...)/A" is
12904 Create project C1 that "extends all" C and imports A1, placing modified
12907 @smallexample @c 0projectfile
12909 project C1 extends all "(...)/C" is
12914 When you build project C1, your entire modified project space will be
12915 recompiled, including the virtual project B1 that has been impacted by the
12916 "extending all" inheritance of project C.
12918 Note that if a Library Project in the hierarchy is virtually extended,
12919 the virtual project that extends the Library Project is not a Library Project.
12921 @c ****************************************
12922 @c * External References in Project Files *
12923 @c ****************************************
12925 @node External References in Project Files
12926 @section External References in Project Files
12929 A project file may contain references to external variables; such references
12930 are called @emph{external references}.
12932 An external variable is either defined as part of the environment (an
12933 environment variable in Unix, for example) or else specified on the command
12934 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
12935 If both, then the command line value is used.
12937 The value of an external reference is obtained by means of the built-in
12938 function @code{external}, which returns a string value.
12939 This function has two forms:
12941 @item @code{external (external_variable_name)}
12942 @item @code{external (external_variable_name, default_value)}
12946 Each parameter must be a string literal. For example:
12948 @smallexample @c projectfile
12950 external ("OS", "GNU/Linux")
12954 In the form with one parameter, the function returns the value of
12955 the external variable given as parameter. If this name is not present in the
12956 environment, the function returns an empty string.
12958 In the form with two string parameters, the second argument is
12959 the value returned when the variable given as the first argument is not
12960 present in the environment. In the example above, if @code{"OS"} is not
12961 the name of ^an environment variable^a logical name^ and is not passed on
12962 the command line, then the returned value is @code{"GNU/Linux"}.
12964 An external reference may be part of a string expression or of a string
12965 list expression, and can therefore appear in a variable declaration or
12966 an attribute declaration.
12968 @smallexample @c projectfile
12970 type Mode_Type is ("Debug", "Release");
12971 Mode : Mode_Type := external ("MODE");
12978 @c *****************************
12979 @c * Packages in Project Files *
12980 @c *****************************
12982 @node Packages in Project Files
12983 @section Packages in Project Files
12986 A @emph{package} defines the settings for project-aware tools within a
12988 For each such tool one can declare a package; the names for these
12989 packages are preset (@pxref{Packages}).
12990 A package may contain variable declarations, attribute declarations, and case
12993 @smallexample @c projectfile
12996 package Builder is -- used by gnatmake
12997 for ^Default_Switches^Default_Switches^ ("Ada")
13006 The syntax of package declarations mimics that of package in Ada.
13008 Most of the packages have an attribute
13009 @code{^Default_Switches^Default_Switches^}.
13010 This attribute is an associative array, and its value is a string list.
13011 The index of the associative array is the name of a programming language (case
13012 insensitive). This attribute indicates the ^switch^switch^
13013 or ^switches^switches^ to be used
13014 with the corresponding tool.
13016 Some packages also have another attribute, @code{^Switches^Switches^},
13017 an associative array whose value is a string list.
13018 The index is the name of a source file.
13019 This attribute indicates the ^switch^switch^
13020 or ^switches^switches^ to be used by the corresponding
13021 tool when dealing with this specific file.
13023 Further information on these ^switch^switch^-related attributes is found in
13024 @ref{^Switches^Switches^ and Project Files}.
13026 A package may be declared as a @emph{renaming} of another package; e.g., from
13027 the project file for an imported project.
13029 @smallexample @c projectfile
13031 with "/global/apex.gpr";
13033 package Naming renames Apex.Naming;
13040 Packages that are renamed in other project files often come from project files
13041 that have no sources: they are just used as templates. Any modification in the
13042 template will be reflected automatically in all the project files that rename
13043 a package from the template.
13045 In addition to the tool-oriented packages, you can also declare a package
13046 named @code{Naming} to establish specialized source file naming conventions
13047 (@pxref{Naming Schemes}).
13049 @c ************************************
13050 @c * Variables from Imported Projects *
13051 @c ************************************
13053 @node Variables from Imported Projects
13054 @section Variables from Imported Projects
13057 An attribute or variable defined in an imported or parent project can
13058 be used in expressions in the importing / extending project.
13059 Such an attribute or variable is denoted by an expanded name whose prefix
13060 is either the name of the project or the expanded name of a package within
13063 @smallexample @c projectfile
13066 project Main extends "base" is
13067 Var1 := Imported.Var;
13068 Var2 := Base.Var & ".new";
13073 for ^Default_Switches^Default_Switches^ ("Ada")
13074 use Imported.Builder'Ada_^Switches^Switches^ &
13075 "^-gnatg^-gnatg^" &
13081 package Compiler is
13082 for ^Default_Switches^Default_Switches^ ("Ada")
13083 use Base.Compiler'Ada_^Switches^Switches^;
13094 The value of @code{Var1} is a copy of the variable @code{Var} defined
13095 in the project file @file{"imported.gpr"}
13097 the value of @code{Var2} is a copy of the value of variable @code{Var}
13098 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
13100 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13101 @code{Builder} is a string list that includes in its value a copy of the value
13102 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
13103 in project file @file{imported.gpr} plus two new elements:
13104 @option{"^-gnatg^-gnatg^"}
13105 and @option{"^-v^-v^"};
13107 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13108 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
13109 defined in the @code{Compiler} package in project file @file{base.gpr},
13110 the project being extended.
13113 @c ******************
13114 @c * Naming Schemes *
13115 @c ******************
13117 @node Naming Schemes
13118 @section Naming Schemes
13121 Sometimes an Ada software system is ported from a foreign compilation
13122 environment to GNAT, and the file names do not use the default GNAT
13123 conventions. Instead of changing all the file names (which for a variety
13124 of reasons might not be possible), you can define the relevant file
13125 naming scheme in the @code{Naming} package in your project file.
13128 Note that the use of pragmas described in
13129 @ref{Alternative File Naming Schemes} by mean of a configuration
13130 pragmas file is not supported when using project files. You must use
13131 the features described in this paragraph. You can however use specify
13132 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
13135 For example, the following
13136 package models the Apex file naming rules:
13138 @smallexample @c projectfile
13141 for Casing use "lowercase";
13142 for Dot_Replacement use ".";
13143 for Spec_Suffix ("Ada") use ".1.ada";
13144 for Body_Suffix ("Ada") use ".2.ada";
13151 For example, the following package models the HP Ada file naming rules:
13153 @smallexample @c projectfile
13156 for Casing use "lowercase";
13157 for Dot_Replacement use "__";
13158 for Spec_Suffix ("Ada") use "_.^ada^ada^";
13159 for Body_Suffix ("Ada") use ".^ada^ada^";
13165 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
13166 names in lower case)
13170 You can define the following attributes in package @code{Naming}:
13174 @item @code{Casing}
13175 This must be a string with one of the three values @code{"lowercase"},
13176 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
13179 If @code{Casing} is not specified, then the default is @code{"lowercase"}.
13181 @item @code{Dot_Replacement}
13182 This must be a string whose value satisfies the following conditions:
13185 @item It must not be empty
13186 @item It cannot start or end with an alphanumeric character
13187 @item It cannot be a single underscore
13188 @item It cannot start with an underscore followed by an alphanumeric
13189 @item It cannot contain a dot @code{'.'} except if the entire string
13194 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
13196 @item @code{Spec_Suffix}
13197 This is an associative array (indexed by the programming language name, case
13198 insensitive) whose value is a string that must satisfy the following
13202 @item It must not be empty
13203 @item It must include at least one dot
13206 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
13207 @code{"^.ads^.ADS^"}.
13209 @item @code{Body_Suffix}
13210 This is an associative array (indexed by the programming language name, case
13211 insensitive) whose value is a string that must satisfy the following
13215 @item It must not be empty
13216 @item It must include at least one dot
13217 @item It cannot be the same as @code{Spec_Suffix ("Ada")}
13220 If @code{Body_Suffix ("Ada")} and @code{Spec_Suffix ("Ada")} end with the
13221 same string, then a file name that ends with the longest of these two suffixes
13222 will be a body if the longest suffix is @code{Body_Suffix ("Ada")} or a spec
13223 if the longest suffix is @code{Spec_Suffix ("Ada")}.
13225 If @code{Body_Suffix ("Ada")} is not specified, then the default is
13226 @code{"^.adb^.ADB^"}.
13228 @item @code{Separate_Suffix}
13229 This must be a string whose value satisfies the same conditions as
13230 @code{Body_Suffix}. The same "longest suffix" rules apply.
13233 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
13234 value as @code{Body_Suffix ("Ada")}.
13238 You can use the associative array attribute @code{Spec} to define
13239 the source file name for an individual Ada compilation unit's spec. The array
13240 index must be a string literal that identifies the Ada unit (case insensitive).
13241 The value of this attribute must be a string that identifies the file that
13242 contains this unit's spec (case sensitive or insensitive depending on the
13245 @smallexample @c projectfile
13246 for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
13251 You can use the associative array attribute @code{Body} to
13252 define the source file name for an individual Ada compilation unit's body
13253 (possibly a subunit). The array index must be a string literal that identifies
13254 the Ada unit (case insensitive). The value of this attribute must be a string
13255 that identifies the file that contains this unit's body or subunit (case
13256 sensitive or insensitive depending on the operating system).
13258 @smallexample @c projectfile
13259 for Body ("MyPack.MyChild") use "mypack.mychild.body";
13263 @c ********************
13264 @c * Library Projects *
13265 @c ********************
13267 @node Library Projects
13268 @section Library Projects
13271 @emph{Library projects} are projects whose object code is placed in a library.
13272 (Note that this facility is not yet supported on all platforms)
13274 To create a library project, you need to define in its project file
13275 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
13276 Additionally, you may define other library-related attributes such as
13277 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
13278 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
13280 The @code{Library_Name} attribute has a string value. There is no restriction
13281 on the name of a library. It is the responsibility of the developer to
13282 choose a name that will be accepted by the platform. It is recommended to
13283 choose names that could be Ada identifiers; such names are almost guaranteed
13284 to be acceptable on all platforms.
13286 The @code{Library_Dir} attribute has a string value that designates the path
13287 (absolute or relative) of the directory where the library will reside.
13288 It must designate an existing directory, and this directory must be writable,
13289 different from the project's object directory and from any source directory
13290 in the project tree.
13292 If both @code{Library_Name} and @code{Library_Dir} are specified and
13293 are legal, then the project file defines a library project. The optional
13294 library-related attributes are checked only for such project files.
13296 The @code{Library_Kind} attribute has a string value that must be one of the
13297 following (case insensitive): @code{"static"}, @code{"dynamic"} or
13298 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
13299 attribute is not specified, the library is a static library, that is
13300 an archive of object files that can be potentially linked into a
13301 static executable. Otherwise, the library may be dynamic or
13302 relocatable, that is a library that is loaded only at the start of execution.
13304 If you need to build both a static and a dynamic library, you should use two
13305 different object directories, since in some cases some extra code needs to
13306 be generated for the latter. For such cases, it is recommended to either use
13307 two different project files, or a single one which uses external variables
13308 to indicate what kind of library should be build.
13310 The @code{Library_ALI_Dir} attribute may be specified to indicate the
13311 directory where the ALI files of the library will be copied. When it is
13312 not specified, the ALI files are copied to the directory specified in
13313 attribute @code{Library_Dir}. The directory specified by @code{Library_ALI_Dir}
13314 must be writable and different from the project's object directory and from
13315 any source directory in the project tree.
13317 The @code{Library_Version} attribute has a string value whose interpretation
13318 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
13319 used only for dynamic/relocatable libraries as the internal name of the
13320 library (the @code{"soname"}). If the library file name (built from the
13321 @code{Library_Name}) is different from the @code{Library_Version}, then the
13322 library file will be a symbolic link to the actual file whose name will be
13323 @code{Library_Version}.
13327 @smallexample @c projectfile
13333 for Library_Dir use "lib_dir";
13334 for Library_Name use "dummy";
13335 for Library_Kind use "relocatable";
13336 for Library_Version use "libdummy.so." & Version;
13343 Directory @file{lib_dir} will contain the internal library file whose name
13344 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
13345 @file{libdummy.so.1}.
13347 When @command{gnatmake} detects that a project file
13348 is a library project file, it will check all immediate sources of the project
13349 and rebuild the library if any of the sources have been recompiled.
13351 Standard project files can import library project files. In such cases,
13352 the libraries will only be rebuilt if some of its sources are recompiled
13353 because they are in the closure of some other source in an importing project.
13354 Sources of the library project files that are not in such a closure will
13355 not be checked, unless the full library is checked, because one of its sources
13356 needs to be recompiled.
13358 For instance, assume the project file @code{A} imports the library project file
13359 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
13360 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
13361 @file{l2.ads}, @file{l2.adb}.
13363 If @file{l1.adb} has been modified, then the library associated with @code{L}
13364 will be rebuilt when compiling all the immediate sources of @code{A} only
13365 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
13368 To be sure that all the sources in the library associated with @code{L} are
13369 up to date, and that all the sources of project @code{A} are also up to date,
13370 the following two commands needs to be used:
13377 When a library is built or rebuilt, an attempt is made first to delete all
13378 files in the library directory.
13379 All @file{ALI} files will also be copied from the object directory to the
13380 library directory. To build executables, @command{gnatmake} will use the
13381 library rather than the individual object files.
13384 It is also possible to create library project files for third-party libraries
13385 that are precompiled and cannot be compiled locally thanks to the
13386 @code{externally_built} attribute. (See @ref{Installing a library}).
13389 @c *******************************
13390 @c * Stand-alone Library Projects *
13391 @c *******************************
13393 @node Stand-alone Library Projects
13394 @section Stand-alone Library Projects
13397 A Stand-alone Library is a library that contains the necessary code to
13398 elaborate the Ada units that are included in the library. A Stand-alone
13399 Library is suitable to be used in an executable when the main is not
13400 in Ada. However, Stand-alone Libraries may also be used with an Ada main
13403 A Stand-alone Library Project is a Library Project where the library is
13404 a Stand-alone Library.
13406 To be a Stand-alone Library Project, in addition to the two attributes
13407 that make a project a Library Project (@code{Library_Name} and
13408 @code{Library_Dir}, see @ref{Library Projects}), the attribute
13409 @code{Library_Interface} must be defined.
13411 @smallexample @c projectfile
13413 for Library_Dir use "lib_dir";
13414 for Library_Name use "dummy";
13415 for Library_Interface use ("int1", "int1.child");
13419 Attribute @code{Library_Interface} has a non empty string list value,
13420 each string in the list designating a unit contained in an immediate source
13421 of the project file.
13423 When a Stand-alone Library is built, first the binder is invoked to build
13424 a package whose name depends on the library name
13425 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
13426 This binder-generated package includes initialization and
13427 finalization procedures whose
13428 names depend on the library name (dummyinit and dummyfinal in the example
13429 above). The object corresponding to this package is included in the library.
13431 A dynamic or relocatable Stand-alone Library is automatically initialized
13432 if automatic initialization of Stand-alone Libraries is supported on the
13433 platform and if attribute @code{Library_Auto_Init} is not specified or
13434 is specified with the value "true". A static Stand-alone Library is never
13435 automatically initialized.
13437 Single string attribute @code{Library_Auto_Init} may be specified with only
13438 two possible values: "false" or "true" (case-insensitive). Specifying
13439 "false" for attribute @code{Library_Auto_Init} will prevent automatic
13440 initialization of dynamic or relocatable libraries.
13442 When a non automatically initialized Stand-alone Library is used
13443 in an executable, its initialization procedure must be called before
13444 any service of the library is used.
13445 When the main subprogram is in Ada, it may mean that the initialization
13446 procedure has to be called during elaboration of another package.
13448 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
13449 (those that are listed in attribute @code{Library_Interface}) are copied to
13450 the Library Directory. As a consequence, only the Interface Units may be
13451 imported from Ada units outside of the library. If other units are imported,
13452 the binding phase will fail.
13454 When a Stand-Alone Library is bound, the switches that are specified in
13455 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
13456 used in the call to @command{gnatbind}.
13458 The string list attribute @code{Library_Options} may be used to specified
13459 additional switches to the call to @command{gcc} to link the library.
13461 The attribute @code{Library_Src_Dir}, may be specified for a
13462 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
13463 single string value. Its value must be the path (absolute or relative to the
13464 project directory) of an existing directory. This directory cannot be the
13465 object directory or one of the source directories, but it can be the same as
13466 the library directory. The sources of the Interface
13467 Units of the library, necessary to an Ada client of the library, will be
13468 copied to the designated directory, called Interface Copy directory.
13469 These sources includes the specs of the Interface Units, but they may also
13470 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
13471 are used, or when there is a generic units in the spec. Before the sources
13472 are copied to the Interface Copy directory, an attempt is made to delete all
13473 files in the Interface Copy directory.
13475 @c *************************************
13476 @c * Switches Related to Project Files *
13477 @c *************************************
13478 @node Switches Related to Project Files
13479 @section Switches Related to Project Files
13482 The following switches are used by GNAT tools that support project files:
13486 @item ^-P^/PROJECT_FILE=^@var{project}
13487 @cindex @option{^-P^/PROJECT_FILE^} (any tool supporting project files)
13488 Indicates the name of a project file. This project file will be parsed with
13489 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
13490 if any, and using the external references indicated
13491 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
13493 There may zero, one or more spaces between @option{-P} and @var{project}.
13497 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
13500 Since the Project Manager parses the project file only after all the switches
13501 on the command line are checked, the order of the switches
13502 @option{^-P^/PROJECT_FILE^},
13503 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
13504 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
13506 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
13507 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any tool supporting project files)
13508 Indicates that external variable @var{name} has the value @var{value}.
13509 The Project Manager will use this value for occurrences of
13510 @code{external(name)} when parsing the project file.
13514 If @var{name} or @var{value} includes a space, then @var{name=value} should be
13515 put between quotes.
13523 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
13524 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
13525 @var{name}, only the last one is used.
13528 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
13529 takes precedence over the value of the same name in the environment.
13531 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
13532 @cindex @code{^-vP^/MESSAGES_PROJECT_FILE^} (any tool supporting project files)
13533 @c Previous line uses code vs option command, to stay less than 80 chars
13534 Indicates the verbosity of the parsing of GNAT project files.
13537 @option{-vP0} means Default;
13538 @option{-vP1} means Medium;
13539 @option{-vP2} means High.
13543 There are three possible options for this qualifier: DEFAULT, MEDIUM and
13548 The default is ^Default^DEFAULT^: no output for syntactically correct
13551 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
13552 only the last one is used.
13556 @c **********************************
13557 @c * Tools Supporting Project Files *
13558 @c **********************************
13560 @node Tools Supporting Project Files
13561 @section Tools Supporting Project Files
13564 * gnatmake and Project Files::
13565 * The GNAT Driver and Project Files::
13568 @node gnatmake and Project Files
13569 @subsection gnatmake and Project Files
13572 This section covers several topics related to @command{gnatmake} and
13573 project files: defining ^switches^switches^ for @command{gnatmake}
13574 and for the tools that it invokes; specifying configuration pragmas;
13575 the use of the @code{Main} attribute; building and rebuilding library project
13579 * ^Switches^Switches^ and Project Files::
13580 * Specifying Configuration Pragmas::
13581 * Project Files and Main Subprograms::
13582 * Library Project Files::
13585 @node ^Switches^Switches^ and Project Files
13586 @subsubsection ^Switches^Switches^ and Project Files
13589 It is not currently possible to specify VMS style qualifiers in the project
13590 files; only Unix style ^switches^switches^ may be specified.
13594 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
13595 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
13596 attribute, a @code{^Switches^Switches^} attribute, or both;
13597 as their names imply, these ^switch^switch^-related
13598 attributes affect the ^switches^switches^ that are used for each of these GNAT
13600 @command{gnatmake} is invoked. As will be explained below, these
13601 component-specific ^switches^switches^ precede
13602 the ^switches^switches^ provided on the @command{gnatmake} command line.
13604 The @code{^Default_Switches^Default_Switches^} attribute is an associative
13605 array indexed by language name (case insensitive) whose value is a string list.
13608 @smallexample @c projectfile
13610 package Compiler is
13611 for ^Default_Switches^Default_Switches^ ("Ada")
13612 use ("^-gnaty^-gnaty^",
13619 The @code{^Switches^Switches^} attribute is also an associative array,
13620 indexed by a file name (which may or may not be case sensitive, depending
13621 on the operating system) whose value is a string list. For example:
13623 @smallexample @c projectfile
13626 for ^Switches^Switches^ ("main1.adb")
13628 for ^Switches^Switches^ ("main2.adb")
13635 For the @code{Builder} package, the file names must designate source files
13636 for main subprograms. For the @code{Binder} and @code{Linker} packages, the
13637 file names must designate @file{ALI} or source files for main subprograms.
13638 In each case just the file name without an explicit extension is acceptable.
13640 For each tool used in a program build (@command{gnatmake}, the compiler, the
13641 binder, and the linker), the corresponding package @dfn{contributes} a set of
13642 ^switches^switches^ for each file on which the tool is invoked, based on the
13643 ^switch^switch^-related attributes defined in the package.
13644 In particular, the ^switches^switches^
13645 that each of these packages contributes for a given file @var{f} comprise:
13649 the value of attribute @code{^Switches^Switches^ (@var{f})},
13650 if it is specified in the package for the given file,
13652 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
13653 if it is specified in the package.
13657 If neither of these attributes is defined in the package, then the package does
13658 not contribute any ^switches^switches^ for the given file.
13660 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
13661 two sets, in the following order: those contributed for the file
13662 by the @code{Builder} package;
13663 and the switches passed on the command line.
13665 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
13666 the ^switches^switches^ passed to the tool comprise three sets,
13667 in the following order:
13671 the applicable ^switches^switches^ contributed for the file
13672 by the @code{Builder} package in the project file supplied on the command line;
13675 those contributed for the file by the package (in the relevant project file --
13676 see below) corresponding to the tool; and
13679 the applicable switches passed on the command line.
13683 The term @emph{applicable ^switches^switches^} reflects the fact that
13684 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
13685 tools, depending on the individual ^switch^switch^.
13687 @command{gnatmake} may invoke the compiler on source files from different
13688 projects. The Project Manager will use the appropriate project file to
13689 determine the @code{Compiler} package for each source file being compiled.
13690 Likewise for the @code{Binder} and @code{Linker} packages.
13692 As an example, consider the following package in a project file:
13694 @smallexample @c projectfile
13697 package Compiler is
13698 for ^Default_Switches^Default_Switches^ ("Ada")
13700 for ^Switches^Switches^ ("a.adb")
13702 for ^Switches^Switches^ ("b.adb")
13704 "^-gnaty^-gnaty^");
13711 If @command{gnatmake} is invoked with this project file, and it needs to
13712 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
13713 @file{a.adb} will be compiled with the ^switch^switch^
13714 @option{^-O1^-O1^},
13715 @file{b.adb} with ^switches^switches^
13717 and @option{^-gnaty^-gnaty^},
13718 and @file{c.adb} with @option{^-g^-g^}.
13720 The following example illustrates the ordering of the ^switches^switches^
13721 contributed by different packages:
13723 @smallexample @c projectfile
13727 for ^Switches^Switches^ ("main.adb")
13735 package Compiler is
13736 for ^Switches^Switches^ ("main.adb")
13744 If you issue the command:
13747 gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
13751 then the compiler will be invoked on @file{main.adb} with the following
13752 sequence of ^switches^switches^
13755 ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
13758 with the last @option{^-O^-O^}
13759 ^switch^switch^ having precedence over the earlier ones;
13760 several other ^switches^switches^
13761 (such as @option{^-c^-c^}) are added implicitly.
13763 The ^switches^switches^
13765 and @option{^-O1^-O1^} are contributed by package
13766 @code{Builder}, @option{^-O2^-O2^} is contributed
13767 by the package @code{Compiler}
13768 and @option{^-O0^-O0^} comes from the command line.
13770 The @option{^-g^-g^}
13771 ^switch^switch^ will also be passed in the invocation of
13772 @command{Gnatlink.}
13774 A final example illustrates switch contributions from packages in different
13777 @smallexample @c projectfile
13780 for Source_Files use ("pack.ads", "pack.adb");
13781 package Compiler is
13782 for ^Default_Switches^Default_Switches^ ("Ada")
13783 use ("^-gnata^-gnata^");
13791 for Source_Files use ("foo_main.adb", "bar_main.adb");
13793 for ^Switches^Switches^ ("foo_main.adb")
13801 -- Ada source file:
13803 procedure Foo_Main is
13811 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
13815 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
13816 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
13817 @option{^-gnato^-gnato^} (passed on the command line).
13818 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
13819 are @option{^-g^-g^} from @code{Proj4.Builder},
13820 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
13821 and @option{^-gnato^-gnato^} from the command line.
13824 When using @command{gnatmake} with project files, some ^switches^switches^ or
13825 arguments may be expressed as relative paths. As the working directory where
13826 compilation occurs may change, these relative paths are converted to absolute
13827 paths. For the ^switches^switches^ found in a project file, the relative paths
13828 are relative to the project file directory, for the switches on the command
13829 line, they are relative to the directory where @command{gnatmake} is invoked.
13830 The ^switches^switches^ for which this occurs are:
13836 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
13838 ^-o^-o^, object files specified in package @code{Linker} or after
13839 -largs on the command line). The exception to this rule is the ^switch^switch^
13840 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
13842 @node Specifying Configuration Pragmas
13843 @subsubsection Specifying Configuration Pragmas
13845 When using @command{gnatmake} with project files, if there exists a file
13846 @file{gnat.adc} that contains configuration pragmas, this file will be
13849 Configuration pragmas can be defined by means of the following attributes in
13850 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
13851 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
13853 Both these attributes are single string attributes. Their values is the path
13854 name of a file containing configuration pragmas. If a path name is relative,
13855 then it is relative to the project directory of the project file where the
13856 attribute is defined.
13858 When compiling a source, the configuration pragmas used are, in order,
13859 those listed in the file designated by attribute
13860 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
13861 project file, if it is specified, and those listed in the file designated by
13862 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
13863 the project file of the source, if it exists.
13865 @node Project Files and Main Subprograms
13866 @subsubsection Project Files and Main Subprograms
13869 When using a project file, you can invoke @command{gnatmake}
13870 with one or several main subprograms, by specifying their source files on the
13874 gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
13878 Each of these needs to be a source file of the same project, except
13879 when the switch ^-u^/UNIQUE^ is used.
13882 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
13883 same project, one of the project in the tree rooted at the project specified
13884 on the command line. The package @code{Builder} of this common project, the
13885 "main project" is the one that is considered by @command{gnatmake}.
13888 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
13889 imported directly or indirectly by the project specified on the command line.
13890 Note that if such a source file is not part of the project specified on the
13891 command line, the ^switches^switches^ found in package @code{Builder} of the
13892 project specified on the command line, if any, that are transmitted
13893 to the compiler will still be used, not those found in the project file of
13897 When using a project file, you can also invoke @command{gnatmake} without
13898 explicitly specifying any main, and the effect depends on whether you have
13899 defined the @code{Main} attribute. This attribute has a string list value,
13900 where each element in the list is the name of a source file (the file
13901 extension is optional) that contains a unit that can be a main subprogram.
13903 If the @code{Main} attribute is defined in a project file as a non-empty
13904 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
13905 line, then invoking @command{gnatmake} with this project file but without any
13906 main on the command line is equivalent to invoking @command{gnatmake} with all
13907 the file names in the @code{Main} attribute on the command line.
13910 @smallexample @c projectfile
13913 for Main use ("main1", "main2", "main3");
13919 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
13921 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
13923 When the project attribute @code{Main} is not specified, or is specified
13924 as an empty string list, or when the switch @option{-u} is used on the command
13925 line, then invoking @command{gnatmake} with no main on the command line will
13926 result in all immediate sources of the project file being checked, and
13927 potentially recompiled. Depending on the presence of the switch @option{-u},
13928 sources from other project files on which the immediate sources of the main
13929 project file depend are also checked and potentially recompiled. In other
13930 words, the @option{-u} switch is applied to all of the immediate sources of the
13933 When no main is specified on the command line and attribute @code{Main} exists
13934 and includes several mains, or when several mains are specified on the
13935 command line, the default ^switches^switches^ in package @code{Builder} will
13936 be used for all mains, even if there are specific ^switches^switches^
13937 specified for one or several mains.
13939 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
13940 the specific ^switches^switches^ for each main, if they are specified.
13942 @node Library Project Files
13943 @subsubsection Library Project Files
13946 When @command{gnatmake} is invoked with a main project file that is a library
13947 project file, it is not allowed to specify one or more mains on the command
13951 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
13952 ^-l^/ACTION=LINK^ have special meanings.
13955 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
13956 to @command{gnatmake} that @command{gnatbind} should be invoked for the
13959 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13960 to @command{gnatmake} that the binder generated file should be compiled
13961 (in the case of a stand-alone library) and that the library should be built.
13965 @node The GNAT Driver and Project Files
13966 @subsection The GNAT Driver and Project Files
13969 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13970 can benefit from project files:
13971 @command{^gnatbind^gnatbind^},
13972 @command{^gnatcheck^gnatcheck^}),
13973 @command{^gnatclean^gnatclean^}),
13974 @command{^gnatelim^gnatelim^},
13975 @command{^gnatfind^gnatfind^},
13976 @command{^gnatlink^gnatlink^},
13977 @command{^gnatls^gnatls^},
13978 @command{^gnatmetric^gnatmetric^},
13979 @command{^gnatpp^gnatpp^},
13980 @command{^gnatstub^gnatstub^},
13981 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
13982 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13983 They must be invoked through the @command{gnat} driver.
13985 The @command{gnat} driver is a wrapper that accepts a number of commands and
13986 calls the corresponding tool. It was designed initially for VMS platforms (to
13987 convert VMS qualifiers to Unix-style switches), but it is now available on all
13990 On non-VMS platforms, the @command{gnat} driver accepts the following commands
13991 (case insensitive):
13995 BIND to invoke @command{^gnatbind^gnatbind^}
13997 CHOP to invoke @command{^gnatchop^gnatchop^}
13999 CLEAN to invoke @command{^gnatclean^gnatclean^}
14001 COMP or COMPILE to invoke the compiler
14003 ELIM to invoke @command{^gnatelim^gnatelim^}
14005 FIND to invoke @command{^gnatfind^gnatfind^}
14007 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
14009 LINK to invoke @command{^gnatlink^gnatlink^}
14011 LS or LIST to invoke @command{^gnatls^gnatls^}
14013 MAKE to invoke @command{^gnatmake^gnatmake^}
14015 NAME to invoke @command{^gnatname^gnatname^}
14017 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
14019 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
14021 METRIC to invoke @command{^gnatmetric^gnatmetric^}
14023 STUB to invoke @command{^gnatstub^gnatstub^}
14025 XREF to invoke @command{^gnatxref^gnatxref^}
14029 (note that the compiler is invoked using the command
14030 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
14033 On non VMS platforms, between @command{gnat} and the command, two
14034 special switches may be used:
14038 @command{-v} to display the invocation of the tool.
14040 @command{-dn} to prevent the @command{gnat} driver from removing
14041 the temporary files it has created. These temporary files are
14042 configuration files and temporary file list files.
14046 The command may be followed by switches and arguments for the invoked
14050 gnat bind -C main.ali
14056 Switches may also be put in text files, one switch per line, and the text
14057 files may be specified with their path name preceded by '@@'.
14060 gnat bind @@args.txt main.ali
14064 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
14065 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
14066 (@option{^-P^/PROJECT_FILE^},
14067 @option{^-X^/EXTERNAL_REFERENCE^} and
14068 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
14069 the switches of the invoking tool.
14072 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
14073 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
14074 the immediate sources of the specified project file.
14077 When GNAT METRIC is used with a project file, but with no source
14078 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
14079 with all the immediate sources of the specified project file and with
14080 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
14084 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
14085 a project file, no source is specified on the command line and
14086 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
14087 the underlying tool (^gnatpp^gnatpp^ or
14088 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
14089 not only for the immediate sources of the main project.
14091 (-U stands for Universal or Union of the project files of the project tree)
14095 For each of the following commands, there is optionally a corresponding
14096 package in the main project.
14100 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
14103 package @code{Check} for command CHECK (invoking
14104 @code{^gnatcheck^gnatcheck^})
14107 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
14110 package @code{Cross_Reference} for command XREF (invoking
14111 @code{^gnatxref^gnatxref^})
14114 package @code{Eliminate} for command ELIM (invoking
14115 @code{^gnatelim^gnatelim^})
14118 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
14121 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
14124 package @code{Gnatstub} for command STUB
14125 (invoking @code{^gnatstub^gnatstub^})
14128 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
14131 package @code{Metrics} for command METRIC
14132 (invoking @code{^gnatmetric^gnatmetric^})
14135 package @code{Pretty_Printer} for command PP or PRETTY
14136 (invoking @code{^gnatpp^gnatpp^})
14141 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
14142 a simple variable with a string list value. It contains ^switches^switches^
14143 for the invocation of @code{^gnatls^gnatls^}.
14145 @smallexample @c projectfile
14149 for ^Switches^Switches^
14158 All other packages have two attribute @code{^Switches^Switches^} and
14159 @code{^Default_Switches^Default_Switches^}.
14162 @code{^Switches^Switches^} is an associative array attribute, indexed by the
14163 source file name, that has a string list value: the ^switches^switches^ to be
14164 used when the tool corresponding to the package is invoked for the specific
14168 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
14169 indexed by the programming language that has a string list value.
14170 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
14171 ^switches^switches^ for the invocation of the tool corresponding
14172 to the package, except if a specific @code{^Switches^Switches^} attribute
14173 is specified for the source file.
14175 @smallexample @c projectfile
14179 for Source_Dirs use ("./**");
14182 for ^Switches^Switches^ use
14189 package Compiler is
14190 for ^Default_Switches^Default_Switches^ ("Ada")
14191 use ("^-gnatv^-gnatv^",
14192 "^-gnatwa^-gnatwa^");
14198 for ^Default_Switches^Default_Switches^ ("Ada")
14206 for ^Default_Switches^Default_Switches^ ("Ada")
14208 for ^Switches^Switches^ ("main.adb")
14217 for ^Default_Switches^Default_Switches^ ("Ada")
14224 package Cross_Reference is
14225 for ^Default_Switches^Default_Switches^ ("Ada")
14230 end Cross_Reference;
14236 With the above project file, commands such as
14239 ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
14240 ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
14241 ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
14242 ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
14243 ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
14247 will set up the environment properly and invoke the tool with the switches
14248 found in the package corresponding to the tool:
14249 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
14250 except @code{^Switches^Switches^ ("main.adb")}
14251 for @code{^gnatlink^gnatlink^}.
14252 It is also possible to invoke some of the tools,
14253 @code{^gnatcheck^gnatcheck^}),
14254 @code{^gnatmetric^gnatmetric^}),
14255 and @code{^gnatpp^gnatpp^})
14256 on a set of project units thanks to the combination of the switches
14257 @option{-P}, @option{-U} and possibly the main unit when one is interested
14258 in its closure. For instance,
14262 will compute the metrics for all the immediate units of project
14265 gnat metric -Pproj -U
14267 will compute the metrics for all the units of the closure of projects
14268 rooted at @code{proj}.
14270 gnat metric -Pproj -U main_unit
14272 will compute the metrics for the closure of units rooted at
14273 @code{main_unit}. This last possibility relies implicitly
14274 on @command{gnatbind}'s option @option{-R}.
14276 @c **********************
14277 @node An Extended Example
14278 @section An Extended Example
14281 Suppose that we have two programs, @var{prog1} and @var{prog2},
14282 whose sources are in corresponding directories. We would like
14283 to build them with a single @command{gnatmake} command, and we want to place
14284 their object files into @file{build} subdirectories of the source directories.
14285 Furthermore, we want to have to have two separate subdirectories
14286 in @file{build} -- @file{release} and @file{debug} -- which will contain
14287 the object files compiled with different set of compilation flags.
14289 In other words, we have the following structure:
14306 Here are the project files that we must place in a directory @file{main}
14307 to maintain this structure:
14311 @item We create a @code{Common} project with a package @code{Compiler} that
14312 specifies the compilation ^switches^switches^:
14317 @b{project} Common @b{is}
14319 @b{for} Source_Dirs @b{use} (); -- No source files
14323 @b{type} Build_Type @b{is} ("release", "debug");
14324 Build : Build_Type := External ("BUILD", "debug");
14327 @b{package} Compiler @b{is}
14328 @b{case} Build @b{is}
14329 @b{when} "release" =>
14330 @b{for} ^Default_Switches^Default_Switches^ ("Ada")
14331 @b{use} ("^-O2^-O2^");
14332 @b{when} "debug" =>
14333 @b{for} ^Default_Switches^Default_Switches^ ("Ada")
14334 @b{use} ("^-g^-g^");
14342 @item We create separate projects for the two programs:
14349 @b{project} Prog1 @b{is}
14351 @b{for} Source_Dirs @b{use} ("prog1");
14352 @b{for} Object_Dir @b{use} "prog1/build/" & Common.Build;
14354 @b{package} Compiler @b{renames} Common.Compiler;
14365 @b{project} Prog2 @b{is}
14367 @b{for} Source_Dirs @b{use} ("prog2");
14368 @b{for} Object_Dir @b{use} "prog2/build/" & Common.Build;
14370 @b{package} Compiler @b{renames} Common.Compiler;
14376 @item We create a wrapping project @code{Main}:
14385 @b{project} Main @b{is}
14387 @b{package} Compiler @b{renames} Common.Compiler;
14393 @item Finally we need to create a dummy procedure that @code{with}s (either
14394 explicitly or implicitly) all the sources of our two programs.
14399 Now we can build the programs using the command
14402 gnatmake ^-P^/PROJECT_FILE=^main dummy
14406 for the Debug mode, or
14410 gnatmake -Pmain -XBUILD=release
14416 GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
14421 for the Release mode.
14423 @c ********************************
14424 @c * Project File Complete Syntax *
14425 @c ********************************
14427 @node Project File Complete Syntax
14428 @section Project File Complete Syntax
14432 context_clause project_declaration
14438 @b{with} path_name @{ , path_name @} ;
14443 project_declaration ::=
14444 simple_project_declaration | project_extension
14446 simple_project_declaration ::=
14447 @b{project} <project_>simple_name @b{is}
14448 @{declarative_item@}
14449 @b{end} <project_>simple_name;
14451 project_extension ::=
14452 @b{project} <project_>simple_name @b{extends} path_name @b{is}
14453 @{declarative_item@}
14454 @b{end} <project_>simple_name;
14456 declarative_item ::=
14457 package_declaration |
14458 typed_string_declaration |
14459 other_declarative_item
14461 package_declaration ::=
14462 package_specification | package_renaming
14464 package_specification ::=
14465 @b{package} package_identifier @b{is}
14466 @{simple_declarative_item@}
14467 @b{end} package_identifier ;
14469 package_identifier ::=
14470 @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
14471 @code{Linker} | @code{Finder} | @code{Cross_Reference} |
14472 @code{^gnatls^gnatls^} | @code{IDE} | @code{Pretty_Printer}
14474 package_renaming ::==
14475 @b{package} package_identifier @b{renames}
14476 <project_>simple_name.package_identifier ;
14478 typed_string_declaration ::=
14479 @b{type} <typed_string_>_simple_name @b{is}
14480 ( string_literal @{, string_literal@} );
14482 other_declarative_item ::=
14483 attribute_declaration |
14484 typed_variable_declaration |
14485 variable_declaration |
14488 attribute_declaration ::=
14489 full_associative_array_declaration |
14490 @b{for} attribute_designator @b{use} expression ;
14492 full_associative_array_declaration ::=
14493 @b{for} <associative_array_attribute_>simple_name @b{use}
14494 <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
14496 attribute_designator ::=
14497 <simple_attribute_>simple_name |
14498 <associative_array_attribute_>simple_name ( string_literal )
14500 typed_variable_declaration ::=
14501 <typed_variable_>simple_name : <typed_string_>name := string_expression ;
14503 variable_declaration ::=
14504 <variable_>simple_name := expression;
14514 attribute_reference
14520 ( <string_>expression @{ , <string_>expression @} )
14523 @b{external} ( string_literal [, string_literal] )
14525 attribute_reference ::=
14526 attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
14528 attribute_prefix ::=
14530 <project_>simple_name | package_identifier |
14531 <project_>simple_name . package_identifier
14533 case_construction ::=
14534 @b{case} <typed_variable_>name @b{is}
14539 @b{when} discrete_choice_list =>
14540 @{case_construction | attribute_declaration@}
14542 discrete_choice_list ::=
14543 string_literal @{| string_literal@} |
14547 simple_name @{. simple_name@}
14550 identifier (same as Ada)
14554 @node The Cross-Referencing Tools gnatxref and gnatfind
14555 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
14560 The compiler generates cross-referencing information (unless
14561 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
14562 This information indicates where in the source each entity is declared and
14563 referenced. Note that entities in package Standard are not included, but
14564 entities in all other predefined units are included in the output.
14566 Before using any of these two tools, you need to compile successfully your
14567 application, so that GNAT gets a chance to generate the cross-referencing
14570 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
14571 information to provide the user with the capability to easily locate the
14572 declaration and references to an entity. These tools are quite similar,
14573 the difference being that @code{gnatfind} is intended for locating
14574 definitions and/or references to a specified entity or entities, whereas
14575 @code{gnatxref} is oriented to generating a full report of all
14578 To use these tools, you must not compile your application using the
14579 @option{-gnatx} switch on the @command{gnatmake} command line
14580 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
14581 information will not be generated.
14583 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
14584 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
14587 * gnatxref Switches::
14588 * gnatfind Switches::
14589 * Project Files for gnatxref and gnatfind::
14590 * Regular Expressions in gnatfind and gnatxref::
14591 * Examples of gnatxref Usage::
14592 * Examples of gnatfind Usage::
14595 @node gnatxref Switches
14596 @section @code{gnatxref} Switches
14599 The command invocation for @code{gnatxref} is:
14601 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
14608 @item sourcefile1, sourcefile2
14609 identifies the source files for which a report is to be generated. The
14610 ``with''ed units will be processed too. You must provide at least one file.
14612 These file names are considered to be regular expressions, so for instance
14613 specifying @file{source*.adb} is the same as giving every file in the current
14614 directory whose name starts with @file{source} and whose extension is
14617 You shouldn't specify any directory name, just base names. @command{gnatxref}
14618 and @command{gnatfind} will be able to locate these files by themselves using
14619 the source path. If you specify directories, no result is produced.
14624 The switches can be:
14628 @cindex @option{--version} @command{gnatxref}
14629 Display Copyright and version, then exit disregarding all other options.
14632 @cindex @option{--help} @command{gnatxref}
14633 If @option{--version} was not used, display usage, then exit disregarding
14636 @item ^-a^/ALL_FILES^
14637 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
14638 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
14639 the read-only files found in the library search path. Otherwise, these files
14640 will be ignored. This option can be used to protect Gnat sources or your own
14641 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
14642 much faster, and their output much smaller. Read-only here refers to access
14643 or permissions status in the file system for the current user.
14646 @cindex @option{-aIDIR} (@command{gnatxref})
14647 When looking for source files also look in directory DIR. The order in which
14648 source file search is undertaken is the same as for @command{gnatmake}.
14651 @cindex @option{-aODIR} (@command{gnatxref})
14652 When searching for library and object files, look in directory
14653 DIR. The order in which library files are searched is the same as for
14654 @command{gnatmake}.
14657 @cindex @option{-nostdinc} (@command{gnatxref})
14658 Do not look for sources in the system default directory.
14661 @cindex @option{-nostdlib} (@command{gnatxref})
14662 Do not look for library files in the system default directory.
14664 @item --RTS=@var{rts-path}
14665 @cindex @option{--RTS} (@command{gnatxref})
14666 Specifies the default location of the runtime library. Same meaning as the
14667 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14669 @item ^-d^/DERIVED_TYPES^
14670 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
14671 If this switch is set @code{gnatxref} will output the parent type
14672 reference for each matching derived types.
14674 @item ^-f^/FULL_PATHNAME^
14675 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
14676 If this switch is set, the output file names will be preceded by their
14677 directory (if the file was found in the search path). If this switch is
14678 not set, the directory will not be printed.
14680 @item ^-g^/IGNORE_LOCALS^
14681 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
14682 If this switch is set, information is output only for library-level
14683 entities, ignoring local entities. The use of this switch may accelerate
14684 @code{gnatfind} and @code{gnatxref}.
14687 @cindex @option{-IDIR} (@command{gnatxref})
14688 Equivalent to @samp{-aODIR -aIDIR}.
14691 @cindex @option{-pFILE} (@command{gnatxref})
14692 Specify a project file to use @xref{Project Files}.
14693 If you need to use the @file{.gpr}
14694 project files, you should use gnatxref through the GNAT driver
14695 (@command{gnat xref -Pproject}).
14697 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14698 project file in the current directory.
14700 If a project file is either specified or found by the tools, then the content
14701 of the source directory and object directory lines are added as if they
14702 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
14703 and @samp{^-aO^OBJECT_SEARCH^}.
14705 Output only unused symbols. This may be really useful if you give your
14706 main compilation unit on the command line, as @code{gnatxref} will then
14707 display every unused entity and 'with'ed package.
14711 Instead of producing the default output, @code{gnatxref} will generate a
14712 @file{tags} file that can be used by vi. For examples how to use this
14713 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
14714 to the standard output, thus you will have to redirect it to a file.
14720 All these switches may be in any order on the command line, and may even
14721 appear after the file names. They need not be separated by spaces, thus
14722 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14723 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14725 @node gnatfind Switches
14726 @section @code{gnatfind} Switches
14729 The command line for @code{gnatfind} is:
14732 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
14741 An entity will be output only if it matches the regular expression found
14742 in @samp{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
14744 Omitting the pattern is equivalent to specifying @samp{*}, which
14745 will match any entity. Note that if you do not provide a pattern, you
14746 have to provide both a sourcefile and a line.
14748 Entity names are given in Latin-1, with uppercase/lowercase equivalence
14749 for matching purposes. At the current time there is no support for
14750 8-bit codes other than Latin-1, or for wide characters in identifiers.
14753 @code{gnatfind} will look for references, bodies or declarations
14754 of symbols referenced in @file{sourcefile}, at line @samp{line}
14755 and column @samp{column}. See @ref{Examples of gnatfind Usage}
14756 for syntax examples.
14759 is a decimal integer identifying the line number containing
14760 the reference to the entity (or entities) to be located.
14763 is a decimal integer identifying the exact location on the
14764 line of the first character of the identifier for the
14765 entity reference. Columns are numbered from 1.
14767 @item file1 file2 ...
14768 The search will be restricted to these source files. If none are given, then
14769 the search will be done for every library file in the search path.
14770 These file must appear only after the pattern or sourcefile.
14772 These file names are considered to be regular expressions, so for instance
14773 specifying 'source*.adb' is the same as giving every file in the current
14774 directory whose name starts with 'source' and whose extension is 'adb'.
14776 The location of the spec of the entity will always be displayed, even if it
14777 isn't in one of file1, file2,... The occurrences of the entity in the
14778 separate units of the ones given on the command line will also be displayed.
14780 Note that if you specify at least one file in this part, @code{gnatfind} may
14781 sometimes not be able to find the body of the subprograms...
14786 At least one of 'sourcefile' or 'pattern' has to be present on
14789 The following switches are available:
14793 @cindex @option{--version} @command{gnatfind}
14794 Display Copyright and version, then exit disregarding all other options.
14797 @cindex @option{--help} @command{gnatfind}
14798 If @option{--version} was not used, display usage, then exit disregarding
14801 @item ^-a^/ALL_FILES^
14802 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
14803 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
14804 the read-only files found in the library search path. Otherwise, these files
14805 will be ignored. This option can be used to protect Gnat sources or your own
14806 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
14807 much faster, and their output much smaller. Read-only here refers to access
14808 or permission status in the file system for the current user.
14811 @cindex @option{-aIDIR} (@command{gnatfind})
14812 When looking for source files also look in directory DIR. The order in which
14813 source file search is undertaken is the same as for @command{gnatmake}.
14816 @cindex @option{-aODIR} (@command{gnatfind})
14817 When searching for library and object files, look in directory
14818 DIR. The order in which library files are searched is the same as for
14819 @command{gnatmake}.
14822 @cindex @option{-nostdinc} (@command{gnatfind})
14823 Do not look for sources in the system default directory.
14826 @cindex @option{-nostdlib} (@command{gnatfind})
14827 Do not look for library files in the system default directory.
14829 @item --RTS=@var{rts-path}
14830 @cindex @option{--RTS} (@command{gnatfind})
14831 Specifies the default location of the runtime library. Same meaning as the
14832 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14834 @item ^-d^/DERIVED_TYPE_INFORMATION^
14835 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
14836 If this switch is set, then @code{gnatfind} will output the parent type
14837 reference for each matching derived types.
14839 @item ^-e^/EXPRESSIONS^
14840 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
14841 By default, @code{gnatfind} accept the simple regular expression set for
14842 @samp{pattern}. If this switch is set, then the pattern will be
14843 considered as full Unix-style regular expression.
14845 @item ^-f^/FULL_PATHNAME^
14846 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
14847 If this switch is set, the output file names will be preceded by their
14848 directory (if the file was found in the search path). If this switch is
14849 not set, the directory will not be printed.
14851 @item ^-g^/IGNORE_LOCALS^
14852 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
14853 If this switch is set, information is output only for library-level
14854 entities, ignoring local entities. The use of this switch may accelerate
14855 @code{gnatfind} and @code{gnatxref}.
14858 @cindex @option{-IDIR} (@command{gnatfind})
14859 Equivalent to @samp{-aODIR -aIDIR}.
14862 @cindex @option{-pFILE} (@command{gnatfind})
14863 Specify a project file (@pxref{Project Files}) to use.
14864 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14865 project file in the current directory.
14867 If a project file is either specified or found by the tools, then the content
14868 of the source directory and object directory lines are added as if they
14869 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
14870 @samp{^-aO^/OBJECT_SEARCH^}.
14872 @item ^-r^/REFERENCES^
14873 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
14874 By default, @code{gnatfind} will output only the information about the
14875 declaration, body or type completion of the entities. If this switch is
14876 set, the @code{gnatfind} will locate every reference to the entities in
14877 the files specified on the command line (or in every file in the search
14878 path if no file is given on the command line).
14880 @item ^-s^/PRINT_LINES^
14881 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
14882 If this switch is set, then @code{gnatfind} will output the content
14883 of the Ada source file lines were the entity was found.
14885 @item ^-t^/TYPE_HIERARCHY^
14886 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
14887 If this switch is set, then @code{gnatfind} will output the type hierarchy for
14888 the specified type. It act like -d option but recursively from parent
14889 type to parent type. When this switch is set it is not possible to
14890 specify more than one file.
14895 All these switches may be in any order on the command line, and may even
14896 appear after the file names. They need not be separated by spaces, thus
14897 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14898 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14900 As stated previously, gnatfind will search in every directory in the
14901 search path. You can force it to look only in the current directory if
14902 you specify @code{*} at the end of the command line.
14904 @node Project Files for gnatxref and gnatfind
14905 @section Project Files for @command{gnatxref} and @command{gnatfind}
14908 Project files allow a programmer to specify how to compile its
14909 application, where to find sources, etc. These files are used
14911 primarily by GPS, but they can also be used
14914 @code{gnatxref} and @code{gnatfind}.
14916 A project file name must end with @file{.gpr}. If a single one is
14917 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
14918 extract the information from it. If multiple project files are found, none of
14919 them is read, and you have to use the @samp{-p} switch to specify the one
14922 The following lines can be included, even though most of them have default
14923 values which can be used in most cases.
14924 The lines can be entered in any order in the file.
14925 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
14926 each line. If you have multiple instances, only the last one is taken into
14931 [default: @code{"^./^[]^"}]
14932 specifies a directory where to look for source files. Multiple @code{src_dir}
14933 lines can be specified and they will be searched in the order they
14937 [default: @code{"^./^[]^"}]
14938 specifies a directory where to look for object and library files. Multiple
14939 @code{obj_dir} lines can be specified, and they will be searched in the order
14942 @item comp_opt=SWITCHES
14943 [default: @code{""}]
14944 creates a variable which can be referred to subsequently by using
14945 the @code{$@{comp_opt@}} notation. This is intended to store the default
14946 switches given to @command{gnatmake} and @command{gcc}.
14948 @item bind_opt=SWITCHES
14949 [default: @code{""}]
14950 creates a variable which can be referred to subsequently by using
14951 the @samp{$@{bind_opt@}} notation. This is intended to store the default
14952 switches given to @command{gnatbind}.
14954 @item link_opt=SWITCHES
14955 [default: @code{""}]
14956 creates a variable which can be referred to subsequently by using
14957 the @samp{$@{link_opt@}} notation. This is intended to store the default
14958 switches given to @command{gnatlink}.
14960 @item main=EXECUTABLE
14961 [default: @code{""}]
14962 specifies the name of the executable for the application. This variable can
14963 be referred to in the following lines by using the @samp{$@{main@}} notation.
14966 @item comp_cmd=COMMAND
14967 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
14970 @item comp_cmd=COMMAND
14971 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
14973 specifies the command used to compile a single file in the application.
14976 @item make_cmd=COMMAND
14977 [default: @code{"GNAT MAKE $@{main@}
14978 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
14979 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
14980 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
14983 @item make_cmd=COMMAND
14984 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
14985 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
14986 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
14988 specifies the command used to recompile the whole application.
14990 @item run_cmd=COMMAND
14991 [default: @code{"$@{main@}"}]
14992 specifies the command used to run the application.
14994 @item debug_cmd=COMMAND
14995 [default: @code{"gdb $@{main@}"}]
14996 specifies the command used to debug the application
15001 @command{gnatxref} and @command{gnatfind} only take into account the
15002 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
15004 @node Regular Expressions in gnatfind and gnatxref
15005 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
15008 As specified in the section about @command{gnatfind}, the pattern can be a
15009 regular expression. Actually, there are to set of regular expressions
15010 which are recognized by the program:
15013 @item globbing patterns
15014 These are the most usual regular expression. They are the same that you
15015 generally used in a Unix shell command line, or in a DOS session.
15017 Here is a more formal grammar:
15024 term ::= elmt -- matches elmt
15025 term ::= elmt elmt -- concatenation (elmt then elmt)
15026 term ::= * -- any string of 0 or more characters
15027 term ::= ? -- matches any character
15028 term ::= [char @{char@}] -- matches any character listed
15029 term ::= [char - char] -- matches any character in range
15033 @item full regular expression
15034 The second set of regular expressions is much more powerful. This is the
15035 type of regular expressions recognized by utilities such a @file{grep}.
15037 The following is the form of a regular expression, expressed in Ada
15038 reference manual style BNF is as follows
15045 regexp ::= term @{| term@} -- alternation (term or term ...)
15047 term ::= item @{item@} -- concatenation (item then item)
15049 item ::= elmt -- match elmt
15050 item ::= elmt * -- zero or more elmt's
15051 item ::= elmt + -- one or more elmt's
15052 item ::= elmt ? -- matches elmt or nothing
15055 elmt ::= nschar -- matches given character
15056 elmt ::= [nschar @{nschar@}] -- matches any character listed
15057 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
15058 elmt ::= [char - char] -- matches chars in given range
15059 elmt ::= \ char -- matches given character
15060 elmt ::= . -- matches any single character
15061 elmt ::= ( regexp ) -- parens used for grouping
15063 char ::= any character, including special characters
15064 nschar ::= any character except ()[].*+?^^^
15068 Following are a few examples:
15072 will match any of the two strings 'abcde' and 'fghi'.
15075 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
15078 will match any string which has only lowercase characters in it (and at
15079 least one character.
15084 @node Examples of gnatxref Usage
15085 @section Examples of @code{gnatxref} Usage
15087 @subsection General Usage
15090 For the following examples, we will consider the following units:
15092 @smallexample @c ada
15098 3: procedure Foo (B : in Integer);
15105 1: package body Main is
15106 2: procedure Foo (B : in Integer) is
15117 2: procedure Print (B : Integer);
15126 The first thing to do is to recompile your application (for instance, in
15127 that case just by doing a @samp{gnatmake main}, so that GNAT generates
15128 the cross-referencing information.
15129 You can then issue any of the following commands:
15131 @item gnatxref main.adb
15132 @code{gnatxref} generates cross-reference information for main.adb
15133 and every unit 'with'ed by main.adb.
15135 The output would be:
15143 Decl: main.ads 3:20
15144 Body: main.adb 2:20
15145 Ref: main.adb 4:13 5:13 6:19
15148 Ref: main.adb 6:8 7:8
15158 Decl: main.ads 3:15
15159 Body: main.adb 2:15
15162 Body: main.adb 1:14
15165 Ref: main.adb 6:12 7:12
15169 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
15170 its body is in main.adb, line 1, column 14 and is not referenced any where.
15172 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
15173 it referenced in main.adb, line 6 column 12 and line 7 column 12.
15175 @item gnatxref package1.adb package2.ads
15176 @code{gnatxref} will generates cross-reference information for
15177 package1.adb, package2.ads and any other package 'with'ed by any
15183 @subsection Using gnatxref with vi
15185 @code{gnatxref} can generate a tags file output, which can be used
15186 directly from @command{vi}. Note that the standard version of @command{vi}
15187 will not work properly with overloaded symbols. Consider using another
15188 free implementation of @command{vi}, such as @command{vim}.
15191 $ gnatxref -v gnatfind.adb > tags
15195 will generate the tags file for @code{gnatfind} itself (if the sources
15196 are in the search path!).
15198 From @command{vi}, you can then use the command @samp{:tag @i{entity}}
15199 (replacing @i{entity} by whatever you are looking for), and vi will
15200 display a new file with the corresponding declaration of entity.
15203 @node Examples of gnatfind Usage
15204 @section Examples of @code{gnatfind} Usage
15208 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
15209 Find declarations for all entities xyz referenced at least once in
15210 main.adb. The references are search in every library file in the search
15213 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
15216 The output will look like:
15218 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15219 ^directory/^[directory]^main.adb:24:10: xyz <= body
15220 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15224 that is to say, one of the entities xyz found in main.adb is declared at
15225 line 12 of main.ads (and its body is in main.adb), and another one is
15226 declared at line 45 of foo.ads
15228 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
15229 This is the same command as the previous one, instead @code{gnatfind} will
15230 display the content of the Ada source file lines.
15232 The output will look like:
15235 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15237 ^directory/^[directory]^main.adb:24:10: xyz <= body
15239 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15244 This can make it easier to find exactly the location your are looking
15247 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
15248 Find references to all entities containing an x that are
15249 referenced on line 123 of main.ads.
15250 The references will be searched only in main.ads and foo.adb.
15252 @item gnatfind main.ads:123
15253 Find declarations and bodies for all entities that are referenced on
15254 line 123 of main.ads.
15256 This is the same as @code{gnatfind "*":main.adb:123}.
15258 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
15259 Find the declaration for the entity referenced at column 45 in
15260 line 123 of file main.adb in directory mydir. Note that it
15261 is usual to omit the identifier name when the column is given,
15262 since the column position identifies a unique reference.
15264 The column has to be the beginning of the identifier, and should not
15265 point to any character in the middle of the identifier.
15269 @c *********************************
15270 @node The GNAT Pretty-Printer gnatpp
15271 @chapter The GNAT Pretty-Printer @command{gnatpp}
15273 @cindex Pretty-Printer
15276 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
15277 for source reformatting / pretty-printing.
15278 It takes an Ada source file as input and generates a reformatted
15280 You can specify various style directives via switches; e.g.,
15281 identifier case conventions, rules of indentation, and comment layout.
15283 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
15284 tree for the input source and thus requires the input to be syntactically and
15285 semantically legal.
15286 If this condition is not met, @command{gnatpp} will terminate with an
15287 error message; no output file will be generated.
15289 If the source files presented to @command{gnatpp} contain
15290 preprocessing directives, then the output file will
15291 correspond to the generated source after all
15292 preprocessing is carried out. There is no way
15293 using @command{gnatpp} to obtain pretty printed files that
15294 include the preprocessing directives.
15296 If the compilation unit
15297 contained in the input source depends semantically upon units located
15298 outside the current directory, you have to provide the source search path
15299 when invoking @command{gnatpp}, if these units are contained in files with
15300 names that do not follow the GNAT file naming rules, you have to provide
15301 the configuration file describing the corresponding naming scheme;
15302 see the description of the @command{gnatpp}
15303 switches below. Another possibility is to use a project file and to
15304 call @command{gnatpp} through the @command{gnat} driver
15306 The @command{gnatpp} command has the form
15309 $ gnatpp [@var{switches}] @var{filename}
15316 @var{switches} is an optional sequence of switches defining such properties as
15317 the formatting rules, the source search path, and the destination for the
15321 @var{filename} is the name (including the extension) of the source file to
15322 reformat; ``wildcards'' or several file names on the same gnatpp command are
15323 allowed. The file name may contain path information; it does not have to
15324 follow the GNAT file naming rules
15328 * Switches for gnatpp::
15329 * Formatting Rules::
15332 @node Switches for gnatpp
15333 @section Switches for @command{gnatpp}
15336 The following subsections describe the various switches accepted by
15337 @command{gnatpp}, organized by category.
15340 You specify a switch by supplying a name and generally also a value.
15341 In many cases the values for a switch with a given name are incompatible with
15343 (for example the switch that controls the casing of a reserved word may have
15344 exactly one value: upper case, lower case, or
15345 mixed case) and thus exactly one such switch can be in effect for an
15346 invocation of @command{gnatpp}.
15347 If more than one is supplied, the last one is used.
15348 However, some values for the same switch are mutually compatible.
15349 You may supply several such switches to @command{gnatpp}, but then
15350 each must be specified in full, with both the name and the value.
15351 Abbreviated forms (the name appearing once, followed by each value) are
15353 For example, to set
15354 the alignment of the assignment delimiter both in declarations and in
15355 assignment statements, you must write @option{-A2A3}
15356 (or @option{-A2 -A3}), but not @option{-A23}.
15360 In many cases the set of options for a given qualifier are incompatible with
15361 each other (for example the qualifier that controls the casing of a reserved
15362 word may have exactly one option, which specifies either upper case, lower
15363 case, or mixed case), and thus exactly one such option can be in effect for
15364 an invocation of @command{gnatpp}.
15365 If more than one is supplied, the last one is used.
15366 However, some qualifiers have options that are mutually compatible,
15367 and then you may then supply several such options when invoking
15371 In most cases, it is obvious whether or not the
15372 ^values for a switch with a given name^options for a given qualifier^
15373 are compatible with each other.
15374 When the semantics might not be evident, the summaries below explicitly
15375 indicate the effect.
15378 * Alignment Control::
15380 * Construct Layout Control::
15381 * General Text Layout Control::
15382 * Other Formatting Options::
15383 * Setting the Source Search Path::
15384 * Output File Control::
15385 * Other gnatpp Switches::
15388 @node Alignment Control
15389 @subsection Alignment Control
15390 @cindex Alignment control in @command{gnatpp}
15393 Programs can be easier to read if certain constructs are vertically aligned.
15394 By default all alignments are set ON.
15395 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
15396 OFF, and then use one or more of the other
15397 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
15398 to activate alignment for specific constructs.
15401 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
15405 Set all alignments to ON
15408 @item ^-A0^/ALIGN=OFF^
15409 Set all alignments to OFF
15411 @item ^-A1^/ALIGN=COLONS^
15412 Align @code{:} in declarations
15414 @item ^-A2^/ALIGN=DECLARATIONS^
15415 Align @code{:=} in initializations in declarations
15417 @item ^-A3^/ALIGN=STATEMENTS^
15418 Align @code{:=} in assignment statements
15420 @item ^-A4^/ALIGN=ARROWS^
15421 Align @code{=>} in associations
15423 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
15424 Align @code{at} keywords in the component clauses in record
15425 representation clauses
15429 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
15432 @node Casing Control
15433 @subsection Casing Control
15434 @cindex Casing control in @command{gnatpp}
15437 @command{gnatpp} allows you to specify the casing for reserved words,
15438 pragma names, attribute designators and identifiers.
15439 For identifiers you may define a
15440 general rule for name casing but also override this rule
15441 via a set of dictionary files.
15443 Three types of casing are supported: lower case, upper case, and mixed case.
15444 Lower and upper case are self-explanatory (but since some letters in
15445 Latin1 and other GNAT-supported character sets
15446 exist only in lower-case form, an upper case conversion will have no
15448 ``Mixed case'' means that the first letter, and also each letter immediately
15449 following an underscore, are converted to their uppercase forms;
15450 all the other letters are converted to their lowercase forms.
15453 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
15454 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
15455 Attribute designators are lower case
15457 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
15458 Attribute designators are upper case
15460 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
15461 Attribute designators are mixed case (this is the default)
15463 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
15464 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
15465 Keywords (technically, these are known in Ada as @emph{reserved words}) are
15466 lower case (this is the default)
15468 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
15469 Keywords are upper case
15471 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
15472 @item ^-nD^/NAME_CASING=AS_DECLARED^
15473 Name casing for defining occurrences are as they appear in the source file
15474 (this is the default)
15476 @item ^-nU^/NAME_CASING=UPPER_CASE^
15477 Names are in upper case
15479 @item ^-nL^/NAME_CASING=LOWER_CASE^
15480 Names are in lower case
15482 @item ^-nM^/NAME_CASING=MIXED_CASE^
15483 Names are in mixed case
15485 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
15486 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
15487 Pragma names are lower case
15489 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
15490 Pragma names are upper case
15492 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
15493 Pragma names are mixed case (this is the default)
15495 @item ^-D@var{file}^/DICTIONARY=@var{file}^
15496 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
15497 Use @var{file} as a @emph{dictionary file} that defines
15498 the casing for a set of specified names,
15499 thereby overriding the effect on these names by
15500 any explicit or implicit
15501 ^-n^/NAME_CASING^ switch.
15502 To supply more than one dictionary file,
15503 use ^several @option{-D} switches^a list of files as options^.
15506 @option{gnatpp} implicitly uses a @emph{default dictionary file}
15507 to define the casing for the Ada predefined names and
15508 the names declared in the GNAT libraries.
15510 @item ^-D-^/SPECIFIC_CASING^
15511 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
15512 Do not use the default dictionary file;
15513 instead, use the casing
15514 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
15519 The structure of a dictionary file, and details on the conventions
15520 used in the default dictionary file, are defined in @ref{Name Casing}.
15522 The @option{^-D-^/SPECIFIC_CASING^} and
15523 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
15526 @node Construct Layout Control
15527 @subsection Construct Layout Control
15528 @cindex Layout control in @command{gnatpp}
15531 This group of @command{gnatpp} switches controls the layout of comments and
15532 complex syntactic constructs. See @ref{Formatting Comments} for details
15536 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
15537 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
15538 All the comments remain unchanged
15540 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
15541 GNAT-style comment line indentation (this is the default).
15543 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
15544 Reference-manual comment line indentation.
15546 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
15547 GNAT-style comment beginning
15549 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
15550 Reformat comment blocks
15552 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
15553 Keep unchanged special form comments
15555 Reformat comment blocks
15557 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
15558 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
15559 GNAT-style layout (this is the default)
15561 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
15564 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
15567 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
15569 All the VT characters are removed from the comment text. All the HT characters
15570 are expanded with the sequences of space characters to get to the next tab
15573 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
15574 @item ^--no-separate-is^/NO_SEPARATE_IS^
15575 Do not place the keyword @code{is} on a separate line in a subprogram body in
15576 case if the specification occupies more then one line.
15578 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
15579 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
15580 Place the keyword @code{loop} in FOR and WHILE loop statements and the
15581 keyword @code{then} in IF statements on a separate line.
15583 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
15584 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
15585 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
15586 keyword @code{then} in IF statements on a separate line. This option is
15587 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
15589 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
15590 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
15591 Start each USE clause in a context clause from a separate line.
15593 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
15594 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
15595 Use a separate line for a loop or block statement name, but do not use an extra
15596 indentation level for the statement itself.
15602 The @option{-c1} and @option{-c2} switches are incompatible.
15603 The @option{-c3} and @option{-c4} switches are compatible with each other and
15604 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
15605 the other comment formatting switches.
15607 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
15612 For the @option{/COMMENTS_LAYOUT} qualifier:
15615 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
15617 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
15618 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
15622 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
15623 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
15626 @node General Text Layout Control
15627 @subsection General Text Layout Control
15630 These switches allow control over line length and indentation.
15633 @item ^-M@i{nnn}^/LINE_LENGTH_MAX=@i{nnn}^
15634 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
15635 Maximum line length, @i{nnn} from 32 ..256, the default value is 79
15637 @item ^-i@i{nnn}^/INDENTATION_LEVEL=@i{nnn}^
15638 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
15639 Indentation level, @i{nnn} from 1 .. 9, the default value is 3
15641 @item ^-cl@i{nnn}^/CONTINUATION_INDENT=@i{nnn}^
15642 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
15643 Indentation level for continuation lines (relative to the line being
15644 continued), @i{nnn} from 1 .. 9.
15646 value is one less then the (normal) indentation level, unless the
15647 indentation is set to 1 (in which case the default value for continuation
15648 line indentation is also 1)
15651 @node Other Formatting Options
15652 @subsection Other Formatting Options
15655 These switches control the inclusion of missing end/exit labels, and
15656 the indentation level in @b{case} statements.
15659 @item ^-e^/NO_MISSED_LABELS^
15660 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
15661 Do not insert missing end/exit labels. An end label is the name of
15662 a construct that may optionally be repeated at the end of the
15663 construct's declaration;
15664 e.g., the names of packages, subprograms, and tasks.
15665 An exit label is the name of a loop that may appear as target
15666 of an exit statement within the loop.
15667 By default, @command{gnatpp} inserts these end/exit labels when
15668 they are absent from the original source. This option suppresses such
15669 insertion, so that the formatted source reflects the original.
15671 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
15672 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
15673 Insert a Form Feed character after a pragma Page.
15675 @item ^-T@i{nnn}^/MAX_INDENT=@i{nnn}^
15676 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
15677 Do not use an additional indentation level for @b{case} alternatives
15678 and variants if there are @i{nnn} or more (the default
15680 If @i{nnn} is 0, an additional indentation level is
15681 used for @b{case} alternatives and variants regardless of their number.
15684 @node Setting the Source Search Path
15685 @subsection Setting the Source Search Path
15688 To define the search path for the input source file, @command{gnatpp}
15689 uses the same switches as the GNAT compiler, with the same effects.
15692 @item ^-I^/SEARCH=^@var{dir}
15693 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
15694 The same as the corresponding gcc switch
15696 @item ^-I-^/NOCURRENT_DIRECTORY^
15697 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
15698 The same as the corresponding gcc switch
15700 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
15701 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
15702 The same as the corresponding gcc switch
15704 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
15705 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
15706 The same as the corresponding gcc switch
15710 @node Output File Control
15711 @subsection Output File Control
15714 By default the output is sent to the file whose name is obtained by appending
15715 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
15716 (if the file with this name already exists, it is unconditionally overwritten).
15717 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
15718 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
15720 The output may be redirected by the following switches:
15723 @item ^-pipe^/STANDARD_OUTPUT^
15724 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
15725 Send the output to @code{Standard_Output}
15727 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
15728 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
15729 Write the output into @var{output_file}.
15730 If @var{output_file} already exists, @command{gnatpp} terminates without
15731 reading or processing the input file.
15733 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
15734 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
15735 Write the output into @var{output_file}, overwriting the existing file
15736 (if one is present).
15738 @item ^-r^/REPLACE^
15739 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
15740 Replace the input source file with the reformatted output, and copy the
15741 original input source into the file whose name is obtained by appending the
15742 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
15743 If a file with this name already exists, @command{gnatpp} terminates without
15744 reading or processing the input file.
15746 @item ^-rf^/OVERRIDING_REPLACE^
15747 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
15748 Like @option{^-r^/REPLACE^} except that if the file with the specified name
15749 already exists, it is overwritten.
15751 @item ^-rnb^/NO_BACKUP^
15752 @cindex @option{^-rnb^/NO_BACKUP^} (@code{gnatpp})
15753 Replace the input source file with the reformatted output without
15754 creating any backup copy of the input source.
15756 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
15757 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
15758 Specifies the format of the reformatted output file. The @var{xxx}
15759 ^string specified with the switch^option^ may be either
15761 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
15762 @item ``@option{^crlf^CRLF^}''
15763 the same as @option{^crlf^CRLF^}
15764 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
15765 @item ``@option{^lf^LF^}''
15766 the same as @option{^unix^UNIX^}
15769 @item ^-W^/RESULT_ENCODING=^@var{e}
15770 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
15771 Specify the wide character encoding method used to write the code in the
15773 @var{e} is one of the following:
15781 Upper half encoding
15783 @item ^s^SHIFT_JIS^
15793 Brackets encoding (default value)
15799 Options @option{^-pipe^/STANDARD_OUTPUT^},
15800 @option{^-o^/OUTPUT^} and
15801 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
15802 contains only one file to reformat.
15804 @option{^--eol^/END_OF_LINE^}
15806 @option{^-W^/RESULT_ENCODING^}
15807 cannot be used together
15808 with @option{^-pipe^/STANDARD_OUTPUT^} option.
15810 @node Other gnatpp Switches
15811 @subsection Other @code{gnatpp} Switches
15814 The additional @command{gnatpp} switches are defined in this subsection.
15817 @item ^-files @var{filename}^/FILES=@var{output_file}^
15818 @cindex @option{^-files^/FILES^} (@code{gnatpp})
15819 Take the argument source files from the specified file. This file should be an
15820 ordinary textual file containing file names separated by spaces or
15821 line breaks. You can use this switch more then once in the same call to
15822 @command{gnatpp}. You also can combine this switch with explicit list of
15825 @item ^-v^/VERBOSE^
15826 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
15828 @command{gnatpp} generates version information and then
15829 a trace of the actions it takes to produce or obtain the ASIS tree.
15831 @item ^-w^/WARNINGS^
15832 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
15834 @command{gnatpp} generates a warning whenever it cannot provide
15835 a required layout in the result source.
15838 @node Formatting Rules
15839 @section Formatting Rules
15842 The following subsections show how @command{gnatpp} treats ``white space'',
15843 comments, program layout, and name casing.
15844 They provide the detailed descriptions of the switches shown above.
15847 * White Space and Empty Lines::
15848 * Formatting Comments::
15849 * Construct Layout::
15853 @node White Space and Empty Lines
15854 @subsection White Space and Empty Lines
15857 @command{gnatpp} does not have an option to control space characters.
15858 It will add or remove spaces according to the style illustrated by the
15859 examples in the @cite{Ada Reference Manual}.
15861 The only format effectors
15862 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
15863 that will appear in the output file are platform-specific line breaks,
15864 and also format effectors within (but not at the end of) comments.
15865 In particular, each horizontal tab character that is not inside
15866 a comment will be treated as a space and thus will appear in the
15867 output file as zero or more spaces depending on
15868 the reformatting of the line in which it appears.
15869 The only exception is a Form Feed character, which is inserted after a
15870 pragma @code{Page} when @option{-ff} is set.
15872 The output file will contain no lines with trailing ``white space'' (spaces,
15875 Empty lines in the original source are preserved
15876 only if they separate declarations or statements.
15877 In such contexts, a
15878 sequence of two or more empty lines is replaced by exactly one empty line.
15879 Note that a blank line will be removed if it separates two ``comment blocks''
15880 (a comment block is a sequence of whole-line comments).
15881 In order to preserve a visual separation between comment blocks, use an
15882 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
15883 Likewise, if for some reason you wish to have a sequence of empty lines,
15884 use a sequence of empty comments instead.
15886 @node Formatting Comments
15887 @subsection Formatting Comments
15890 Comments in Ada code are of two kinds:
15893 a @emph{whole-line comment}, which appears by itself (possibly preceded by
15894 ``white space'') on a line
15897 an @emph{end-of-line comment}, which follows some other Ada lexical element
15902 The indentation of a whole-line comment is that of either
15903 the preceding or following line in
15904 the formatted source, depending on switch settings as will be described below.
15906 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
15907 between the end of the preceding Ada lexical element and the beginning
15908 of the comment as appear in the original source,
15909 unless either the comment has to be split to
15910 satisfy the line length limitation, or else the next line contains a
15911 whole line comment that is considered a continuation of this end-of-line
15912 comment (because it starts at the same position).
15914 cases, the start of the end-of-line comment is moved right to the nearest
15915 multiple of the indentation level.
15916 This may result in a ``line overflow'' (the right-shifted comment extending
15917 beyond the maximum line length), in which case the comment is split as
15920 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
15921 (GNAT-style comment line indentation)
15922 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
15923 (reference-manual comment line indentation).
15924 With reference-manual style, a whole-line comment is indented as if it
15925 were a declaration or statement at the same place
15926 (i.e., according to the indentation of the preceding line(s)).
15927 With GNAT style, a whole-line comment that is immediately followed by an
15928 @b{if} or @b{case} statement alternative, a record variant, or the reserved
15929 word @b{begin}, is indented based on the construct that follows it.
15932 @smallexample @c ada
15944 Reference-manual indentation produces:
15946 @smallexample @c ada
15958 while GNAT-style indentation produces:
15960 @smallexample @c ada
15972 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
15973 (GNAT style comment beginning) has the following
15978 For each whole-line comment that does not end with two hyphens,
15979 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
15980 to ensure that there are at least two spaces between these hyphens and the
15981 first non-blank character of the comment.
15985 For an end-of-line comment, if in the original source the next line is a
15986 whole-line comment that starts at the same position
15987 as the end-of-line comment,
15988 then the whole-line comment (and all whole-line comments
15989 that follow it and that start at the same position)
15990 will start at this position in the output file.
15993 That is, if in the original source we have:
15995 @smallexample @c ada
15998 A := B + C; -- B must be in the range Low1..High1
15999 -- C must be in the range Low2..High2
16000 --B+C will be in the range Low1+Low2..High1+High2
16006 Then in the formatted source we get
16008 @smallexample @c ada
16011 A := B + C; -- B must be in the range Low1..High1
16012 -- C must be in the range Low2..High2
16013 -- B+C will be in the range Low1+Low2..High1+High2
16019 A comment that exceeds the line length limit will be split.
16021 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
16022 the line belongs to a reformattable block, splitting the line generates a
16023 @command{gnatpp} warning.
16024 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
16025 comments may be reformatted in typical
16026 word processor style (that is, moving words between lines and putting as
16027 many words in a line as possible).
16030 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
16031 that has a special format (that is, a character that is neither a letter nor digit
16032 not white space nor line break immediately following the leading @code{--} of
16033 the comment) should be without any change moved from the argument source
16034 into reformatted source. This switch allows to preserve comments that are used
16035 as a special marks in the code (e.g. SPARK annotation).
16037 @node Construct Layout
16038 @subsection Construct Layout
16041 In several cases the suggested layout in the Ada Reference Manual includes
16042 an extra level of indentation that many programmers prefer to avoid. The
16043 affected cases include:
16047 @item Record type declaration (RM 3.8)
16049 @item Record representation clause (RM 13.5.1)
16051 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
16053 @item Block statement in case if a block has a statement identifier (RM 5.6)
16057 In compact mode (when GNAT style layout or compact layout is set),
16058 the pretty printer uses one level of indentation instead
16059 of two. This is achieved in the record definition and record representation
16060 clause cases by putting the @code{record} keyword on the same line as the
16061 start of the declaration or representation clause, and in the block and loop
16062 case by putting the block or loop header on the same line as the statement
16066 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
16067 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
16068 layout on the one hand, and uncompact layout
16069 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
16070 can be illustrated by the following examples:
16074 @multitable @columnfractions .5 .5
16075 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
16078 @smallexample @c ada
16085 @smallexample @c ada
16094 @smallexample @c ada
16096 a at 0 range 0 .. 31;
16097 b at 4 range 0 .. 31;
16101 @smallexample @c ada
16104 a at 0 range 0 .. 31;
16105 b at 4 range 0 .. 31;
16110 @smallexample @c ada
16118 @smallexample @c ada
16128 @smallexample @c ada
16129 Clear : for J in 1 .. 10 loop
16134 @smallexample @c ada
16136 for J in 1 .. 10 loop
16147 GNAT style, compact layout Uncompact layout
16149 type q is record type q is
16150 a : integer; record
16151 b : integer; a : integer;
16152 end record; b : integer;
16155 for q use record for q use
16156 a at 0 range 0 .. 31; record
16157 b at 4 range 0 .. 31; a at 0 range 0 .. 31;
16158 end record; b at 4 range 0 .. 31;
16161 Block : declare Block :
16162 A : Integer := 3; declare
16163 begin A : Integer := 3;
16165 end Block; Proc (A, A);
16168 Clear : for J in 1 .. 10 loop Clear :
16169 A (J) := 0; for J in 1 .. 10 loop
16170 end loop Clear; A (J) := 0;
16177 A further difference between GNAT style layout and compact layout is that
16178 GNAT style layout inserts empty lines as separation for
16179 compound statements, return statements and bodies.
16181 Note that the layout specified by
16182 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
16183 for named block and loop statements overrides the layout defined by these
16184 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
16185 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
16186 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
16189 @subsection Name Casing
16192 @command{gnatpp} always converts the usage occurrence of a (simple) name to
16193 the same casing as the corresponding defining identifier.
16195 You control the casing for defining occurrences via the
16196 @option{^-n^/NAME_CASING^} switch.
16198 With @option{-nD} (``as declared'', which is the default),
16201 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
16203 defining occurrences appear exactly as in the source file
16204 where they are declared.
16205 The other ^values for this switch^options for this qualifier^ ---
16206 @option{^-nU^UPPER_CASE^},
16207 @option{^-nL^LOWER_CASE^},
16208 @option{^-nM^MIXED_CASE^} ---
16210 ^upper, lower, or mixed case, respectively^the corresponding casing^.
16211 If @command{gnatpp} changes the casing of a defining
16212 occurrence, it analogously changes the casing of all the
16213 usage occurrences of this name.
16215 If the defining occurrence of a name is not in the source compilation unit
16216 currently being processed by @command{gnatpp}, the casing of each reference to
16217 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
16218 switch (subject to the dictionary file mechanism described below).
16219 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
16221 casing for the defining occurrence of the name.
16223 Some names may need to be spelled with casing conventions that are not
16224 covered by the upper-, lower-, and mixed-case transformations.
16225 You can arrange correct casing by placing such names in a
16226 @emph{dictionary file},
16227 and then supplying a @option{^-D^/DICTIONARY^} switch.
16228 The casing of names from dictionary files overrides
16229 any @option{^-n^/NAME_CASING^} switch.
16231 To handle the casing of Ada predefined names and the names from GNAT libraries,
16232 @command{gnatpp} assumes a default dictionary file.
16233 The name of each predefined entity is spelled with the same casing as is used
16234 for the entity in the @cite{Ada Reference Manual}.
16235 The name of each entity in the GNAT libraries is spelled with the same casing
16236 as is used in the declaration of that entity.
16238 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
16239 default dictionary file.
16240 Instead, the casing for predefined and GNAT-defined names will be established
16241 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
16242 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
16243 will appear as just shown,
16244 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
16245 To ensure that even such names are rendered in uppercase,
16246 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
16247 (or else, less conveniently, place these names in upper case in a dictionary
16250 A dictionary file is
16251 a plain text file; each line in this file can be either a blank line
16252 (containing only space characters and ASCII.HT characters), an Ada comment
16253 line, or the specification of exactly one @emph{casing schema}.
16255 A casing schema is a string that has the following syntax:
16259 @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
16261 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
16266 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
16267 @var{identifier} lexical element and the @var{letter_or_digit} category.)
16269 The casing schema string can be followed by white space and/or an Ada-style
16270 comment; any amount of white space is allowed before the string.
16272 If a dictionary file is passed as
16274 the value of a @option{-D@var{file}} switch
16277 an option to the @option{/DICTIONARY} qualifier
16280 simple name and every identifier, @command{gnatpp} checks if the dictionary
16281 defines the casing for the name or for some of its parts (the term ``subword''
16282 is used below to denote the part of a name which is delimited by ``_'' or by
16283 the beginning or end of the word and which does not contain any ``_'' inside):
16287 if the whole name is in the dictionary, @command{gnatpp} uses for this name
16288 the casing defined by the dictionary; no subwords are checked for this word
16291 for every subword @command{gnatpp} checks if the dictionary contains the
16292 corresponding string of the form @code{*@var{simple_identifier}*},
16293 and if it does, the casing of this @var{simple_identifier} is used
16297 if the whole name does not contain any ``_'' inside, and if for this name
16298 the dictionary contains two entries - one of the form @var{identifier},
16299 and another - of the form *@var{simple_identifier}*, then the first one
16300 is applied to define the casing of this name
16303 if more than one dictionary file is passed as @command{gnatpp} switches, each
16304 dictionary adds new casing exceptions and overrides all the existing casing
16305 exceptions set by the previous dictionaries
16308 when @command{gnatpp} checks if the word or subword is in the dictionary,
16309 this check is not case sensitive
16313 For example, suppose we have the following source to reformat:
16315 @smallexample @c ada
16318 name1 : integer := 1;
16319 name4_name3_name2 : integer := 2;
16320 name2_name3_name4 : Boolean;
16323 name2_name3_name4 := name4_name3_name2 > name1;
16329 And suppose we have two dictionaries:
16346 If @command{gnatpp} is called with the following switches:
16350 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
16353 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
16358 then we will get the following name casing in the @command{gnatpp} output:
16360 @smallexample @c ada
16363 NAME1 : Integer := 1;
16364 Name4_NAME3_Name2 : Integer := 2;
16365 Name2_NAME3_Name4 : Boolean;
16368 Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
16373 @c *********************************
16374 @node The GNAT Metric Tool gnatmetric
16375 @chapter The GNAT Metric Tool @command{gnatmetric}
16377 @cindex Metric tool
16380 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
16381 for computing various program metrics.
16382 It takes an Ada source file as input and generates a file containing the
16383 metrics data as output. Various switches control which
16384 metrics are computed and output.
16386 @command{gnatmetric} generates and uses the ASIS
16387 tree for the input source and thus requires the input to be syntactically and
16388 semantically legal.
16389 If this condition is not met, @command{gnatmetric} will generate
16390 an error message; no metric information for this file will be
16391 computed and reported.
16393 If the compilation unit contained in the input source depends semantically
16394 upon units in files located outside the current directory, you have to provide
16395 the source search path when invoking @command{gnatmetric}.
16396 If it depends semantically upon units that are contained
16397 in files with names that do not follow the GNAT file naming rules, you have to
16398 provide the configuration file describing the corresponding naming scheme (see
16399 the description of the @command{gnatmetric} switches below.)
16400 Alternatively, you may use a project file and invoke @command{gnatmetric}
16401 through the @command{gnat} driver.
16403 The @command{gnatmetric} command has the form
16406 $ gnatmetric [@i{switches}] @{@i{filename}@} [@i{-cargs gcc_switches}]
16413 @i{switches} specify the metrics to compute and define the destination for
16417 Each @i{filename} is the name (including the extension) of a source
16418 file to process. ``Wildcards'' are allowed, and
16419 the file name may contain path information.
16420 If no @i{filename} is supplied, then the @i{switches} list must contain
16422 @option{-files} switch (@pxref{Other gnatmetric Switches}).
16423 Including both a @option{-files} switch and one or more
16424 @i{filename} arguments is permitted.
16427 @i{-cargs gcc_switches} is a list of switches for
16428 @command{gcc}. They will be passed on to all compiler invocations made by
16429 @command{gnatmetric} to generate the ASIS trees. Here you can provide
16430 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
16431 and use the @option{-gnatec} switch to set the configuration file.
16435 * Switches for gnatmetric::
16438 @node Switches for gnatmetric
16439 @section Switches for @command{gnatmetric}
16442 The following subsections describe the various switches accepted by
16443 @command{gnatmetric}, organized by category.
16446 * Output Files Control::
16447 * Disable Metrics For Local Units::
16448 * Specifying a set of metrics to compute::
16449 * Other gnatmetric Switches::
16450 * Generate project-wide metrics::
16453 @node Output Files Control
16454 @subsection Output File Control
16455 @cindex Output file control in @command{gnatmetric}
16458 @command{gnatmetric} has two output formats. It can generate a
16459 textual (human-readable) form, and also XML. By default only textual
16460 output is generated.
16462 When generating the output in textual form, @command{gnatmetric} creates
16463 for each Ada source file a corresponding text file
16464 containing the computed metrics, except for the case when the set of metrics
16465 specified by gnatmetric parameters consists only of metrics that are computed
16466 for the whole set of analyzed sources, but not for each Ada source.
16467 By default, this file is placed in the same directory as where the source
16468 file is located, and its name is obtained
16469 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
16472 All the output information generated in XML format is placed in a single
16473 file. By default this file is placed in the current directory and has the
16474 name ^@file{metrix.xml}^@file{METRIX$XML}^.
16476 Some of the computed metrics are summed over the units passed to
16477 @command{gnatmetric}; for example, the total number of lines of code.
16478 By default this information is sent to @file{stdout}, but a file
16479 can be specified with the @option{-og} switch.
16481 The following switches control the @command{gnatmetric} output:
16484 @cindex @option{^-x^/XML^} (@command{gnatmetric})
16486 Generate the XML output
16488 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
16489 @item ^-nt^/NO_TEXT^
16490 Do not generate the output in text form (implies @option{^-x^/XML^})
16492 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
16493 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
16494 Put textual files with detailed metrics into @var{output_dir}
16496 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
16497 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
16498 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
16499 in the name of the output file.
16501 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
16502 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
16503 Put global metrics into @var{file_name}
16505 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
16506 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
16507 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
16509 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
16510 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
16511 Use ``short'' source file names in the output. (The @command{gnatmetric}
16512 output includes the name(s) of the Ada source file(s) from which the metrics
16513 are computed. By default each name includes the absolute path. The
16514 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
16515 to exclude all directory information from the file names that are output.)
16519 @node Disable Metrics For Local Units
16520 @subsection Disable Metrics For Local Units
16521 @cindex Disable Metrics For Local Units in @command{gnatmetric}
16524 @command{gnatmetric} relies on the GNAT compilation model @minus{}
16526 unit per one source file. It computes line metrics for the whole source
16527 file, and it also computes syntax
16528 and complexity metrics for the file's outermost unit.
16530 By default, @command{gnatmetric} will also compute all metrics for certain
16531 kinds of locally declared program units:
16535 subprogram (and generic subprogram) bodies;
16538 package (and generic package) specifications and bodies;
16541 task object and type specifications and bodies;
16544 protected object and type specifications and bodies.
16548 These kinds of entities will be referred to as
16549 @emph{eligible local program units}, or simply @emph{eligible local units},
16550 @cindex Eligible local unit (for @command{gnatmetric})
16551 in the discussion below.
16553 Note that a subprogram declaration, generic instantiation,
16554 or renaming declaration only receives metrics
16555 computation when it appear as the outermost entity
16558 Suppression of metrics computation for eligible local units can be
16559 obtained via the following switch:
16562 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
16563 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
16564 Do not compute detailed metrics for eligible local program units
16568 @node Specifying a set of metrics to compute
16569 @subsection Specifying a set of metrics to compute
16572 By default all the metrics are computed and reported. The switches
16573 described in this subsection allow you to control, on an individual
16574 basis, whether metrics are computed and
16575 reported. If at least one positive metric
16576 switch is specified (that is, a switch that defines that a given
16577 metric or set of metrics is to be computed), then only
16578 explicitly specified metrics are reported.
16581 * Line Metrics Control::
16582 * Syntax Metrics Control::
16583 * Complexity Metrics Control::
16586 @node Line Metrics Control
16587 @subsubsection Line Metrics Control
16588 @cindex Line metrics control in @command{gnatmetric}
16591 For any (legal) source file, and for each of its
16592 eligible local program units, @command{gnatmetric} computes the following
16597 the total number of lines;
16600 the total number of code lines (i.e., non-blank lines that are not comments)
16603 the number of comment lines
16606 the number of code lines containing end-of-line comments;
16609 the comment percentage: the ratio between the number of lines that contain
16610 comments and the number of all non-blank lines, expressed as a percentage;
16613 the number of empty lines and lines containing only space characters and/or
16614 format effectors (blank lines)
16617 the average number of code lines in subprogram bodies, task bodies, entry
16618 bodies and statement sequences in package bodies (this metric is only computed
16619 across the whole set of the analyzed units)
16624 @command{gnatmetric} sums the values of the line metrics for all the
16625 files being processed and then generates the cumulative results. The tool
16626 also computes for all the files being processed the average number of code
16629 You can use the following switches to select the specific line metrics
16630 to be computed and reported.
16633 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
16636 @cindex @option{--no-lines@var{x}}
16639 @item ^--lines-all^/LINE_COUNT_METRICS=ALL_ON^
16640 Report all the line metrics
16642 @item ^--no-lines-all^/LINE_COUNT_METRICS=ALL_OFF^
16643 Do not report any of line metrics
16645 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES_ON^
16646 Report the number of all lines
16648 @item ^--no-lines^/LINE_COUNT_METRICS=ALL_LINES_OFF^
16649 Do not report the number of all lines
16651 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES_ON^
16652 Report the number of code lines
16654 @item ^--no-lines-code^/LINE_COUNT_METRICS=CODE_LINES_OFF^
16655 Do not report the number of code lines
16657 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES_ON^
16658 Report the number of comment lines
16660 @item ^--no-lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES_OFF^
16661 Do not report the number of comment lines
16663 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES_ON^
16664 Report the number of code lines containing
16665 end-of-line comments
16667 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES_OFF^
16668 Do not report the number of code lines containing
16669 end-of-line comments
16671 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE_ON^
16672 Report the comment percentage in the program text
16674 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE_OFF^
16675 Do not report the comment percentage in the program text
16677 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES_ON^
16678 Report the number of blank lines
16680 @item ^--no-lines-blank^/LINE_COUNT_METRICS=BLANK_LINES_OFF^
16681 Do not report the number of blank lines
16683 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES_ON^
16684 Report the average number of code lines in subprogram bodies, task bodies,
16685 entry bodies and statement sequences in package bodies. The metric is computed
16686 and reported for the whole set of processed Ada sources only.
16688 @item ^--no-lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES_OFF^
16689 Do not report the average number of code lines in subprogram bodies,
16690 task bodies, entry bodies and statement sequences in package bodies.
16694 @node Syntax Metrics Control
16695 @subsubsection Syntax Metrics Control
16696 @cindex Syntax metrics control in @command{gnatmetric}
16699 @command{gnatmetric} computes various syntactic metrics for the
16700 outermost unit and for each eligible local unit:
16703 @item LSLOC (``Logical Source Lines Of Code'')
16704 The total number of declarations and the total number of statements
16706 @item Maximal static nesting level of inner program units
16708 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
16709 package, a task unit, a protected unit, a
16710 protected entry, a generic unit, or an explicitly declared subprogram other
16711 than an enumeration literal.''
16713 @item Maximal nesting level of composite syntactic constructs
16714 This corresponds to the notion of the
16715 maximum nesting level in the GNAT built-in style checks
16716 (@pxref{Style Checking})
16720 For the outermost unit in the file, @command{gnatmetric} additionally computes
16721 the following metrics:
16724 @item Public subprograms
16725 This metric is computed for package specifications. It is the
16726 number of subprograms and generic subprograms declared in the visible
16727 part (including the visible part of nested packages, protected objects, and
16730 @item All subprograms
16731 This metric is computed for bodies and subunits. The
16732 metric is equal to a total number of subprogram bodies in the compilation
16734 Neither generic instantiations nor renamings-as-a-body nor body stubs
16735 are counted. Any subprogram body is counted, independently of its nesting
16736 level and enclosing constructs. Generic bodies and bodies of protected
16737 subprograms are counted in the same way as ``usual'' subprogram bodies.
16740 This metric is computed for package specifications and
16741 generic package declarations. It is the total number of types
16742 that can be referenced from outside this compilation unit, plus the
16743 number of types from all the visible parts of all the visible generic
16744 packages. Generic formal types are not counted. Only types, not subtypes,
16748 Along with the total number of public types, the following
16749 types are counted and reported separately:
16756 Root tagged types (abstract, non-abstract, private, non-private). Type
16757 extensions are @emph{not} counted
16760 Private types (including private extensions)
16771 This metric is computed for any compilation unit. It is equal to the total
16772 number of the declarations of different types given in the compilation unit.
16773 The private and the corresponding full type declaration are counted as one
16774 type declaration. Incomplete type declarations and generic formal types
16776 No distinction is made among different kinds of types (abstract,
16777 private etc.); the total number of types is computed and reported.
16782 By default, all the syntax metrics are computed and reported. You can use the
16783 following switches to select specific syntax metrics.
16787 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
16790 @cindex @option{--no-syntax@var{x}}
16793 @item ^--syntax-all^/SYNTAX_METRICS=ALL_ON^
16794 Report all the syntax metrics
16796 @item ^--no-syntax-all^/ALL_OFF^
16797 Do not report any of syntax metrics
16799 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS_ON^
16800 Report the total number of declarations
16802 @item ^--no-declarations^/SYNTAX_METRICS=DECLARATIONS_OFF^
16803 Do not report the total number of declarations
16805 @item ^--statements^/SYNTAX_METRICS=STATEMENTS_ON^
16806 Report the total number of statements
16808 @item ^--no-statements^/SYNTAX_METRICS=STATEMENTS_OFF^
16809 Do not report the total number of statements
16811 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS_ON^
16812 Report the number of public subprograms in a compilation unit
16814 @item ^--no-public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS_OFF^
16815 Do not report the number of public subprograms in a compilation unit
16817 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS_ON^
16818 Report the number of all the subprograms in a compilation unit
16820 @item ^--no-all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS_OFF^
16821 Do not report the number of all the subprograms in a compilation unit
16823 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES_ON^
16824 Report the number of public types in a compilation unit
16826 @item ^--no-public-types^/SYNTAX_METRICS=PUBLIC_TYPES_OFF^
16827 Do not report the number of public types in a compilation unit
16829 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES_ON^
16830 Report the number of all the types in a compilation unit
16832 @item ^--no-all-types^/SYNTAX_METRICS=ALL_TYPES_OFF^
16833 Do not report the number of all the types in a compilation unit
16835 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_ON^
16836 Report the maximal program unit nesting level
16838 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
16839 Do not report the maximal program unit nesting level
16841 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING_ON^
16842 Report the maximal construct nesting level
16844 @item ^--no-construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING_OFF^
16845 Do not report the maximal construct nesting level
16849 @node Complexity Metrics Control
16850 @subsubsection Complexity Metrics Control
16851 @cindex Complexity metrics control in @command{gnatmetric}
16854 For a program unit that is an executable body (a subprogram body (including
16855 generic bodies), task body, entry body or a package body containing
16856 its own statement sequence) @command{gnatmetric} computes the following
16857 complexity metrics:
16861 McCabe cyclomatic complexity;
16864 McCabe essential complexity;
16867 maximal loop nesting level
16872 The McCabe complexity metrics are defined
16873 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
16875 According to McCabe, both control statements and short-circuit control forms
16876 should be taken into account when computing cyclomatic complexity. For each
16877 body, we compute three metric values:
16881 the complexity introduced by control
16882 statements only, without taking into account short-circuit forms,
16885 the complexity introduced by short-circuit control forms only, and
16889 cyclomatic complexity, which is the sum of these two values.
16893 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
16894 the code in the exception handlers and in all the nested program units.
16896 By default, all the complexity metrics are computed and reported.
16897 For more fine-grained control you can use
16898 the following switches:
16901 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
16904 @cindex @option{--no-complexity@var{x}}
16907 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL_ON^
16908 Report all the complexity metrics
16910 @item ^--no-complexity-all^/COMPLEXITY_METRICS=ALL_OFF^
16911 Do not report any of complexity metrics
16913 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC_ON^
16914 Report the McCabe Cyclomatic Complexity
16916 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC_OFF^
16917 Do not report the McCabe Cyclomatic Complexity
16919 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL_ON^
16920 Report the Essential Complexity
16922 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL_OFF^
16923 Do not report the Essential Complexity
16925 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
16926 Report maximal loop nesting level
16928 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_OFF^
16929 Do not report maximal loop nesting level
16931 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY_ON^
16932 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
16933 task bodies, entry bodies and statement sequences in package bodies.
16934 The metric is computed and reported for whole set of processed Ada sources
16937 @item ^--no-complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY_OFF^
16938 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
16939 bodies, task bodies, entry bodies and statement sequences in package bodies
16941 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
16942 @item ^-ne^/NO_EXITS_AS_GOTOS^
16943 Do not consider @code{exit} statements as @code{goto}s when
16944 computing Essential Complexity
16948 @node Other gnatmetric Switches
16949 @subsection Other @code{gnatmetric} Switches
16952 Additional @command{gnatmetric} switches are as follows:
16955 @item ^-files @var{filename}^/FILES=@var{filename}^
16956 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
16957 Take the argument source files from the specified file. This file should be an
16958 ordinary text file containing file names separated by spaces or
16959 line breaks. You can use this switch more then once in the same call to
16960 @command{gnatmetric}. You also can combine this switch with
16961 an explicit list of files.
16963 @item ^-v^/VERBOSE^
16964 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
16966 @command{gnatmetric} generates version information and then
16967 a trace of sources being processed.
16969 @item ^-dv^/DEBUG_OUTPUT^
16970 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
16972 @command{gnatmetric} generates various messages useful to understand what
16973 happens during the metrics computation
16976 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
16980 @node Generate project-wide metrics
16981 @subsection Generate project-wide metrics
16983 In order to compute metrics on all units of a given project, you can use
16984 the @command{gnat} driver along with the @option{-P} option:
16990 If the project @code{proj} depends upon other projects, you can compute
16991 the metrics on the project closure using the @option{-U} option:
16993 gnat metric -Pproj -U
16997 Finally, if not all the units are relevant to a particular main
16998 program in the project closure, you can generate metrics for the set
16999 of units needed to create a given main program (unit closure) using
17000 the @option{-U} option followed by the name of the main unit:
17002 gnat metric -Pproj -U main
17006 @c ***********************************
17007 @node File Name Krunching Using gnatkr
17008 @chapter File Name Krunching Using @code{gnatkr}
17012 This chapter discusses the method used by the compiler to shorten
17013 the default file names chosen for Ada units so that they do not
17014 exceed the maximum length permitted. It also describes the
17015 @code{gnatkr} utility that can be used to determine the result of
17016 applying this shortening.
17020 * Krunching Method::
17021 * Examples of gnatkr Usage::
17025 @section About @code{gnatkr}
17028 The default file naming rule in GNAT
17029 is that the file name must be derived from
17030 the unit name. The exact default rule is as follows:
17033 Take the unit name and replace all dots by hyphens.
17035 If such a replacement occurs in the
17036 second character position of a name, and the first character is
17037 ^a, g, s, or i^A, G, S, or I^ then replace the dot by the character
17038 ^~ (tilde)^$ (dollar sign)^
17039 instead of a minus.
17041 The reason for this exception is to avoid clashes
17042 with the standard names for children of System, Ada, Interfaces,
17043 and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^
17046 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
17047 switch of the compiler activates a ``krunching''
17048 circuit that limits file names to nn characters (where nn is a decimal
17049 integer). For example, using OpenVMS,
17050 where the maximum file name length is
17051 39, the value of nn is usually set to 39, but if you want to generate
17052 a set of files that would be usable if ported to a system with some
17053 different maximum file length, then a different value can be specified.
17054 The default value of 39 for OpenVMS need not be specified.
17056 The @code{gnatkr} utility can be used to determine the krunched name for
17057 a given file, when krunched to a specified maximum length.
17060 @section Using @code{gnatkr}
17063 The @code{gnatkr} command has the form
17067 $ gnatkr @var{name} [@var{length}]
17073 $ gnatkr @var{name} /COUNT=nn
17078 @var{name} is the uncrunched file name, derived from the name of the unit
17079 in the standard manner described in the previous section (i.e. in particular
17080 all dots are replaced by hyphens). The file name may or may not have an
17081 extension (defined as a suffix of the form period followed by arbitrary
17082 characters other than period). If an extension is present then it will
17083 be preserved in the output. For example, when krunching @file{hellofile.ads}
17084 to eight characters, the result will be hellofil.ads.
17086 Note: for compatibility with previous versions of @code{gnatkr} dots may
17087 appear in the name instead of hyphens, but the last dot will always be
17088 taken as the start of an extension. So if @code{gnatkr} is given an argument
17089 such as @file{Hello.World.adb} it will be treated exactly as if the first
17090 period had been a hyphen, and for example krunching to eight characters
17091 gives the result @file{hellworl.adb}.
17093 Note that the result is always all lower case (except on OpenVMS where it is
17094 all upper case). Characters of the other case are folded as required.
17096 @var{length} represents the length of the krunched name. The default
17097 when no argument is given is ^8^39^ characters. A length of zero stands for
17098 unlimited, in other words do not chop except for system files where the
17099 implied crunching length is always eight characters.
17102 The output is the krunched name. The output has an extension only if the
17103 original argument was a file name with an extension.
17105 @node Krunching Method
17106 @section Krunching Method
17109 The initial file name is determined by the name of the unit that the file
17110 contains. The name is formed by taking the full expanded name of the
17111 unit and replacing the separating dots with hyphens and
17112 using ^lowercase^uppercase^
17113 for all letters, except that a hyphen in the second character position is
17114 replaced by a ^tilde^dollar sign^ if the first character is
17115 ^a, i, g, or s^A, I, G, or S^.
17116 The extension is @code{.ads} for a
17117 specification and @code{.adb} for a body.
17118 Krunching does not affect the extension, but the file name is shortened to
17119 the specified length by following these rules:
17123 The name is divided into segments separated by hyphens, tildes or
17124 underscores and all hyphens, tildes, and underscores are
17125 eliminated. If this leaves the name short enough, we are done.
17128 If the name is too long, the longest segment is located (left-most
17129 if there are two of equal length), and shortened by dropping
17130 its last character. This is repeated until the name is short enough.
17132 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
17133 to fit the name into 8 characters as required by some operating systems.
17136 our-strings-wide_fixed 22
17137 our strings wide fixed 19
17138 our string wide fixed 18
17139 our strin wide fixed 17
17140 our stri wide fixed 16
17141 our stri wide fixe 15
17142 our str wide fixe 14
17143 our str wid fixe 13
17149 Final file name: oustwifi.adb
17153 The file names for all predefined units are always krunched to eight
17154 characters. The krunching of these predefined units uses the following
17155 special prefix replacements:
17159 replaced by @file{^a^A^-}
17162 replaced by @file{^g^G^-}
17165 replaced by @file{^i^I^-}
17168 replaced by @file{^s^S^-}
17171 These system files have a hyphen in the second character position. That
17172 is why normal user files replace such a character with a
17173 ^tilde^dollar sign^, to
17174 avoid confusion with system file names.
17176 As an example of this special rule, consider
17177 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
17180 ada-strings-wide_fixed 22
17181 a- strings wide fixed 18
17182 a- string wide fixed 17
17183 a- strin wide fixed 16
17184 a- stri wide fixed 15
17185 a- stri wide fixe 14
17186 a- str wide fixe 13
17192 Final file name: a-stwifi.adb
17196 Of course no file shortening algorithm can guarantee uniqueness over all
17197 possible unit names, and if file name krunching is used then it is your
17198 responsibility to ensure that no name clashes occur. The utility
17199 program @code{gnatkr} is supplied for conveniently determining the
17200 krunched name of a file.
17202 @node Examples of gnatkr Usage
17203 @section Examples of @code{gnatkr} Usage
17210 $ gnatkr very_long_unit_name.ads --> velounna.ads
17211 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
17212 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
17213 $ gnatkr grandparent-parent-child --> grparchi
17215 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
17216 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
17219 @node Preprocessing Using gnatprep
17220 @chapter Preprocessing Using @code{gnatprep}
17224 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
17226 Although designed for use with GNAT, @code{gnatprep} does not depend on any
17227 special GNAT features.
17228 For further discussion of conditional compilation in general, see
17229 @ref{Conditional Compilation}.
17233 * Switches for gnatprep::
17234 * Form of Definitions File::
17235 * Form of Input Text for gnatprep::
17239 @node Using gnatprep
17240 @section Using @code{gnatprep}
17243 To call @code{gnatprep} use
17246 $ gnatprep [switches] infile outfile [deffile]
17253 is an optional sequence of switches as described in the next section.
17256 is the full name of the input file, which is an Ada source
17257 file containing preprocessor directives.
17260 is the full name of the output file, which is an Ada source
17261 in standard Ada form. When used with GNAT, this file name will
17262 normally have an ads or adb suffix.
17265 is the full name of a text file containing definitions of
17266 symbols to be referenced by the preprocessor. This argument is
17267 optional, and can be replaced by the use of the @option{-D} switch.
17271 @node Switches for gnatprep
17272 @section Switches for @code{gnatprep}
17277 @item ^-b^/BLANK_LINES^
17278 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
17279 Causes both preprocessor lines and the lines deleted by
17280 preprocessing to be replaced by blank lines in the output source file,
17281 preserving line numbers in the output file.
17283 @item ^-c^/COMMENTS^
17284 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
17285 Causes both preprocessor lines and the lines deleted
17286 by preprocessing to be retained in the output source as comments marked
17287 with the special string @code{"--! "}. This option will result in line numbers
17288 being preserved in the output file.
17290 @item ^-C^/REPLACE_IN_COMMENTS^
17291 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
17292 Causes comments to be scanned. Normally comments are ignored by gnatprep.
17293 If this option is specified, then comments are scanned and any $symbol
17294 substitutions performed as in program text. This is particularly useful
17295 when structured comments are used (e.g. when writing programs in the
17296 SPARK dialect of Ada). Note that this switch is not available when
17297 doing integrated preprocessing (it would be useless in this context
17298 since comments are ignored by the compiler in any case).
17300 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
17301 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
17302 Defines a new symbol, associated with value. If no value is given on the
17303 command line, then symbol is considered to be @code{True}. This switch
17304 can be used in place of a definition file.
17308 @cindex @option{/REMOVE} (@command{gnatprep})
17309 This is the default setting which causes lines deleted by preprocessing
17310 to be entirely removed from the output file.
17313 @item ^-r^/REFERENCE^
17314 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
17315 Causes a @code{Source_Reference} pragma to be generated that
17316 references the original input file, so that error messages will use
17317 the file name of this original file. The use of this switch implies
17318 that preprocessor lines are not to be removed from the file, so its
17319 use will force @option{^-b^/BLANK_LINES^} mode if
17320 @option{^-c^/COMMENTS^}
17321 has not been specified explicitly.
17323 Note that if the file to be preprocessed contains multiple units, then
17324 it will be necessary to @code{gnatchop} the output file from
17325 @code{gnatprep}. If a @code{Source_Reference} pragma is present
17326 in the preprocessed file, it will be respected by
17327 @code{gnatchop ^-r^/REFERENCE^}
17328 so that the final chopped files will correctly refer to the original
17329 input source file for @code{gnatprep}.
17331 @item ^-s^/SYMBOLS^
17332 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
17333 Causes a sorted list of symbol names and values to be
17334 listed on the standard output file.
17336 @item ^-u^/UNDEFINED^
17337 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
17338 Causes undefined symbols to be treated as having the value FALSE in the context
17339 of a preprocessor test. In the absence of this option, an undefined symbol in
17340 a @code{#if} or @code{#elsif} test will be treated as an error.
17346 Note: if neither @option{-b} nor @option{-c} is present,
17347 then preprocessor lines and
17348 deleted lines are completely removed from the output, unless -r is
17349 specified, in which case -b is assumed.
17352 @node Form of Definitions File
17353 @section Form of Definitions File
17356 The definitions file contains lines of the form
17363 where symbol is an identifier, following normal Ada (case-insensitive)
17364 rules for its syntax, and value is one of the following:
17368 Empty, corresponding to a null substitution
17370 A string literal using normal Ada syntax
17372 Any sequence of characters from the set
17373 (letters, digits, period, underline).
17377 Comment lines may also appear in the definitions file, starting with
17378 the usual @code{--},
17379 and comments may be added to the definitions lines.
17381 @node Form of Input Text for gnatprep
17382 @section Form of Input Text for @code{gnatprep}
17385 The input text may contain preprocessor conditional inclusion lines,
17386 as well as general symbol substitution sequences.
17388 The preprocessor conditional inclusion commands have the form
17393 #if @i{expression} [then]
17395 #elsif @i{expression} [then]
17397 #elsif @i{expression} [then]
17408 In this example, @i{expression} is defined by the following grammar:
17410 @i{expression} ::= <symbol>
17411 @i{expression} ::= <symbol> = "<value>"
17412 @i{expression} ::= <symbol> = <symbol>
17413 @i{expression} ::= <symbol> 'Defined
17414 @i{expression} ::= not @i{expression}
17415 @i{expression} ::= @i{expression} and @i{expression}
17416 @i{expression} ::= @i{expression} or @i{expression}
17417 @i{expression} ::= @i{expression} and then @i{expression}
17418 @i{expression} ::= @i{expression} or else @i{expression}
17419 @i{expression} ::= ( @i{expression} )
17423 For the first test (@i{expression} ::= <symbol>) the symbol must have
17424 either the value true or false, that is to say the right-hand of the
17425 symbol definition must be one of the (case-insensitive) literals
17426 @code{True} or @code{False}. If the value is true, then the
17427 corresponding lines are included, and if the value is false, they are
17430 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
17431 the symbol has been defined in the definition file or by a @option{-D}
17432 switch on the command line. Otherwise, the test is false.
17434 The equality tests are case insensitive, as are all the preprocessor lines.
17436 If the symbol referenced is not defined in the symbol definitions file,
17437 then the effect depends on whether or not switch @option{-u}
17438 is specified. If so, then the symbol is treated as if it had the value
17439 false and the test fails. If this switch is not specified, then
17440 it is an error to reference an undefined symbol. It is also an error to
17441 reference a symbol that is defined with a value other than @code{True}
17444 The use of the @code{not} operator inverts the sense of this logical test.
17445 The @code{not} operator cannot be combined with the @code{or} or @code{and}
17446 operators, without parentheses. For example, "if not X or Y then" is not
17447 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
17449 The @code{then} keyword is optional as shown
17451 The @code{#} must be the first non-blank character on a line, but
17452 otherwise the format is free form. Spaces or tabs may appear between
17453 the @code{#} and the keyword. The keywords and the symbols are case
17454 insensitive as in normal Ada code. Comments may be used on a
17455 preprocessor line, but other than that, no other tokens may appear on a
17456 preprocessor line. Any number of @code{elsif} clauses can be present,
17457 including none at all. The @code{else} is optional, as in Ada.
17459 The @code{#} marking the start of a preprocessor line must be the first
17460 non-blank character on the line, i.e. it must be preceded only by
17461 spaces or horizontal tabs.
17463 Symbol substitution outside of preprocessor lines is obtained by using
17471 anywhere within a source line, except in a comment or within a
17472 string literal. The identifier
17473 following the @code{$} must match one of the symbols defined in the symbol
17474 definition file, and the result is to substitute the value of the
17475 symbol in place of @code{$symbol} in the output file.
17477 Note that although the substitution of strings within a string literal
17478 is not possible, it is possible to have a symbol whose defined value is
17479 a string literal. So instead of setting XYZ to @code{hello} and writing:
17482 Header : String := "$XYZ";
17486 you should set XYZ to @code{"hello"} and write:
17489 Header : String := $XYZ;
17493 and then the substitution will occur as desired.
17496 @node The GNAT Run-Time Library Builder gnatlbr
17497 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
17499 @cindex Library builder
17502 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
17503 supplied configuration pragmas.
17506 * Running gnatlbr::
17507 * Switches for gnatlbr::
17508 * Examples of gnatlbr Usage::
17511 @node Running gnatlbr
17512 @section Running @code{gnatlbr}
17515 The @code{gnatlbr} command has the form
17518 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
17521 @node Switches for gnatlbr
17522 @section Switches for @code{gnatlbr}
17525 @code{gnatlbr} recognizes the following switches:
17529 @item /CREATE=directory
17530 @cindex @code{/CREATE} (@code{gnatlbr})
17531 Create the new run-time library in the specified directory.
17533 @item /SET=directory
17534 @cindex @code{/SET} (@code{gnatlbr})
17535 Make the library in the specified directory the current run-time
17538 @item /DELETE=directory
17539 @cindex @code{/DELETE} (@code{gnatlbr})
17540 Delete the run-time library in the specified directory.
17543 @cindex @code{/CONFIG} (@code{gnatlbr})
17545 Use the configuration pragmas in the specified file when building
17549 Use the configuration pragmas in the specified file when compiling.
17553 @node Examples of gnatlbr Usage
17554 @section Example of @code{gnatlbr} Usage
17557 Contents of VAXFLOAT.ADC:
17558 pragma Float_Representation (VAX_Float);
17560 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
17562 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
17567 @node The GNAT Library Browser gnatls
17568 @chapter The GNAT Library Browser @code{gnatls}
17570 @cindex Library browser
17573 @code{gnatls} is a tool that outputs information about compiled
17574 units. It gives the relationship between objects, unit names and source
17575 files. It can also be used to check the source dependencies of a unit
17576 as well as various characteristics.
17578 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
17579 driver (see @ref{The GNAT Driver and Project Files}).
17583 * Switches for gnatls::
17584 * Examples of gnatls Usage::
17587 @node Running gnatls
17588 @section Running @code{gnatls}
17591 The @code{gnatls} command has the form
17594 $ gnatls switches @var{object_or_ali_file}
17598 The main argument is the list of object or @file{ali} files
17599 (@pxref{The Ada Library Information Files})
17600 for which information is requested.
17602 In normal mode, without additional option, @code{gnatls} produces a
17603 four-column listing. Each line represents information for a specific
17604 object. The first column gives the full path of the object, the second
17605 column gives the name of the principal unit in this object, the third
17606 column gives the status of the source and the fourth column gives the
17607 full path of the source representing this unit.
17608 Here is a simple example of use:
17612 ^./^[]^demo1.o demo1 DIF demo1.adb
17613 ^./^[]^demo2.o demo2 OK demo2.adb
17614 ^./^[]^hello.o h1 OK hello.adb
17615 ^./^[]^instr-child.o instr.child MOK instr-child.adb
17616 ^./^[]^instr.o instr OK instr.adb
17617 ^./^[]^tef.o tef DIF tef.adb
17618 ^./^[]^text_io_example.o text_io_example OK text_io_example.adb
17619 ^./^[]^tgef.o tgef DIF tgef.adb
17623 The first line can be interpreted as follows: the main unit which is
17625 object file @file{demo1.o} is demo1, whose main source is in
17626 @file{demo1.adb}. Furthermore, the version of the source used for the
17627 compilation of demo1 has been modified (DIF). Each source file has a status
17628 qualifier which can be:
17631 @item OK (unchanged)
17632 The version of the source file used for the compilation of the
17633 specified unit corresponds exactly to the actual source file.
17635 @item MOK (slightly modified)
17636 The version of the source file used for the compilation of the
17637 specified unit differs from the actual source file but not enough to
17638 require recompilation. If you use gnatmake with the qualifier
17639 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
17640 MOK will not be recompiled.
17642 @item DIF (modified)
17643 No version of the source found on the path corresponds to the source
17644 used to build this object.
17646 @item ??? (file not found)
17647 No source file was found for this unit.
17649 @item HID (hidden, unchanged version not first on PATH)
17650 The version of the source that corresponds exactly to the source used
17651 for compilation has been found on the path but it is hidden by another
17652 version of the same source that has been modified.
17656 @node Switches for gnatls
17657 @section Switches for @code{gnatls}
17660 @code{gnatls} recognizes the following switches:
17664 @cindex @option{--version} @command{gnatls}
17665 Display Copyright and version, then exit disregarding all other options.
17668 @cindex @option{--help} @command{gnatls}
17669 If @option{--version} was not used, display usage, then exit disregarding
17672 @item ^-a^/ALL_UNITS^
17673 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
17674 Consider all units, including those of the predefined Ada library.
17675 Especially useful with @option{^-d^/DEPENDENCIES^}.
17677 @item ^-d^/DEPENDENCIES^
17678 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
17679 List sources from which specified units depend on.
17681 @item ^-h^/OUTPUT=OPTIONS^
17682 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
17683 Output the list of options.
17685 @item ^-o^/OUTPUT=OBJECTS^
17686 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
17687 Only output information about object files.
17689 @item ^-s^/OUTPUT=SOURCES^
17690 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
17691 Only output information about source files.
17693 @item ^-u^/OUTPUT=UNITS^
17694 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
17695 Only output information about compilation units.
17697 @item ^-files^/FILES^=@var{file}
17698 @cindex @option{^-files^/FILES^} (@code{gnatls})
17699 Take as arguments the files listed in text file @var{file}.
17700 Text file @var{file} may contain empty lines that are ignored.
17701 Each non empty line should contain the name of an existing file.
17702 Several such switches may be specified simultaneously.
17704 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17705 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
17706 @itemx ^-I^/SEARCH=^@var{dir}
17707 @itemx ^-I-^/NOCURRENT_DIRECTORY^
17709 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
17710 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
17711 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
17712 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
17713 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
17714 flags (@pxref{Switches for gnatmake}).
17716 @item --RTS=@var{rts-path}
17717 @cindex @option{--RTS} (@code{gnatls})
17718 Specifies the default location of the runtime library. Same meaning as the
17719 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
17721 @item ^-v^/OUTPUT=VERBOSE^
17722 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
17723 Verbose mode. Output the complete source, object and project paths. Do not use
17724 the default column layout but instead use long format giving as much as
17725 information possible on each requested units, including special
17726 characteristics such as:
17729 @item Preelaborable
17730 The unit is preelaborable in the Ada sense.
17733 No elaboration code has been produced by the compiler for this unit.
17736 The unit is pure in the Ada sense.
17738 @item Elaborate_Body
17739 The unit contains a pragma Elaborate_Body.
17742 The unit contains a pragma Remote_Types.
17744 @item Shared_Passive
17745 The unit contains a pragma Shared_Passive.
17748 This unit is part of the predefined environment and cannot be modified
17751 @item Remote_Call_Interface
17752 The unit contains a pragma Remote_Call_Interface.
17758 @node Examples of gnatls Usage
17759 @section Example of @code{gnatls} Usage
17763 Example of using the verbose switch. Note how the source and
17764 object paths are affected by the -I switch.
17767 $ gnatls -v -I.. demo1.o
17769 GNATLS 5.03w (20041123-34)
17770 Copyright 1997-2004 Free Software Foundation, Inc.
17772 Source Search Path:
17773 <Current_Directory>
17775 /home/comar/local/adainclude/
17777 Object Search Path:
17778 <Current_Directory>
17780 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
17782 Project Search Path:
17783 <Current_Directory>
17784 /home/comar/local/lib/gnat/
17789 Kind => subprogram body
17790 Flags => No_Elab_Code
17791 Source => demo1.adb modified
17795 The following is an example of use of the dependency list.
17796 Note the use of the -s switch
17797 which gives a straight list of source files. This can be useful for
17798 building specialized scripts.
17801 $ gnatls -d demo2.o
17802 ./demo2.o demo2 OK demo2.adb
17808 $ gnatls -d -s -a demo1.o
17810 /home/comar/local/adainclude/ada.ads
17811 /home/comar/local/adainclude/a-finali.ads
17812 /home/comar/local/adainclude/a-filico.ads
17813 /home/comar/local/adainclude/a-stream.ads
17814 /home/comar/local/adainclude/a-tags.ads
17817 /home/comar/local/adainclude/gnat.ads
17818 /home/comar/local/adainclude/g-io.ads
17820 /home/comar/local/adainclude/system.ads
17821 /home/comar/local/adainclude/s-exctab.ads
17822 /home/comar/local/adainclude/s-finimp.ads
17823 /home/comar/local/adainclude/s-finroo.ads
17824 /home/comar/local/adainclude/s-secsta.ads
17825 /home/comar/local/adainclude/s-stalib.ads
17826 /home/comar/local/adainclude/s-stoele.ads
17827 /home/comar/local/adainclude/s-stratt.ads
17828 /home/comar/local/adainclude/s-tasoli.ads
17829 /home/comar/local/adainclude/s-unstyp.ads
17830 /home/comar/local/adainclude/unchconv.ads
17836 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
17838 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
17839 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
17840 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
17841 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
17842 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
17846 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
17847 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
17849 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
17850 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
17851 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
17852 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
17853 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
17854 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
17855 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
17856 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
17857 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
17858 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
17859 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
17863 @node Cleaning Up Using gnatclean
17864 @chapter Cleaning Up Using @code{gnatclean}
17866 @cindex Cleaning tool
17869 @code{gnatclean} is a tool that allows the deletion of files produced by the
17870 compiler, binder and linker, including ALI files, object files, tree files,
17871 expanded source files, library files, interface copy source files, binder
17872 generated files and executable files.
17875 * Running gnatclean::
17876 * Switches for gnatclean::
17877 @c * Examples of gnatclean Usage::
17880 @node Running gnatclean
17881 @section Running @code{gnatclean}
17884 The @code{gnatclean} command has the form:
17887 $ gnatclean switches @var{names}
17891 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
17892 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
17893 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
17896 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17897 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
17898 the linker. In informative-only mode, specified by switch
17899 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
17900 normal mode is listed, but no file is actually deleted.
17902 @node Switches for gnatclean
17903 @section Switches for @code{gnatclean}
17906 @code{gnatclean} recognizes the following switches:
17910 @cindex @option{--version} @command{gnatclean}
17911 Display Copyright and version, then exit disregarding all other options.
17914 @cindex @option{--help} @command{gnatclean}
17915 If @option{--version} was not used, display usage, then exit disregarding
17918 @item ^-c^/COMPILER_FILES_ONLY^
17919 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
17920 Only attempt to delete the files produced by the compiler, not those produced
17921 by the binder or the linker. The files that are not to be deleted are library
17922 files, interface copy files, binder generated files and executable files.
17924 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
17925 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
17926 Indicate that ALI and object files should normally be found in directory
17929 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
17930 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
17931 When using project files, if some errors or warnings are detected during
17932 parsing and verbose mode is not in effect (no use of switch
17933 ^-v^/VERBOSE^), then error lines start with the full path name of the project
17934 file, rather than its simple file name.
17937 @cindex @option{^-h^/HELP^} (@code{gnatclean})
17938 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
17940 @item ^-n^/NODELETE^
17941 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
17942 Informative-only mode. Do not delete any files. Output the list of the files
17943 that would have been deleted if this switch was not specified.
17945 @item ^-P^/PROJECT_FILE=^@var{project}
17946 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
17947 Use project file @var{project}. Only one such switch can be used.
17948 When cleaning a project file, the files produced by the compilation of the
17949 immediate sources or inherited sources of the project files are to be
17950 deleted. This is not depending on the presence or not of executable names
17951 on the command line.
17954 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
17955 Quiet output. If there are no errors, do not output anything, except in
17956 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
17957 (switch ^-n^/NODELETE^).
17959 @item ^-r^/RECURSIVE^
17960 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
17961 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
17962 clean all imported and extended project files, recursively. If this switch
17963 is not specified, only the files related to the main project file are to be
17964 deleted. This switch has no effect if no project file is specified.
17966 @item ^-v^/VERBOSE^
17967 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
17970 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
17971 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
17972 Indicates the verbosity of the parsing of GNAT project files.
17973 @xref{Switches Related to Project Files}.
17975 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
17976 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
17977 Indicates that external variable @var{name} has the value @var{value}.
17978 The Project Manager will use this value for occurrences of
17979 @code{external(name)} when parsing the project file.
17980 @xref{Switches Related to Project Files}.
17982 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17983 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
17984 When searching for ALI and object files, look in directory
17987 @item ^-I^/SEARCH=^@var{dir}
17988 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
17989 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
17991 @item ^-I-^/NOCURRENT_DIRECTORY^
17992 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
17993 @cindex Source files, suppressing search
17994 Do not look for ALI or object files in the directory
17995 where @code{gnatclean} was invoked.
17999 @c @node Examples of gnatclean Usage
18000 @c @section Examples of @code{gnatclean} Usage
18003 @node GNAT and Libraries
18004 @chapter GNAT and Libraries
18005 @cindex Library, building, installing, using
18008 This chapter describes how to build and use libraries with GNAT, and also shows
18009 how to recompile the GNAT run-time library. You should be familiar with the
18010 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
18014 * Introduction to Libraries in GNAT::
18015 * General Ada Libraries::
18016 * Stand-alone Ada Libraries::
18017 * Rebuilding the GNAT Run-Time Library::
18020 @node Introduction to Libraries in GNAT
18021 @section Introduction to Libraries in GNAT
18024 A library is, conceptually, a collection of objects which does not have its
18025 own main thread of execution, but rather provides certain services to the
18026 applications that use it. A library can be either statically linked with the
18027 application, in which case its code is directly included in the application,
18028 or, on platforms that support it, be dynamically linked, in which case
18029 its code is shared by all applications making use of this library.
18031 GNAT supports both types of libraries.
18032 In the static case, the compiled code can be provided in different ways. The
18033 simplest approach is to provide directly the set of objects resulting from
18034 compilation of the library source files. Alternatively, you can group the
18035 objects into an archive using whatever commands are provided by the operating
18036 system. For the latter case, the objects are grouped into a shared library.
18038 In the GNAT environment, a library has three types of components:
18044 @xref{The Ada Library Information Files}.
18046 Object files, an archive or a shared library.
18050 A GNAT library may expose all its source files, which is useful for
18051 documentation purposes. Alternatively, it may expose only the units needed by
18052 an external user to make use of the library. That is to say, the specs
18053 reflecting the library services along with all the units needed to compile
18054 those specs, which can include generic bodies or any body implementing an
18055 inlined routine. In the case of @emph{stand-alone libraries} those exposed
18056 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
18058 All compilation units comprising an application, including those in a library,
18059 need to be elaborated in an order partially defined by Ada's semantics. GNAT
18060 computes the elaboration order from the @file{ALI} files and this is why they
18061 constitute a mandatory part of GNAT libraries. Except in the case of
18062 @emph{stand-alone libraries}, where a specific library elaboration routine is
18063 produced independently of the application(s) using the library.
18065 @node General Ada Libraries
18066 @section General Ada Libraries
18069 * Building a library::
18070 * Installing a library::
18071 * Using a library::
18074 @node Building a library
18075 @subsection Building a library
18078 The easiest way to build a library is to use the Project Manager,
18079 which supports a special type of project called a @emph{Library Project}
18080 (@pxref{Library Projects}).
18082 A project is considered a library project, when two project-level attributes
18083 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
18084 control different aspects of library configuration, additional optional
18085 project-level attributes can be specified:
18088 This attribute controls whether the library is to be static or dynamic
18090 @item Library_Version
18091 This attribute specifies the library version; this value is used
18092 during dynamic linking of shared libraries to determine if the currently
18093 installed versions of the binaries are compatible.
18095 @item Library_Options
18097 These attributes specify additional low-level options to be used during
18098 library generation, and redefine the actual application used to generate
18103 The GNAT Project Manager takes full care of the library maintenance task,
18104 including recompilation of the source files for which objects do not exist
18105 or are not up to date, assembly of the library archive, and installation of
18106 the library (i.e., copying associated source, object and @file{ALI} files
18107 to the specified location).
18109 Here is a simple library project file:
18110 @smallexample @c ada
18112 for Source_Dirs use ("src1", "src2");
18113 for Object_Dir use "obj";
18114 for Library_Name use "mylib";
18115 for Library_Dir use "lib";
18116 for Library_Kind use "dynamic";
18121 and the compilation command to build and install the library:
18123 @smallexample @c ada
18124 $ gnatmake -Pmy_lib
18128 It is not entirely trivial to perform manually all the steps required to
18129 produce a library. We recommend that you use the GNAT Project Manager
18130 for this task. In special cases where this is not desired, the necessary
18131 steps are discussed below.
18133 There are various possibilities for compiling the units that make up the
18134 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
18135 with a conventional script. For simple libraries, it is also possible to create
18136 a dummy main program which depends upon all the packages that comprise the
18137 interface of the library. This dummy main program can then be given to
18138 @command{gnatmake}, which will ensure that all necessary objects are built.
18140 After this task is accomplished, you should follow the standard procedure
18141 of the underlying operating system to produce the static or shared library.
18143 Here is an example of such a dummy program:
18144 @smallexample @c ada
18146 with My_Lib.Service1;
18147 with My_Lib.Service2;
18148 with My_Lib.Service3;
18149 procedure My_Lib_Dummy is
18157 Here are the generic commands that will build an archive or a shared library.
18160 # compiling the library
18161 $ gnatmake -c my_lib_dummy.adb
18163 # we don't need the dummy object itself
18164 $ rm my_lib_dummy.o my_lib_dummy.ali
18166 # create an archive with the remaining objects
18167 $ ar rc libmy_lib.a *.o
18168 # some systems may require "ranlib" to be run as well
18170 # or create a shared library
18171 $ gcc -shared -o libmy_lib.so *.o
18172 # some systems may require the code to have been compiled with -fPIC
18174 # remove the object files that are now in the library
18177 # Make the ALI files read-only so that gnatmake will not try to
18178 # regenerate the objects that are in the library
18183 Please note that the library must have a name of the form @file{libxxx.a} or
18184 @file{libxxx.so} (or @file{libxxx.dll} on Windows) in order to be accessed by
18185 the directive @option{-lxxx} at link time.
18187 @node Installing a library
18188 @subsection Installing a library
18189 @cindex @code{ADA_PROJECT_PATH}
18192 If you use project files, library installation is part of the library build
18193 process. Thus no further action is needed in order to make use of the
18194 libraries that are built as part of the general application build. A usable
18195 version of the library is installed in the directory specified by the
18196 @code{Library_Dir} attribute of the library project file.
18198 You may want to install a library in a context different from where the library
18199 is built. This situation arises with third party suppliers, who may want
18200 to distribute a library in binary form where the user is not expected to be
18201 able to recompile the library. The simplest option in this case is to provide
18202 a project file slightly different from the one used to build the library, by
18203 using the @code{externally_built} attribute. For instance, the project
18204 file used to build the library in the previous section can be changed into the
18205 following one when the library is installed:
18207 @smallexample @c projectfile
18209 for Source_Dirs use ("src1", "src2");
18210 for Library_Name use "mylib";
18211 for Library_Dir use "lib";
18212 for Library_Kind use "dynamic";
18213 for Externally_Built use "true";
18218 This project file assumes that the directories @file{src1},
18219 @file{src2}, and @file{lib} exist in
18220 the directory containing the project file. The @code{externally_built}
18221 attribute makes it clear to the GNAT builder that it should not attempt to
18222 recompile any of the units from this library. It allows the library provider to
18223 restrict the source set to the minimum necessary for clients to make use of the
18224 library as described in the first section of this chapter. It is the
18225 responsibility of the library provider to install the necessary sources, ALI
18226 files and libraries in the directories mentioned in the project file. For
18227 convenience, the user's library project file should be installed in a location
18228 that will be searched automatically by the GNAT
18229 builder. These are the directories referenced in the @code{ADA_PROJECT_PATH}
18230 environment variable (@pxref{Importing Projects}), and also the default GNAT
18231 library location that can be queried with @command{gnatls -v} and is usually of
18232 the form $gnat_install_root/lib/gnat.
18234 When project files are not an option, it is also possible, but not recommended,
18235 to install the library so that the sources needed to use the library are on the
18236 Ada source path and the ALI files & libraries be on the Ada Object path (see
18237 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
18238 administrator can place general-purpose libraries in the default compiler
18239 paths, by specifying the libraries' location in the configuration files
18240 @file{ada_source_path} and @file{ada_object_path}. These configuration files
18241 must be located in the GNAT installation tree at the same place as the gcc spec
18242 file. The location of the gcc spec file can be determined as follows:
18248 The configuration files mentioned above have a simple format: each line
18249 must contain one unique directory name.
18250 Those names are added to the corresponding path
18251 in their order of appearance in the file. The names can be either absolute
18252 or relative; in the latter case, they are relative to where theses files
18255 The files @file{ada_source_path} and @file{ada_object_path} might not be
18257 GNAT installation, in which case, GNAT will look for its run-time library in
18258 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
18259 objects and @file{ALI} files). When the files exist, the compiler does not
18260 look in @file{adainclude} and @file{adalib}, and thus the
18261 @file{ada_source_path} file
18262 must contain the location for the GNAT run-time sources (which can simply
18263 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
18264 contain the location for the GNAT run-time objects (which can simply
18267 You can also specify a new default path to the run-time library at compilation
18268 time with the switch @option{--RTS=rts-path}. You can thus choose / change
18269 the run-time library you want your program to be compiled with. This switch is
18270 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
18271 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
18273 It is possible to install a library before or after the standard GNAT
18274 library, by reordering the lines in the configuration files. In general, a
18275 library must be installed before the GNAT library if it redefines
18278 @node Using a library
18279 @subsection Using a library
18281 @noindent Once again, the project facility greatly simplifies the use of
18282 libraries. In this context, using a library is just a matter of adding a
18283 @code{with} clause in the user project. For instance, to make use of the
18284 library @code{My_Lib} shown in examples in earlier sections, you can
18287 @smallexample @c projectfile
18294 Even if you have a third-party, non-Ada library, you can still use GNAT's
18295 Project Manager facility to provide a wrapper for it. For example, the
18296 following project, when @code{with}ed by your main project, will link with the
18297 third-party library @file{liba.a}:
18299 @smallexample @c projectfile
18302 for Externally_Built use "true";
18303 for Source_Files use ();
18304 for Library_Dir use "lib";
18305 for Library_Name use "a";
18306 for Library_Kind use "static";
18310 This is an alternative to the use of @code{pragma Linker_Options}. It is
18311 especially interesting in the context of systems with several interdependent
18312 static libraries where finding a proper linker order is not easy and best be
18313 left to the tools having visibility over project dependence information.
18316 In order to use an Ada library manually, you need to make sure that this
18317 library is on both your source and object path
18318 (see @ref{Search Paths and the Run-Time Library (RTL)}
18319 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
18320 in an archive or a shared library, you need to specify the desired
18321 library at link time.
18323 For example, you can use the library @file{mylib} installed in
18324 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
18327 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
18332 This can be expressed more simply:
18337 when the following conditions are met:
18340 @file{/dir/my_lib_src} has been added by the user to the environment
18341 variable @code{ADA_INCLUDE_PATH}, or by the administrator to the file
18342 @file{ada_source_path}
18344 @file{/dir/my_lib_obj} has been added by the user to the environment
18345 variable @code{ADA_OBJECTS_PATH}, or by the administrator to the file
18346 @file{ada_object_path}
18348 a pragma @code{Linker_Options} has been added to one of the sources.
18351 @smallexample @c ada
18352 pragma Linker_Options ("-lmy_lib");
18356 @node Stand-alone Ada Libraries
18357 @section Stand-alone Ada Libraries
18358 @cindex Stand-alone library, building, using
18361 * Introduction to Stand-alone Libraries::
18362 * Building a Stand-alone Library::
18363 * Creating a Stand-alone Library to be used in a non-Ada context::
18364 * Restrictions in Stand-alone Libraries::
18367 @node Introduction to Stand-alone Libraries
18368 @subsection Introduction to Stand-alone Libraries
18371 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
18373 elaborate the Ada units that are included in the library. In contrast with
18374 an ordinary library, which consists of all sources, objects and @file{ALI}
18376 library, a SAL may specify a restricted subset of compilation units
18377 to serve as a library interface. In this case, the fully
18378 self-sufficient set of files will normally consist of an objects
18379 archive, the sources of interface units' specs, and the @file{ALI}
18380 files of interface units.
18381 If an interface spec contains a generic unit or an inlined subprogram,
18383 source must also be provided; if the units that must be provided in the source
18384 form depend on other units, the source and @file{ALI} files of those must
18387 The main purpose of a SAL is to minimize the recompilation overhead of client
18388 applications when a new version of the library is installed. Specifically,
18389 if the interface sources have not changed, client applications do not need to
18390 be recompiled. If, furthermore, a SAL is provided in the shared form and its
18391 version, controlled by @code{Library_Version} attribute, is not changed,
18392 then the clients do not need to be relinked.
18394 SALs also allow the library providers to minimize the amount of library source
18395 text exposed to the clients. Such ``information hiding'' might be useful or
18396 necessary for various reasons.
18398 Stand-alone libraries are also well suited to be used in an executable whose
18399 main routine is not written in Ada.
18401 @node Building a Stand-alone Library
18402 @subsection Building a Stand-alone Library
18405 GNAT's Project facility provides a simple way of building and installing
18406 stand-alone libraries; see @ref{Stand-alone Library Projects}.
18407 To be a Stand-alone Library Project, in addition to the two attributes
18408 that make a project a Library Project (@code{Library_Name} and
18409 @code{Library_Dir}; see @ref{Library Projects}), the attribute
18410 @code{Library_Interface} must be defined. For example:
18412 @smallexample @c projectfile
18414 for Library_Dir use "lib_dir";
18415 for Library_Name use "dummy";
18416 for Library_Interface use ("int1", "int1.child");
18421 Attribute @code{Library_Interface} has a non-empty string list value,
18422 each string in the list designating a unit contained in an immediate source
18423 of the project file.
18425 When a Stand-alone Library is built, first the binder is invoked to build
18426 a package whose name depends on the library name
18427 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
18428 This binder-generated package includes initialization and
18429 finalization procedures whose
18430 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
18432 above). The object corresponding to this package is included in the library.
18434 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
18435 calling of these procedures if a static SAL is built, or if a shared SAL
18437 with the project-level attribute @code{Library_Auto_Init} set to
18440 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
18441 (those that are listed in attribute @code{Library_Interface}) are copied to
18442 the Library Directory. As a consequence, only the Interface Units may be
18443 imported from Ada units outside of the library. If other units are imported,
18444 the binding phase will fail.
18446 The attribute @code{Library_Src_Dir} may be specified for a
18447 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
18448 single string value. Its value must be the path (absolute or relative to the
18449 project directory) of an existing directory. This directory cannot be the
18450 object directory or one of the source directories, but it can be the same as
18451 the library directory. The sources of the Interface
18452 Units of the library that are needed by an Ada client of the library will be
18453 copied to the designated directory, called the Interface Copy directory.
18454 These sources include the specs of the Interface Units, but they may also
18455 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
18456 are used, or when there is a generic unit in the spec. Before the sources
18457 are copied to the Interface Copy directory, an attempt is made to delete all
18458 files in the Interface Copy directory.
18460 Building stand-alone libraries by hand is somewhat tedious, but for those
18461 occasions when it is necessary here are the steps that you need to perform:
18464 Compile all library sources.
18467 Invoke the binder with the switch @option{-n} (No Ada main program),
18468 with all the @file{ALI} files of the interfaces, and
18469 with the switch @option{-L} to give specific names to the @code{init}
18470 and @code{final} procedures. For example:
18472 gnatbind -n int1.ali int2.ali -Lsal1
18476 Compile the binder generated file:
18482 Link the dynamic library with all the necessary object files,
18483 indicating to the linker the names of the @code{init} (and possibly
18484 @code{final}) procedures for automatic initialization (and finalization).
18485 The built library should be placed in a directory different from
18486 the object directory.
18489 Copy the @code{ALI} files of the interface to the library directory,
18490 add in this copy an indication that it is an interface to a SAL
18491 (i.e. add a word @option{SL} on the line in the @file{ALI} file that starts
18492 with letter ``P'') and make the modified copy of the @file{ALI} file
18497 Using SALs is not different from using other libraries
18498 (see @ref{Using a library}).
18500 @node Creating a Stand-alone Library to be used in a non-Ada context
18501 @subsection Creating a Stand-alone Library to be used in a non-Ada context
18504 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
18507 The only extra step required is to ensure that library interface subprograms
18508 are compatible with the main program, by means of @code{pragma Export}
18509 or @code{pragma Convention}.
18511 Here is an example of simple library interface for use with C main program:
18513 @smallexample @c ada
18514 package Interface is
18516 procedure Do_Something;
18517 pragma Export (C, Do_Something, "do_something");
18519 procedure Do_Something_Else;
18520 pragma Export (C, Do_Something_Else, "do_something_else");
18526 On the foreign language side, you must provide a ``foreign'' view of the
18527 library interface; remember that it should contain elaboration routines in
18528 addition to interface subprograms.
18530 The example below shows the content of @code{mylib_interface.h} (note
18531 that there is no rule for the naming of this file, any name can be used)
18533 /* the library elaboration procedure */
18534 extern void mylibinit (void);
18536 /* the library finalization procedure */
18537 extern void mylibfinal (void);
18539 /* the interface exported by the library */
18540 extern void do_something (void);
18541 extern void do_something_else (void);
18545 Libraries built as explained above can be used from any program, provided
18546 that the elaboration procedures (named @code{mylibinit} in the previous
18547 example) are called before the library services are used. Any number of
18548 libraries can be used simultaneously, as long as the elaboration
18549 procedure of each library is called.
18551 Below is an example of a C program that uses the @code{mylib} library.
18554 #include "mylib_interface.h"
18559 /* First, elaborate the library before using it */
18562 /* Main program, using the library exported entities */
18564 do_something_else ();
18566 /* Library finalization at the end of the program */
18573 Note that invoking any library finalization procedure generated by
18574 @code{gnatbind} shuts down the Ada run-time environment.
18576 finalization of all Ada libraries must be performed at the end of the program.
18577 No call to these libraries or to the Ada run-time library should be made
18578 after the finalization phase.
18580 @node Restrictions in Stand-alone Libraries
18581 @subsection Restrictions in Stand-alone Libraries
18584 The pragmas listed below should be used with caution inside libraries,
18585 as they can create incompatibilities with other Ada libraries:
18587 @item pragma @code{Locking_Policy}
18588 @item pragma @code{Queuing_Policy}
18589 @item pragma @code{Task_Dispatching_Policy}
18590 @item pragma @code{Unreserve_All_Interrupts}
18594 When using a library that contains such pragmas, the user must make sure
18595 that all libraries use the same pragmas with the same values. Otherwise,
18596 @code{Program_Error} will
18597 be raised during the elaboration of the conflicting
18598 libraries. The usage of these pragmas and its consequences for the user
18599 should therefore be well documented.
18601 Similarly, the traceback in the exception occurrence mechanism should be
18602 enabled or disabled in a consistent manner across all libraries.
18603 Otherwise, Program_Error will be raised during the elaboration of the
18604 conflicting libraries.
18606 If the @code{Version} or @code{Body_Version}
18607 attributes are used inside a library, then you need to
18608 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
18609 libraries, so that version identifiers can be properly computed.
18610 In practice these attributes are rarely used, so this is unlikely
18611 to be a consideration.
18613 @node Rebuilding the GNAT Run-Time Library
18614 @section Rebuilding the GNAT Run-Time Library
18615 @cindex GNAT Run-Time Library, rebuilding
18616 @cindex Building the GNAT Run-Time Library
18617 @cindex Rebuilding the GNAT Run-Time Library
18618 @cindex Run-Time Library, rebuilding
18621 It may be useful to recompile the GNAT library in various contexts, the
18622 most important one being the use of partition-wide configuration pragmas
18623 such as @code{Normalize_Scalars}. A special Makefile called
18624 @code{Makefile.adalib} is provided to that effect and can be found in
18625 the directory containing the GNAT library. The location of this
18626 directory depends on the way the GNAT environment has been installed and can
18627 be determined by means of the command:
18634 The last entry in the object search path usually contains the
18635 gnat library. This Makefile contains its own documentation and in
18636 particular the set of instructions needed to rebuild a new library and
18639 @node Using the GNU make Utility
18640 @chapter Using the GNU @code{make} Utility
18644 This chapter offers some examples of makefiles that solve specific
18645 problems. It does not explain how to write a makefile (see the GNU make
18646 documentation), nor does it try to replace the @command{gnatmake} utility
18647 (@pxref{The GNAT Make Program gnatmake}).
18649 All the examples in this section are specific to the GNU version of
18650 make. Although @command{make} is a standard utility, and the basic language
18651 is the same, these examples use some advanced features found only in
18655 * Using gnatmake in a Makefile::
18656 * Automatically Creating a List of Directories::
18657 * Generating the Command Line Switches::
18658 * Overcoming Command Line Length Limits::
18661 @node Using gnatmake in a Makefile
18662 @section Using gnatmake in a Makefile
18667 Complex project organizations can be handled in a very powerful way by
18668 using GNU make combined with gnatmake. For instance, here is a Makefile
18669 which allows you to build each subsystem of a big project into a separate
18670 shared library. Such a makefile allows you to significantly reduce the link
18671 time of very big applications while maintaining full coherence at
18672 each step of the build process.
18674 The list of dependencies are handled automatically by
18675 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
18676 the appropriate directories.
18678 Note that you should also read the example on how to automatically
18679 create the list of directories
18680 (@pxref{Automatically Creating a List of Directories})
18681 which might help you in case your project has a lot of subdirectories.
18686 @font@heightrm=cmr8
18689 ## This Makefile is intended to be used with the following directory
18691 ## - The sources are split into a series of csc (computer software components)
18692 ## Each of these csc is put in its own directory.
18693 ## Their name are referenced by the directory names.
18694 ## They will be compiled into shared library (although this would also work
18695 ## with static libraries
18696 ## - The main program (and possibly other packages that do not belong to any
18697 ## csc is put in the top level directory (where the Makefile is).
18698 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
18699 ## \_ second_csc (sources) __ lib (will contain the library)
18701 ## Although this Makefile is build for shared library, it is easy to modify
18702 ## to build partial link objects instead (modify the lines with -shared and
18705 ## With this makefile, you can change any file in the system or add any new
18706 ## file, and everything will be recompiled correctly (only the relevant shared
18707 ## objects will be recompiled, and the main program will be re-linked).
18709 # The list of computer software component for your project. This might be
18710 # generated automatically.
18713 # Name of the main program (no extension)
18716 # If we need to build objects with -fPIC, uncomment the following line
18719 # The following variable should give the directory containing libgnat.so
18720 # You can get this directory through 'gnatls -v'. This is usually the last
18721 # directory in the Object_Path.
18724 # The directories for the libraries
18725 # (This macro expands the list of CSC to the list of shared libraries, you
18726 # could simply use the expanded form:
18727 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
18728 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
18730 $@{MAIN@}: objects $@{LIB_DIR@}
18731 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
18732 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
18735 # recompile the sources
18736 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
18738 # Note: In a future version of GNAT, the following commands will be simplified
18739 # by a new tool, gnatmlib
18741 mkdir -p $@{dir $@@ @}
18742 cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
18743 cd $@{dir $@@ @} && cp -f ../*.ali .
18745 # The dependencies for the modules
18746 # Note that we have to force the expansion of *.o, since in some cases
18747 # make won't be able to do it itself.
18748 aa/lib/libaa.so: $@{wildcard aa/*.o@}
18749 bb/lib/libbb.so: $@{wildcard bb/*.o@}
18750 cc/lib/libcc.so: $@{wildcard cc/*.o@}
18752 # Make sure all of the shared libraries are in the path before starting the
18755 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
18758 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
18759 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
18760 $@{RM@} $@{CSC_LIST:%=%/*.o@}
18761 $@{RM@} *.o *.ali $@{MAIN@}
18764 @node Automatically Creating a List of Directories
18765 @section Automatically Creating a List of Directories
18768 In most makefiles, you will have to specify a list of directories, and
18769 store it in a variable. For small projects, it is often easier to
18770 specify each of them by hand, since you then have full control over what
18771 is the proper order for these directories, which ones should be
18774 However, in larger projects, which might involve hundreds of
18775 subdirectories, it might be more convenient to generate this list
18778 The example below presents two methods. The first one, although less
18779 general, gives you more control over the list. It involves wildcard
18780 characters, that are automatically expanded by @command{make}. Its
18781 shortcoming is that you need to explicitly specify some of the
18782 organization of your project, such as for instance the directory tree
18783 depth, whether some directories are found in a separate tree,...
18785 The second method is the most general one. It requires an external
18786 program, called @command{find}, which is standard on all Unix systems. All
18787 the directories found under a given root directory will be added to the
18793 @font@heightrm=cmr8
18796 # The examples below are based on the following directory hierarchy:
18797 # All the directories can contain any number of files
18798 # ROOT_DIRECTORY -> a -> aa -> aaa
18801 # -> b -> ba -> baa
18804 # This Makefile creates a variable called DIRS, that can be reused any time
18805 # you need this list (see the other examples in this section)
18807 # The root of your project's directory hierarchy
18811 # First method: specify explicitly the list of directories
18812 # This allows you to specify any subset of all the directories you need.
18815 DIRS := a/aa/ a/ab/ b/ba/
18818 # Second method: use wildcards
18819 # Note that the argument(s) to wildcard below should end with a '/'.
18820 # Since wildcards also return file names, we have to filter them out
18821 # to avoid duplicate directory names.
18822 # We thus use make's @code{dir} and @code{sort} functions.
18823 # It sets DIRs to the following value (note that the directories aaa and baa
18824 # are not given, unless you change the arguments to wildcard).
18825 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
18828 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
18829 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
18832 # Third method: use an external program
18833 # This command is much faster if run on local disks, avoiding NFS slowdowns.
18834 # This is the most complete command: it sets DIRs to the following value:
18835 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
18838 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
18842 @node Generating the Command Line Switches
18843 @section Generating the Command Line Switches
18846 Once you have created the list of directories as explained in the
18847 previous section (@pxref{Automatically Creating a List of Directories}),
18848 you can easily generate the command line arguments to pass to gnatmake.
18850 For the sake of completeness, this example assumes that the source path
18851 is not the same as the object path, and that you have two separate lists
18855 # see "Automatically creating a list of directories" to create
18860 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
18861 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
18864 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
18867 @node Overcoming Command Line Length Limits
18868 @section Overcoming Command Line Length Limits
18871 One problem that might be encountered on big projects is that many
18872 operating systems limit the length of the command line. It is thus hard to give
18873 gnatmake the list of source and object directories.
18875 This example shows how you can set up environment variables, which will
18876 make @command{gnatmake} behave exactly as if the directories had been
18877 specified on the command line, but have a much higher length limit (or
18878 even none on most systems).
18880 It assumes that you have created a list of directories in your Makefile,
18881 using one of the methods presented in
18882 @ref{Automatically Creating a List of Directories}.
18883 For the sake of completeness, we assume that the object
18884 path (where the ALI files are found) is different from the sources patch.
18886 Note a small trick in the Makefile below: for efficiency reasons, we
18887 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
18888 expanded immediately by @code{make}. This way we overcome the standard
18889 make behavior which is to expand the variables only when they are
18892 On Windows, if you are using the standard Windows command shell, you must
18893 replace colons with semicolons in the assignments to these variables.
18898 @font@heightrm=cmr8
18901 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
18902 # This is the same thing as putting the -I arguments on the command line.
18903 # (the equivalent of using -aI on the command line would be to define
18904 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
18905 # You can of course have different values for these variables.
18907 # Note also that we need to keep the previous values of these variables, since
18908 # they might have been set before running 'make' to specify where the GNAT
18909 # library is installed.
18911 # see "Automatically creating a list of directories" to create these
18917 space:=$@{empty@} $@{empty@}
18918 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
18919 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
18920 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
18921 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
18922 export ADA_INCLUDE_PATH
18923 export ADA_OBJECT_PATH
18930 @node Memory Management Issues
18931 @chapter Memory Management Issues
18934 This chapter describes some useful memory pools provided in the GNAT library
18935 and in particular the GNAT Debug Pool facility, which can be used to detect
18936 incorrect uses of access values (including ``dangling references'').
18938 It also describes the @command{gnatmem} tool, which can be used to track down
18943 * Some Useful Memory Pools::
18944 * The GNAT Debug Pool Facility::
18946 * The gnatmem Tool::
18950 @node Some Useful Memory Pools
18951 @section Some Useful Memory Pools
18952 @findex Memory Pool
18953 @cindex storage, pool
18956 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
18957 storage pool. Allocations use the standard system call @code{malloc} while
18958 deallocations use the standard system call @code{free}. No reclamation is
18959 performed when the pool goes out of scope. For performance reasons, the
18960 standard default Ada allocators/deallocators do not use any explicit storage
18961 pools but if they did, they could use this storage pool without any change in
18962 behavior. That is why this storage pool is used when the user
18963 manages to make the default implicit allocator explicit as in this example:
18964 @smallexample @c ada
18965 type T1 is access Something;
18966 -- no Storage pool is defined for T2
18967 type T2 is access Something_Else;
18968 for T2'Storage_Pool use T1'Storage_Pool;
18969 -- the above is equivalent to
18970 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
18974 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
18975 pool. The allocation strategy is similar to @code{Pool_Local}'s
18976 except that the all
18977 storage allocated with this pool is reclaimed when the pool object goes out of
18978 scope. This pool provides a explicit mechanism similar to the implicit one
18979 provided by several Ada 83 compilers for allocations performed through a local
18980 access type and whose purpose was to reclaim memory when exiting the
18981 scope of a given local access. As an example, the following program does not
18982 leak memory even though it does not perform explicit deallocation:
18984 @smallexample @c ada
18985 with System.Pool_Local;
18986 procedure Pooloc1 is
18987 procedure Internal is
18988 type A is access Integer;
18989 X : System.Pool_Local.Unbounded_Reclaim_Pool;
18990 for A'Storage_Pool use X;
18993 for I in 1 .. 50 loop
18998 for I in 1 .. 100 loop
19005 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
19006 @code{Storage_Size} is specified for an access type.
19007 The whole storage for the pool is
19008 allocated at once, usually on the stack at the point where the access type is
19009 elaborated. It is automatically reclaimed when exiting the scope where the
19010 access type is defined. This package is not intended to be used directly by the
19011 user and it is implicitly used for each such declaration:
19013 @smallexample @c ada
19014 type T1 is access Something;
19015 for T1'Storage_Size use 10_000;
19018 @node The GNAT Debug Pool Facility
19019 @section The GNAT Debug Pool Facility
19021 @cindex storage, pool, memory corruption
19024 The use of unchecked deallocation and unchecked conversion can easily
19025 lead to incorrect memory references. The problems generated by such
19026 references are usually difficult to tackle because the symptoms can be
19027 very remote from the origin of the problem. In such cases, it is
19028 very helpful to detect the problem as early as possible. This is the
19029 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
19031 In order to use the GNAT specific debugging pool, the user must
19032 associate a debug pool object with each of the access types that may be
19033 related to suspected memory problems. See Ada Reference Manual 13.11.
19034 @smallexample @c ada
19035 type Ptr is access Some_Type;
19036 Pool : GNAT.Debug_Pools.Debug_Pool;
19037 for Ptr'Storage_Pool use Pool;
19041 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
19042 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
19043 allow the user to redefine allocation and deallocation strategies. They
19044 also provide a checkpoint for each dereference, through the use of
19045 the primitive operation @code{Dereference} which is implicitly called at
19046 each dereference of an access value.
19048 Once an access type has been associated with a debug pool, operations on
19049 values of the type may raise four distinct exceptions,
19050 which correspond to four potential kinds of memory corruption:
19053 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
19055 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
19057 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
19059 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
19063 For types associated with a Debug_Pool, dynamic allocation is performed using
19064 the standard GNAT allocation routine. References to all allocated chunks of
19065 memory are kept in an internal dictionary. Several deallocation strategies are
19066 provided, whereupon the user can choose to release the memory to the system,
19067 keep it allocated for further invalid access checks, or fill it with an easily
19068 recognizable pattern for debug sessions. The memory pattern is the old IBM
19069 hexadecimal convention: @code{16#DEADBEEF#}.
19071 See the documentation in the file g-debpoo.ads for more information on the
19072 various strategies.
19074 Upon each dereference, a check is made that the access value denotes a
19075 properly allocated memory location. Here is a complete example of use of
19076 @code{Debug_Pools}, that includes typical instances of memory corruption:
19077 @smallexample @c ada
19081 with Gnat.Io; use Gnat.Io;
19082 with Unchecked_Deallocation;
19083 with Unchecked_Conversion;
19084 with GNAT.Debug_Pools;
19085 with System.Storage_Elements;
19086 with Ada.Exceptions; use Ada.Exceptions;
19087 procedure Debug_Pool_Test is
19089 type T is access Integer;
19090 type U is access all T;
19092 P : GNAT.Debug_Pools.Debug_Pool;
19093 for T'Storage_Pool use P;
19095 procedure Free is new Unchecked_Deallocation (Integer, T);
19096 function UC is new Unchecked_Conversion (U, T);
19099 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
19109 Put_Line (Integer'Image(B.all));
19111 when E : others => Put_Line ("raised: " & Exception_Name (E));
19116 when E : others => Put_Line ("raised: " & Exception_Name (E));
19120 Put_Line (Integer'Image(B.all));
19122 when E : others => Put_Line ("raised: " & Exception_Name (E));
19127 when E : others => Put_Line ("raised: " & Exception_Name (E));
19130 end Debug_Pool_Test;
19134 The debug pool mechanism provides the following precise diagnostics on the
19135 execution of this erroneous program:
19138 Total allocated bytes : 0
19139 Total deallocated bytes : 0
19140 Current Water Mark: 0
19144 Total allocated bytes : 8
19145 Total deallocated bytes : 0
19146 Current Water Mark: 8
19149 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
19150 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
19151 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
19152 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
19154 Total allocated bytes : 8
19155 Total deallocated bytes : 4
19156 Current Water Mark: 4
19161 @node The gnatmem Tool
19162 @section The @command{gnatmem} Tool
19166 The @code{gnatmem} utility monitors dynamic allocation and
19167 deallocation activity in a program, and displays information about
19168 incorrect deallocations and possible sources of memory leaks.
19169 It provides three type of information:
19172 General information concerning memory management, such as the total
19173 number of allocations and deallocations, the amount of allocated
19174 memory and the high water mark, i.e. the largest amount of allocated
19175 memory in the course of program execution.
19178 Backtraces for all incorrect deallocations, that is to say deallocations
19179 which do not correspond to a valid allocation.
19182 Information on each allocation that is potentially the origin of a memory
19187 * Running gnatmem::
19188 * Switches for gnatmem::
19189 * Example of gnatmem Usage::
19192 @node Running gnatmem
19193 @subsection Running @code{gnatmem}
19196 @code{gnatmem} makes use of the output created by the special version of
19197 allocation and deallocation routines that record call information. This
19198 allows to obtain accurate dynamic memory usage history at a minimal cost to
19199 the execution speed. Note however, that @code{gnatmem} is not supported on
19200 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
19201 Solaris and Windows NT/2000/XP (x86).
19204 The @code{gnatmem} command has the form
19207 $ gnatmem [switches] user_program
19211 The program must have been linked with the instrumented version of the
19212 allocation and deallocation routines. This is done by linking with the
19213 @file{libgmem.a} library. For correct symbolic backtrace information,
19214 the user program should be compiled with debugging options
19215 (see @ref{Switches for gcc}). For example to build @file{my_program}:
19218 $ gnatmake -g my_program -largs -lgmem
19222 As library @file{libgmem.a} contains an alternate body for package
19223 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
19224 when an executable is linked with library @file{libgmem.a}. It is then not
19225 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
19228 When @file{my_program} is executed, the file @file{gmem.out} is produced.
19229 This file contains information about all allocations and deallocations
19230 performed by the program. It is produced by the instrumented allocations and
19231 deallocations routines and will be used by @code{gnatmem}.
19233 In order to produce symbolic backtrace information for allocations and
19234 deallocations performed by the GNAT run-time library, you need to use a
19235 version of that library that has been compiled with the @option{-g} switch
19236 (see @ref{Rebuilding the GNAT Run-Time Library}).
19238 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
19239 examine. If the location of @file{gmem.out} file was not explicitly supplied by
19240 @option{-i} switch, gnatmem will assume that this file can be found in the
19241 current directory. For example, after you have executed @file{my_program},
19242 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
19245 $ gnatmem my_program
19249 This will produce the output with the following format:
19251 *************** debut cc
19253 $ gnatmem my_program
19257 Total number of allocations : 45
19258 Total number of deallocations : 6
19259 Final Water Mark (non freed mem) : 11.29 Kilobytes
19260 High Water Mark : 11.40 Kilobytes
19265 Allocation Root # 2
19266 -------------------
19267 Number of non freed allocations : 11
19268 Final Water Mark (non freed mem) : 1.16 Kilobytes
19269 High Water Mark : 1.27 Kilobytes
19271 my_program.adb:23 my_program.alloc
19277 The first block of output gives general information. In this case, the
19278 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
19279 Unchecked_Deallocation routine occurred.
19282 Subsequent paragraphs display information on all allocation roots.
19283 An allocation root is a specific point in the execution of the program
19284 that generates some dynamic allocation, such as a ``@code{@b{new}}''
19285 construct. This root is represented by an execution backtrace (or subprogram
19286 call stack). By default the backtrace depth for allocations roots is 1, so
19287 that a root corresponds exactly to a source location. The backtrace can
19288 be made deeper, to make the root more specific.
19290 @node Switches for gnatmem
19291 @subsection Switches for @code{gnatmem}
19294 @code{gnatmem} recognizes the following switches:
19299 @cindex @option{-q} (@code{gnatmem})
19300 Quiet. Gives the minimum output needed to identify the origin of the
19301 memory leaks. Omits statistical information.
19304 @cindex @var{N} (@code{gnatmem})
19305 N is an integer literal (usually between 1 and 10) which controls the
19306 depth of the backtraces defining allocation root. The default value for
19307 N is 1. The deeper the backtrace, the more precise the localization of
19308 the root. Note that the total number of roots can depend on this
19309 parameter. This parameter must be specified @emph{before} the name of the
19310 executable to be analyzed, to avoid ambiguity.
19313 @cindex @option{-b} (@code{gnatmem})
19314 This switch has the same effect as just depth parameter.
19316 @item -i @var{file}
19317 @cindex @option{-i} (@code{gnatmem})
19318 Do the @code{gnatmem} processing starting from @file{file}, rather than
19319 @file{gmem.out} in the current directory.
19322 @cindex @option{-m} (@code{gnatmem})
19323 This switch causes @code{gnatmem} to mask the allocation roots that have less
19324 than n leaks. The default value is 1. Specifying the value of 0 will allow to
19325 examine even the roots that didn't result in leaks.
19328 @cindex @option{-s} (@code{gnatmem})
19329 This switch causes @code{gnatmem} to sort the allocation roots according to the
19330 specified order of sort criteria, each identified by a single letter. The
19331 currently supported criteria are @code{n, h, w} standing respectively for
19332 number of unfreed allocations, high watermark, and final watermark
19333 corresponding to a specific root. The default order is @code{nwh}.
19337 @node Example of gnatmem Usage
19338 @subsection Example of @code{gnatmem} Usage
19341 The following example shows the use of @code{gnatmem}
19342 on a simple memory-leaking program.
19343 Suppose that we have the following Ada program:
19345 @smallexample @c ada
19348 with Unchecked_Deallocation;
19349 procedure Test_Gm is
19351 type T is array (1..1000) of Integer;
19352 type Ptr is access T;
19353 procedure Free is new Unchecked_Deallocation (T, Ptr);
19356 procedure My_Alloc is
19361 procedure My_DeAlloc is
19369 for I in 1 .. 5 loop
19370 for J in I .. 5 loop
19381 The program needs to be compiled with debugging option and linked with
19382 @code{gmem} library:
19385 $ gnatmake -g test_gm -largs -lgmem
19389 Then we execute the program as usual:
19396 Then @code{gnatmem} is invoked simply with
19402 which produces the following output (result may vary on different platforms):
19407 Total number of allocations : 18
19408 Total number of deallocations : 5
19409 Final Water Mark (non freed mem) : 53.00 Kilobytes
19410 High Water Mark : 56.90 Kilobytes
19412 Allocation Root # 1
19413 -------------------
19414 Number of non freed allocations : 11
19415 Final Water Mark (non freed mem) : 42.97 Kilobytes
19416 High Water Mark : 46.88 Kilobytes
19418 test_gm.adb:11 test_gm.my_alloc
19420 Allocation Root # 2
19421 -------------------
19422 Number of non freed allocations : 1
19423 Final Water Mark (non freed mem) : 10.02 Kilobytes
19424 High Water Mark : 10.02 Kilobytes
19426 s-secsta.adb:81 system.secondary_stack.ss_init
19428 Allocation Root # 3
19429 -------------------
19430 Number of non freed allocations : 1
19431 Final Water Mark (non freed mem) : 12 Bytes
19432 High Water Mark : 12 Bytes
19434 s-secsta.adb:181 system.secondary_stack.ss_init
19438 Note that the GNAT run time contains itself a certain number of
19439 allocations that have no corresponding deallocation,
19440 as shown here for root #2 and root
19441 #3. This is a normal behavior when the number of non freed allocations
19442 is one, it allocates dynamic data structures that the run time needs for
19443 the complete lifetime of the program. Note also that there is only one
19444 allocation root in the user program with a single line back trace:
19445 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
19446 program shows that 'My_Alloc' is called at 2 different points in the
19447 source (line 21 and line 24). If those two allocation roots need to be
19448 distinguished, the backtrace depth parameter can be used:
19451 $ gnatmem 3 test_gm
19455 which will give the following output:
19460 Total number of allocations : 18
19461 Total number of deallocations : 5
19462 Final Water Mark (non freed mem) : 53.00 Kilobytes
19463 High Water Mark : 56.90 Kilobytes
19465 Allocation Root # 1
19466 -------------------
19467 Number of non freed allocations : 10
19468 Final Water Mark (non freed mem) : 39.06 Kilobytes
19469 High Water Mark : 42.97 Kilobytes
19471 test_gm.adb:11 test_gm.my_alloc
19472 test_gm.adb:24 test_gm
19473 b_test_gm.c:52 main
19475 Allocation Root # 2
19476 -------------------
19477 Number of non freed allocations : 1
19478 Final Water Mark (non freed mem) : 10.02 Kilobytes
19479 High Water Mark : 10.02 Kilobytes
19481 s-secsta.adb:81 system.secondary_stack.ss_init
19482 s-secsta.adb:283 <system__secondary_stack___elabb>
19483 b_test_gm.c:33 adainit
19485 Allocation Root # 3
19486 -------------------
19487 Number of non freed allocations : 1
19488 Final Water Mark (non freed mem) : 3.91 Kilobytes
19489 High Water Mark : 3.91 Kilobytes
19491 test_gm.adb:11 test_gm.my_alloc
19492 test_gm.adb:21 test_gm
19493 b_test_gm.c:52 main
19495 Allocation Root # 4
19496 -------------------
19497 Number of non freed allocations : 1
19498 Final Water Mark (non freed mem) : 12 Bytes
19499 High Water Mark : 12 Bytes
19501 s-secsta.adb:181 system.secondary_stack.ss_init
19502 s-secsta.adb:283 <system__secondary_stack___elabb>
19503 b_test_gm.c:33 adainit
19507 The allocation root #1 of the first example has been split in 2 roots #1
19508 and #3 thanks to the more precise associated backtrace.
19512 @node Stack Related Facilities
19513 @chapter Stack Related Facilities
19516 This chapter describes some useful tools associated with stack
19517 checking and analysis. In
19518 particular, it deals with dynamic and static stack usage measurements.
19521 * Stack Overflow Checking::
19522 * Static Stack Usage Analysis::
19523 * Dynamic Stack Usage Analysis::
19526 @node Stack Overflow Checking
19527 @section Stack Overflow Checking
19528 @cindex Stack Overflow Checking
19529 @cindex -fstack-check
19532 For most operating systems, @command{gcc} does not perform stack overflow
19533 checking by default. This means that if the main environment task or
19534 some other task exceeds the available stack space, then unpredictable
19535 behavior will occur. Most native systems offer some level of protection by
19536 adding a guard page at the end of each task stack. This mechanism is usually
19537 not enough for dealing properly with stack overflow situations because
19538 a large local variable could ``jump'' above the guard page.
19539 Furthermore, when the
19540 guard page is hit, there may not be any space left on the stack for executing
19541 the exception propagation code. Enabling stack checking avoids
19544 To activate stack checking, compile all units with the gcc option
19545 @option{-fstack-check}. For example:
19548 gcc -c -fstack-check package1.adb
19552 Units compiled with this option will generate extra instructions to check
19553 that any use of the stack (for procedure calls or for declaring local
19554 variables in declare blocks) does not exceed the available stack space.
19555 If the space is exceeded, then a @code{Storage_Error} exception is raised.
19557 For declared tasks, the stack size is controlled by the size
19558 given in an applicable @code{Storage_Size} pragma or by the value specified
19559 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
19560 the default size as defined in the GNAT runtime otherwise.
19562 For the environment task, the stack size depends on
19563 system defaults and is unknown to the compiler. Stack checking
19564 may still work correctly if a fixed
19565 size stack is allocated, but this cannot be guaranteed.
19567 To ensure that a clean exception is signalled for stack
19568 overflow, set the environment variable
19569 @code{GNAT_STACK_LIMIT} to indicate the maximum
19570 stack area that can be used, as in:
19571 @cindex GNAT_STACK_LIMIT
19574 SET GNAT_STACK_LIMIT 1600
19578 The limit is given in kilobytes, so the above declaration would
19579 set the stack limit of the environment task to 1.6 megabytes.
19580 Note that the only purpose of this usage is to limit the amount
19581 of stack used by the environment task. If it is necessary to
19582 increase the amount of stack for the environment task, then this
19583 is an operating systems issue, and must be addressed with the
19584 appropriate operating systems commands.
19587 To have a fixed size stack in the environment task, the stack must be put
19588 in the P0 address space and its size specified. Use these switches to
19592 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
19596 The quotes are required to keep case. The number after @samp{STACK=} is the
19597 size of the environmental task stack in pagelets (512 bytes). In this example
19598 the stack size is about 2 megabytes.
19601 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
19602 be placed in P0 space. Refer to @cite{HP OpenVMS Linker Utility Manual} for
19603 more details about the @option{/p0image} qualifier and the @option{stack}
19607 @node Static Stack Usage Analysis
19608 @section Static Stack Usage Analysis
19609 @cindex Static Stack Usage Analysis
19610 @cindex -fstack-usage
19613 A unit compiled with @option{-fstack-usage} will generate an extra file
19615 the maximum amount of stack used, on a per-function basis.
19616 The file has the same
19617 basename as the target object file with a @file{.su} extension.
19618 Each line of this file is made up of three fields:
19622 The name of the function.
19626 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
19629 The second field corresponds to the size of the known part of the function
19632 The qualifier @code{static} means that the function frame size
19634 It usually means that all local variables have a static size.
19635 In this case, the second field is a reliable measure of the function stack
19638 The qualifier @code{dynamic} means that the function frame size is not static.
19639 It happens mainly when some local variables have a dynamic size. When this
19640 qualifier appears alone, the second field is not a reliable measure
19641 of the function stack analysis. When it is qualified with @code{bounded}, it
19642 means that the second field is a reliable maximum of the function stack
19645 @node Dynamic Stack Usage Analysis
19646 @section Dynamic Stack Usage Analysis
19649 It is possible to measure the maximum amount of stack used by a task, by
19650 adding a switch to @command{gnatbind}, as:
19653 $ gnatbind -u0 file
19657 With this option, at each task termination, its stack usage is output on
19659 It is not always convenient to output the stack usage when the program
19660 is still running. Hence, it is possible to delay this output until program
19661 termination. for a given number of tasks specified as the argument of the
19662 @option{-u} option. For instance:
19665 $ gnatbind -u100 file
19669 will buffer the stack usage information of the first 100 tasks to terminate and
19670 output this info at program termination. Results are displayed in four
19674 Index | Task Name | Stack Size | Actual Use [min - max]
19681 is a number associated with each task.
19684 is the name of the task analyzed.
19687 is the maximum size for the stack.
19690 is the measure done by the stack analyzer. In order to prevent overflow,
19691 the stack is not entirely analyzed, and it's not possible to know exactly how
19692 much has actually been used. The real amount of stack used is between the min
19698 The environment task stack, e.g. the stack that contains the main unit, is
19699 only processed when the environment variable GNAT_STACK_LIMIT is set.
19702 @c *********************************
19704 @c *********************************
19705 @node Verifying Properties Using gnatcheck
19706 @chapter Verifying Properties Using @command{gnatcheck}
19708 @cindex @command{gnatcheck}
19711 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
19712 of Ada source files according to a given set of semantic rules.
19715 In order to check compliance with a given rule, @command{gnatcheck} has to
19716 semantically analyze the Ada sources.
19717 Therefore, checks can only be performed on
19718 legal Ada units. Moreover, when a unit depends semantically upon units located
19719 outside the current directory, the source search path has to be provided when
19720 calling @command{gnatcheck}, either through a specified project file or
19721 through @command{gnatcheck} switches as described below.
19723 A number of rules are predefined in @command{gnatcheck} and are described
19724 later in this chapter.
19725 You can also add new rules, by modifying the @command{gnatcheck} code and
19726 rebuilding the tool. In order to add a simple rule making some local checks,
19727 a small amount of straightforward ASIS-based programming is usually needed.
19729 Project support for @command{gnatcheck} is provided by the GNAT
19730 driver (see @ref{The GNAT Driver and Project Files}).
19732 Invoking @command{gnatcheck} on the command line has the form:
19735 $ gnatcheck [@i{switches}] @{@i{filename}@}
19736 [^-files^/FILES^=@{@i{arg_list_filename}@}]
19737 [-cargs @i{gcc_switches}] [-rules @i{rule_options}]
19744 @i{switches} specify the general tool options
19747 Each @i{filename} is the name (including the extension) of a source
19748 file to process. ``Wildcards'' are allowed, and
19749 the file name may contain path information.
19752 Each @i{arg_list_filename} is the name (including the extension) of a text
19753 file containing the names of the source files to process, separated by spaces
19757 @i{gcc_switches} is a list of switches for
19758 @command{gcc}. They will be passed on to all compiler invocations made by
19759 @command{gnatcheck} to generate the ASIS trees. Here you can provide
19760 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19761 and use the @option{-gnatec} switch to set the configuration file.
19764 @i{rule_options} is a list of options for controlling a set of
19765 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
19769 Either a @i{filename} or an @i{arg_list_filename} must be supplied.
19772 * Format of the Report File::
19773 * General gnatcheck Switches::
19774 * gnatcheck Rule Options::
19775 * Adding the Results of Compiler Checks to gnatcheck Output::
19776 * Project-Wide Checks::
19777 * Predefined Rules::
19780 @node Format of the Report File
19781 @section Format of the Report File
19782 @cindex Report file (for @code{gnatcheck})
19785 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
19787 It also creates, in the current
19788 directory, a text file named @file{^gnatcheck.out^GNATCHECK.OUT^} that
19789 contains the complete report of the last gnatcheck run. This report contains:
19791 @item a list of the Ada source files being checked,
19792 @item a list of enabled and disabled rules,
19793 @item a list of the diagnostic messages, ordered in three different ways
19794 and collected in three separate
19795 sections. Section 1 contains the raw list of diagnostic messages. It
19796 corresponds to the output going to @file{stdout}. Section 2 contains
19797 messages ordered by rules.
19798 Section 3 contains messages ordered by source files.
19801 @node General gnatcheck Switches
19802 @section General @command{gnatcheck} Switches
19805 The following switches control the general @command{gnatcheck} behavior
19809 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
19811 Process all units including those with read-only ALI files such as
19812 those from GNAT Run-Time library.
19816 @cindex @option{-d} (@command{gnatcheck})
19821 @cindex @option{-dd} (@command{gnatcheck})
19823 Progress indicator mode (for use in GPS)
19826 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
19828 List the predefined and user-defined rules. For more details see
19829 @ref{Predefined Rules}.
19831 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
19833 Use full source locations references in the report file. For a construct from
19834 a generic instantiation a full source location is a chain from the location
19835 of this construct in the generic unit to the place where this unit is
19838 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
19840 Quiet mode. All the diagnoses about rule violations are placed in the
19841 @command{gnatcheck} report file only, without duplicating in @file{stdout}.
19843 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
19845 Short format of the report file (no version information, no list of applied
19846 rules, no list of checked sources is included)
19848 @cindex @option{^-s1^/COMPILER_STYLE^} (@command{gnatcheck})
19849 @item ^-s1^/COMPILER_STYLE^
19850 Include the compiler-style section in the report file
19852 @cindex @option{^-s2^/BY_RULES^} (@command{gnatcheck})
19853 @item ^-s2^/BY_RULES^
19854 Include the section containing diagnoses ordered by rules in the report file
19856 @cindex @option{^-s3^/BY_FILES_BY_RULES^} (@command{gnatcheck})
19857 @item ^-s3^/BY_FILES_BY_RULES^
19858 Include the section containing diagnoses ordered by files and then by rules
19861 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
19862 @item ^-v^/VERBOSE^
19863 Verbose mode; @command{gnatcheck} generates version information and then
19864 a trace of sources being processed.
19869 Note that if any of the options @option{^-s1^/COMPILER_STYLE^},
19870 @option{^-s2^/BY_RULES^} or
19871 @option{^-s3^/BY_FILES_BY_RULES^} is specified,
19872 then the @command{gnatcheck} report file will only contain sections
19873 explicitly denoted by these options.
19875 @node gnatcheck Rule Options
19876 @section @command{gnatcheck} Rule Options
19879 The following options control the processing performed by
19880 @command{gnatcheck}.
19883 @cindex @option{+ALL} (@command{gnatcheck})
19885 Turn all the rule checks ON.
19887 @cindex @option{-ALL} (@command{gnatcheck})
19889 Turn all the rule checks OFF.
19891 @cindex @option{+R} (@command{gnatcheck})
19892 @item +R@i{rule_id[:param]}
19893 Turn on the check for a specified rule with the specified parameter, if any.
19894 @i{rule_id} must be the identifier of one of the currently implemented rules
19895 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
19896 are not case-sensitive. The @i{param} item must
19897 be a string representing a valid parameter(s) for the specified rule.
19898 If it contains any space characters then this string must be enclosed in
19901 @cindex @option{-R} (@command{gnatcheck})
19902 @item -R@i{rule_id[:param]}
19903 Turn off the check for a specified rule with the specified parameter, if any.
19905 @cindex @option{-from} (@command{gnatcheck})
19906 @item -from=@i{rule_option_filename}
19907 Read the rule options from the text file @i{rule_option_filename}, referred as
19908 ``rule file'' below.
19913 The default behavior is that all the rule checks are enabled, except for
19914 the checks performed by the compiler.
19916 and the checks associated with the
19920 A rule file is a text file containing a set of rule options.
19921 @cindex Rule file (for @code{gnatcheck})
19922 The file may contain empty lines and Ada-style comments (comment
19923 lines and end-of-line comments). The rule file has free format; that is,
19924 you do not have to start a new rule option on a new line.
19926 A rule file may contain other @option{-from=@i{rule_option_filename}}
19927 options, each such option being replaced with the content of the
19928 corresponding rule file during the rule files processing. In case a
19929 cycle is detected (that is, @i{rule_file_1} reads rule options from
19930 @i{rule_file_2}, and @i{rule_file_2} reads (directly or indirectly)
19931 rule options from @i{rule_file_1}), the processing
19932 of rule files is interrupted and a part of their content is ignored.
19935 @node Adding the Results of Compiler Checks to gnatcheck Output
19936 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
19939 The @command{gnatcheck} tool can include in the generated diagnostic messages
19941 the report file the results of the checks performed by the compiler. Though
19942 disabled by default, this effect may be obtained by using @option{+R} with
19943 the following rule identifiers and parameters:
19947 To record restrictions violations (that are performed by the compiler if the
19948 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
19950 @code{Restrictions} with the same parameters as pragma
19951 @code{Restrictions} or @code{Restriction_Warnings}.
19954 To record compiler style checks, use the rule named
19955 @code{Style_Checks}. A parameter of this rule can be either @code{All_Checks},
19956 which enables all the style checks, or a string that has exactly the same
19957 structure and semantics as the @code{string_LITERAL} parameter of GNAT pragma
19958 @code{Style_Checks} (for further information about this pragma, please
19959 refer to the @cite{@value{EDITION} Reference Manual}).
19962 To record compiler warnings (@pxref{Warning Message Control}), use the rule
19963 named @code{Warnings} with a parameter that is a valid
19964 @i{static_string_expression} argument of GNAT pragma @code{Warnings}
19965 (for further information about this pragma, please
19966 refer to the @cite{@value{EDITION} Reference Manual}).
19970 @node Project-Wide Checks
19971 @section Project-Wide Checks
19972 @cindex Project-wide checks (for @command{gnatcheck})
19975 In order to perform checks on all units of a given project, you can use
19976 the GNAT driver along with the @option{-P} option:
19978 gnat check -Pproj -rules -from=my_rules
19982 If the project @code{proj} depends upon other projects, you can perform
19983 checks on the project closure using the @option{-U} option:
19985 gnat check -Pproj -U -rules -from=my_rules
19989 Finally, if not all the units are relevant to a particular main
19990 program in the project closure, you can perform checks for the set
19991 of units needed to create a given main program (unit closure) using
19992 the @option{-U} option followed by the name of the main unit:
19994 gnat check -Pproj -U main -rules -from=my_rules
19998 @node Predefined Rules
19999 @section Predefined Rules
20000 @cindex Predefined rules (for @command{gnatcheck})
20003 @c (Jan 2007) Since the global rules are still under development and are not
20004 @c documented, there is no point in explaining the difference between
20005 @c global and local rules
20007 A rule in @command{gnatcheck} is either local or global.
20008 A @emph{local rule} is a rule that applies to a well-defined section
20009 of a program and that can be checked by analyzing only this section.
20010 A @emph{global rule} requires analysis of some global properties of the
20011 whole program (mostly related to the program call graph).
20012 As of @value{NOW}, the implementation of global rules should be
20013 considered to be at a preliminary stage. You can use the
20014 @option{+GLOBAL} option to enable all the global rules, and the
20015 @option{-GLOBAL} rule option to disable all the global rules.
20017 All the global rules in the list below are
20018 so indicated by marking them ``GLOBAL''.
20019 This +GLOBAL and -GLOBAL options are not
20020 included in the list of gnatcheck options above, because at the moment they
20021 are considered as a temporary debug options.
20023 @command{gnatcheck} performs rule checks for generic
20024 instances only for global rules. This limitation may be relaxed in a later
20029 The following subsections document the rules implemented in
20030 @command{gnatcheck}.
20031 The subsection title is the same as the rule identifier, which may be
20032 used as a parameter of the @option{+R} or @option{-R} options.
20036 * Abstract_Type_Declarations::
20037 * Anonymous_Arrays::
20038 * Anonymous_Subtypes::
20040 * Boolean_Relational_Operators::
20042 * Ceiling_Violations::
20044 * Controlled_Type_Declarations::
20045 * Declarations_In_Blocks::
20046 * Default_Parameters::
20047 * Discriminated_Records::
20048 * Enumeration_Ranges_In_CASE_Statements::
20049 * Exceptions_As_Control_Flow::
20050 * EXIT_Statements_With_No_Loop_Name::
20051 * Expanded_Loop_Exit_Names::
20052 * Explicit_Full_Discrete_Ranges::
20053 * Float_Equality_Checks::
20054 * Forbidden_Pragmas::
20055 * Function_Style_Procedures::
20056 * Generics_In_Subprograms::
20057 * GOTO_Statements::
20058 * Implicit_IN_Mode_Parameters::
20059 * Implicit_SMALL_For_Fixed_Point_Types::
20060 * Improperly_Located_Instantiations::
20061 * Improper_Returns::
20062 * Library_Level_Subprograms::
20065 * Improperly_Called_Protected_Entries::
20067 * Misnamed_Identifiers::
20068 * Multiple_Entries_In_Protected_Definitions::
20070 * Non_Qualified_Aggregates::
20071 * Non_Short_Circuit_Operators::
20072 * Non_SPARK_Attributes::
20073 * Non_Tagged_Derived_Types::
20074 * Non_Visible_Exceptions::
20075 * Numeric_Literals::
20076 * OTHERS_In_Aggregates::
20077 * OTHERS_In_CASE_Statements::
20078 * OTHERS_In_Exception_Handlers::
20079 * Outer_Loop_Exits::
20080 * Overloaded_Operators::
20081 * Overly_Nested_Control_Structures::
20082 * Parameters_Out_Of_Order::
20083 * Positional_Actuals_For_Defaulted_Generic_Parameters::
20084 * Positional_Actuals_For_Defaulted_Parameters::
20085 * Positional_Components::
20086 * Positional_Generic_Parameters::
20087 * Positional_Parameters::
20088 * Predefined_Numeric_Types::
20089 * Raising_External_Exceptions::
20090 * Raising_Predefined_Exceptions::
20093 * Side_Effect_Functions::
20096 * Unassigned_OUT_Parameters::
20097 * Uncommented_BEGIN_In_Package_Bodies::
20098 * Unconstrained_Array_Returns::
20099 * Universal_Ranges::
20100 * Unnamed_Blocks_And_Loops::
20102 * Unused_Subprograms::
20104 * USE_PACKAGE_Clauses::
20105 * Volatile_Objects_Without_Address_Clauses::
20109 @node Abstract_Type_Declarations
20110 @subsection @code{Abstract_Type_Declarations}
20111 @cindex @code{Abstract_Type_Declarations} rule (for @command{gnatcheck})
20114 Flag all declarations of abstract types. For an abstract private
20115 type, both the private and full type declarations are flagged.
20117 This rule has no parameters.
20120 @node Anonymous_Arrays
20121 @subsection @code{Anonymous_Arrays}
20122 @cindex @code{Anonymous_Arrays} rule (for @command{gnatcheck})
20125 Flag all anonymous array type definitions (by Ada semantics these can only
20126 occur in object declarations).
20128 This rule has no parameters.
20130 @node Anonymous_Subtypes
20131 @subsection @code{Anonymous_Subtypes}
20132 @cindex @code{Anonymous_Subtypes} rule (for @command{gnatcheck})
20135 Flag all uses of anonymous subtypes. A use of an anonymous subtype is
20136 any instance of a subtype indication with a constraint, other than one
20137 that occurs immediately within a subtype declaration. Any use of a range
20138 other than as a constraint used immediately within a subtype declaration
20139 is considered as an anonymous subtype.
20141 An effect of this rule is that @code{for} loops such as the following are
20142 flagged (since @code{1..N} is formally a ``range''):
20144 @smallexample @c ada
20145 for I in 1 .. N loop
20151 Declaring an explicit subtype solves the problem:
20153 @smallexample @c ada
20154 subtype S is Integer range 1..N;
20162 This rule has no parameters.
20165 @subsection @code{Blocks}
20166 @cindex @code{Blocks} rule (for @command{gnatcheck})
20169 Flag each block statement.
20171 This rule has no parameters.
20173 @node Boolean_Relational_Operators
20174 @subsection @code{Boolean_Relational_Operators}
20175 @cindex @code{Boolean_Relational_Operators} rule (for @command{gnatcheck})
20178 Flag each call to a predefined relational operator (``<'', ``>'', ``<='',
20179 ``>='', ``='' and ``/='') for the predefined Boolean type.
20180 (This rule is useful in enforcing the SPARK language restrictions.)
20182 Calls to predefined relational operators of any type derived from
20183 @code{Standard.Boolean} are not detected. Calls to user-defined functions
20184 with these designators, and uses of operators that are renamings
20185 of the predefined relational operators for @code{Standard.Boolean},
20186 are likewise not detected.
20188 This rule has no parameters.
20191 @node Ceiling_Violations
20192 @subsection @code{Ceiling_Violations} (under construction, GLOBAL)
20193 @cindex @code{Ceiling_Violations} rule (for @command{gnatcheck})
20196 Flag invocations of a protected operation by a task whose priority exceeds
20197 the protected object's ceiling.
20199 As of @value{NOW}, this rule has the following limitations:
20204 We consider only pragmas Priority and Interrupt_Priority as means to define
20205 a task/protected operation priority. We do not consider the effect of using
20206 Ada.Dynamic_Priorities.Set_Priority procedure;
20209 We consider only base task priorities, and no priority inheritance. That is,
20210 we do not make a difference between calls issued during task activation and
20211 execution of the sequence of statements from task body;
20214 Any situation when the priority of protected operation caller is set by a
20215 dynamic expression (that is, the corresponding Priority or
20216 Interrupt_Priority pragma has a non-static expression as an argument) we
20217 treat as a priority inconsistency (and, therefore, detect this situation).
20221 At the moment the notion of the main subprogram is not implemented in
20222 gnatcheck, so any pragma Priority in a library level subprogram body (in case
20223 if this subprogram can be a main subprogram of a partition) changes the
20224 priority of an environment task. So if we have more then one such pragma in
20225 the set of processed sources, the pragma that is processed last, defines the
20226 priority of an environment task.
20228 This rule has no parameters.
20231 @node Controlled_Type_Declarations
20232 @subsection @code{Controlled_Type_Declarations}
20233 @cindex @code{Controlled_Type_Declarations} rule (for @command{gnatcheck})
20236 Flag all declarations of controlled types. A declaration of a private type
20237 is flagged if its full declaration declares a controlled type. A declaration
20238 of a derived type is flagged if its ancestor type is controlled. Subtype
20239 declarations are not checked. A declaration of a type that itself is not a
20240 descendant of a type declared in @code{Ada.Finalization} but has a controlled
20241 component is not checked.
20243 This rule has no parameters.
20247 @node Declarations_In_Blocks
20248 @subsection @code{Declarations_In_Blocks}
20249 @cindex @code{Declarations_In_Blocks} rule (for @command{gnatcheck})
20252 Flag all block statements containing local declarations. A @code{declare}
20253 block with an empty @i{declarative_part} or with a @i{declarative part}
20254 containing only pragmas and/or @code{use} clauses is not flagged.
20256 This rule has no parameters.
20259 @node Default_Parameters
20260 @subsection @code{Default_Parameters}
20261 @cindex @code{Default_Parameters} rule (for @command{gnatcheck})
20264 Flag all default expressions for subprogram parameters. Parameter
20265 declarations of formal and generic subprograms are also checked.
20267 This rule has no parameters.
20270 @node Discriminated_Records
20271 @subsection @code{Discriminated_Records}
20272 @cindex @code{Discriminated_Records} rule (for @command{gnatcheck})
20275 Flag all declarations of record types with discriminants. Only the
20276 declarations of record and record extension types are checked. Incomplete,
20277 formal, private, derived and private extension type declarations are not
20278 checked. Task and protected type declarations also are not checked.
20280 This rule has no parameters.
20283 @node Enumeration_Ranges_In_CASE_Statements
20284 @subsection @code{Enumeration_Ranges_In_CASE_Statements}
20285 @cindex @code{Enumeration_Ranges_In_CASE_Statements} (for @command{gnatcheck})
20288 Flag each use of a range of enumeration literals as a choice in a
20289 @code{case} statement.
20290 All forms for specifying a range (explicit ranges
20291 such as @code{A .. B}, subtype marks and @code{'Range} attributes) are flagged.
20292 An enumeration range is
20293 flagged even if contains exactly one enumeration value or no values at all. A
20294 type derived from an enumeration type is considered as an enumeration type.
20296 This rule helps prevent maintenance problems arising from adding an
20297 enumeration value to a type and having it implicitly handled by an existing
20298 @code{case} statement with an enumeration range that includes the new literal.
20300 This rule has no parameters.
20303 @node Exceptions_As_Control_Flow
20304 @subsection @code{Exceptions_As_Control_Flow}
20305 @cindex @code{Exceptions_As_Control_Flow} (for @command{gnatcheck})
20308 Flag each place where an exception is explicitly raised and handled in the
20309 same subprogram body. A @code{raise} statement in an exception handler,
20310 package body, task body or entry body is not flagged.
20312 The rule has no parameters.
20314 @node EXIT_Statements_With_No_Loop_Name
20315 @subsection @code{EXIT_Statements_With_No_Loop_Name}
20316 @cindex @code{EXIT_Statements_With_No_Loop_Name} (for @command{gnatcheck})
20319 Flag each @code{exit} statement that does not specify the name of the loop
20322 The rule has no parameters.
20325 @node Expanded_Loop_Exit_Names
20326 @subsection @code{Expanded_Loop_Exit_Names}
20327 @cindex @code{Expanded_Loop_Exit_Names} rule (for @command{gnatcheck})
20330 Flag all expanded loop names in @code{exit} statements.
20332 This rule has no parameters.
20334 @node Explicit_Full_Discrete_Ranges
20335 @subsection @code{Explicit_Full_Discrete_Ranges}
20336 @cindex @code{Explicit_Full_Discrete_Ranges} rule (for @command{gnatcheck})
20339 Flag each discrete range that has the form @code{A'First .. A'Last}.
20341 This rule has no parameters.
20343 @node Float_Equality_Checks
20344 @subsection @code{Float_Equality_Checks}
20345 @cindex @code{Float_Equality_Checks} rule (for @command{gnatcheck})
20348 Flag all calls to the predefined equality operations for floating-point types.
20349 Both ``@code{=}'' and ``@code{/=}'' operations are checked.
20350 User-defined equality operations are not flagged, nor are ``@code{=}''
20351 and ``@code{/=}'' operations for fixed-point types.
20353 This rule has no parameters.
20356 @node Forbidden_Pragmas
20357 @subsection @code{Forbidden_Pragmas}
20358 @cindex @code{Forbidden_Pragmas} rule (for @command{gnatcheck})
20361 Flag each use of the specified pragmas. The pragmas to be detected
20362 are named in the rule's parameters.
20364 This rule has the following parameters:
20367 @item For the @option{+R} option
20370 @item @emph{Pragma_Name}
20371 Adds the specified pragma to the set of pragmas to be
20372 checked and sets the checks for all the specified pragmas
20373 ON. @emph{Pragma_Name} is treated as a name of a pragma. If it
20374 does not correspond to any pragma name defined in the Ada
20375 standard or to the name of a GNAT-specific pragma defined
20376 in the GNAT Reference Manual, it is treated as the name of
20380 All the GNAT-specific pragmas are detected; this sets
20381 the checks for all the specified pragmas ON.
20384 All pragmas are detected; this sets the rule ON.
20387 @item For the @option{-R} option
20389 @item @emph{Pragma_Name}
20390 Removes the specified pragma from the set of pragmas to be
20391 checked without affecting checks for
20392 other pragmas. @emph{Pragma_Name} is treated as a name
20393 of a pragma. If it does not correspond to any pragma
20394 defined in the Ada standard or to any name defined in the
20395 GNAT Reference Manual,
20396 this option is treated as turning OFF detection of all
20400 Turn OFF detection of all GNAT-specific pragmas
20403 Clear the list of the pragmas to be detected and
20409 Parameters are not case sensitive. If @emph{Pragma_Name} does not have
20410 the syntax of an Ada identifier and therefore can not be considered
20411 as a pragma name, a diagnostic message is generated and the corresponding
20412 parameter is ignored.
20414 When more then one parameter is given in the same rule option, the parameters
20415 must be separated by a comma.
20417 If more then one option for this rule is specified for the @command{gnatcheck}
20418 call, a new option overrides the previous one(s).
20420 The @option{+R} option with no parameters turns the rule ON with the set of
20421 pragmas to be detected defined by the previous rule options.
20422 (By default this set is empty, so if the only option specified for the rule is
20423 @option{+RForbidden_Pragmas} (with
20424 no parameter), then the rule is enabled, but it does not detect anything).
20425 The @option{-R} option with no parameter turns the rule OFF, but it does not
20426 affect the set of pragmas to be detected.
20431 @node Function_Style_Procedures
20432 @subsection @code{Function_Style_Procedures}
20433 @cindex @code{Function_Style_Procedures} rule (for @command{gnatcheck})
20436 Flag each procedure that can be rewritten as a function. A procedure can be
20437 converted into a function if it has exactly one parameter of mode @code{out}
20438 and no parameters of mode @code{in out}. Procedure declarations,
20439 formal procedure declarations, and generic procedure declarations are always
20441 bodies and body stubs are flagged only if they do not have corresponding
20442 separate declarations. Procedure renamings and procedure instantiations are
20445 If a procedure can be rewritten as a function, but its @code{out} parameter is
20446 of a limited type, it is not flagged.
20448 Protected procedures are not flagged. Null procedures also are not flagged.
20450 This rule has no parameters.
20453 @node Generics_In_Subprograms
20454 @subsection @code{Generics_In_Subprograms}
20455 @cindex @code{Generics_In_Subprograms} rule (for @command{gnatcheck})
20458 Flag each declaration of a generic unit in a subprogram. Generic
20459 declarations in the bodies of generic subprograms are also flagged.
20460 A generic unit nested in another generic unit is not flagged.
20461 If a generic unit is
20462 declared in a local package that is declared in a subprogram body, the
20463 generic unit is flagged.
20465 This rule has no parameters.
20468 @node GOTO_Statements
20469 @subsection @code{GOTO_Statements}
20470 @cindex @code{GOTO_Statements} rule (for @command{gnatcheck})
20473 Flag each occurrence of a @code{goto} statement.
20475 This rule has no parameters.
20478 @node Implicit_IN_Mode_Parameters
20479 @subsection @code{Implicit_IN_Mode_Parameters}
20480 @cindex @code{Implicit_IN_Mode_Parameters} rule (for @command{gnatcheck})
20483 Flag each occurrence of a formal parameter with an implicit @code{in} mode.
20484 Note that @code{access} parameters, although they technically behave
20485 like @code{in} parameters, are not flagged.
20487 This rule has no parameters.
20490 @node Implicit_SMALL_For_Fixed_Point_Types
20491 @subsection @code{Implicit_SMALL_For_Fixed_Point_Types}
20492 @cindex @code{Implicit_SMALL_For_Fixed_Point_Types} rule (for @command{gnatcheck})
20495 Flag each fixed point type declaration that lacks an explicit
20496 representation clause to define its @code{'Small} value.
20497 Since @code{'Small} can be defined only for ordinary fixed point types,
20498 decimal fixed point type declarations are not checked.
20500 This rule has no parameters.
20503 @node Improperly_Located_Instantiations
20504 @subsection @code{Improperly_Located_Instantiations}
20505 @cindex @code{Improperly_Located_Instantiations} rule (for @command{gnatcheck})
20508 Flag all generic instantiations in library-level package specifications
20509 (including library generic packages) and in all subprogram bodies.
20511 Instantiations in task and entry bodies are not flagged. Instantiations in the
20512 bodies of protected subprograms are flagged.
20514 This rule has no parameters.
20518 @node Improper_Returns
20519 @subsection @code{Improper_Returns}
20520 @cindex @code{Improper_Returns} rule (for @command{gnatcheck})
20523 Flag each explicit @code{return} statement in procedures, and
20524 multiple @code{return} statements in functions.
20525 Diagnostic messages are generated for all @code{return} statements
20526 in a procedure (thus each procedure must be written so that it
20527 returns implicitly at the end of its statement part),
20528 and for all @code{return} statements in a function after the first one.
20529 This rule supports the stylistic convention that each subprogram
20530 should have no more than one point of normal return.
20532 This rule has no parameters.
20535 @node Library_Level_Subprograms
20536 @subsection @code{Library_Level_Subprograms}
20537 @cindex @code{Library_Level_Subprograms} rule (for @command{gnatcheck})
20540 Flag all library-level subprograms (including generic subprogram instantiations).
20542 This rule has no parameters.
20545 @node Local_Packages
20546 @subsection @code{Local_Packages}
20547 @cindex @code{Local_Packages} rule (for @command{gnatcheck})
20550 Flag all local packages declared in package and generic package
20552 Local packages in bodies are not flagged.
20554 This rule has no parameters.
20557 @node Improperly_Called_Protected_Entries
20558 @subsection @code{Improperly_Called_Protected_Entries} (under construction, GLOBAL)
20559 @cindex @code{Improperly_Called_Protected_Entries} rule (for @command{gnatcheck})
20562 Flag each protected entry that can be called from more than one task.
20564 This rule has no parameters.
20568 @node Misnamed_Identifiers
20569 @subsection @code{Misnamed_Identifiers}
20570 @cindex @code{Misnamed_Identifiers} rule (for @command{gnatcheck})
20573 Flag the declaration of each identifier that does not have a suffix
20574 corresponding to the kind of entity being declared.
20575 The following declarations are checked:
20582 constant declarations (but not number declarations)
20585 package renaming declarations (but not generic package renaming
20590 This rule may have parameters. When used without parameters, the rule enforces
20591 the following checks:
20595 type-defining names end with @code{_T}, unless the type is an access type,
20596 in which case the suffix must be @code{_A}
20598 constant names end with @code{_C}
20600 names defining package renamings end with @code{_R}
20604 For a private or incomplete type declaration the following checks are
20605 made for the defining name suffix:
20609 For an incomplete type declaration: if the corresponding full type
20610 declaration is available, the defining identifier from the full type
20611 declaration is checked, but the defining identifier from the incomplete type
20612 declaration is not; otherwise the defining identifier from the incomplete
20613 type declaration is checked against the suffix specified for type
20617 For a private type declaration (including private extensions), the defining
20618 identifier from the private type declaration is checked against the type
20619 suffix (even if the corresponding full declaration is an access type
20620 declaration), and the defining identifier from the corresponding full type
20621 declaration is not checked.
20625 For a deferred constant, the defining name in the corresponding full constant
20626 declaration is not checked.
20628 Defining names of formal types are not checked.
20630 The rule may have the following parameters:
20634 For the @option{+R} option:
20637 Sets the default listed above for all the names to be checked.
20639 @item Type_Suffix=@emph{string}
20640 Specifies the suffix for a type name.
20642 @item Access_Suffix=@emph{string}
20643 Specifies the suffix for an access type name. If
20644 this parameter is set, it overrides for access
20645 types the suffix set by the @code{Type_Suffix} parameter.
20647 @item Constant_Suffix=@emph{string}
20648 Specifies the suffix for a constant name.
20650 @item Renaming_Suffix=@emph{string}
20651 Specifies the suffix for a package renaming name.
20655 For the @option{-R} option:
20658 Remove all the suffixes specified for the
20659 identifier suffix checks, whether by default or
20660 as specified by other rule parameters. All the
20661 checks for this rule are disabled as a result.
20664 Removes the suffix specified for types. This
20665 disables checks for types but does not disable
20666 any other checks for this rule (including the
20667 check for access type names if @code{Access_Suffix} is
20670 @item Access_Suffix
20671 Removes the suffix specified for access types.
20672 This disables checks for access type names but
20673 does not disable any other checks for this rule.
20674 If @code{Type_Suffix} is set, access type names are
20675 checked as ordinary type names.
20677 @item Constant_Suffix
20678 Removes the suffix specified for constants. This
20679 disables checks for constant names but does not
20680 disable any other checks for this rule.
20682 @item Renaming_Suffix
20683 Removes the suffix specified for package
20684 renamings. This disables checks for package
20685 renamings but does not disable any other checks
20691 If more than one parameter is used, parameters must be separated by commas.
20693 If more than one option is specified for the @command{gnatcheck} invocation,
20694 a new option overrides the previous one(s).
20696 The @option{+RMisnamed_Identifiers} option (with no parameter) enables
20698 name suffixes specified by previous options used for this rule.
20700 The @option{-RMisnamed_Identifiers} option (with no parameter) disables
20701 all the checks but keeps
20702 all the suffixes specified by previous options used for this rule.
20704 The @emph{string} value must be a valid suffix for an Ada identifier (after
20705 trimming all the leading and trailing space characters, if any).
20706 Parameters are not case sensitive, except the @emph{string} part.
20708 If any error is detected in a rule parameter, the parameter is ignored.
20709 In such a case the options that are set for the rule are not
20714 @node Multiple_Entries_In_Protected_Definitions
20715 @subsection @code{Multiple_Entries_In_Protected_Definitions}
20716 @cindex @code{Multiple_Entries_In_Protected_Definitions} rule (for @command{gnatcheck})
20719 Flag each protected definition (i.e., each protected object/type declaration)
20720 that defines more than one entry.
20721 Diagnostic messages are generated for all the entry declarations
20722 except the first one. An entry family is counted as one entry. Entries from
20723 the private part of the protected definition are also checked.
20725 This rule has no parameters.
20728 @subsection @code{Name_Clashes}
20729 @cindex @code{Name_Clashes} rule (for @command{gnatcheck})
20732 Check that certain names are not used as defining identifiers. To activate
20733 this rule, you need to supply a reference to the dictionary file(s) as a rule
20734 parameter(s) (more then one dictionary file can be specified). If no
20735 dictionary file is set, this rule will not cause anything to be flagged.
20736 Only defining occurrences, not references, are checked.
20737 The check is not case-sensitive.
20739 This rule is enabled by default, but without setting any corresponding
20740 dictionary file(s); thus the default effect is to do no checks.
20742 A dictionary file is a plain text file. The maximum line length for this file
20743 is 1024 characters. If the line is longer then this limit, extra characters
20746 Each line can be either an empty line, a comment line, or a line containing
20747 a list of identifiers separated by space or HT characters.
20748 A comment is an Ada-style comment (from @code{--} to end-of-line).
20749 Identifiers must follow the Ada syntax for identifiers.
20750 A line containing one or more identifiers may end with a comment.
20752 @node Non_Qualified_Aggregates
20753 @subsection @code{Non_Qualified_Aggregates}
20754 @cindex @code{Non_Qualified_Aggregates} rule (for @command{gnatcheck})
20757 Flag each non-qualified aggregate.
20758 A non-qualified aggregate is an
20759 aggregate that is not the expression of a qualified expression. A
20760 string literal is not considered an aggregate, but an array
20761 aggregate of a string type is considered as a normal aggregate.
20762 Aggregates of anonymous array types are not flagged.
20764 This rule has no parameters.
20767 @node Non_Short_Circuit_Operators
20768 @subsection @code{Non_Short_Circuit_Operators}
20769 @cindex @code{Non_Short_Circuit_Operators} rule (for @command{gnatcheck})
20772 Flag all calls to predefined @code{and} and @code{or} operators for
20773 any boolean type. Calls to
20774 user-defined @code{and} and @code{or} and to operators defined by renaming
20775 declarations are not flagged. Calls to predefined @code{and} and @code{or}
20776 operators for modular types or boolean array types are not flagged.
20778 This rule has no parameters.
20782 @node Non_SPARK_Attributes
20783 @subsection @code{Non_SPARK_Attributes}
20784 @cindex @code{Non_SPARK_Attributes} rule (for @command{gnatcheck})
20787 The SPARK language defines the following subset of Ada 95 attribute
20788 designators as those that can be used in SPARK programs. The use of
20789 any other attribute is flagged.
20792 @item @code{'Adjacent}
20795 @item @code{'Ceiling}
20796 @item @code{'Component_Size}
20797 @item @code{'Compose}
20798 @item @code{'Copy_Sign}
20799 @item @code{'Delta}
20800 @item @code{'Denorm}
20801 @item @code{'Digits}
20802 @item @code{'Exponent}
20803 @item @code{'First}
20804 @item @code{'Floor}
20806 @item @code{'Fraction}
20808 @item @code{'Leading_Part}
20809 @item @code{'Length}
20810 @item @code{'Machine}
20811 @item @code{'Machine_Emax}
20812 @item @code{'Machine_Emin}
20813 @item @code{'Machine_Mantissa}
20814 @item @code{'Machine_Overflows}
20815 @item @code{'Machine_Radix}
20816 @item @code{'Machine_Rounds}
20819 @item @code{'Model}
20820 @item @code{'Model_Emin}
20821 @item @code{'Model_Epsilon}
20822 @item @code{'Model_Mantissa}
20823 @item @code{'Model_Small}
20824 @item @code{'Modulus}
20827 @item @code{'Range}
20828 @item @code{'Remainder}
20829 @item @code{'Rounding}
20830 @item @code{'Safe_First}
20831 @item @code{'Safe_Last}
20832 @item @code{'Scaling}
20833 @item @code{'Signed_Zeros}
20835 @item @code{'Small}
20837 @item @code{'Truncation}
20838 @item @code{'Unbiased_Rounding}
20840 @item @code{'Valid}
20844 This rule has no parameters.
20847 @node Non_Tagged_Derived_Types
20848 @subsection @code{Non_Tagged_Derived_Types}
20849 @cindex @code{Non_Tagged_Derived_Types} rule (for @command{gnatcheck})
20852 Flag all derived type declarations that do not have a record extension part.
20854 This rule has no parameters.
20858 @node Non_Visible_Exceptions
20859 @subsection @code{Non_Visible_Exceptions}
20860 @cindex @code{Non_Visible_Exceptions} rule (for @command{gnatcheck})
20863 Flag constructs leading to the possibility of propagating an exception
20864 out of the scope in which the exception is declared.
20865 Two cases are detected:
20869 An exception declaration in a subprogram body, task body or block
20870 statement is flagged if the body or statement does not contain a handler for
20871 that exception or a handler with an @code{others} choice.
20874 A @code{raise} statement in an exception handler of a subprogram body,
20875 task body or block statement is flagged if it (re)raises a locally
20876 declared exception. This may occur under the following circumstances:
20879 it explicitly raises a locally declared exception, or
20881 it does not specify an exception name (i.e., it is simply @code{raise;})
20882 and the enclosing handler contains a locally declared exception in its
20888 Renamings of local exceptions are not flagged.
20890 This rule has no parameters.
20893 @node Numeric_Literals
20894 @subsection @code{Numeric_Literals}
20895 @cindex @code{Numeric_Literals} rule (for @command{gnatcheck})
20898 Flag each use of a numeric literal in an index expression, and in any
20899 circumstance except for the following:
20903 a literal occurring in the initialization expression for a constant
20904 declaration or a named number declaration, or
20907 an integer literal that is less than or equal to a value
20908 specified by the @option{N} rule parameter.
20912 This rule may have the following parameters for the @option{+R} option:
20916 @emph{N} is an integer literal used as the maximal value that is not flagged
20917 (i.e., integer literals not exceeding this value are allowed)
20920 All integer literals are flagged
20924 If no parameters are set, the maximum unflagged value is 1.
20926 The last specified check limit (or the fact that there is no limit at
20927 all) is used when multiple @option{+R} options appear.
20929 The @option{-R} option for this rule has no parameters.
20930 It disables the rule but retains the last specified maximum unflagged value.
20931 If the @option{+R} option subsequently appears, this value is used as the
20932 threshold for the check.
20935 @node OTHERS_In_Aggregates
20936 @subsection @code{OTHERS_In_Aggregates}
20937 @cindex @code{OTHERS_In_Aggregates} rule (for @command{gnatcheck})
20940 Flag each use of an @code{others} choice in extension aggregates.
20941 In record and array aggregates, an @code{others} choice is flagged unless
20942 it is used to refer to all components, or to all but one component.
20944 If, in case of a named array aggregate, there are two associations, one
20945 with an @code{others} choice and another with a discrete range, the
20946 @code{others} choice is flagged even if the discrete range specifies
20947 exactly one component; for example, @code{(1..1 => 0, others => 1)}.
20949 This rule has no parameters.
20951 @node OTHERS_In_CASE_Statements
20952 @subsection @code{OTHERS_In_CASE_Statements}
20953 @cindex @code{OTHERS_In_CASE_Statements} rule (for @command{gnatcheck})
20956 Flag any use of an @code{others} choice in a @code{case} statement.
20958 This rule has no parameters.
20960 @node OTHERS_In_Exception_Handlers
20961 @subsection @code{OTHERS_In_Exception_Handlers}
20962 @cindex @code{OTHERS_In_Exception_Handlers} rule (for @command{gnatcheck})
20965 Flag any use of an @code{others} choice in an exception handler.
20967 This rule has no parameters.
20970 @node Outer_Loop_Exits
20971 @subsection @code{Outer_Loop_Exits}
20972 @cindex @code{Outer_Loop_Exits} rule (for @command{gnatcheck})
20975 Flag each @code{exit} statement containing a loop name that is not the name
20976 of the immediately enclosing @code{loop} statement.
20978 This rule has no parameters.
20981 @node Overloaded_Operators
20982 @subsection @code{Overloaded_Operators}
20983 @cindex @code{Overloaded_Operators} rule (for @command{gnatcheck})
20986 Flag each function declaration that overloads an operator symbol.
20987 A function body is checked only if the body does not have a
20988 separate spec. Formal functions are also checked. For a
20989 renaming declaration, only renaming-as-declaration is checked
20991 This rule has no parameters.
20994 @node Overly_Nested_Control_Structures
20995 @subsection @code{Overly_Nested_Control_Structures}
20996 @cindex @code{Overly_Nested_Control_Structures} rule (for @command{gnatcheck})
20999 Flag each control structure whose nesting level exceeds the value provided
21000 in the rule parameter.
21002 The control structures checked are the following:
21005 @item @code{if} statement
21006 @item @code{case} statement
21007 @item @code{loop} statement
21008 @item Selective accept statement
21009 @item Timed entry call statement
21010 @item Conditional entry call
21011 @item Asynchronous select statement
21015 The rule may have the following parameter for the @option{+R} option:
21019 Positive integer specifying the maximal control structure nesting
21020 level that is not flagged
21024 If the parameter for the @option{+R} option is not a positive integer,
21025 the parameter is ignored and the rule is turned ON with the most recently
21026 specified maximal non-flagged nesting level.
21028 If more then one option is specified for the gnatcheck call, the later option and
21029 new parameter override the previous one(s).
21031 A @option{+R} option with no parameter turns the rule ON using the maximal
21032 non-flagged nesting level specified by the most recent @option{+R} option with
21033 a parameter, or the value 4 if there is no such previous @option{+R} option.
21037 @node Parameters_Out_Of_Order
21038 @subsection @code{Parameters_Out_Of_Order}
21039 @cindex @code{Parameters_Out_Of_Order} rule (for @command{gnatcheck})
21042 Flag each subprogram and entry declaration whose formal parameters are not
21043 ordered according to the following scheme:
21047 @item @code{in} and @code{access} parameters first,
21048 then @code{in out} parameters,
21049 and then @code{out} parameters;
21051 @item for @code{in} mode, parameters with default initialization expressions
21056 Only the first violation of the described order is flagged.
21058 The following constructs are checked:
21061 @item subprogram declarations (including null procedures);
21062 @item generic subprogram declarations;
21063 @item formal subprogram declarations;
21064 @item entry declarations;
21065 @item subprogram bodies and subprogram body stubs that do not
21066 have separate specifications
21070 Subprogram renamings are not checked.
21072 This rule has no parameters.
21075 @node Positional_Actuals_For_Defaulted_Generic_Parameters
21076 @subsection @code{Positional_Actuals_For_Defaulted_Generic_Parameters}
21077 @cindex @code{Positional_Actuals_For_Defaulted_Generic_Parameters} rule (for @command{gnatcheck})
21080 Flag each generic actual parameter corresponding to a generic formal
21081 parameter with a default initialization, if positional notation is used.
21083 This rule has no parameters.
21085 @node Positional_Actuals_For_Defaulted_Parameters
21086 @subsection @code{Positional_Actuals_For_Defaulted_Parameters}
21087 @cindex @code{Positional_Actuals_For_Defaulted_Parameters} rule (for @command{gnatcheck})
21090 Flag each actual parameter to a subprogram or entry call where the
21091 corresponding formal parameter has a default expression, if positional
21094 This rule has no parameters.
21096 @node Positional_Components
21097 @subsection @code{Positional_Components}
21098 @cindex @code{Positional_Components} rule (for @command{gnatcheck})
21101 Flag each array, record and extension aggregate that includes positional
21104 This rule has no parameters.
21107 @node Positional_Generic_Parameters
21108 @subsection @code{Positional_Generic_Parameters}
21109 @cindex @code{Positional_Generic_Parameters} rule (for @command{gnatcheck})
21112 Flag each instantiation using positional parameter notation.
21114 This rule has no parameters.
21117 @node Positional_Parameters
21118 @subsection @code{Positional_Parameters}
21119 @cindex @code{Positional_Parameters} rule (for @command{gnatcheck})
21122 Flag each subprogram or entry call using positional parameter notation,
21123 except for the following:
21127 Invocations of prefix or infix operators are not flagged
21129 If the called subprogram or entry has only one formal parameter,
21130 the call is not flagged;
21132 If a subprogram call uses the @emph{Object.Operation} notation, then
21135 the first parameter (that is, @emph{Object}) is not flagged;
21137 if the called subprogram has only two parameters, the second parameter
21138 of the call is not flagged;
21143 This rule has no parameters.
21148 @node Predefined_Numeric_Types
21149 @subsection @code{Predefined_Numeric_Types}
21150 @cindex @code{Predefined_Numeric_Types} rule (for @command{gnatcheck})
21153 Flag each explicit use of the name of any numeric type or subtype defined
21154 in package @code{Standard}.
21156 The rationale for this rule is to detect when the
21157 program may depend on platform-specific characteristics of the implementation
21158 of the predefined numeric types. Note that this rule is over-pessimistic;
21159 for example, a program that uses @code{String} indexing
21160 likely needs a variable of type @code{Integer}.
21161 Another example is the flagging of predefined numeric types with explicit
21164 @smallexample @c ada
21165 subtype My_Integer is Integer range Left .. Right;
21166 Vy_Var : My_Integer;
21170 This rule detects only numeric types and subtypes defined in
21171 @code{Standard}. The use of numeric types and subtypes defined in other
21172 predefined packages (such as @code{System.Any_Priority} or
21173 @code{Ada.Text_IO.Count}) is not flagged
21175 This rule has no parameters.
21179 @node Raising_External_Exceptions
21180 @subsection @code{Raising_External_Exceptions}
21181 @cindex @code{Raising_External_Exceptions} rule (for @command{gnatcheck})
21184 Flag any @code{raise} statement, in a program unit declared in a library
21185 package or in a generic library package, for an exception that is
21186 neither a predefined exception nor an exception that is also declared (or
21187 renamed) in the visible part of the package.
21189 This rule has no parameters.
21193 @node Raising_Predefined_Exceptions
21194 @subsection @code{Raising_Predefined_Exceptions}
21195 @cindex @code{Raising_Predefined_Exceptions} rule (for @command{gnatcheck})
21198 Flag each @code{raise} statement that raises a predefined exception
21199 (i.e., one of the exceptions @code{Constraint_Error}, @code{Numeric_Error},
21200 @code{Program_Error}, @code{Storage_Error}, or @code{Tasking_Error}).
21202 This rule has no parameters.
21207 @subsection @code{Recursion} (under construction, GLOBAL)
21208 @cindex @code{Recursion} rule (for @command{gnatcheck})
21211 Flag recursive subprograms (cycles in the call graph). Declarations, and not
21212 calls, of recursive subprograms are detected.
21214 This rule has no parameters.
21218 @node Side_Effect_Functions
21219 @subsection @code{Side_Effect_Functions} (under construction, GLOBAL)
21220 @cindex @code{Side_Effect_Functions} rule (for @command{gnatcheck})
21223 Flag functions with side effects.
21225 We define a side effect as changing any data object that is not local for the
21226 body of this function.
21228 At the moment, we do NOT consider a side effect any input-output operations
21229 (changing a state or a content of any file).
21231 We do not consider protected functions for this rule (???)
21233 There are the following sources of side effect:
21236 @item Explicit (or direct) side-effect:
21240 direct assignment to a non-local variable;
21243 direct call to an entity that is known to change some data object that is
21244 not local for the body of this function (Note, that if F1 calls F2 and F2
21245 does have a side effect, this does not automatically mean that F1 also
21246 have a side effect, because it may be the case that F2 is declared in
21247 F1's body and it changes some data object that is global for F2, but
21251 @item Indirect side-effect:
21254 Subprogram calls implicitly issued by:
21257 computing initialization expressions from type declarations as a part
21258 of object elaboration or allocator evaluation;
21260 computing implicit parameters of subprogram or entry calls or generic
21265 activation of a task that change some non-local data object (directly or
21269 elaboration code of a package that is a result of a package instantiation;
21272 controlled objects;
21275 @item Situations when we can suspect a side-effect, but the full static check
21276 is either impossible or too hard:
21279 assignment to access variables or to the objects pointed by access
21283 call to a subprogram pointed by access-to-subprogram value
21291 This rule has no parameters.
21295 @subsection @code{Slices}
21296 @cindex @code{Slices} rule (for @command{gnatcheck})
21299 Flag all uses of array slicing
21301 This rule has no parameters.
21304 @node Unassigned_OUT_Parameters
21305 @subsection @code{Unassigned_OUT_Parameters}
21306 @cindex @code{Unassigned_OUT_Parameters} rule (for @command{gnatcheck})
21309 Flags procedures' @code{out} parameters that are not assigned, and
21310 identifies the contexts in which the assignments are missing.
21312 An @code{out} parameter is flagged in the statements in the procedure
21313 body's handled sequence of statements (before the procedure body's
21314 @code{exception} part, if any) if this sequence of statements contains
21315 no assignments to the parameter.
21317 An @code{out} parameter is flagged in an exception handler in the exception
21318 part of the procedure body's handled sequence of statements if the handler
21319 contains no assignment to the parameter.
21321 Bodies of generic procedures are also considered.
21323 The following are treated as assignments to an @code{out} parameter:
21327 an assignment statement, with the parameter or some component as the target;
21330 passing the parameter (or one of its components) as an @code{out} or
21331 @code{in out} parameter.
21335 This rule does not have any parameters.
21339 @node Uncommented_BEGIN_In_Package_Bodies
21340 @subsection @code{Uncommented_BEGIN_In_Package_Bodies}
21341 @cindex @code{Uncommented_BEGIN_In_Package_Bodies} rule (for @command{gnatcheck})
21344 Flags each package body with declarations and a statement part that does not
21345 include a trailing comment on the line containing the @code{begin} keyword;
21346 this trailing comment needs to specify the package name and nothing else.
21347 The @code{begin} is not flagged if the package body does not
21348 contain any declarations.
21350 If the @code{begin} keyword is placed on the
21351 same line as the last declaration or the first statement, it is flagged
21352 independently of whether the line contains a trailing comment. The
21353 diagnostic message is attached to the line containing the first statement.
21355 This rule has no parameters.
21358 @node Unconstrained_Array_Returns
21359 @subsection @code{Unconstrained_Array_Returns}
21360 @cindex @code{Unconstrained_Array_Returns} rule (for @command{gnatcheck})
21363 Flag each function returning an unconstrained array. Function declarations,
21364 function bodies (and body stubs) having no separate specifications,
21365 and generic function instantiations are checked.
21366 Generic function declarations, function calls and function renamings are
21369 This rule has no parameters.
21371 @node Universal_Ranges
21372 @subsection @code{Universal_Ranges}
21373 @cindex @code{Universal_Ranges} rule (for @command{gnatcheck})
21376 Flag discrete ranges that are a part of an index constraint, constrained
21377 array definition, or @code{for}-loop parameter specification, and whose bounds
21378 are both of type @i{universal_integer}. Ranges that have at least one
21379 bound of a specific type (such as @code{1 .. N}, where @code{N} is a variable
21380 or an expression of non-universal type) are not flagged.
21382 This rule has no parameters.
21385 @node Unnamed_Blocks_And_Loops
21386 @subsection @code{Unnamed_Blocks_And_Loops}
21387 @cindex @code{Unnamed_Blocks_And_Loops} rule (for @command{gnatcheck})
21390 Flag each unnamed block statement and loop statement.
21392 The rule has no parameters.
21397 @node Unused_Subprograms
21398 @subsection @code{Unused_Subprograms} (under construction, GLOBAL)
21399 @cindex @code{Unused_Subprograms} rule (for @command{gnatcheck})
21402 Flag all unused subprograms.
21404 This rule has no parameters.
21410 @node USE_PACKAGE_Clauses
21411 @subsection @code{USE_PACKAGE_Clauses}
21412 @cindex @code{USE_PACKAGE_Clauses} rule (for @command{gnatcheck})
21415 Flag all @code{use} clauses for packages; @code{use type} clauses are
21418 This rule has no parameters.
21422 @node Volatile_Objects_Without_Address_Clauses
21423 @subsection @code{Volatile_Objects_Without_Address_Clauses}
21424 @cindex @code{Volatile_Objects_Without_Address_Clauses} rule (for @command{gnatcheck})
21427 Flag each volatile object that does not have an address clause.
21429 The following check is made: if the pragma @code{Volatile} is applied to a
21430 data object or to its type, then an address clause must
21431 be supplied for this object.
21433 This rule does not check the components of data objects,
21434 array components that are volatile as a result of the pragma
21435 @code{Volatile_Components}, or objects that are volatile because
21436 they are atomic as a result of pragmas @code{Atomic} or
21437 @code{Atomic_Components}.
21439 Only variable declarations, and not constant declarations, are checked.
21441 This rule has no parameters.
21444 @c *********************************
21445 @node Creating Sample Bodies Using gnatstub
21446 @chapter Creating Sample Bodies Using @command{gnatstub}
21450 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
21451 for library unit declarations.
21453 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
21454 driver (see @ref{The GNAT Driver and Project Files}).
21456 To create a body stub, @command{gnatstub} has to compile the library
21457 unit declaration. Therefore, bodies can be created only for legal
21458 library units. Moreover, if a library unit depends semantically upon
21459 units located outside the current directory, you have to provide
21460 the source search path when calling @command{gnatstub}, see the description
21461 of @command{gnatstub} switches below.
21464 * Running gnatstub::
21465 * Switches for gnatstub::
21468 @node Running gnatstub
21469 @section Running @command{gnatstub}
21472 @command{gnatstub} has the command-line interface of the form
21475 $ gnatstub [switches] filename [directory]
21482 is the name of the source file that contains a library unit declaration
21483 for which a body must be created. The file name may contain the path
21485 The file name does not have to follow the GNAT file name conventions. If the
21487 does not follow GNAT file naming conventions, the name of the body file must
21489 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
21490 If the file name follows the GNAT file naming
21491 conventions and the name of the body file is not provided,
21494 of the body file from the argument file name by replacing the @file{.ads}
21496 with the @file{.adb} suffix.
21499 indicates the directory in which the body stub is to be placed (the default
21504 is an optional sequence of switches as described in the next section
21507 @node Switches for gnatstub
21508 @section Switches for @command{gnatstub}
21514 @cindex @option{^-f^/FULL^} (@command{gnatstub})
21515 If the destination directory already contains a file with the name of the
21517 for the argument spec file, replace it with the generated body stub.
21519 @item ^-hs^/HEADER=SPEC^
21520 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
21521 Put the comment header (i.e., all the comments preceding the
21522 compilation unit) from the source of the library unit declaration
21523 into the body stub.
21525 @item ^-hg^/HEADER=GENERAL^
21526 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
21527 Put a sample comment header into the body stub.
21531 @cindex @option{-IDIR} (@command{gnatstub})
21533 @cindex @option{-I-} (@command{gnatstub})
21536 @item /NOCURRENT_DIRECTORY
21537 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
21539 ^These switches have ^This switch has^ the same meaning as in calls to
21541 ^They define ^It defines ^ the source search path in the call to
21542 @command{gcc} issued
21543 by @command{gnatstub} to compile an argument source file.
21545 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
21546 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
21547 This switch has the same meaning as in calls to @command{gcc}.
21548 It defines the additional configuration file to be passed to the call to
21549 @command{gcc} issued
21550 by @command{gnatstub} to compile an argument source file.
21552 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
21553 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
21554 (@var{n} is a non-negative integer). Set the maximum line length in the
21555 body stub to @var{n}; the default is 79. The maximum value that can be
21556 specified is 32767. Note that in the special case of configuration
21557 pragma files, the maximum is always 32767 regardless of whether or
21558 not this switch appears.
21560 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
21561 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
21562 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
21563 the generated body sample to @var{n}.
21564 The default indentation is 3.
21566 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
21567 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
21568 Order local bodies alphabetically. (By default local bodies are ordered
21569 in the same way as the corresponding local specs in the argument spec file.)
21571 @item ^-i^/INDENTATION=^@var{n}
21572 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
21573 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
21575 @item ^-k^/TREE_FILE=SAVE^
21576 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
21577 Do not remove the tree file (i.e., the snapshot of the compiler internal
21578 structures used by @command{gnatstub}) after creating the body stub.
21580 @item ^-l^/LINE_LENGTH=^@var{n}
21581 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
21582 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
21584 @item ^-o^/BODY=^@var{body-name}
21585 @cindex @option{^-o^/BODY^} (@command{gnatstub})
21586 Body file name. This should be set if the argument file name does not
21588 the GNAT file naming
21589 conventions. If this switch is omitted the default name for the body will be
21591 from the argument file name according to the GNAT file naming conventions.
21594 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
21595 Quiet mode: do not generate a confirmation when a body is
21596 successfully created, and do not generate a message when a body is not
21600 @item ^-r^/TREE_FILE=REUSE^
21601 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
21602 Reuse the tree file (if it exists) instead of creating it. Instead of
21603 creating the tree file for the library unit declaration, @command{gnatstub}
21604 tries to find it in the current directory and use it for creating
21605 a body. If the tree file is not found, no body is created. This option
21606 also implies @option{^-k^/SAVE^}, whether or not
21607 the latter is set explicitly.
21609 @item ^-t^/TREE_FILE=OVERWRITE^
21610 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
21611 Overwrite the existing tree file. If the current directory already
21612 contains the file which, according to the GNAT file naming rules should
21613 be considered as a tree file for the argument source file,
21615 will refuse to create the tree file needed to create a sample body
21616 unless this option is set.
21618 @item ^-v^/VERBOSE^
21619 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
21620 Verbose mode: generate version information.
21624 @node Other Utility Programs
21625 @chapter Other Utility Programs
21628 This chapter discusses some other utility programs available in the Ada
21632 * Using Other Utility Programs with GNAT::
21633 * The External Symbol Naming Scheme of GNAT::
21634 * Converting Ada Files to html with gnathtml::
21635 * Installing gnathtml::
21642 @node Using Other Utility Programs with GNAT
21643 @section Using Other Utility Programs with GNAT
21646 The object files generated by GNAT are in standard system format and in
21647 particular the debugging information uses this format. This means
21648 programs generated by GNAT can be used with existing utilities that
21649 depend on these formats.
21652 In general, any utility program that works with C will also often work with
21653 Ada programs generated by GNAT. This includes software utilities such as
21654 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
21658 @node The External Symbol Naming Scheme of GNAT
21659 @section The External Symbol Naming Scheme of GNAT
21662 In order to interpret the output from GNAT, when using tools that are
21663 originally intended for use with other languages, it is useful to
21664 understand the conventions used to generate link names from the Ada
21667 All link names are in all lowercase letters. With the exception of library
21668 procedure names, the mechanism used is simply to use the full expanded
21669 Ada name with dots replaced by double underscores. For example, suppose
21670 we have the following package spec:
21672 @smallexample @c ada
21683 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
21684 the corresponding link name is @code{qrs__mn}.
21686 Of course if a @code{pragma Export} is used this may be overridden:
21688 @smallexample @c ada
21693 pragma Export (Var1, C, External_Name => "var1_name");
21695 pragma Export (Var2, C, Link_Name => "var2_link_name");
21702 In this case, the link name for @var{Var1} is whatever link name the
21703 C compiler would assign for the C function @var{var1_name}. This typically
21704 would be either @var{var1_name} or @var{_var1_name}, depending on operating
21705 system conventions, but other possibilities exist. The link name for
21706 @var{Var2} is @var{var2_link_name}, and this is not operating system
21710 One exception occurs for library level procedures. A potential ambiguity
21711 arises between the required name @code{_main} for the C main program,
21712 and the name we would otherwise assign to an Ada library level procedure
21713 called @code{Main} (which might well not be the main program).
21715 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
21716 names. So if we have a library level procedure such as
21718 @smallexample @c ada
21721 procedure Hello (S : String);
21727 the external name of this procedure will be @var{_ada_hello}.
21730 @node Converting Ada Files to html with gnathtml
21731 @section Converting Ada Files to HTML with @code{gnathtml}
21734 This @code{Perl} script allows Ada source files to be browsed using
21735 standard Web browsers. For installation procedure, see the section
21736 @xref{Installing gnathtml}.
21738 Ada reserved keywords are highlighted in a bold font and Ada comments in
21739 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
21740 switch to suppress the generation of cross-referencing information, user
21741 defined variables and types will appear in a different color; you will
21742 be able to click on any identifier and go to its declaration.
21744 The command line is as follow:
21746 $ perl gnathtml.pl [^switches^options^] ada-files
21750 You can pass it as many Ada files as you want. @code{gnathtml} will generate
21751 an html file for every ada file, and a global file called @file{index.htm}.
21752 This file is an index of every identifier defined in the files.
21754 The available ^switches^options^ are the following ones:
21758 @cindex @option{-83} (@code{gnathtml})
21759 Only the Ada 83 subset of keywords will be highlighted.
21761 @item -cc @var{color}
21762 @cindex @option{-cc} (@code{gnathtml})
21763 This option allows you to change the color used for comments. The default
21764 value is green. The color argument can be any name accepted by html.
21767 @cindex @option{-d} (@code{gnathtml})
21768 If the Ada files depend on some other files (for instance through
21769 @code{with} clauses, the latter files will also be converted to html.
21770 Only the files in the user project will be converted to html, not the files
21771 in the run-time library itself.
21774 @cindex @option{-D} (@code{gnathtml})
21775 This command is the same as @option{-d} above, but @command{gnathtml} will
21776 also look for files in the run-time library, and generate html files for them.
21778 @item -ext @var{extension}
21779 @cindex @option{-ext} (@code{gnathtml})
21780 This option allows you to change the extension of the generated HTML files.
21781 If you do not specify an extension, it will default to @file{htm}.
21784 @cindex @option{-f} (@code{gnathtml})
21785 By default, gnathtml will generate html links only for global entities
21786 ('with'ed units, global variables and types,...). If you specify
21787 @option{-f} on the command line, then links will be generated for local
21790 @item -l @var{number}
21791 @cindex @option{-l} (@code{gnathtml})
21792 If this ^switch^option^ is provided and @var{number} is not 0, then
21793 @code{gnathtml} will number the html files every @var{number} line.
21796 @cindex @option{-I} (@code{gnathtml})
21797 Specify a directory to search for library files (@file{.ALI} files) and
21798 source files. You can provide several -I switches on the command line,
21799 and the directories will be parsed in the order of the command line.
21802 @cindex @option{-o} (@code{gnathtml})
21803 Specify the output directory for html files. By default, gnathtml will
21804 saved the generated html files in a subdirectory named @file{html/}.
21806 @item -p @var{file}
21807 @cindex @option{-p} (@code{gnathtml})
21808 If you are using Emacs and the most recent Emacs Ada mode, which provides
21809 a full Integrated Development Environment for compiling, checking,
21810 running and debugging applications, you may use @file{.gpr} files
21811 to give the directories where Emacs can find sources and object files.
21813 Using this ^switch^option^, you can tell gnathtml to use these files.
21814 This allows you to get an html version of your application, even if it
21815 is spread over multiple directories.
21817 @item -sc @var{color}
21818 @cindex @option{-sc} (@code{gnathtml})
21819 This ^switch^option^ allows you to change the color used for symbol
21821 The default value is red. The color argument can be any name accepted by html.
21823 @item -t @var{file}
21824 @cindex @option{-t} (@code{gnathtml})
21825 This ^switch^option^ provides the name of a file. This file contains a list of
21826 file names to be converted, and the effect is exactly as though they had
21827 appeared explicitly on the command line. This
21828 is the recommended way to work around the command line length limit on some
21833 @node Installing gnathtml
21834 @section Installing @code{gnathtml}
21837 @code{Perl} needs to be installed on your machine to run this script.
21838 @code{Perl} is freely available for almost every architecture and
21839 Operating System via the Internet.
21841 On Unix systems, you may want to modify the first line of the script
21842 @code{gnathtml}, to explicitly tell the Operating system where Perl
21843 is. The syntax of this line is:
21845 #!full_path_name_to_perl
21849 Alternatively, you may run the script using the following command line:
21852 $ perl gnathtml.pl [switches] files
21861 The GNAT distribution provides an Ada 95 template for the HP Language
21862 Sensitive Editor (LSE), a component of DECset. In order to
21863 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
21870 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
21871 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
21872 the collection phase with the /DEBUG qualifier.
21875 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
21876 $ DEFINE LIB$DEBUG PCA$COLLECTOR
21877 $ RUN/DEBUG <PROGRAM_NAME>
21882 @node Running and Debugging Ada Programs
21883 @chapter Running and Debugging Ada Programs
21887 This chapter discusses how to debug Ada programs.
21889 It applies to GNAT on the Alpha OpenVMS platform;
21890 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
21891 since HP has implemented Ada support in the OpenVMS debugger on I64.
21894 An incorrect Ada program may be handled in three ways by the GNAT compiler:
21898 The illegality may be a violation of the static semantics of Ada. In
21899 that case GNAT diagnoses the constructs in the program that are illegal.
21900 It is then a straightforward matter for the user to modify those parts of
21904 The illegality may be a violation of the dynamic semantics of Ada. In
21905 that case the program compiles and executes, but may generate incorrect
21906 results, or may terminate abnormally with some exception.
21909 When presented with a program that contains convoluted errors, GNAT
21910 itself may terminate abnormally without providing full diagnostics on
21911 the incorrect user program.
21915 * The GNAT Debugger GDB::
21917 * Introduction to GDB Commands::
21918 * Using Ada Expressions::
21919 * Calling User-Defined Subprograms::
21920 * Using the Next Command in a Function::
21923 * Debugging Generic Units::
21924 * GNAT Abnormal Termination or Failure to Terminate::
21925 * Naming Conventions for GNAT Source Files::
21926 * Getting Internal Debugging Information::
21927 * Stack Traceback::
21933 @node The GNAT Debugger GDB
21934 @section The GNAT Debugger GDB
21937 @code{GDB} is a general purpose, platform-independent debugger that
21938 can be used to debug mixed-language programs compiled with @command{gcc},
21939 and in particular is capable of debugging Ada programs compiled with
21940 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
21941 complex Ada data structures.
21943 The manual @cite{Debugging with GDB}
21945 , located in the GNU:[DOCS] directory,
21947 contains full details on the usage of @code{GDB}, including a section on
21948 its usage on programs. This manual should be consulted for full
21949 details. The section that follows is a brief introduction to the
21950 philosophy and use of @code{GDB}.
21952 When GNAT programs are compiled, the compiler optionally writes debugging
21953 information into the generated object file, including information on
21954 line numbers, and on declared types and variables. This information is
21955 separate from the generated code. It makes the object files considerably
21956 larger, but it does not add to the size of the actual executable that
21957 will be loaded into memory, and has no impact on run-time performance. The
21958 generation of debug information is triggered by the use of the
21959 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
21960 used to carry out the compilations. It is important to emphasize that
21961 the use of these options does not change the generated code.
21963 The debugging information is written in standard system formats that
21964 are used by many tools, including debuggers and profilers. The format
21965 of the information is typically designed to describe C types and
21966 semantics, but GNAT implements a translation scheme which allows full
21967 details about Ada types and variables to be encoded into these
21968 standard C formats. Details of this encoding scheme may be found in
21969 the file exp_dbug.ads in the GNAT source distribution. However, the
21970 details of this encoding are, in general, of no interest to a user,
21971 since @code{GDB} automatically performs the necessary decoding.
21973 When a program is bound and linked, the debugging information is
21974 collected from the object files, and stored in the executable image of
21975 the program. Again, this process significantly increases the size of
21976 the generated executable file, but it does not increase the size of
21977 the executable program itself. Furthermore, if this program is run in
21978 the normal manner, it runs exactly as if the debug information were
21979 not present, and takes no more actual memory.
21981 However, if the program is run under control of @code{GDB}, the
21982 debugger is activated. The image of the program is loaded, at which
21983 point it is ready to run. If a run command is given, then the program
21984 will run exactly as it would have if @code{GDB} were not present. This
21985 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
21986 entirely non-intrusive until a breakpoint is encountered. If no
21987 breakpoint is ever hit, the program will run exactly as it would if no
21988 debugger were present. When a breakpoint is hit, @code{GDB} accesses
21989 the debugging information and can respond to user commands to inspect
21990 variables, and more generally to report on the state of execution.
21994 @section Running GDB
21997 This section describes how to initiate the debugger.
21998 @c The above sentence is really just filler, but it was otherwise
21999 @c clumsy to get the first paragraph nonindented given the conditional
22000 @c nature of the description
22003 The debugger can be launched from a @code{GPS} menu or
22004 directly from the command line. The description below covers the latter use.
22005 All the commands shown can be used in the @code{GPS} debug console window,
22006 but there are usually more GUI-based ways to achieve the same effect.
22009 The command to run @code{GDB} is
22012 $ ^gdb program^GDB PROGRAM^
22016 where @code{^program^PROGRAM^} is the name of the executable file. This
22017 activates the debugger and results in a prompt for debugger commands.
22018 The simplest command is simply @code{run}, which causes the program to run
22019 exactly as if the debugger were not present. The following section
22020 describes some of the additional commands that can be given to @code{GDB}.
22022 @c *******************************
22023 @node Introduction to GDB Commands
22024 @section Introduction to GDB Commands
22027 @code{GDB} contains a large repertoire of commands. The manual
22028 @cite{Debugging with GDB}
22030 (located in the GNU:[DOCS] directory)
22032 includes extensive documentation on the use
22033 of these commands, together with examples of their use. Furthermore,
22034 the command @command{help} invoked from within GDB activates a simple help
22035 facility which summarizes the available commands and their options.
22036 In this section we summarize a few of the most commonly
22037 used commands to give an idea of what @code{GDB} is about. You should create
22038 a simple program with debugging information and experiment with the use of
22039 these @code{GDB} commands on the program as you read through the
22043 @item set args @var{arguments}
22044 The @var{arguments} list above is a list of arguments to be passed to
22045 the program on a subsequent run command, just as though the arguments
22046 had been entered on a normal invocation of the program. The @code{set args}
22047 command is not needed if the program does not require arguments.
22050 The @code{run} command causes execution of the program to start from
22051 the beginning. If the program is already running, that is to say if
22052 you are currently positioned at a breakpoint, then a prompt will ask
22053 for confirmation that you want to abandon the current execution and
22056 @item breakpoint @var{location}
22057 The breakpoint command sets a breakpoint, that is to say a point at which
22058 execution will halt and @code{GDB} will await further
22059 commands. @var{location} is
22060 either a line number within a file, given in the format @code{file:linenumber},
22061 or it is the name of a subprogram. If you request that a breakpoint be set on
22062 a subprogram that is overloaded, a prompt will ask you to specify on which of
22063 those subprograms you want to breakpoint. You can also
22064 specify that all of them should be breakpointed. If the program is run
22065 and execution encounters the breakpoint, then the program
22066 stops and @code{GDB} signals that the breakpoint was encountered by
22067 printing the line of code before which the program is halted.
22069 @item breakpoint exception @var{name}
22070 A special form of the breakpoint command which breakpoints whenever
22071 exception @var{name} is raised.
22072 If @var{name} is omitted,
22073 then a breakpoint will occur when any exception is raised.
22075 @item print @var{expression}
22076 This will print the value of the given expression. Most simple
22077 Ada expression formats are properly handled by @code{GDB}, so the expression
22078 can contain function calls, variables, operators, and attribute references.
22081 Continues execution following a breakpoint, until the next breakpoint or the
22082 termination of the program.
22085 Executes a single line after a breakpoint. If the next statement
22086 is a subprogram call, execution continues into (the first statement of)
22087 the called subprogram.
22090 Executes a single line. If this line is a subprogram call, executes and
22091 returns from the call.
22094 Lists a few lines around the current source location. In practice, it
22095 is usually more convenient to have a separate edit window open with the
22096 relevant source file displayed. Successive applications of this command
22097 print subsequent lines. The command can be given an argument which is a
22098 line number, in which case it displays a few lines around the specified one.
22101 Displays a backtrace of the call chain. This command is typically
22102 used after a breakpoint has occurred, to examine the sequence of calls that
22103 leads to the current breakpoint. The display includes one line for each
22104 activation record (frame) corresponding to an active subprogram.
22107 At a breakpoint, @code{GDB} can display the values of variables local
22108 to the current frame. The command @code{up} can be used to
22109 examine the contents of other active frames, by moving the focus up
22110 the stack, that is to say from callee to caller, one frame at a time.
22113 Moves the focus of @code{GDB} down from the frame currently being
22114 examined to the frame of its callee (the reverse of the previous command),
22116 @item frame @var{n}
22117 Inspect the frame with the given number. The value 0 denotes the frame
22118 of the current breakpoint, that is to say the top of the call stack.
22123 The above list is a very short introduction to the commands that
22124 @code{GDB} provides. Important additional capabilities, including conditional
22125 breakpoints, the ability to execute command sequences on a breakpoint,
22126 the ability to debug at the machine instruction level and many other
22127 features are described in detail in @cite{Debugging with GDB}.
22128 Note that most commands can be abbreviated
22129 (for example, c for continue, bt for backtrace).
22131 @node Using Ada Expressions
22132 @section Using Ada Expressions
22133 @cindex Ada expressions
22136 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
22137 extensions. The philosophy behind the design of this subset is
22141 That @code{GDB} should provide basic literals and access to operations for
22142 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
22143 leaving more sophisticated computations to subprograms written into the
22144 program (which therefore may be called from @code{GDB}).
22147 That type safety and strict adherence to Ada language restrictions
22148 are not particularly important to the @code{GDB} user.
22151 That brevity is important to the @code{GDB} user.
22155 Thus, for brevity, the debugger acts as if there were
22156 implicit @code{with} and @code{use} clauses in effect for all user-written
22157 packages, thus making it unnecessary to fully qualify most names with
22158 their packages, regardless of context. Where this causes ambiguity,
22159 @code{GDB} asks the user's intent.
22161 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
22163 @node Calling User-Defined Subprograms
22164 @section Calling User-Defined Subprograms
22167 An important capability of @code{GDB} is the ability to call user-defined
22168 subprograms while debugging. This is achieved simply by entering
22169 a subprogram call statement in the form:
22172 call subprogram-name (parameters)
22176 The keyword @code{call} can be omitted in the normal case where the
22177 @code{subprogram-name} does not coincide with any of the predefined
22178 @code{GDB} commands.
22180 The effect is to invoke the given subprogram, passing it the
22181 list of parameters that is supplied. The parameters can be expressions and
22182 can include variables from the program being debugged. The
22183 subprogram must be defined
22184 at the library level within your program, and @code{GDB} will call the
22185 subprogram within the environment of your program execution (which
22186 means that the subprogram is free to access or even modify variables
22187 within your program).
22189 The most important use of this facility is in allowing the inclusion of
22190 debugging routines that are tailored to particular data structures
22191 in your program. Such debugging routines can be written to provide a suitably
22192 high-level description of an abstract type, rather than a low-level dump
22193 of its physical layout. After all, the standard
22194 @code{GDB print} command only knows the physical layout of your
22195 types, not their abstract meaning. Debugging routines can provide information
22196 at the desired semantic level and are thus enormously useful.
22198 For example, when debugging GNAT itself, it is crucial to have access to
22199 the contents of the tree nodes used to represent the program internally.
22200 But tree nodes are represented simply by an integer value (which in turn
22201 is an index into a table of nodes).
22202 Using the @code{print} command on a tree node would simply print this integer
22203 value, which is not very useful. But the PN routine (defined in file
22204 treepr.adb in the GNAT sources) takes a tree node as input, and displays
22205 a useful high level representation of the tree node, which includes the
22206 syntactic category of the node, its position in the source, the integers
22207 that denote descendant nodes and parent node, as well as varied
22208 semantic information. To study this example in more detail, you might want to
22209 look at the body of the PN procedure in the stated file.
22211 @node Using the Next Command in a Function
22212 @section Using the Next Command in a Function
22215 When you use the @code{next} command in a function, the current source
22216 location will advance to the next statement as usual. A special case
22217 arises in the case of a @code{return} statement.
22219 Part of the code for a return statement is the ``epilog'' of the function.
22220 This is the code that returns to the caller. There is only one copy of
22221 this epilog code, and it is typically associated with the last return
22222 statement in the function if there is more than one return. In some
22223 implementations, this epilog is associated with the first statement
22226 The result is that if you use the @code{next} command from a return
22227 statement that is not the last return statement of the function you
22228 may see a strange apparent jump to the last return statement or to
22229 the start of the function. You should simply ignore this odd jump.
22230 The value returned is always that from the first return statement
22231 that was stepped through.
22233 @node Ada Exceptions
22234 @section Breaking on Ada Exceptions
22238 You can set breakpoints that trip when your program raises
22239 selected exceptions.
22242 @item break exception
22243 Set a breakpoint that trips whenever (any task in the) program raises
22246 @item break exception @var{name}
22247 Set a breakpoint that trips whenever (any task in the) program raises
22248 the exception @var{name}.
22250 @item break exception unhandled
22251 Set a breakpoint that trips whenever (any task in the) program raises an
22252 exception for which there is no handler.
22254 @item info exceptions
22255 @itemx info exceptions @var{regexp}
22256 The @code{info exceptions} command permits the user to examine all defined
22257 exceptions within Ada programs. With a regular expression, @var{regexp}, as
22258 argument, prints out only those exceptions whose name matches @var{regexp}.
22266 @code{GDB} allows the following task-related commands:
22270 This command shows a list of current Ada tasks, as in the following example:
22277 ID TID P-ID Thread Pri State Name
22278 1 8088000 0 807e000 15 Child Activation Wait main_task
22279 2 80a4000 1 80ae000 15 Accept/Select Wait b
22280 3 809a800 1 80a4800 15 Child Activation Wait a
22281 * 4 80ae800 3 80b8000 15 Running c
22285 In this listing, the asterisk before the first task indicates it to be the
22286 currently running task. The first column lists the task ID that is used
22287 to refer to tasks in the following commands.
22289 @item break @var{linespec} task @var{taskid}
22290 @itemx break @var{linespec} task @var{taskid} if @dots{}
22291 @cindex Breakpoints and tasks
22292 These commands are like the @code{break @dots{} thread @dots{}}.
22293 @var{linespec} specifies source lines.
22295 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
22296 to specify that you only want @code{GDB} to stop the program when a
22297 particular Ada task reaches this breakpoint. @var{taskid} is one of the
22298 numeric task identifiers assigned by @code{GDB}, shown in the first
22299 column of the @samp{info tasks} display.
22301 If you do not specify @samp{task @var{taskid}} when you set a
22302 breakpoint, the breakpoint applies to @emph{all} tasks of your
22305 You can use the @code{task} qualifier on conditional breakpoints as
22306 well; in this case, place @samp{task @var{taskid}} before the
22307 breakpoint condition (before the @code{if}).
22309 @item task @var{taskno}
22310 @cindex Task switching
22312 This command allows to switch to the task referred by @var{taskno}. In
22313 particular, This allows to browse the backtrace of the specified
22314 task. It is advised to switch back to the original task before
22315 continuing execution otherwise the scheduling of the program may be
22320 For more detailed information on the tasking support,
22321 see @cite{Debugging with GDB}.
22323 @node Debugging Generic Units
22324 @section Debugging Generic Units
22325 @cindex Debugging Generic Units
22329 GNAT always uses code expansion for generic instantiation. This means that
22330 each time an instantiation occurs, a complete copy of the original code is
22331 made, with appropriate substitutions of formals by actuals.
22333 It is not possible to refer to the original generic entities in
22334 @code{GDB}, but it is always possible to debug a particular instance of
22335 a generic, by using the appropriate expanded names. For example, if we have
22337 @smallexample @c ada
22342 generic package k is
22343 procedure kp (v1 : in out integer);
22347 procedure kp (v1 : in out integer) is
22353 package k1 is new k;
22354 package k2 is new k;
22356 var : integer := 1;
22369 Then to break on a call to procedure kp in the k2 instance, simply
22373 (gdb) break g.k2.kp
22377 When the breakpoint occurs, you can step through the code of the
22378 instance in the normal manner and examine the values of local variables, as for
22381 @node GNAT Abnormal Termination or Failure to Terminate
22382 @section GNAT Abnormal Termination or Failure to Terminate
22383 @cindex GNAT Abnormal Termination or Failure to Terminate
22386 When presented with programs that contain serious errors in syntax
22388 GNAT may on rare occasions experience problems in operation, such
22390 segmentation fault or illegal memory access, raising an internal
22391 exception, terminating abnormally, or failing to terminate at all.
22392 In such cases, you can activate
22393 various features of GNAT that can help you pinpoint the construct in your
22394 program that is the likely source of the problem.
22396 The following strategies are presented in increasing order of
22397 difficulty, corresponding to your experience in using GNAT and your
22398 familiarity with compiler internals.
22402 Run @command{gcc} with the @option{-gnatf}. This first
22403 switch causes all errors on a given line to be reported. In its absence,
22404 only the first error on a line is displayed.
22406 The @option{-gnatdO} switch causes errors to be displayed as soon as they
22407 are encountered, rather than after compilation is terminated. If GNAT
22408 terminates prematurely or goes into an infinite loop, the last error
22409 message displayed may help to pinpoint the culprit.
22412 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
22413 mode, @command{gcc} produces ongoing information about the progress of the
22414 compilation and provides the name of each procedure as code is
22415 generated. This switch allows you to find which Ada procedure was being
22416 compiled when it encountered a code generation problem.
22419 @cindex @option{-gnatdc} switch
22420 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
22421 switch that does for the front-end what @option{^-v^VERBOSE^} does
22422 for the back end. The system prints the name of each unit,
22423 either a compilation unit or nested unit, as it is being analyzed.
22425 Finally, you can start
22426 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
22427 front-end of GNAT, and can be run independently (normally it is just
22428 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
22429 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
22430 @code{where} command is the first line of attack; the variable
22431 @code{lineno} (seen by @code{print lineno}), used by the second phase of
22432 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
22433 which the execution stopped, and @code{input_file name} indicates the name of
22437 @node Naming Conventions for GNAT Source Files
22438 @section Naming Conventions for GNAT Source Files
22441 In order to examine the workings of the GNAT system, the following
22442 brief description of its organization may be helpful:
22446 Files with prefix @file{^sc^SC^} contain the lexical scanner.
22449 All files prefixed with @file{^par^PAR^} are components of the parser. The
22450 numbers correspond to chapters of the Ada Reference Manual. For example,
22451 parsing of select statements can be found in @file{par-ch9.adb}.
22454 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
22455 numbers correspond to chapters of the Ada standard. For example, all
22456 issues involving context clauses can be found in @file{sem_ch10.adb}. In
22457 addition, some features of the language require sufficient special processing
22458 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
22459 dynamic dispatching, etc.
22462 All files prefixed with @file{^exp^EXP^} perform normalization and
22463 expansion of the intermediate representation (abstract syntax tree, or AST).
22464 these files use the same numbering scheme as the parser and semantics files.
22465 For example, the construction of record initialization procedures is done in
22466 @file{exp_ch3.adb}.
22469 The files prefixed with @file{^bind^BIND^} implement the binder, which
22470 verifies the consistency of the compilation, determines an order of
22471 elaboration, and generates the bind file.
22474 The files @file{atree.ads} and @file{atree.adb} detail the low-level
22475 data structures used by the front-end.
22478 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
22479 the abstract syntax tree as produced by the parser.
22482 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
22483 all entities, computed during semantic analysis.
22486 Library management issues are dealt with in files with prefix
22492 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
22493 defined in Annex A.
22498 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
22499 defined in Annex B.
22503 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
22504 both language-defined children and GNAT run-time routines.
22508 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
22509 general-purpose packages, fully documented in their specifications. All
22510 the other @file{.c} files are modifications of common @command{gcc} files.
22513 @node Getting Internal Debugging Information
22514 @section Getting Internal Debugging Information
22517 Most compilers have internal debugging switches and modes. GNAT
22518 does also, except GNAT internal debugging switches and modes are not
22519 secret. A summary and full description of all the compiler and binder
22520 debug flags are in the file @file{debug.adb}. You must obtain the
22521 sources of the compiler to see the full detailed effects of these flags.
22523 The switches that print the source of the program (reconstructed from
22524 the internal tree) are of general interest for user programs, as are the
22526 the full internal tree, and the entity table (the symbol table
22527 information). The reconstructed source provides a readable version of the
22528 program after the front-end has completed analysis and expansion,
22529 and is useful when studying the performance of specific constructs.
22530 For example, constraint checks are indicated, complex aggregates
22531 are replaced with loops and assignments, and tasking primitives
22532 are replaced with run-time calls.
22534 @node Stack Traceback
22535 @section Stack Traceback
22537 @cindex stack traceback
22538 @cindex stack unwinding
22541 Traceback is a mechanism to display the sequence of subprogram calls that
22542 leads to a specified execution point in a program. Often (but not always)
22543 the execution point is an instruction at which an exception has been raised.
22544 This mechanism is also known as @i{stack unwinding} because it obtains
22545 its information by scanning the run-time stack and recovering the activation
22546 records of all active subprograms. Stack unwinding is one of the most
22547 important tools for program debugging.
22549 The first entry stored in traceback corresponds to the deepest calling level,
22550 that is to say the subprogram currently executing the instruction
22551 from which we want to obtain the traceback.
22553 Note that there is no runtime performance penalty when stack traceback
22554 is enabled, and no exception is raised during program execution.
22557 * Non-Symbolic Traceback::
22558 * Symbolic Traceback::
22561 @node Non-Symbolic Traceback
22562 @subsection Non-Symbolic Traceback
22563 @cindex traceback, non-symbolic
22566 Note: this feature is not supported on all platforms. See
22567 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
22571 * Tracebacks From an Unhandled Exception::
22572 * Tracebacks From Exception Occurrences (non-symbolic)::
22573 * Tracebacks From Anywhere in a Program (non-symbolic)::
22576 @node Tracebacks From an Unhandled Exception
22577 @subsubsection Tracebacks From an Unhandled Exception
22580 A runtime non-symbolic traceback is a list of addresses of call instructions.
22581 To enable this feature you must use the @option{-E}
22582 @code{gnatbind}'s option. With this option a stack traceback is stored as part
22583 of exception information. You can retrieve this information using the
22584 @code{addr2line} tool.
22586 Here is a simple example:
22588 @smallexample @c ada
22594 raise Constraint_Error;
22609 $ gnatmake stb -bargs -E
22612 Execution terminated by unhandled exception
22613 Exception name: CONSTRAINT_ERROR
22615 Call stack traceback locations:
22616 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
22620 As we see the traceback lists a sequence of addresses for the unhandled
22621 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
22622 guess that this exception come from procedure P1. To translate these
22623 addresses into the source lines where the calls appear, the
22624 @code{addr2line} tool, described below, is invaluable. The use of this tool
22625 requires the program to be compiled with debug information.
22628 $ gnatmake -g stb -bargs -E
22631 Execution terminated by unhandled exception
22632 Exception name: CONSTRAINT_ERROR
22634 Call stack traceback locations:
22635 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
22637 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
22638 0x4011f1 0x77e892a4
22640 00401373 at d:/stb/stb.adb:5
22641 0040138B at d:/stb/stb.adb:10
22642 0040139C at d:/stb/stb.adb:14
22643 00401335 at d:/stb/b~stb.adb:104
22644 004011C4 at /build/.../crt1.c:200
22645 004011F1 at /build/.../crt1.c:222
22646 77E892A4 in ?? at ??:0
22650 The @code{addr2line} tool has several other useful options:
22654 to get the function name corresponding to any location
22656 @item --demangle=gnat
22657 to use the gnat decoding mode for the function names. Note that
22658 for binutils version 2.9.x the option is simply @option{--demangle}.
22662 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
22663 0x40139c 0x401335 0x4011c4 0x4011f1
22665 00401373 in stb.p1 at d:/stb/stb.adb:5
22666 0040138B in stb.p2 at d:/stb/stb.adb:10
22667 0040139C in stb at d:/stb/stb.adb:14
22668 00401335 in main at d:/stb/b~stb.adb:104
22669 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
22670 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
22674 From this traceback we can see that the exception was raised in
22675 @file{stb.adb} at line 5, which was reached from a procedure call in
22676 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
22677 which contains the call to the main program.
22678 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
22679 and the output will vary from platform to platform.
22681 It is also possible to use @code{GDB} with these traceback addresses to debug
22682 the program. For example, we can break at a given code location, as reported
22683 in the stack traceback:
22689 Furthermore, this feature is not implemented inside Windows DLL. Only
22690 the non-symbolic traceback is reported in this case.
22693 (gdb) break *0x401373
22694 Breakpoint 1 at 0x401373: file stb.adb, line 5.
22698 It is important to note that the stack traceback addresses
22699 do not change when debug information is included. This is particularly useful
22700 because it makes it possible to release software without debug information (to
22701 minimize object size), get a field report that includes a stack traceback
22702 whenever an internal bug occurs, and then be able to retrieve the sequence
22703 of calls with the same program compiled with debug information.
22705 @node Tracebacks From Exception Occurrences (non-symbolic)
22706 @subsubsection Tracebacks From Exception Occurrences
22709 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
22710 The stack traceback is attached to the exception information string, and can
22711 be retrieved in an exception handler within the Ada program, by means of the
22712 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
22714 @smallexample @c ada
22716 with Ada.Exceptions;
22721 use Ada.Exceptions;
22729 Text_IO.Put_Line (Exception_Information (E));
22743 This program will output:
22748 Exception name: CONSTRAINT_ERROR
22749 Message: stb.adb:12
22750 Call stack traceback locations:
22751 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
22754 @node Tracebacks From Anywhere in a Program (non-symbolic)
22755 @subsubsection Tracebacks From Anywhere in a Program
22758 It is also possible to retrieve a stack traceback from anywhere in a
22759 program. For this you need to
22760 use the @code{GNAT.Traceback} API. This package includes a procedure called
22761 @code{Call_Chain} that computes a complete stack traceback, as well as useful
22762 display procedures described below. It is not necessary to use the
22763 @option{-E gnatbind} option in this case, because the stack traceback mechanism
22764 is invoked explicitly.
22767 In the following example we compute a traceback at a specific location in
22768 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
22769 convert addresses to strings:
22771 @smallexample @c ada
22773 with GNAT.Traceback;
22774 with GNAT.Debug_Utilities;
22780 use GNAT.Traceback;
22783 TB : Tracebacks_Array (1 .. 10);
22784 -- We are asking for a maximum of 10 stack frames.
22786 -- Len will receive the actual number of stack frames returned.
22788 Call_Chain (TB, Len);
22790 Text_IO.Put ("In STB.P1 : ");
22792 for K in 1 .. Len loop
22793 Text_IO.Put (Debug_Utilities.Image (TB (K)));
22814 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
22815 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
22819 You can then get further information by invoking the @code{addr2line}
22820 tool as described earlier (note that the hexadecimal addresses
22821 need to be specified in C format, with a leading ``0x'').
22823 @node Symbolic Traceback
22824 @subsection Symbolic Traceback
22825 @cindex traceback, symbolic
22828 A symbolic traceback is a stack traceback in which procedure names are
22829 associated with each code location.
22832 Note that this feature is not supported on all platforms. See
22833 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
22834 list of currently supported platforms.
22837 Note that the symbolic traceback requires that the program be compiled
22838 with debug information. If it is not compiled with debug information
22839 only the non-symbolic information will be valid.
22842 * Tracebacks From Exception Occurrences (symbolic)::
22843 * Tracebacks From Anywhere in a Program (symbolic)::
22846 @node Tracebacks From Exception Occurrences (symbolic)
22847 @subsubsection Tracebacks From Exception Occurrences
22849 @smallexample @c ada
22851 with GNAT.Traceback.Symbolic;
22857 raise Constraint_Error;
22874 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
22879 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
22882 0040149F in stb.p1 at stb.adb:8
22883 004014B7 in stb.p2 at stb.adb:13
22884 004014CF in stb.p3 at stb.adb:18
22885 004015DD in ada.stb at stb.adb:22
22886 00401461 in main at b~stb.adb:168
22887 004011C4 in __mingw_CRTStartup at crt1.c:200
22888 004011F1 in mainCRTStartup at crt1.c:222
22889 77E892A4 in ?? at ??:0
22893 In the above example the ``.\'' syntax in the @command{gnatmake} command
22894 is currently required by @command{addr2line} for files that are in
22895 the current working directory.
22896 Moreover, the exact sequence of linker options may vary from platform
22898 The above @option{-largs} section is for Windows platforms. By contrast,
22899 under Unix there is no need for the @option{-largs} section.
22900 Differences across platforms are due to details of linker implementation.
22902 @node Tracebacks From Anywhere in a Program (symbolic)
22903 @subsubsection Tracebacks From Anywhere in a Program
22906 It is possible to get a symbolic stack traceback
22907 from anywhere in a program, just as for non-symbolic tracebacks.
22908 The first step is to obtain a non-symbolic
22909 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
22910 information. Here is an example:
22912 @smallexample @c ada
22914 with GNAT.Traceback;
22915 with GNAT.Traceback.Symbolic;
22920 use GNAT.Traceback;
22921 use GNAT.Traceback.Symbolic;
22924 TB : Tracebacks_Array (1 .. 10);
22925 -- We are asking for a maximum of 10 stack frames.
22927 -- Len will receive the actual number of stack frames returned.
22929 Call_Chain (TB, Len);
22930 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
22943 @c ******************************
22945 @node Compatibility with HP Ada
22946 @chapter Compatibility with HP Ada
22947 @cindex Compatibility
22952 @cindex Compatibility between GNAT and HP Ada
22953 This chapter compares HP Ada (formerly known as ``DEC Ada'')
22954 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
22955 GNAT is highly compatible
22956 with HP Ada, and it should generally be straightforward to port code
22957 from the HP Ada environment to GNAT. However, there are a few language
22958 and implementation differences of which the user must be aware. These
22959 differences are discussed in this chapter. In
22960 addition, the operating environment and command structure for the
22961 compiler are different, and these differences are also discussed.
22963 For further details on these and other compatibility issues,
22964 see Appendix E of the HP publication
22965 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
22967 Except where otherwise indicated, the description of GNAT for OpenVMS
22968 applies to both the Alpha and I64 platforms.
22970 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
22971 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
22973 The discussion in this chapter addresses specifically the implementation
22974 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
22975 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
22976 GNAT always follows the Alpha implementation.
22978 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
22979 attributes are recognized, although only a subset of them can sensibly
22980 be implemented. The description of pragmas in the
22981 @cite{GNAT Reference Manual} indicates whether or not they are applicable
22982 to non-VMS systems.
22985 * Ada Language Compatibility::
22986 * Differences in the Definition of Package System::
22987 * Language-Related Features::
22988 * The Package STANDARD::
22989 * The Package SYSTEM::
22990 * Tasking and Task-Related Features::
22991 * Pragmas and Pragma-Related Features::
22992 * Library of Predefined Units::
22994 * Main Program Definition::
22995 * Implementation-Defined Attributes::
22996 * Compiler and Run-Time Interfacing::
22997 * Program Compilation and Library Management::
22999 * Implementation Limits::
23000 * Tools and Utilities::
23003 @node Ada Language Compatibility
23004 @section Ada Language Compatibility
23007 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
23008 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
23009 with Ada 83, and therefore Ada 83 programs will compile
23010 and run under GNAT with
23011 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
23012 provides details on specific incompatibilities.
23014 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
23015 as well as the pragma @code{ADA_83}, to force the compiler to
23016 operate in Ada 83 mode. This mode does not guarantee complete
23017 conformance to Ada 83, but in practice is sufficient to
23018 eliminate most sources of incompatibilities.
23019 In particular, it eliminates the recognition of the
23020 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
23021 in Ada 83 programs is legal, and handles the cases of packages
23022 with optional bodies, and generics that instantiate unconstrained
23023 types without the use of @code{(<>)}.
23025 @node Differences in the Definition of Package System
23026 @section Differences in the Definition of Package @code{System}
23029 An Ada compiler is allowed to add
23030 implementation-dependent declarations to package @code{System}.
23032 GNAT does not take advantage of this permission, and the version of
23033 @code{System} provided by GNAT exactly matches that defined in the Ada
23036 However, HP Ada adds an extensive set of declarations to package
23038 as fully documented in the HP Ada manuals. To minimize changes required
23039 for programs that make use of these extensions, GNAT provides the pragma
23040 @code{Extend_System} for extending the definition of package System. By using:
23041 @cindex pragma @code{Extend_System}
23042 @cindex @code{Extend_System} pragma
23044 @smallexample @c ada
23047 pragma Extend_System (Aux_DEC);
23053 the set of definitions in @code{System} is extended to include those in
23054 package @code{System.Aux_DEC}.
23055 @cindex @code{System.Aux_DEC} package
23056 @cindex @code{Aux_DEC} package (child of @code{System})
23057 These definitions are incorporated directly into package @code{System},
23058 as though they had been declared there. For a
23059 list of the declarations added, see the specification of this package,
23060 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
23061 @cindex @file{s-auxdec.ads} file
23062 The pragma @code{Extend_System} is a configuration pragma, which means that
23063 it can be placed in the file @file{gnat.adc}, so that it will automatically
23064 apply to all subsequent compilations. See @ref{Configuration Pragmas},
23065 for further details.
23067 An alternative approach that avoids the use of the non-standard
23068 @code{Extend_System} pragma is to add a context clause to the unit that
23069 references these facilities:
23071 @smallexample @c ada
23073 with System.Aux_DEC;
23074 use System.Aux_DEC;
23079 The effect is not quite semantically identical to incorporating
23080 the declarations directly into package @code{System},
23081 but most programs will not notice a difference
23082 unless they use prefix notation (e.g. @code{System.Integer_8})
23083 to reference the entities directly in package @code{System}.
23084 For units containing such references,
23085 the prefixes must either be removed, or the pragma @code{Extend_System}
23088 @node Language-Related Features
23089 @section Language-Related Features
23092 The following sections highlight differences in types,
23093 representations of types, operations, alignment, and
23097 * Integer Types and Representations::
23098 * Floating-Point Types and Representations::
23099 * Pragmas Float_Representation and Long_Float::
23100 * Fixed-Point Types and Representations::
23101 * Record and Array Component Alignment::
23102 * Address Clauses::
23103 * Other Representation Clauses::
23106 @node Integer Types and Representations
23107 @subsection Integer Types and Representations
23110 The set of predefined integer types is identical in HP Ada and GNAT.
23111 Furthermore the representation of these integer types is also identical,
23112 including the capability of size clauses forcing biased representation.
23115 HP Ada for OpenVMS Alpha systems has defined the
23116 following additional integer types in package @code{System}:
23133 @code{LARGEST_INTEGER}
23137 In GNAT, the first four of these types may be obtained from the
23138 standard Ada package @code{Interfaces}.
23139 Alternatively, by use of the pragma @code{Extend_System}, identical
23140 declarations can be referenced directly in package @code{System}.
23141 On both GNAT and HP Ada, the maximum integer size is 64 bits.
23143 @node Floating-Point Types and Representations
23144 @subsection Floating-Point Types and Representations
23145 @cindex Floating-Point types
23148 The set of predefined floating-point types is identical in HP Ada and GNAT.
23149 Furthermore the representation of these floating-point
23150 types is also identical. One important difference is that the default
23151 representation for HP Ada is @code{VAX_Float}, but the default representation
23154 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
23155 pragma @code{Float_Representation} as described in the HP Ada
23157 For example, the declarations:
23159 @smallexample @c ada
23161 type F_Float is digits 6;
23162 pragma Float_Representation (VAX_Float, F_Float);
23167 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
23169 This set of declarations actually appears in @code{System.Aux_DEC},
23171 the full set of additional floating-point declarations provided in
23172 the HP Ada version of package @code{System}.
23173 This and similar declarations may be accessed in a user program
23174 by using pragma @code{Extend_System}. The use of this
23175 pragma, and the related pragma @code{Long_Float} is described in further
23176 detail in the following section.
23178 @node Pragmas Float_Representation and Long_Float
23179 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
23182 HP Ada provides the pragma @code{Float_Representation}, which
23183 acts as a program library switch to allow control over
23184 the internal representation chosen for the predefined
23185 floating-point types declared in the package @code{Standard}.
23186 The format of this pragma is as follows:
23188 @smallexample @c ada
23190 pragma Float_Representation(VAX_Float | IEEE_Float);
23195 This pragma controls the representation of floating-point
23200 @code{VAX_Float} specifies that floating-point
23201 types are represented by default with the VAX system hardware types
23202 @code{F-floating}, @code{D-floating}, @code{G-floating}.
23203 Note that the @code{H-floating}
23204 type was available only on VAX systems, and is not available
23205 in either HP Ada or GNAT.
23208 @code{IEEE_Float} specifies that floating-point
23209 types are represented by default with the IEEE single and
23210 double floating-point types.
23214 GNAT provides an identical implementation of the pragma
23215 @code{Float_Representation}, except that it functions as a
23216 configuration pragma. Note that the
23217 notion of configuration pragma corresponds closely to the
23218 HP Ada notion of a program library switch.
23220 When no pragma is used in GNAT, the default is @code{IEEE_Float},
23222 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
23223 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
23224 advisable to change the format of numbers passed to standard library
23225 routines, and if necessary explicit type conversions may be needed.
23227 The use of @code{IEEE_Float} is recommended in GNAT since it is more
23228 efficient, and (given that it conforms to an international standard)
23229 potentially more portable.
23230 The situation in which @code{VAX_Float} may be useful is in interfacing
23231 to existing code and data that expect the use of @code{VAX_Float}.
23232 In such a situation use the predefined @code{VAX_Float}
23233 types in package @code{System}, as extended by
23234 @code{Extend_System}. For example, use @code{System.F_Float}
23235 to specify the 32-bit @code{F-Float} format.
23238 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
23239 to allow control over the internal representation chosen
23240 for the predefined type @code{Long_Float} and for floating-point
23241 type declarations with digits specified in the range 7 .. 15.
23242 The format of this pragma is as follows:
23244 @smallexample @c ada
23246 pragma Long_Float (D_FLOAT | G_FLOAT);
23250 @node Fixed-Point Types and Representations
23251 @subsection Fixed-Point Types and Representations
23254 On HP Ada for OpenVMS Alpha systems, rounding is
23255 away from zero for both positive and negative numbers.
23256 Therefore, @code{+0.5} rounds to @code{1},
23257 and @code{-0.5} rounds to @code{-1}.
23259 On GNAT the results of operations
23260 on fixed-point types are in accordance with the Ada
23261 rules. In particular, results of operations on decimal
23262 fixed-point types are truncated.
23264 @node Record and Array Component Alignment
23265 @subsection Record and Array Component Alignment
23268 On HP Ada for OpenVMS Alpha, all non composite components
23269 are aligned on natural boundaries. For example, 1-byte
23270 components are aligned on byte boundaries, 2-byte
23271 components on 2-byte boundaries, 4-byte components on 4-byte
23272 byte boundaries, and so on. The OpenVMS Alpha hardware
23273 runs more efficiently with naturally aligned data.
23275 On GNAT, alignment rules are compatible
23276 with HP Ada for OpenVMS Alpha.
23278 @node Address Clauses
23279 @subsection Address Clauses
23282 In HP Ada and GNAT, address clauses are supported for
23283 objects and imported subprograms.
23284 The predefined type @code{System.Address} is a private type
23285 in both compilers on Alpha OpenVMS, with the same representation
23286 (it is simply a machine pointer). Addition, subtraction, and comparison
23287 operations are available in the standard Ada package
23288 @code{System.Storage_Elements}, or in package @code{System}
23289 if it is extended to include @code{System.Aux_DEC} using a
23290 pragma @code{Extend_System} as previously described.
23292 Note that code that @code{with}'s both this extended package @code{System}
23293 and the package @code{System.Storage_Elements} should not @code{use}
23294 both packages, or ambiguities will result. In general it is better
23295 not to mix these two sets of facilities. The Ada package was
23296 designed specifically to provide the kind of features that HP Ada
23297 adds directly to package @code{System}.
23299 The type @code{System.Address} is a 64-bit integer type in GNAT for
23300 I64 OpenVMS. For more information,
23301 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
23303 GNAT is compatible with HP Ada in its handling of address
23304 clauses, except for some limitations in
23305 the form of address clauses for composite objects with
23306 initialization. Such address clauses are easily replaced
23307 by the use of an explicitly-defined constant as described
23308 in the Ada Reference Manual (13.1(22)). For example, the sequence
23311 @smallexample @c ada
23313 X, Y : Integer := Init_Func;
23314 Q : String (X .. Y) := "abc";
23316 for Q'Address use Compute_Address;
23321 will be rejected by GNAT, since the address cannot be computed at the time
23322 that @code{Q} is declared. To achieve the intended effect, write instead:
23324 @smallexample @c ada
23327 X, Y : Integer := Init_Func;
23328 Q_Address : constant Address := Compute_Address;
23329 Q : String (X .. Y) := "abc";
23331 for Q'Address use Q_Address;
23337 which will be accepted by GNAT (and other Ada compilers), and is also
23338 compatible with Ada 83. A fuller description of the restrictions
23339 on address specifications is found in the @cite{GNAT Reference Manual}.
23341 @node Other Representation Clauses
23342 @subsection Other Representation Clauses
23345 GNAT implements in a compatible manner all the representation
23346 clauses supported by HP Ada. In addition, GNAT
23347 implements the representation clause forms that were introduced in Ada 95,
23348 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
23350 @node The Package STANDARD
23351 @section The Package @code{STANDARD}
23354 The package @code{STANDARD}, as implemented by HP Ada, is fully
23355 described in the @cite{Ada Reference Manual} and in the
23356 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
23357 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
23359 In addition, HP Ada supports the Latin-1 character set in
23360 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
23361 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
23362 the type @code{WIDE_CHARACTER}.
23364 The floating-point types supported by GNAT are those
23365 supported by HP Ada, but the defaults are different, and are controlled by
23366 pragmas. See @ref{Floating-Point Types and Representations}, for details.
23368 @node The Package SYSTEM
23369 @section The Package @code{SYSTEM}
23372 HP Ada provides a specific version of the package
23373 @code{SYSTEM} for each platform on which the language is implemented.
23374 For the complete specification of the package @code{SYSTEM}, see
23375 Appendix F of the @cite{HP Ada Language Reference Manual}.
23377 On HP Ada, the package @code{SYSTEM} includes the following conversion
23380 @item @code{TO_ADDRESS(INTEGER)}
23382 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
23384 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
23386 @item @code{TO_INTEGER(ADDRESS)}
23388 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
23390 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
23391 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
23395 By default, GNAT supplies a version of @code{SYSTEM} that matches
23396 the definition given in the @cite{Ada Reference Manual}.
23398 is a subset of the HP system definitions, which is as
23399 close as possible to the original definitions. The only difference
23400 is that the definition of @code{SYSTEM_NAME} is different:
23402 @smallexample @c ada
23404 type Name is (SYSTEM_NAME_GNAT);
23405 System_Name : constant Name := SYSTEM_NAME_GNAT;
23410 Also, GNAT adds the Ada declarations for
23411 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
23413 However, the use of the following pragma causes GNAT
23414 to extend the definition of package @code{SYSTEM} so that it
23415 encompasses the full set of HP-specific extensions,
23416 including the functions listed above:
23418 @smallexample @c ada
23420 pragma Extend_System (Aux_DEC);
23425 The pragma @code{Extend_System} is a configuration pragma that
23426 is most conveniently placed in the @file{gnat.adc} file. See the
23427 @cite{GNAT Reference Manual} for further details.
23429 HP Ada does not allow the recompilation of the package
23430 @code{SYSTEM}. Instead HP Ada provides several pragmas
23431 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
23432 to modify values in the package @code{SYSTEM}.
23433 On OpenVMS Alpha systems, the pragma
23434 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
23435 its single argument.
23437 GNAT does permit the recompilation of package @code{SYSTEM} using
23438 the special switch @option{-gnatg}, and this switch can be used if
23439 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
23440 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
23441 or @code{MEMORY_SIZE} by any other means.
23443 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
23444 enumeration literal @code{SYSTEM_NAME_GNAT}.
23446 The definitions provided by the use of
23448 @smallexample @c ada
23449 pragma Extend_System (AUX_Dec);
23453 are virtually identical to those provided by the HP Ada 83 package
23454 @code{SYSTEM}. One important difference is that the name of the
23456 function for type @code{UNSIGNED_LONGWORD} is changed to
23457 @code{TO_ADDRESS_LONG}.
23458 See the @cite{GNAT Reference Manual} for a discussion of why this change was
23462 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
23464 an extension to Ada 83 not strictly compatible with the reference manual.
23465 GNAT, in order to be exactly compatible with the standard,
23466 does not provide this capability. In HP Ada 83, the
23467 point of this definition is to deal with a call like:
23469 @smallexample @c ada
23470 TO_ADDRESS (16#12777#);
23474 Normally, according to Ada 83 semantics, one would expect this to be
23475 ambiguous, since it matches both the @code{INTEGER} and
23476 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
23477 However, in HP Ada 83, there is no ambiguity, since the
23478 definition using @i{universal_integer} takes precedence.
23480 In GNAT, since the version with @i{universal_integer} cannot be supplied,
23482 not possible to be 100% compatible. Since there are many programs using
23483 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
23485 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
23486 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
23488 @smallexample @c ada
23489 function To_Address (X : Integer) return Address;
23490 pragma Pure_Function (To_Address);
23492 function To_Address_Long (X : Unsigned_Longword) return Address;
23493 pragma Pure_Function (To_Address_Long);
23497 This means that programs using @code{TO_ADDRESS} for
23498 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
23500 @node Tasking and Task-Related Features
23501 @section Tasking and Task-Related Features
23504 This section compares the treatment of tasking in GNAT
23505 and in HP Ada for OpenVMS Alpha.
23506 The GNAT description applies to both Alpha and I64 OpenVMS.
23507 For detailed information on tasking in
23508 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
23509 relevant run-time reference manual.
23512 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
23513 * Assigning Task IDs::
23514 * Task IDs and Delays::
23515 * Task-Related Pragmas::
23516 * Scheduling and Task Priority::
23518 * External Interrupts::
23521 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
23522 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
23525 On OpenVMS Alpha systems, each Ada task (except a passive
23526 task) is implemented as a single stream of execution
23527 that is created and managed by the kernel. On these
23528 systems, HP Ada tasking support is based on DECthreads,
23529 an implementation of the POSIX standard for threads.
23531 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
23532 code that calls DECthreads routines can be used together.
23533 The interaction between Ada tasks and DECthreads routines
23534 can have some benefits. For example when on OpenVMS Alpha,
23535 HP Ada can call C code that is already threaded.
23537 GNAT uses the facilities of DECthreads,
23538 and Ada tasks are mapped to threads.
23540 @node Assigning Task IDs
23541 @subsection Assigning Task IDs
23544 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
23545 the environment task that executes the main program. On
23546 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
23547 that have been created but are not yet activated.
23549 On OpenVMS Alpha systems, task IDs are assigned at
23550 activation. On GNAT systems, task IDs are also assigned at
23551 task creation but do not have the same form or values as
23552 task ID values in HP Ada. There is no null task, and the
23553 environment task does not have a specific task ID value.
23555 @node Task IDs and Delays
23556 @subsection Task IDs and Delays
23559 On OpenVMS Alpha systems, tasking delays are implemented
23560 using Timer System Services. The Task ID is used for the
23561 identification of the timer request (the @code{REQIDT} parameter).
23562 If Timers are used in the application take care not to use
23563 @code{0} for the identification, because cancelling such a timer
23564 will cancel all timers and may lead to unpredictable results.
23566 @node Task-Related Pragmas
23567 @subsection Task-Related Pragmas
23570 Ada supplies the pragma @code{TASK_STORAGE}, which allows
23571 specification of the size of the guard area for a task
23572 stack. (The guard area forms an area of memory that has no
23573 read or write access and thus helps in the detection of
23574 stack overflow.) On OpenVMS Alpha systems, if the pragma
23575 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
23576 area is created. In the absence of a pragma @code{TASK_STORAGE},
23577 a default guard area is created.
23579 GNAT supplies the following task-related pragmas:
23582 @item @code{TASK_INFO}
23584 This pragma appears within a task definition and
23585 applies to the task in which it appears. The argument
23586 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
23588 @item @code{TASK_STORAGE}
23590 GNAT implements pragma @code{TASK_STORAGE} in the same way as
23592 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
23593 @code{SUPPRESS}, and @code{VOLATILE}.
23595 @node Scheduling and Task Priority
23596 @subsection Scheduling and Task Priority
23599 HP Ada implements the Ada language requirement that
23600 when two tasks are eligible for execution and they have
23601 different priorities, the lower priority task does not
23602 execute while the higher priority task is waiting. The HP
23603 Ada Run-Time Library keeps a task running until either the
23604 task is suspended or a higher priority task becomes ready.
23606 On OpenVMS Alpha systems, the default strategy is round-
23607 robin with preemption. Tasks of equal priority take turns
23608 at the processor. A task is run for a certain period of
23609 time and then placed at the tail of the ready queue for
23610 its priority level.
23612 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
23613 which can be used to enable or disable round-robin
23614 scheduling of tasks with the same priority.
23615 See the relevant HP Ada run-time reference manual for
23616 information on using the pragmas to control HP Ada task
23619 GNAT follows the scheduling rules of Annex D (Real-Time
23620 Annex) of the @cite{Ada Reference Manual}. In general, this
23621 scheduling strategy is fully compatible with HP Ada
23622 although it provides some additional constraints (as
23623 fully documented in Annex D).
23624 GNAT implements time slicing control in a manner compatible with
23625 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
23626 are identical to the HP Ada 83 pragma of the same name.
23627 Note that it is not possible to mix GNAT tasking and
23628 HP Ada 83 tasking in the same program, since the two run-time
23629 libraries are not compatible.
23631 @node The Task Stack
23632 @subsection The Task Stack
23635 In HP Ada, a task stack is allocated each time a
23636 non-passive task is activated. As soon as the task is
23637 terminated, the storage for the task stack is deallocated.
23638 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
23639 a default stack size is used. Also, regardless of the size
23640 specified, some additional space is allocated for task
23641 management purposes. On OpenVMS Alpha systems, at least
23642 one page is allocated.
23644 GNAT handles task stacks in a similar manner. In accordance with
23645 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
23646 an alternative method for controlling the task stack size.
23647 The specification of the attribute @code{T'STORAGE_SIZE} is also
23648 supported in a manner compatible with HP Ada.
23650 @node External Interrupts
23651 @subsection External Interrupts
23654 On HP Ada, external interrupts can be associated with task entries.
23655 GNAT is compatible with HP Ada in its handling of external interrupts.
23657 @node Pragmas and Pragma-Related Features
23658 @section Pragmas and Pragma-Related Features
23661 Both HP Ada and GNAT supply all language-defined pragmas
23662 as specified by the Ada 83 standard. GNAT also supplies all
23663 language-defined pragmas introduced by Ada 95 and Ada 2005.
23664 In addition, GNAT implements the implementation-defined pragmas
23668 @item @code{AST_ENTRY}
23670 @item @code{COMMON_OBJECT}
23672 @item @code{COMPONENT_ALIGNMENT}
23674 @item @code{EXPORT_EXCEPTION}
23676 @item @code{EXPORT_FUNCTION}
23678 @item @code{EXPORT_OBJECT}
23680 @item @code{EXPORT_PROCEDURE}
23682 @item @code{EXPORT_VALUED_PROCEDURE}
23684 @item @code{FLOAT_REPRESENTATION}
23688 @item @code{IMPORT_EXCEPTION}
23690 @item @code{IMPORT_FUNCTION}
23692 @item @code{IMPORT_OBJECT}
23694 @item @code{IMPORT_PROCEDURE}
23696 @item @code{IMPORT_VALUED_PROCEDURE}
23698 @item @code{INLINE_GENERIC}
23700 @item @code{INTERFACE_NAME}
23702 @item @code{LONG_FLOAT}
23704 @item @code{MAIN_STORAGE}
23706 @item @code{PASSIVE}
23708 @item @code{PSECT_OBJECT}
23710 @item @code{SHARE_GENERIC}
23712 @item @code{SUPPRESS_ALL}
23714 @item @code{TASK_STORAGE}
23716 @item @code{TIME_SLICE}
23722 These pragmas are all fully implemented, with the exception of @code{TITLE},
23723 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
23724 recognized, but which have no
23725 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
23726 use of Ada protected objects. In GNAT, all generics are inlined.
23728 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
23729 a separate subprogram specification which must appear before the
23732 GNAT also supplies a number of implementation-defined pragmas as follows:
23734 @item @code{ABORT_DEFER}
23736 @item @code{ADA_83}
23738 @item @code{ADA_95}
23740 @item @code{ADA_05}
23742 @item @code{ANNOTATE}
23744 @item @code{ASSERT}
23746 @item @code{C_PASS_BY_COPY}
23748 @item @code{CPP_CLASS}
23750 @item @code{CPP_CONSTRUCTOR}
23752 @item @code{CPP_DESTRUCTOR}
23756 @item @code{EXTEND_SYSTEM}
23758 @item @code{LINKER_ALIAS}
23760 @item @code{LINKER_SECTION}
23762 @item @code{MACHINE_ATTRIBUTE}
23764 @item @code{NO_RETURN}
23766 @item @code{PURE_FUNCTION}
23768 @item @code{SOURCE_FILE_NAME}
23770 @item @code{SOURCE_REFERENCE}
23772 @item @code{TASK_INFO}
23774 @item @code{UNCHECKED_UNION}
23776 @item @code{UNIMPLEMENTED_UNIT}
23778 @item @code{UNIVERSAL_DATA}
23780 @item @code{UNSUPPRESS}
23782 @item @code{WARNINGS}
23784 @item @code{WEAK_EXTERNAL}
23788 For full details on these GNAT implementation-defined pragmas, see
23789 the GNAT Reference Manual.
23792 * Restrictions on the Pragma INLINE::
23793 * Restrictions on the Pragma INTERFACE::
23794 * Restrictions on the Pragma SYSTEM_NAME::
23797 @node Restrictions on the Pragma INLINE
23798 @subsection Restrictions on Pragma @code{INLINE}
23801 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
23803 @item Parameters cannot have a task type.
23805 @item Function results cannot be task types, unconstrained
23806 array types, or unconstrained types with discriminants.
23808 @item Bodies cannot declare the following:
23810 @item Subprogram body or stub (imported subprogram is allowed)
23814 @item Generic declarations
23816 @item Instantiations
23820 @item Access types (types derived from access types allowed)
23822 @item Array or record types
23824 @item Dependent tasks
23826 @item Direct recursive calls of subprogram or containing
23827 subprogram, directly or via a renaming
23833 In GNAT, the only restriction on pragma @code{INLINE} is that the
23834 body must occur before the call if both are in the same
23835 unit, and the size must be appropriately small. There are
23836 no other specific restrictions which cause subprograms to
23837 be incapable of being inlined.
23839 @node Restrictions on the Pragma INTERFACE
23840 @subsection Restrictions on Pragma @code{INTERFACE}
23843 The following restrictions on pragma @code{INTERFACE}
23844 are enforced by both HP Ada and GNAT:
23846 @item Languages accepted: Ada, Bliss, C, Fortran, Default.
23847 Default is the default on OpenVMS Alpha systems.
23849 @item Parameter passing: Language specifies default
23850 mechanisms but can be overridden with an @code{EXPORT} pragma.
23853 @item Ada: Use internal Ada rules.
23855 @item Bliss, C: Parameters must be mode @code{in}; cannot be
23856 record or task type. Result cannot be a string, an
23857 array, or a record.
23859 @item Fortran: Parameters cannot have a task type. Result cannot
23860 be a string, an array, or a record.
23865 GNAT is entirely upwards compatible with HP Ada, and in addition allows
23866 record parameters for all languages.
23868 @node Restrictions on the Pragma SYSTEM_NAME
23869 @subsection Restrictions on Pragma @code{SYSTEM_NAME}
23872 For HP Ada for OpenVMS Alpha, the enumeration literal
23873 for the type @code{NAME} is @code{OPENVMS_AXP}.
23874 In GNAT, the enumeration
23875 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
23877 @node Library of Predefined Units
23878 @section Library of Predefined Units
23881 A library of predefined units is provided as part of the
23882 HP Ada and GNAT implementations. HP Ada does not provide
23883 the package @code{MACHINE_CODE} but instead recommends importing
23886 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
23887 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
23889 The HP Ada Predefined Library units are modified to remove post-Ada 83
23890 incompatibilities and to make them interoperable with GNAT
23891 (@pxref{Changes to DECLIB}, for details).
23892 The units are located in the @file{DECLIB} directory.
23894 The GNAT RTL is contained in
23895 the @file{ADALIB} directory, and
23896 the default search path is set up to find @code{DECLIB} units in preference
23897 to @code{ADALIB} units with the same name (@code{TEXT_IO},
23898 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
23901 * Changes to DECLIB::
23904 @node Changes to DECLIB
23905 @subsection Changes to @code{DECLIB}
23908 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
23909 compatibility are minor and include the following:
23912 @item Adjusting the location of pragmas and record representation
23913 clauses to obey Ada 95 (and thus Ada 2005) rules
23915 @item Adding the proper notation to generic formal parameters
23916 that take unconstrained types in instantiation
23918 @item Adding pragma @code{ELABORATE_BODY} to package specifications
23919 that have package bodies not otherwise allowed
23921 @item Replacing occurrences of the identifier ``@code{PROTECTED}'' by
23922 ``@code{PROTECTD}''.
23923 Currently these are found only in the @code{STARLET} package spec.
23925 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
23926 where the address size is constrained to 32 bits.
23930 None of the above changes is visible to users.
23936 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
23939 @item Command Language Interpreter (CLI interface)
23941 @item DECtalk Run-Time Library (DTK interface)
23943 @item Librarian utility routines (LBR interface)
23945 @item General Purpose Run-Time Library (LIB interface)
23947 @item Math Run-Time Library (MTH interface)
23949 @item National Character Set Run-Time Library (NCS interface)
23951 @item Compiled Code Support Run-Time Library (OTS interface)
23953 @item Parallel Processing Run-Time Library (PPL interface)
23955 @item Screen Management Run-Time Library (SMG interface)
23957 @item Sort Run-Time Library (SOR interface)
23959 @item String Run-Time Library (STR interface)
23961 @item STARLET System Library
23964 @item X Window System Version 11R4 and 11R5 (X, XLIB interface)
23966 @item X Windows Toolkit (XT interface)
23968 @item X/Motif Version 1.1.3 and 1.2 (XM interface)
23972 GNAT provides implementations of these HP bindings in the @code{DECLIB}
23973 directory, on both the Alpha and I64 OpenVMS platforms.
23975 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
23977 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
23978 A pragma @code{Linker_Options} has been added to packages @code{Xm},
23979 @code{Xt}, and @code{X_Lib}
23980 causing the default X/Motif sharable image libraries to be linked in. This
23981 is done via options files named @file{xm.opt}, @file{xt.opt}, and
23982 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
23984 It may be necessary to edit these options files to update or correct the
23985 library names if, for example, the newer X/Motif bindings from
23986 @file{ADA$EXAMPLES}
23987 had been (previous to installing GNAT) copied and renamed to supersede the
23988 default @file{ADA$PREDEFINED} versions.
23991 * Shared Libraries and Options Files::
23992 * Interfaces to C::
23995 @node Shared Libraries and Options Files
23996 @subsection Shared Libraries and Options Files
23999 When using the HP Ada
24000 predefined X and Motif bindings, the linking with their sharable images is
24001 done automatically by @command{GNAT LINK}.
24002 When using other X and Motif bindings, you need
24003 to add the corresponding sharable images to the command line for
24004 @code{GNAT LINK}. When linking with shared libraries, or with
24005 @file{.OPT} files, you must
24006 also add them to the command line for @command{GNAT LINK}.
24008 A shared library to be used with GNAT is built in the same way as other
24009 libraries under VMS. The VMS Link command can be used in standard fashion.
24011 @node Interfaces to C
24012 @subsection Interfaces to C
24016 provides the following Ada types and operations:
24019 @item C types package (@code{C_TYPES})
24021 @item C strings (@code{C_TYPES.NULL_TERMINATED})
24023 @item Other_types (@code{SHORT_INT})
24027 Interfacing to C with GNAT, you can use the above approach
24028 described for HP Ada or the facilities of Annex B of
24029 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
24030 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
24031 information, see the section ``Interfacing to C'' in the
24032 @cite{GNAT Reference Manual}.
24034 The @option{-gnatF} qualifier forces default and explicit
24035 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
24036 to be uppercased for compatibility with the default behavior
24037 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
24039 @node Main Program Definition
24040 @section Main Program Definition
24043 The following section discusses differences in the
24044 definition of main programs on HP Ada and GNAT.
24045 On HP Ada, main programs are defined to meet the
24046 following conditions:
24048 @item Procedure with no formal parameters (returns @code{0} upon
24051 @item Procedure with no formal parameters (returns @code{42} when
24052 an unhandled exception is raised)
24054 @item Function with no formal parameters whose returned value
24055 is of a discrete type
24057 @item Procedure with one @code{out} formal of a discrete type for
24058 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE}
24064 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
24065 a main function or main procedure returns a discrete
24066 value whose size is less than 64 bits (32 on VAX systems),
24067 the value is zero- or sign-extended as appropriate.
24068 On GNAT, main programs are defined as follows:
24070 @item Must be a non-generic, parameterless subprogram that
24071 is either a procedure or function returning an Ada
24072 @code{STANDARD.INTEGER} (the predefined type)
24074 @item Cannot be a generic subprogram or an instantiation of a
24078 @node Implementation-Defined Attributes
24079 @section Implementation-Defined Attributes
24082 GNAT provides all HP Ada implementation-defined
24085 @node Compiler and Run-Time Interfacing
24086 @section Compiler and Run-Time Interfacing
24089 HP Ada provides the following qualifiers to pass options to the linker
24092 @item @option{/WAIT} and @option{/SUBMIT}
24094 @item @option{/COMMAND}
24096 @item @option{/[NO]MAP}
24098 @item @option{/OUTPUT=@i{file-spec}}
24100 @item @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK}
24104 To pass options to the linker, GNAT provides the following
24108 @item @option{/EXECUTABLE=@i{exec-name}}
24110 @item @option{/VERBOSE}
24112 @item @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK}
24116 For more information on these switches, see
24117 @ref{Switches for gnatlink}.
24118 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
24119 to control optimization. HP Ada also supplies the
24122 @item @code{OPTIMIZE}
24124 @item @code{INLINE}
24126 @item @code{INLINE_GENERIC}
24128 @item @code{SUPPRESS_ALL}
24130 @item @code{PASSIVE}
24134 In GNAT, optimization is controlled strictly by command
24135 line parameters, as described in the corresponding section of this guide.
24136 The HP pragmas for control of optimization are
24137 recognized but ignored.
24139 Note that in GNAT, the default is optimization off, whereas in HP Ada
24140 the default is that optimization is turned on.
24142 @node Program Compilation and Library Management
24143 @section Program Compilation and Library Management
24146 HP Ada and GNAT provide a comparable set of commands to
24147 build programs. HP Ada also provides a program library,
24148 which is a concept that does not exist on GNAT. Instead,
24149 GNAT provides directories of sources that are compiled as
24152 The following table summarizes
24153 the HP Ada commands and provides
24154 equivalent GNAT commands. In this table, some GNAT
24155 equivalents reflect the fact that GNAT does not use the
24156 concept of a program library. Instead, it uses a model
24157 in which collections of source and object files are used
24158 in a manner consistent with other languages like C and
24159 Fortran. Therefore, standard system file commands are used
24160 to manipulate these elements. Those GNAT commands are marked with
24162 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
24165 @multitable @columnfractions .35 .65
24167 @item @emph{HP Ada Command}
24168 @tab @emph{GNAT Equivalent / Description}
24170 @item @command{ADA}
24171 @tab @command{GNAT COMPILE}@*
24172 Invokes the compiler to compile one or more Ada source files.
24174 @item @command{ACS ATTACH}@*
24175 @tab [No equivalent]@*
24176 Switches control of terminal from current process running the program
24179 @item @command{ACS CHECK}
24180 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
24181 Forms the execution closure of one
24182 or more compiled units and checks completeness and currency.
24184 @item @command{ACS COMPILE}
24185 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
24186 Forms the execution closure of one or
24187 more specified units, checks completeness and currency,
24188 identifies units that have revised source files, compiles same,
24189 and recompiles units that are or will become obsolete.
24190 Also completes incomplete generic instantiations.
24192 @item @command{ACS COPY FOREIGN}
24194 Copies a foreign object file into the program library as a
24197 @item @command{ACS COPY UNIT}
24199 Copies a compiled unit from one program library to another.
24201 @item @command{ACS CREATE LIBRARY}
24202 @tab Create /directory (*)@*
24203 Creates a program library.
24205 @item @command{ACS CREATE SUBLIBRARY}
24206 @tab Create /directory (*)@*
24207 Creates a program sublibrary.
24209 @item @command{ACS DELETE LIBRARY}
24211 Deletes a program library and its contents.
24213 @item @command{ACS DELETE SUBLIBRARY}
24215 Deletes a program sublibrary and its contents.
24217 @item @command{ACS DELETE UNIT}
24218 @tab Delete file (*)@*
24219 On OpenVMS systems, deletes one or more compiled units from
24220 the current program library.
24222 @item @command{ACS DIRECTORY}
24223 @tab Directory (*)@*
24224 On OpenVMS systems, lists units contained in the current
24227 @item @command{ACS ENTER FOREIGN}
24229 Allows the import of a foreign body as an Ada library
24230 specification and enters a reference to a pointer.
24232 @item @command{ACS ENTER UNIT}
24234 Enters a reference (pointer) from the current program library to
24235 a unit compiled into another program library.
24237 @item @command{ACS EXIT}
24238 @tab [No equivalent]@*
24239 Exits from the program library manager.
24241 @item @command{ACS EXPORT}
24243 Creates an object file that contains system-specific object code
24244 for one or more units. With GNAT, object files can simply be copied
24245 into the desired directory.
24247 @item @command{ACS EXTRACT SOURCE}
24249 Allows access to the copied source file for each Ada compilation unit
24251 @item @command{ACS HELP}
24252 @tab @command{HELP GNAT}@*
24253 Provides online help.
24255 @item @command{ACS LINK}
24256 @tab @command{GNAT LINK}@*
24257 Links an object file containing Ada units into an executable file.
24259 @item @command{ACS LOAD}
24261 Loads (partially compiles) Ada units into the program library.
24262 Allows loading a program from a collection of files into a library
24263 without knowing the relationship among units.
24265 @item @command{ACS MERGE}
24267 Merges into the current program library, one or more units from
24268 another library where they were modified.
24270 @item @command{ACS RECOMPILE}
24271 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
24272 Recompiles from external or copied source files any obsolete
24273 unit in the closure. Also, completes any incomplete generic
24276 @item @command{ACS REENTER}
24277 @tab @command{GNAT MAKE}@*
24278 Reenters current references to units compiled after last entered
24279 with the @command{ACS ENTER UNIT} command.
24281 @item @command{ACS SET LIBRARY}
24282 @tab Set default (*)@*
24283 Defines a program library to be the compilation context as well
24284 as the target library for compiler output and commands in general.
24286 @item @command{ACS SET PRAGMA}
24287 @tab Edit @file{gnat.adc} (*)@*
24288 Redefines specified values of the library characteristics
24289 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
24290 and @code{Float_Representation}.
24292 @item @command{ACS SET SOURCE}
24293 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
24294 Defines the source file search list for the @command{ACS COMPILE} command.
24296 @item @command{ACS SHOW LIBRARY}
24297 @tab Directory (*)@*
24298 Lists information about one or more program libraries.
24300 @item @command{ACS SHOW PROGRAM}
24301 @tab [No equivalent]@*
24302 Lists information about the execution closure of one or
24303 more units in the program library.
24305 @item @command{ACS SHOW SOURCE}
24306 @tab Show logical @code{ADA_INCLUDE_PATH}@*
24307 Shows the source file search used when compiling units.
24309 @item @command{ACS SHOW VERSION}
24310 @tab Compile with @option{VERBOSE} option
24311 Displays the version number of the compiler and program library
24314 @item @command{ACS SPAWN}
24315 @tab [No equivalent]@*
24316 Creates a subprocess of the current process (same as @command{DCL SPAWN}
24319 @item @command{ACS VERIFY}
24320 @tab [No equivalent]@*
24321 Performs a series of consistency checks on a program library to
24322 determine whether the library structure and library files are in
24329 @section Input-Output
24332 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
24333 Management Services (RMS) to perform operations on
24337 HP Ada and GNAT predefine an identical set of input-
24338 output packages. To make the use of the
24339 generic @code{TEXT_IO} operations more convenient, HP Ada
24340 provides predefined library packages that instantiate the
24341 integer and floating-point operations for the predefined
24342 integer and floating-point types as shown in the following table.
24344 @multitable @columnfractions .45 .55
24345 @item @emph{Package Name} @tab Instantiation
24347 @item @code{INTEGER_TEXT_IO}
24348 @tab @code{INTEGER_IO(INTEGER)}
24350 @item @code{SHORT_INTEGER_TEXT_IO}
24351 @tab @code{INTEGER_IO(SHORT_INTEGER)}
24353 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
24354 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
24356 @item @code{FLOAT_TEXT_IO}
24357 @tab @code{FLOAT_IO(FLOAT)}
24359 @item @code{LONG_FLOAT_TEXT_IO}
24360 @tab @code{FLOAT_IO(LONG_FLOAT)}
24364 The HP Ada predefined packages and their operations
24365 are implemented using OpenVMS Alpha files and input-output
24366 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
24367 Familiarity with the following is recommended:
24369 @item RMS file organizations and access methods
24371 @item OpenVMS file specifications and directories
24373 @item OpenVMS File Definition Language (FDL)
24377 GNAT provides I/O facilities that are completely
24378 compatible with HP Ada. The distribution includes the
24379 standard HP Ada versions of all I/O packages, operating
24380 in a manner compatible with HP Ada. In particular, the
24381 following packages are by default the HP Ada (Ada 83)
24382 versions of these packages rather than the renamings
24383 suggested in Annex J of the Ada Reference Manual:
24385 @item @code{TEXT_IO}
24387 @item @code{SEQUENTIAL_IO}
24389 @item @code{DIRECT_IO}
24393 The use of the standard child package syntax (for
24394 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
24396 GNAT provides HP-compatible predefined instantiations
24397 of the @code{TEXT_IO} packages, and also
24398 provides the standard predefined instantiations required
24399 by the @cite{Ada Reference Manual}.
24401 For further information on how GNAT interfaces to the file
24402 system or how I/O is implemented in programs written in
24403 mixed languages, see the chapter ``Implementation of the
24404 Standard I/O'' in the @cite{GNAT Reference Manual}.
24405 This chapter covers the following:
24407 @item Standard I/O packages
24409 @item @code{FORM} strings
24411 @item @code{ADA.DIRECT_IO}
24413 @item @code{ADA.SEQUENTIAL_IO}
24415 @item @code{ADA.TEXT_IO}
24417 @item Stream pointer positioning
24419 @item Reading and writing non-regular files
24421 @item @code{GET_IMMEDIATE}
24423 @item Treating @code{TEXT_IO} files as streams
24430 @node Implementation Limits
24431 @section Implementation Limits
24434 The following table lists implementation limits for HP Ada
24436 @multitable @columnfractions .60 .20 .20
24438 @item @emph{Compilation Parameter}
24443 @item In a subprogram or entry declaration, maximum number of
24444 formal parameters that are of an unconstrained record type
24449 @item Maximum identifier length (number of characters)
24454 @item Maximum number of characters in a source line
24459 @item Maximum collection size (number of bytes)
24464 @item Maximum number of discriminants for a record type
24469 @item Maximum number of formal parameters in an entry or
24470 subprogram declaration
24475 @item Maximum number of dimensions in an array type
24480 @item Maximum number of library units and subunits in a compilation.
24485 @item Maximum number of library units and subunits in an execution.
24490 @item Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
24491 or @code{PSECT_OBJECT}
24496 @item Maximum number of enumeration literals in an enumeration type
24502 @item Maximum number of lines in a source file
24507 @item Maximum number of bits in any object
24512 @item Maximum size of the static portion of a stack frame (approximate)
24517 @node Tools and Utilities
24518 @section Tools and Utilities
24521 The following table lists some of the OpenVMS development tools
24522 available for HP Ada, and the corresponding tools for
24523 use with @value{EDITION} on Alpha and I64 platforms.
24524 Aside from the debugger, all the OpenVMS tools identified are part
24525 of the DECset package.
24528 @c Specify table in TeX since Texinfo does a poor job
24532 \settabs\+Language-Sensitive Editor\quad
24533 &Product with HP Ada\quad
24536 &\it Product with HP Ada
24537 & \it Product with GNAT Pro\cr
24539 \+Code Management System
24543 \+Language-Sensitive Editor
24545 & emacs or HP LSE (Alpha)\cr
24555 & OpenVMS Debug (I64)\cr
24557 \+Source Code Analyzer /
24574 \+Coverage Analyzer
24578 \+Module Management
24580 & Not applicable\cr
24590 @c This is the Texinfo version of the table. It renders poorly in pdf, hence
24591 @c the TeX version above for the printed version
24593 @c @multitable @columnfractions .3 .4 .4
24594 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
24596 @tab @i{Tool with HP Ada}
24597 @tab @i{Tool with @value{EDITION}}
24598 @item Code Management@*System
24601 @item Language-Sensitive@*Editor
24603 @tab emacs or HP LSE (Alpha)
24612 @tab OpenVMS Debug (I64)
24613 @item Source Code Analyzer /@*Cross Referencer
24617 @tab HP Digital Test@*Manager (DTM)
24619 @item Performance and@*Coverage Analyzer
24622 @item Module Management@*System
24624 @tab Not applicable
24631 @c **************************************
24632 @node Platform-Specific Information for the Run-Time Libraries
24633 @appendix Platform-Specific Information for the Run-Time Libraries
24634 @cindex Tasking and threads libraries
24635 @cindex Threads libraries and tasking
24636 @cindex Run-time libraries (platform-specific information)
24639 The GNAT run-time implementation may vary with respect to both the
24640 underlying threads library and the exception handling scheme.
24641 For threads support, one or more of the following are supplied:
24643 @item @b{native threads library}, a binding to the thread package from
24644 the underlying operating system
24646 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
24647 POSIX thread package
24651 For exception handling, either or both of two models are supplied:
24653 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
24654 Most programs should experience a substantial speed improvement by
24655 being compiled with a ZCX run-time.
24656 This is especially true for
24657 tasking applications or applications with many exception handlers.}
24658 @cindex Zero-Cost Exceptions
24659 @cindex ZCX (Zero-Cost Exceptions)
24660 which uses binder-generated tables that
24661 are interrogated at run time to locate a handler
24663 @item @b{setjmp / longjmp} (``SJLJ''),
24664 @cindex setjmp/longjmp Exception Model
24665 @cindex SJLJ (setjmp/longjmp Exception Model)
24666 which uses dynamically-set data to establish
24667 the set of handlers
24671 This appendix summarizes which combinations of threads and exception support
24672 are supplied on various GNAT platforms.
24673 It then shows how to select a particular library either
24674 permanently or temporarily,
24675 explains the properties of (and tradeoffs among) the various threads
24676 libraries, and provides some additional
24677 information about several specific platforms.
24680 * Summary of Run-Time Configurations::
24681 * Specifying a Run-Time Library::
24682 * Choosing the Scheduling Policy::
24683 * Solaris-Specific Considerations::
24684 * Linux-Specific Considerations::
24685 * AIX-Specific Considerations::
24688 @node Summary of Run-Time Configurations
24689 @section Summary of Run-Time Configurations
24691 @multitable @columnfractions .30 .70
24692 @item @b{alpha-openvms}
24693 @item @code{@ @ }@i{rts-native (default)}
24694 @item @code{@ @ @ @ }Tasking @tab native VMS threads
24695 @item @code{@ @ @ @ }Exceptions @tab ZCX
24697 @item @b{alpha-tru64}
24698 @item @code{@ @ }@i{rts-native (default)}
24699 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
24700 @item @code{@ @ @ @ }Exceptions @tab ZCX
24702 @item @code{@ @ }@i{rts-sjlj}
24703 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
24704 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24706 @item @b{ia64-hp_linux}
24707 @item @code{@ @ }@i{rts-native (default)}
24708 @item @code{@ @ @ @ }Tasking @tab pthread library
24709 @item @code{@ @ @ @ }Exceptions @tab ZCX
24711 @item @b{ia64-hpux}
24712 @item @code{@ @ }@i{rts-native (default)}
24713 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
24714 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24716 @item @b{ia64-openvms}
24717 @item @code{@ @ }@i{rts-native (default)}
24718 @item @code{@ @ @ @ }Tasking @tab native VMS threads
24719 @item @code{@ @ @ @ }Exceptions @tab ZCX
24721 @item @b{ia64-sgi_linux}
24722 @item @code{@ @ }@i{rts-native (default)}
24723 @item @code{@ @ @ @ }Tasking @tab pthread library
24724 @item @code{@ @ @ @ }Exceptions @tab ZCX
24726 @item @b{mips-irix}
24727 @item @code{@ @ }@i{rts-native (default)}
24728 @item @code{@ @ @ @ }Tasking @tab native IRIX threads
24729 @item @code{@ @ @ @ }Exceptions @tab ZCX
24732 @item @code{@ @ }@i{rts-native (default)}
24733 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
24734 @item @code{@ @ @ @ }Exceptions @tab ZCX
24736 @item @code{@ @ }@i{rts-sjlj}
24737 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
24738 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24741 @item @code{@ @ }@i{rts-native (default)}
24742 @item @code{@ @ @ @ }Tasking @tab native AIX threads
24743 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24745 @item @b{ppc-darwin}
24746 @item @code{@ @ }@i{rts-native (default)}
24747 @item @code{@ @ @ @ }Tasking @tab native MacOS threads
24748 @item @code{@ @ @ @ }Exceptions @tab ZCX
24750 @item @b{sparc-solaris} @tab
24751 @item @code{@ @ }@i{rts-native (default)}
24752 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
24753 @item @code{@ @ @ @ }Exceptions @tab ZCX
24755 @item @code{@ @ }@i{rts-pthread}
24756 @item @code{@ @ @ @ }Tasking @tab pthread library
24757 @item @code{@ @ @ @ }Exceptions @tab ZCX
24759 @item @code{@ @ }@i{rts-sjlj}
24760 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
24761 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24763 @item @b{sparc64-solaris} @tab
24764 @item @code{@ @ }@i{rts-native (default)}
24765 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
24766 @item @code{@ @ @ @ }Exceptions @tab ZCX
24768 @item @b{x86-linux}
24769 @item @code{@ @ }@i{rts-native (default)}
24770 @item @code{@ @ @ @ }Tasking @tab pthread library
24771 @item @code{@ @ @ @ }Exceptions @tab ZCX
24773 @item @code{@ @ }@i{rts-sjlj}
24774 @item @code{@ @ @ @ }Tasking @tab pthread library
24775 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24778 @item @code{@ @ }@i{rts-native (default)}
24779 @item @code{@ @ @ @ }Tasking @tab native LynxOS threads
24780 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24782 @item @b{x86-solaris}
24783 @item @code{@ @ }@i{rts-native (default)}
24784 @item @code{@ @ @ @ }Tasking @tab native Solaris threads
24785 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24787 @item @b{x86-windows}
24788 @item @code{@ @ }@i{rts-native (default)}
24789 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
24790 @item @code{@ @ @ @ }Exceptions @tab ZCX
24792 @item @code{@ @ }@i{rts-sjlj (default)}
24793 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
24794 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24796 @item @b{x86_64-linux}
24797 @item @code{@ @ }@i{rts-native (default)}
24798 @item @code{@ @ @ @ }Tasking @tab pthread library
24799 @item @code{@ @ @ @ }Exceptions @tab ZCX
24801 @item @code{@ @ }@i{rts-sjlj}
24802 @item @code{@ @ @ @ }Tasking @tab pthread library
24803 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24807 @node Specifying a Run-Time Library
24808 @section Specifying a Run-Time Library
24811 The @file{adainclude} subdirectory containing the sources of the GNAT
24812 run-time library, and the @file{adalib} subdirectory containing the
24813 @file{ALI} files and the static and/or shared GNAT library, are located
24814 in the gcc target-dependent area:
24817 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
24821 As indicated above, on some platforms several run-time libraries are supplied.
24822 These libraries are installed in the target dependent area and
24823 contain a complete source and binary subdirectory. The detailed description
24824 below explains the differences between the different libraries in terms of
24825 their thread support.
24827 The default run-time library (when GNAT is installed) is @emph{rts-native}.
24828 This default run time is selected by the means of soft links.
24829 For example on x86-linux:
24835 +--- adainclude----------+
24837 +--- adalib-----------+ |
24839 +--- rts-native | |
24841 | +--- adainclude <---+
24843 | +--- adalib <----+
24854 If the @i{rts-sjlj} library is to be selected on a permanent basis,
24855 these soft links can be modified with the following commands:
24859 $ rm -f adainclude adalib
24860 $ ln -s rts-sjlj/adainclude adainclude
24861 $ ln -s rts-sjlj/adalib adalib
24865 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
24866 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
24867 @file{$target/ada_object_path}.
24869 Selecting another run-time library temporarily can be
24870 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
24871 @cindex @option{--RTS} option
24873 @node Choosing the Scheduling Policy
24874 @section Choosing the Scheduling Policy
24877 When using a POSIX threads implementation, you have a choice of several
24878 scheduling policies: @code{SCHED_FIFO},
24879 @cindex @code{SCHED_FIFO} scheduling policy
24881 @cindex @code{SCHED_RR} scheduling policy
24882 and @code{SCHED_OTHER}.
24883 @cindex @code{SCHED_OTHER} scheduling policy
24884 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
24885 or @code{SCHED_RR} requires special (e.g., root) privileges.
24887 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
24889 @cindex @code{SCHED_FIFO} scheduling policy
24890 you can use one of the following:
24894 @code{pragma Time_Slice (0.0)}
24895 @cindex pragma Time_Slice
24897 the corresponding binder option @option{-T0}
24898 @cindex @option{-T0} option
24900 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
24901 @cindex pragma Task_Dispatching_Policy
24905 To specify @code{SCHED_RR},
24906 @cindex @code{SCHED_RR} scheduling policy
24907 you should use @code{pragma Time_Slice} with a
24908 value greater than @code{0.0}, or else use the corresponding @option{-T}
24911 @node Solaris-Specific Considerations
24912 @section Solaris-Specific Considerations
24913 @cindex Solaris Sparc threads libraries
24916 This section addresses some topics related to the various threads libraries
24920 * Solaris Threads Issues::
24923 @node Solaris Threads Issues
24924 @subsection Solaris Threads Issues
24927 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
24928 library based on POSIX threads --- @emph{rts-pthread}.
24929 @cindex rts-pthread threads library
24930 This run-time library has the advantage of being mostly shared across all
24931 POSIX-compliant thread implementations, and it also provides under
24932 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
24933 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
24934 and @code{PTHREAD_PRIO_PROTECT}
24935 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
24936 semantics that can be selected using the predefined pragma
24937 @code{Locking_Policy}
24938 @cindex pragma Locking_Policy (under rts-pthread)
24940 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
24941 @cindex @code{Inheritance_Locking} (under rts-pthread)
24942 @cindex @code{Ceiling_Locking} (under rts-pthread)
24944 As explained above, the native run-time library is based on the Solaris thread
24945 library (@code{libthread}) and is the default library.
24947 When the Solaris threads library is used (this is the default), programs
24948 compiled with GNAT can automatically take advantage of
24949 and can thus execute on multiple processors.
24950 The user can alternatively specify a processor on which the program should run
24951 to emulate a single-processor system. The multiprocessor / uniprocessor choice
24953 setting the environment variable @code{GNAT_PROCESSOR}
24954 @cindex @code{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
24955 to one of the following:
24959 Use the default configuration (run the program on all
24960 available processors) - this is the same as having
24961 @code{GNAT_PROCESSOR} unset
24964 Let the run-time implementation choose one processor and run the program on
24967 @item 0 .. Last_Proc
24968 Run the program on the specified processor.
24969 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
24970 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
24973 @node Linux-Specific Considerations
24974 @section Linux-Specific Considerations
24975 @cindex Linux threads libraries
24978 On GNU/Linux without NPTL support (usually system with GNU C Library
24979 older than 2.3), the signal model is not POSIX compliant, which means
24980 that to send a signal to the process, you need to send the signal to all
24981 threads, e.g. by using @code{killpg()}.
24983 @node AIX-Specific Considerations
24984 @section AIX-Specific Considerations
24985 @cindex AIX resolver library
24988 On AIX, the resolver library initializes some internal structure on
24989 the first call to @code{get*by*} functions, which are used to implement
24990 @code{GNAT.Sockets.Get_Host_By_Name} and
24991 @code{GNAT.Sockets.Get_Host_By_Address}.
24992 If such initialization occurs within an Ada task, and the stack size for
24993 the task is the default size, a stack overflow may occur.
24995 To avoid this overflow, the user should either ensure that the first call
24996 to @code{GNAT.Sockets.Get_Host_By_Name} or
24997 @code{GNAT.Sockets.Get_Host_By_Addrss}
24998 occurs in the environment task, or use @code{pragma Storage_Size} to
24999 specify a sufficiently large size for the stack of the task that contains
25002 @c *******************************
25003 @node Example of Binder Output File
25004 @appendix Example of Binder Output File
25007 This Appendix displays the source code for @command{gnatbind}'s output
25008 file generated for a simple ``Hello World'' program.
25009 Comments have been added for clarification purposes.
25011 @smallexample @c adanocomment
25015 -- The package is called Ada_Main unless this name is actually used
25016 -- as a unit name in the partition, in which case some other unique
25020 package ada_main is
25022 Elab_Final_Code : Integer;
25023 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
25025 -- The main program saves the parameters (argument count,
25026 -- argument values, environment pointer) in global variables
25027 -- for later access by other units including
25028 -- Ada.Command_Line.
25030 gnat_argc : Integer;
25031 gnat_argv : System.Address;
25032 gnat_envp : System.Address;
25034 -- The actual variables are stored in a library routine. This
25035 -- is useful for some shared library situations, where there
25036 -- are problems if variables are not in the library.
25038 pragma Import (C, gnat_argc);
25039 pragma Import (C, gnat_argv);
25040 pragma Import (C, gnat_envp);
25042 -- The exit status is similarly an external location
25044 gnat_exit_status : Integer;
25045 pragma Import (C, gnat_exit_status);
25047 GNAT_Version : constant String :=
25048 "GNAT Version: 6.0.0w (20061115)";
25049 pragma Export (C, GNAT_Version, "__gnat_version");
25051 -- This is the generated adafinal routine that performs
25052 -- finalization at the end of execution. In the case where
25053 -- Ada is the main program, this main program makes a call
25054 -- to adafinal at program termination.
25056 procedure adafinal;
25057 pragma Export (C, adafinal, "adafinal");
25059 -- This is the generated adainit routine that performs
25060 -- initialization at the start of execution. In the case
25061 -- where Ada is the main program, this main program makes
25062 -- a call to adainit at program startup.
25065 pragma Export (C, adainit, "adainit");
25067 -- This routine is called at the start of execution. It is
25068 -- a dummy routine that is used by the debugger to breakpoint
25069 -- at the start of execution.
25071 procedure Break_Start;
25072 pragma Import (C, Break_Start, "__gnat_break_start");
25074 -- This is the actual generated main program (it would be
25075 -- suppressed if the no main program switch were used). As
25076 -- required by standard system conventions, this program has
25077 -- the external name main.
25081 argv : System.Address;
25082 envp : System.Address)
25084 pragma Export (C, main, "main");
25086 -- The following set of constants give the version
25087 -- identification values for every unit in the bound
25088 -- partition. This identification is computed from all
25089 -- dependent semantic units, and corresponds to the
25090 -- string that would be returned by use of the
25091 -- Body_Version or Version attributes.
25093 type Version_32 is mod 2 ** 32;
25094 u00001 : constant Version_32 := 16#7880BEB3#;
25095 u00002 : constant Version_32 := 16#0D24CBD0#;
25096 u00003 : constant Version_32 := 16#3283DBEB#;
25097 u00004 : constant Version_32 := 16#2359F9ED#;
25098 u00005 : constant Version_32 := 16#664FB847#;
25099 u00006 : constant Version_32 := 16#68E803DF#;
25100 u00007 : constant Version_32 := 16#5572E604#;
25101 u00008 : constant Version_32 := 16#46B173D8#;
25102 u00009 : constant Version_32 := 16#156A40CF#;
25103 u00010 : constant Version_32 := 16#033DABE0#;
25104 u00011 : constant Version_32 := 16#6AB38FEA#;
25105 u00012 : constant Version_32 := 16#22B6217D#;
25106 u00013 : constant Version_32 := 16#68A22947#;
25107 u00014 : constant Version_32 := 16#18CC4A56#;
25108 u00015 : constant Version_32 := 16#08258E1B#;
25109 u00016 : constant Version_32 := 16#367D5222#;
25110 u00017 : constant Version_32 := 16#20C9ECA4#;
25111 u00018 : constant Version_32 := 16#50D32CB6#;
25112 u00019 : constant Version_32 := 16#39A8BB77#;
25113 u00020 : constant Version_32 := 16#5CF8FA2B#;
25114 u00021 : constant Version_32 := 16#2F1EB794#;
25115 u00022 : constant Version_32 := 16#31AB6444#;
25116 u00023 : constant Version_32 := 16#1574B6E9#;
25117 u00024 : constant Version_32 := 16#5109C189#;
25118 u00025 : constant Version_32 := 16#56D770CD#;
25119 u00026 : constant Version_32 := 16#02F9DE3D#;
25120 u00027 : constant Version_32 := 16#08AB6B2C#;
25121 u00028 : constant Version_32 := 16#3FA37670#;
25122 u00029 : constant Version_32 := 16#476457A0#;
25123 u00030 : constant Version_32 := 16#731E1B6E#;
25124 u00031 : constant Version_32 := 16#23C2E789#;
25125 u00032 : constant Version_32 := 16#0F1BD6A1#;
25126 u00033 : constant Version_32 := 16#7C25DE96#;
25127 u00034 : constant Version_32 := 16#39ADFFA2#;
25128 u00035 : constant Version_32 := 16#571DE3E7#;
25129 u00036 : constant Version_32 := 16#5EB646AB#;
25130 u00037 : constant Version_32 := 16#4249379B#;
25131 u00038 : constant Version_32 := 16#0357E00A#;
25132 u00039 : constant Version_32 := 16#3784FB72#;
25133 u00040 : constant Version_32 := 16#2E723019#;
25134 u00041 : constant Version_32 := 16#623358EA#;
25135 u00042 : constant Version_32 := 16#107F9465#;
25136 u00043 : constant Version_32 := 16#6843F68A#;
25137 u00044 : constant Version_32 := 16#63305874#;
25138 u00045 : constant Version_32 := 16#31E56CE1#;
25139 u00046 : constant Version_32 := 16#02917970#;
25140 u00047 : constant Version_32 := 16#6CCBA70E#;
25141 u00048 : constant Version_32 := 16#41CD4204#;
25142 u00049 : constant Version_32 := 16#572E3F58#;
25143 u00050 : constant Version_32 := 16#20729FF5#;
25144 u00051 : constant Version_32 := 16#1D4F93E8#;
25145 u00052 : constant Version_32 := 16#30B2EC3D#;
25146 u00053 : constant Version_32 := 16#34054F96#;
25147 u00054 : constant Version_32 := 16#5A199860#;
25148 u00055 : constant Version_32 := 16#0E7F912B#;
25149 u00056 : constant Version_32 := 16#5760634A#;
25150 u00057 : constant Version_32 := 16#5D851835#;
25152 -- The following Export pragmas export the version numbers
25153 -- with symbolic names ending in B (for body) or S
25154 -- (for spec) so that they can be located in a link. The
25155 -- information provided here is sufficient to track down
25156 -- the exact versions of units used in a given build.
25158 pragma Export (C, u00001, "helloB");
25159 pragma Export (C, u00002, "system__standard_libraryB");
25160 pragma Export (C, u00003, "system__standard_libraryS");
25161 pragma Export (C, u00004, "adaS");
25162 pragma Export (C, u00005, "ada__text_ioB");
25163 pragma Export (C, u00006, "ada__text_ioS");
25164 pragma Export (C, u00007, "ada__exceptionsB");
25165 pragma Export (C, u00008, "ada__exceptionsS");
25166 pragma Export (C, u00009, "gnatS");
25167 pragma Export (C, u00010, "gnat__heap_sort_aB");
25168 pragma Export (C, u00011, "gnat__heap_sort_aS");
25169 pragma Export (C, u00012, "systemS");
25170 pragma Export (C, u00013, "system__exception_tableB");
25171 pragma Export (C, u00014, "system__exception_tableS");
25172 pragma Export (C, u00015, "gnat__htableB");
25173 pragma Export (C, u00016, "gnat__htableS");
25174 pragma Export (C, u00017, "system__exceptionsS");
25175 pragma Export (C, u00018, "system__machine_state_operationsB");
25176 pragma Export (C, u00019, "system__machine_state_operationsS");
25177 pragma Export (C, u00020, "system__machine_codeS");
25178 pragma Export (C, u00021, "system__storage_elementsB");
25179 pragma Export (C, u00022, "system__storage_elementsS");
25180 pragma Export (C, u00023, "system__secondary_stackB");
25181 pragma Export (C, u00024, "system__secondary_stackS");
25182 pragma Export (C, u00025, "system__parametersB");
25183 pragma Export (C, u00026, "system__parametersS");
25184 pragma Export (C, u00027, "system__soft_linksB");
25185 pragma Export (C, u00028, "system__soft_linksS");
25186 pragma Export (C, u00029, "system__stack_checkingB");
25187 pragma Export (C, u00030, "system__stack_checkingS");
25188 pragma Export (C, u00031, "system__tracebackB");
25189 pragma Export (C, u00032, "system__tracebackS");
25190 pragma Export (C, u00033, "ada__streamsS");
25191 pragma Export (C, u00034, "ada__tagsB");
25192 pragma Export (C, u00035, "ada__tagsS");
25193 pragma Export (C, u00036, "system__string_opsB");
25194 pragma Export (C, u00037, "system__string_opsS");
25195 pragma Export (C, u00038, "interfacesS");
25196 pragma Export (C, u00039, "interfaces__c_streamsB");
25197 pragma Export (C, u00040, "interfaces__c_streamsS");
25198 pragma Export (C, u00041, "system__file_ioB");
25199 pragma Export (C, u00042, "system__file_ioS");
25200 pragma Export (C, u00043, "ada__finalizationB");
25201 pragma Export (C, u00044, "ada__finalizationS");
25202 pragma Export (C, u00045, "system__finalization_rootB");
25203 pragma Export (C, u00046, "system__finalization_rootS");
25204 pragma Export (C, u00047, "system__finalization_implementationB");
25205 pragma Export (C, u00048, "system__finalization_implementationS");
25206 pragma Export (C, u00049, "system__string_ops_concat_3B");
25207 pragma Export (C, u00050, "system__string_ops_concat_3S");
25208 pragma Export (C, u00051, "system__stream_attributesB");
25209 pragma Export (C, u00052, "system__stream_attributesS");
25210 pragma Export (C, u00053, "ada__io_exceptionsS");
25211 pragma Export (C, u00054, "system__unsigned_typesS");
25212 pragma Export (C, u00055, "system__file_control_blockS");
25213 pragma Export (C, u00056, "ada__finalization__list_controllerB");
25214 pragma Export (C, u00057, "ada__finalization__list_controllerS");
25216 -- BEGIN ELABORATION ORDER
25219 -- gnat.heap_sort_a (spec)
25220 -- gnat.heap_sort_a (body)
25221 -- gnat.htable (spec)
25222 -- gnat.htable (body)
25223 -- interfaces (spec)
25225 -- system.machine_code (spec)
25226 -- system.parameters (spec)
25227 -- system.parameters (body)
25228 -- interfaces.c_streams (spec)
25229 -- interfaces.c_streams (body)
25230 -- system.standard_library (spec)
25231 -- ada.exceptions (spec)
25232 -- system.exception_table (spec)
25233 -- system.exception_table (body)
25234 -- ada.io_exceptions (spec)
25235 -- system.exceptions (spec)
25236 -- system.storage_elements (spec)
25237 -- system.storage_elements (body)
25238 -- system.machine_state_operations (spec)
25239 -- system.machine_state_operations (body)
25240 -- system.secondary_stack (spec)
25241 -- system.stack_checking (spec)
25242 -- system.soft_links (spec)
25243 -- system.soft_links (body)
25244 -- system.stack_checking (body)
25245 -- system.secondary_stack (body)
25246 -- system.standard_library (body)
25247 -- system.string_ops (spec)
25248 -- system.string_ops (body)
25251 -- ada.streams (spec)
25252 -- system.finalization_root (spec)
25253 -- system.finalization_root (body)
25254 -- system.string_ops_concat_3 (spec)
25255 -- system.string_ops_concat_3 (body)
25256 -- system.traceback (spec)
25257 -- system.traceback (body)
25258 -- ada.exceptions (body)
25259 -- system.unsigned_types (spec)
25260 -- system.stream_attributes (spec)
25261 -- system.stream_attributes (body)
25262 -- system.finalization_implementation (spec)
25263 -- system.finalization_implementation (body)
25264 -- ada.finalization (spec)
25265 -- ada.finalization (body)
25266 -- ada.finalization.list_controller (spec)
25267 -- ada.finalization.list_controller (body)
25268 -- system.file_control_block (spec)
25269 -- system.file_io (spec)
25270 -- system.file_io (body)
25271 -- ada.text_io (spec)
25272 -- ada.text_io (body)
25274 -- END ELABORATION ORDER
25278 -- The following source file name pragmas allow the generated file
25279 -- names to be unique for different main programs. They are needed
25280 -- since the package name will always be Ada_Main.
25282 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
25283 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
25285 -- Generated package body for Ada_Main starts here
25287 package body ada_main is
25289 -- The actual finalization is performed by calling the
25290 -- library routine in System.Standard_Library.Adafinal
25292 procedure Do_Finalize;
25293 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
25300 procedure adainit is
25302 -- These booleans are set to True once the associated unit has
25303 -- been elaborated. It is also used to avoid elaborating the
25304 -- same unit twice.
25307 pragma Import (Ada, E040, "interfaces__c_streams_E");
25310 pragma Import (Ada, E008, "ada__exceptions_E");
25313 pragma Import (Ada, E014, "system__exception_table_E");
25316 pragma Import (Ada, E053, "ada__io_exceptions_E");
25319 pragma Import (Ada, E017, "system__exceptions_E");
25322 pragma Import (Ada, E024, "system__secondary_stack_E");
25325 pragma Import (Ada, E030, "system__stack_checking_E");
25328 pragma Import (Ada, E028, "system__soft_links_E");
25331 pragma Import (Ada, E035, "ada__tags_E");
25334 pragma Import (Ada, E033, "ada__streams_E");
25337 pragma Import (Ada, E046, "system__finalization_root_E");
25340 pragma Import (Ada, E048, "system__finalization_implementation_E");
25343 pragma Import (Ada, E044, "ada__finalization_E");
25346 pragma Import (Ada, E057, "ada__finalization__list_controller_E");
25349 pragma Import (Ada, E055, "system__file_control_block_E");
25352 pragma Import (Ada, E042, "system__file_io_E");
25355 pragma Import (Ada, E006, "ada__text_io_E");
25357 -- Set_Globals is a library routine that stores away the
25358 -- value of the indicated set of global values in global
25359 -- variables within the library.
25361 procedure Set_Globals
25362 (Main_Priority : Integer;
25363 Time_Slice_Value : Integer;
25364 WC_Encoding : Character;
25365 Locking_Policy : Character;
25366 Queuing_Policy : Character;
25367 Task_Dispatching_Policy : Character;
25368 Adafinal : System.Address;
25369 Unreserve_All_Interrupts : Integer;
25370 Exception_Tracebacks : Integer);
25371 @findex __gnat_set_globals
25372 pragma Import (C, Set_Globals, "__gnat_set_globals");
25374 -- SDP_Table_Build is a library routine used to build the
25375 -- exception tables. See unit Ada.Exceptions in files
25376 -- a-except.ads/adb for full details of how zero cost
25377 -- exception handling works. This procedure, the call to
25378 -- it, and the two following tables are all omitted if the
25379 -- build is in longjmp/setjump exception mode.
25381 @findex SDP_Table_Build
25382 @findex Zero Cost Exceptions
25383 procedure SDP_Table_Build
25384 (SDP_Addresses : System.Address;
25385 SDP_Count : Natural;
25386 Elab_Addresses : System.Address;
25387 Elab_Addr_Count : Natural);
25388 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
25390 -- Table of Unit_Exception_Table addresses. Used for zero
25391 -- cost exception handling to build the top level table.
25393 ST : aliased constant array (1 .. 23) of System.Address := (
25395 Ada.Text_Io'UET_Address,
25396 Ada.Exceptions'UET_Address,
25397 Gnat.Heap_Sort_A'UET_Address,
25398 System.Exception_Table'UET_Address,
25399 System.Machine_State_Operations'UET_Address,
25400 System.Secondary_Stack'UET_Address,
25401 System.Parameters'UET_Address,
25402 System.Soft_Links'UET_Address,
25403 System.Stack_Checking'UET_Address,
25404 System.Traceback'UET_Address,
25405 Ada.Streams'UET_Address,
25406 Ada.Tags'UET_Address,
25407 System.String_Ops'UET_Address,
25408 Interfaces.C_Streams'UET_Address,
25409 System.File_Io'UET_Address,
25410 Ada.Finalization'UET_Address,
25411 System.Finalization_Root'UET_Address,
25412 System.Finalization_Implementation'UET_Address,
25413 System.String_Ops_Concat_3'UET_Address,
25414 System.Stream_Attributes'UET_Address,
25415 System.File_Control_Block'UET_Address,
25416 Ada.Finalization.List_Controller'UET_Address);
25418 -- Table of addresses of elaboration routines. Used for
25419 -- zero cost exception handling to make sure these
25420 -- addresses are included in the top level procedure
25423 EA : aliased constant array (1 .. 23) of System.Address := (
25424 adainit'Code_Address,
25425 Do_Finalize'Code_Address,
25426 Ada.Exceptions'Elab_Spec'Address,
25427 System.Exceptions'Elab_Spec'Address,
25428 Interfaces.C_Streams'Elab_Spec'Address,
25429 System.Exception_Table'Elab_Body'Address,
25430 Ada.Io_Exceptions'Elab_Spec'Address,
25431 System.Stack_Checking'Elab_Spec'Address,
25432 System.Soft_Links'Elab_Body'Address,
25433 System.Secondary_Stack'Elab_Body'Address,
25434 Ada.Tags'Elab_Spec'Address,
25435 Ada.Tags'Elab_Body'Address,
25436 Ada.Streams'Elab_Spec'Address,
25437 System.Finalization_Root'Elab_Spec'Address,
25438 Ada.Exceptions'Elab_Body'Address,
25439 System.Finalization_Implementation'Elab_Spec'Address,
25440 System.Finalization_Implementation'Elab_Body'Address,
25441 Ada.Finalization'Elab_Spec'Address,
25442 Ada.Finalization.List_Controller'Elab_Spec'Address,
25443 System.File_Control_Block'Elab_Spec'Address,
25444 System.File_Io'Elab_Body'Address,
25445 Ada.Text_Io'Elab_Spec'Address,
25446 Ada.Text_Io'Elab_Body'Address);
25448 -- Start of processing for adainit
25452 -- Call SDP_Table_Build to build the top level procedure
25453 -- table for zero cost exception handling (omitted in
25454 -- longjmp/setjump mode).
25456 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
25458 -- Call Set_Globals to record various information for
25459 -- this partition. The values are derived by the binder
25460 -- from information stored in the ali files by the compiler.
25462 @findex __gnat_set_globals
25464 (Main_Priority => -1,
25465 -- Priority of main program, -1 if no pragma Priority used
25467 Time_Slice_Value => -1,
25468 -- Time slice from Time_Slice pragma, -1 if none used
25470 WC_Encoding => 'b',
25471 -- Wide_Character encoding used, default is brackets
25473 Locking_Policy => ' ',
25474 -- Locking_Policy used, default of space means not
25475 -- specified, otherwise it is the first character of
25476 -- the policy name.
25478 Queuing_Policy => ' ',
25479 -- Queuing_Policy used, default of space means not
25480 -- specified, otherwise it is the first character of
25481 -- the policy name.
25483 Task_Dispatching_Policy => ' ',
25484 -- Task_Dispatching_Policy used, default of space means
25485 -- not specified, otherwise first character of the
25488 Adafinal => System.Null_Address,
25489 -- Address of Adafinal routine, not used anymore
25491 Unreserve_All_Interrupts => 0,
25492 -- Set true if pragma Unreserve_All_Interrupts was used
25494 Exception_Tracebacks => 0);
25495 -- Indicates if exception tracebacks are enabled
25497 Elab_Final_Code := 1;
25499 -- Now we have the elaboration calls for all units in the partition.
25500 -- The Elab_Spec and Elab_Body attributes generate references to the
25501 -- implicit elaboration procedures generated by the compiler for
25502 -- each unit that requires elaboration.
25505 Interfaces.C_Streams'Elab_Spec;
25509 Ada.Exceptions'Elab_Spec;
25512 System.Exception_Table'Elab_Body;
25516 Ada.Io_Exceptions'Elab_Spec;
25520 System.Exceptions'Elab_Spec;
25524 System.Stack_Checking'Elab_Spec;
25527 System.Soft_Links'Elab_Body;
25532 System.Secondary_Stack'Elab_Body;
25536 Ada.Tags'Elab_Spec;
25539 Ada.Tags'Elab_Body;
25543 Ada.Streams'Elab_Spec;
25547 System.Finalization_Root'Elab_Spec;
25551 Ada.Exceptions'Elab_Body;
25555 System.Finalization_Implementation'Elab_Spec;
25558 System.Finalization_Implementation'Elab_Body;
25562 Ada.Finalization'Elab_Spec;
25566 Ada.Finalization.List_Controller'Elab_Spec;
25570 System.File_Control_Block'Elab_Spec;
25574 System.File_Io'Elab_Body;
25578 Ada.Text_Io'Elab_Spec;
25581 Ada.Text_Io'Elab_Body;
25585 Elab_Final_Code := 0;
25593 procedure adafinal is
25602 -- main is actually a function, as in the ANSI C standard,
25603 -- defined to return the exit status. The three parameters
25604 -- are the argument count, argument values and environment
25607 @findex Main Program
25610 argv : System.Address;
25611 envp : System.Address)
25614 -- The initialize routine performs low level system
25615 -- initialization using a standard library routine which
25616 -- sets up signal handling and performs any other
25617 -- required setup. The routine can be found in file
25620 @findex __gnat_initialize
25621 procedure initialize;
25622 pragma Import (C, initialize, "__gnat_initialize");
25624 -- The finalize routine performs low level system
25625 -- finalization using a standard library routine. The
25626 -- routine is found in file a-final.c and in the standard
25627 -- distribution is a dummy routine that does nothing, so
25628 -- really this is a hook for special user finalization.
25630 @findex __gnat_finalize
25631 procedure finalize;
25632 pragma Import (C, finalize, "__gnat_finalize");
25634 -- We get to the main program of the partition by using
25635 -- pragma Import because if we try to with the unit and
25636 -- call it Ada style, then not only do we waste time
25637 -- recompiling it, but also, we don't really know the right
25638 -- switches (e.g. identifier character set) to be used
25641 procedure Ada_Main_Program;
25642 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
25644 -- Start of processing for main
25647 -- Save global variables
25653 -- Call low level system initialization
25657 -- Call our generated Ada initialization routine
25661 -- This is the point at which we want the debugger to get
25666 -- Now we call the main program of the partition
25670 -- Perform Ada finalization
25674 -- Perform low level system finalization
25678 -- Return the proper exit status
25679 return (gnat_exit_status);
25682 -- This section is entirely comments, so it has no effect on the
25683 -- compilation of the Ada_Main package. It provides the list of
25684 -- object files and linker options, as well as some standard
25685 -- libraries needed for the link. The gnatlink utility parses
25686 -- this b~hello.adb file to read these comment lines to generate
25687 -- the appropriate command line arguments for the call to the
25688 -- system linker. The BEGIN/END lines are used for sentinels for
25689 -- this parsing operation.
25691 -- The exact file names will of course depend on the environment,
25692 -- host/target and location of files on the host system.
25694 @findex Object file list
25695 -- BEGIN Object file/option list
25698 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
25699 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
25700 -- END Object file/option list
25706 The Ada code in the above example is exactly what is generated by the
25707 binder. We have added comments to more clearly indicate the function
25708 of each part of the generated @code{Ada_Main} package.
25710 The code is standard Ada in all respects, and can be processed by any
25711 tools that handle Ada. In particular, it is possible to use the debugger
25712 in Ada mode to debug the generated @code{Ada_Main} package. For example,
25713 suppose that for reasons that you do not understand, your program is crashing
25714 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
25715 you can place a breakpoint on the call:
25717 @smallexample @c ada
25718 Ada.Text_Io'Elab_Body;
25722 and trace the elaboration routine for this package to find out where
25723 the problem might be (more usually of course you would be debugging
25724 elaboration code in your own application).
25726 @node Elaboration Order Handling in GNAT
25727 @appendix Elaboration Order Handling in GNAT
25728 @cindex Order of elaboration
25729 @cindex Elaboration control
25732 * Elaboration Code::
25733 * Checking the Elaboration Order::
25734 * Controlling the Elaboration Order::
25735 * Controlling Elaboration in GNAT - Internal Calls::
25736 * Controlling Elaboration in GNAT - External Calls::
25737 * Default Behavior in GNAT - Ensuring Safety::
25738 * Treatment of Pragma Elaborate::
25739 * Elaboration Issues for Library Tasks::
25740 * Mixing Elaboration Models::
25741 * What to Do If the Default Elaboration Behavior Fails::
25742 * Elaboration for Access-to-Subprogram Values::
25743 * Summary of Procedures for Elaboration Control::
25744 * Other Elaboration Order Considerations::
25748 This chapter describes the handling of elaboration code in Ada and
25749 in GNAT, and discusses how the order of elaboration of program units can
25750 be controlled in GNAT, either automatically or with explicit programming
25753 @node Elaboration Code
25754 @section Elaboration Code
25757 Ada provides rather general mechanisms for executing code at elaboration
25758 time, that is to say before the main program starts executing. Such code arises
25762 @item Initializers for variables.
25763 Variables declared at the library level, in package specs or bodies, can
25764 require initialization that is performed at elaboration time, as in:
25765 @smallexample @c ada
25767 Sqrt_Half : Float := Sqrt (0.5);
25771 @item Package initialization code
25772 Code in a @code{BEGIN-END} section at the outer level of a package body is
25773 executed as part of the package body elaboration code.
25775 @item Library level task allocators
25776 Tasks that are declared using task allocators at the library level
25777 start executing immediately and hence can execute at elaboration time.
25781 Subprogram calls are possible in any of these contexts, which means that
25782 any arbitrary part of the program may be executed as part of the elaboration
25783 code. It is even possible to write a program which does all its work at
25784 elaboration time, with a null main program, although stylistically this
25785 would usually be considered an inappropriate way to structure
25788 An important concern arises in the context of elaboration code:
25789 we have to be sure that it is executed in an appropriate order. What we
25790 have is a series of elaboration code sections, potentially one section
25791 for each unit in the program. It is important that these execute
25792 in the correct order. Correctness here means that, taking the above
25793 example of the declaration of @code{Sqrt_Half},
25794 if some other piece of
25795 elaboration code references @code{Sqrt_Half},
25796 then it must run after the
25797 section of elaboration code that contains the declaration of
25800 There would never be any order of elaboration problem if we made a rule
25801 that whenever you @code{with} a unit, you must elaborate both the spec and body
25802 of that unit before elaborating the unit doing the @code{with}'ing:
25804 @smallexample @c ada
25808 package Unit_2 is ...
25814 would require that both the body and spec of @code{Unit_1} be elaborated
25815 before the spec of @code{Unit_2}. However, a rule like that would be far too
25816 restrictive. In particular, it would make it impossible to have routines
25817 in separate packages that were mutually recursive.
25819 You might think that a clever enough compiler could look at the actual
25820 elaboration code and determine an appropriate correct order of elaboration,
25821 but in the general case, this is not possible. Consider the following
25824 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
25826 the variable @code{Sqrt_1}, which is declared in the elaboration code
25827 of the body of @code{Unit_1}:
25829 @smallexample @c ada
25831 Sqrt_1 : Float := Sqrt (0.1);
25836 The elaboration code of the body of @code{Unit_1} also contains:
25838 @smallexample @c ada
25841 if expression_1 = 1 then
25842 Q := Unit_2.Func_2;
25849 @code{Unit_2} is exactly parallel,
25850 it has a procedure @code{Func_2} that references
25851 the variable @code{Sqrt_2}, which is declared in the elaboration code of
25852 the body @code{Unit_2}:
25854 @smallexample @c ada
25856 Sqrt_2 : Float := Sqrt (0.1);
25861 The elaboration code of the body of @code{Unit_2} also contains:
25863 @smallexample @c ada
25866 if expression_2 = 2 then
25867 Q := Unit_1.Func_1;
25874 Now the question is, which of the following orders of elaboration is
25899 If you carefully analyze the flow here, you will see that you cannot tell
25900 at compile time the answer to this question.
25901 If @code{expression_1} is not equal to 1,
25902 and @code{expression_2} is not equal to 2,
25903 then either order is acceptable, because neither of the function calls is
25904 executed. If both tests evaluate to true, then neither order is acceptable
25905 and in fact there is no correct order.
25907 If one of the two expressions is true, and the other is false, then one
25908 of the above orders is correct, and the other is incorrect. For example,
25909 if @code{expression_1} /= 1 and @code{expression_2} = 2,
25910 then the call to @code{Func_1}
25911 will occur, but not the call to @code{Func_2.}
25912 This means that it is essential
25913 to elaborate the body of @code{Unit_1} before
25914 the body of @code{Unit_2}, so the first
25915 order of elaboration is correct and the second is wrong.
25917 By making @code{expression_1} and @code{expression_2}
25918 depend on input data, or perhaps
25919 the time of day, we can make it impossible for the compiler or binder
25920 to figure out which of these expressions will be true, and hence it
25921 is impossible to guarantee a safe order of elaboration at run time.
25923 @node Checking the Elaboration Order
25924 @section Checking the Elaboration Order
25927 In some languages that involve the same kind of elaboration problems,
25928 e.g. Java and C++, the programmer is expected to worry about these
25929 ordering problems himself, and it is common to
25930 write a program in which an incorrect elaboration order gives
25931 surprising results, because it references variables before they
25933 Ada is designed to be a safe language, and a programmer-beware approach is
25934 clearly not sufficient. Consequently, the language provides three lines
25938 @item Standard rules
25939 Some standard rules restrict the possible choice of elaboration
25940 order. In particular, if you @code{with} a unit, then its spec is always
25941 elaborated before the unit doing the @code{with}. Similarly, a parent
25942 spec is always elaborated before the child spec, and finally
25943 a spec is always elaborated before its corresponding body.
25945 @item Dynamic elaboration checks
25946 @cindex Elaboration checks
25947 @cindex Checks, elaboration
25948 Dynamic checks are made at run time, so that if some entity is accessed
25949 before it is elaborated (typically by means of a subprogram call)
25950 then the exception (@code{Program_Error}) is raised.
25952 @item Elaboration control
25953 Facilities are provided for the programmer to specify the desired order
25957 Let's look at these facilities in more detail. First, the rules for
25958 dynamic checking. One possible rule would be simply to say that the
25959 exception is raised if you access a variable which has not yet been
25960 elaborated. The trouble with this approach is that it could require
25961 expensive checks on every variable reference. Instead Ada has two
25962 rules which are a little more restrictive, but easier to check, and
25966 @item Restrictions on calls
25967 A subprogram can only be called at elaboration time if its body
25968 has been elaborated. The rules for elaboration given above guarantee
25969 that the spec of the subprogram has been elaborated before the
25970 call, but not the body. If this rule is violated, then the
25971 exception @code{Program_Error} is raised.
25973 @item Restrictions on instantiations
25974 A generic unit can only be instantiated if the body of the generic
25975 unit has been elaborated. Again, the rules for elaboration given above
25976 guarantee that the spec of the generic unit has been elaborated
25977 before the instantiation, but not the body. If this rule is
25978 violated, then the exception @code{Program_Error} is raised.
25982 The idea is that if the body has been elaborated, then any variables
25983 it references must have been elaborated; by checking for the body being
25984 elaborated we guarantee that none of its references causes any
25985 trouble. As we noted above, this is a little too restrictive, because a
25986 subprogram that has no non-local references in its body may in fact be safe
25987 to call. However, it really would be unsafe to rely on this, because
25988 it would mean that the caller was aware of details of the implementation
25989 in the body. This goes against the basic tenets of Ada.
25991 A plausible implementation can be described as follows.
25992 A Boolean variable is associated with each subprogram
25993 and each generic unit. This variable is initialized to False, and is set to
25994 True at the point body is elaborated. Every call or instantiation checks the
25995 variable, and raises @code{Program_Error} if the variable is False.
25997 Note that one might think that it would be good enough to have one Boolean
25998 variable for each package, but that would not deal with cases of trying
25999 to call a body in the same package as the call
26000 that has not been elaborated yet.
26001 Of course a compiler may be able to do enough analysis to optimize away
26002 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
26003 does such optimizations, but still the easiest conceptual model is to
26004 think of there being one variable per subprogram.
26006 @node Controlling the Elaboration Order
26007 @section Controlling the Elaboration Order
26010 In the previous section we discussed the rules in Ada which ensure
26011 that @code{Program_Error} is raised if an incorrect elaboration order is
26012 chosen. This prevents erroneous executions, but we need mechanisms to
26013 specify a correct execution and avoid the exception altogether.
26014 To achieve this, Ada provides a number of features for controlling
26015 the order of elaboration. We discuss these features in this section.
26017 First, there are several ways of indicating to the compiler that a given
26018 unit has no elaboration problems:
26021 @item packages that do not require a body
26022 A library package that does not require a body does not permit
26023 a body (this rule was introduced in Ada 95).
26024 Thus if we have a such a package, as in:
26026 @smallexample @c ada
26029 package Definitions is
26031 type m is new integer;
26033 type a is array (1 .. 10) of m;
26034 type b is array (1 .. 20) of m;
26042 A package that @code{with}'s @code{Definitions} may safely instantiate
26043 @code{Definitions.Subp} because the compiler can determine that there
26044 definitely is no package body to worry about in this case
26047 @cindex pragma Pure
26049 Places sufficient restrictions on a unit to guarantee that
26050 no call to any subprogram in the unit can result in an
26051 elaboration problem. This means that the compiler does not need
26052 to worry about the point of elaboration of such units, and in
26053 particular, does not need to check any calls to any subprograms
26056 @item pragma Preelaborate
26057 @findex Preelaborate
26058 @cindex pragma Preelaborate
26059 This pragma places slightly less stringent restrictions on a unit than
26061 but these restrictions are still sufficient to ensure that there
26062 are no elaboration problems with any calls to the unit.
26064 @item pragma Elaborate_Body
26065 @findex Elaborate_Body
26066 @cindex pragma Elaborate_Body
26067 This pragma requires that the body of a unit be elaborated immediately
26068 after its spec. Suppose a unit @code{A} has such a pragma,
26069 and unit @code{B} does
26070 a @code{with} of unit @code{A}. Recall that the standard rules require
26071 the spec of unit @code{A}
26072 to be elaborated before the @code{with}'ing unit; given the pragma in
26073 @code{A}, we also know that the body of @code{A}
26074 will be elaborated before @code{B}, so
26075 that calls to @code{A} are safe and do not need a check.
26080 unlike pragma @code{Pure} and pragma @code{Preelaborate},
26082 @code{Elaborate_Body} does not guarantee that the program is
26083 free of elaboration problems, because it may not be possible
26084 to satisfy the requested elaboration order.
26085 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
26087 marks @code{Unit_1} as @code{Elaborate_Body},
26088 and not @code{Unit_2,} then the order of
26089 elaboration will be:
26101 Now that means that the call to @code{Func_1} in @code{Unit_2}
26102 need not be checked,
26103 it must be safe. But the call to @code{Func_2} in
26104 @code{Unit_1} may still fail if
26105 @code{Expression_1} is equal to 1,
26106 and the programmer must still take
26107 responsibility for this not being the case.
26109 If all units carry a pragma @code{Elaborate_Body}, then all problems are
26110 eliminated, except for calls entirely within a body, which are
26111 in any case fully under programmer control. However, using the pragma
26112 everywhere is not always possible.
26113 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
26114 we marked both of them as having pragma @code{Elaborate_Body}, then
26115 clearly there would be no possible elaboration order.
26117 The above pragmas allow a server to guarantee safe use by clients, and
26118 clearly this is the preferable approach. Consequently a good rule
26119 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
26120 and if this is not possible,
26121 mark them as @code{Elaborate_Body} if possible.
26122 As we have seen, there are situations where neither of these
26123 three pragmas can be used.
26124 So we also provide methods for clients to control the
26125 order of elaboration of the servers on which they depend:
26128 @item pragma Elaborate (unit)
26130 @cindex pragma Elaborate
26131 This pragma is placed in the context clause, after a @code{with} clause,
26132 and it requires that the body of the named unit be elaborated before
26133 the unit in which the pragma occurs. The idea is to use this pragma
26134 if the current unit calls at elaboration time, directly or indirectly,
26135 some subprogram in the named unit.
26137 @item pragma Elaborate_All (unit)
26138 @findex Elaborate_All
26139 @cindex pragma Elaborate_All
26140 This is a stronger version of the Elaborate pragma. Consider the
26144 Unit A @code{with}'s unit B and calls B.Func in elab code
26145 Unit B @code{with}'s unit C, and B.Func calls C.Func
26149 Now if we put a pragma @code{Elaborate (B)}
26150 in unit @code{A}, this ensures that the
26151 body of @code{B} is elaborated before the call, but not the
26152 body of @code{C}, so
26153 the call to @code{C.Func} could still cause @code{Program_Error} to
26156 The effect of a pragma @code{Elaborate_All} is stronger, it requires
26157 not only that the body of the named unit be elaborated before the
26158 unit doing the @code{with}, but also the bodies of all units that the
26159 named unit uses, following @code{with} links transitively. For example,
26160 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
26162 not only that the body of @code{B} be elaborated before @code{A},
26164 body of @code{C}, because @code{B} @code{with}'s @code{C}.
26168 We are now in a position to give a usage rule in Ada for avoiding
26169 elaboration problems, at least if dynamic dispatching and access to
26170 subprogram values are not used. We will handle these cases separately
26173 The rule is simple. If a unit has elaboration code that can directly or
26174 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
26175 a generic package in a @code{with}'ed unit,
26176 then if the @code{with}'ed unit does not have
26177 pragma @code{Pure} or @code{Preelaborate}, then the client should have
26178 a pragma @code{Elaborate_All}
26179 for the @code{with}'ed unit. By following this rule a client is
26180 assured that calls can be made without risk of an exception.
26182 For generic subprogram instantiations, the rule can be relaxed to
26183 require only a pragma @code{Elaborate} since elaborating the body
26184 of a subprogram cannot cause any transitive elaboration (we are
26185 not calling the subprogram in this case, just elaborating its
26188 If this rule is not followed, then a program may be in one of four
26192 @item No order exists
26193 No order of elaboration exists which follows the rules, taking into
26194 account any @code{Elaborate}, @code{Elaborate_All},
26195 or @code{Elaborate_Body} pragmas. In
26196 this case, an Ada compiler must diagnose the situation at bind
26197 time, and refuse to build an executable program.
26199 @item One or more orders exist, all incorrect
26200 One or more acceptable elaboration orders exist, and all of them
26201 generate an elaboration order problem. In this case, the binder
26202 can build an executable program, but @code{Program_Error} will be raised
26203 when the program is run.
26205 @item Several orders exist, some right, some incorrect
26206 One or more acceptable elaboration orders exists, and some of them
26207 work, and some do not. The programmer has not controlled
26208 the order of elaboration, so the binder may or may not pick one of
26209 the correct orders, and the program may or may not raise an
26210 exception when it is run. This is the worst case, because it means
26211 that the program may fail when moved to another compiler, or even
26212 another version of the same compiler.
26214 @item One or more orders exists, all correct
26215 One ore more acceptable elaboration orders exist, and all of them
26216 work. In this case the program runs successfully. This state of
26217 affairs can be guaranteed by following the rule we gave above, but
26218 may be true even if the rule is not followed.
26222 Note that one additional advantage of following our rules on the use
26223 of @code{Elaborate} and @code{Elaborate_All}
26224 is that the program continues to stay in the ideal (all orders OK) state
26225 even if maintenance
26226 changes some bodies of some units. Conversely, if a program that does
26227 not follow this rule happens to be safe at some point, this state of affairs
26228 may deteriorate silently as a result of maintenance changes.
26230 You may have noticed that the above discussion did not mention
26231 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
26232 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
26233 code in the body makes calls to some other unit, so it is still necessary
26234 to use @code{Elaborate_All} on such units.
26236 @node Controlling Elaboration in GNAT - Internal Calls
26237 @section Controlling Elaboration in GNAT - Internal Calls
26240 In the case of internal calls, i.e. calls within a single package, the
26241 programmer has full control over the order of elaboration, and it is up
26242 to the programmer to elaborate declarations in an appropriate order. For
26245 @smallexample @c ada
26248 function One return Float;
26252 function One return Float is
26261 will obviously raise @code{Program_Error} at run time, because function
26262 One will be called before its body is elaborated. In this case GNAT will
26263 generate a warning that the call will raise @code{Program_Error}:
26269 2. function One return Float;
26271 4. Q : Float := One;
26273 >>> warning: cannot call "One" before body is elaborated
26274 >>> warning: Program_Error will be raised at run time
26277 6. function One return Float is
26290 Note that in this particular case, it is likely that the call is safe, because
26291 the function @code{One} does not access any global variables.
26292 Nevertheless in Ada, we do not want the validity of the check to depend on
26293 the contents of the body (think about the separate compilation case), so this
26294 is still wrong, as we discussed in the previous sections.
26296 The error is easily corrected by rearranging the declarations so that the
26297 body of @code{One} appears before the declaration containing the call
26298 (note that in Ada 95 and Ada 2005,
26299 declarations can appear in any order, so there is no restriction that
26300 would prevent this reordering, and if we write:
26302 @smallexample @c ada
26305 function One return Float;
26307 function One return Float is
26318 then all is well, no warning is generated, and no
26319 @code{Program_Error} exception
26321 Things are more complicated when a chain of subprograms is executed:
26323 @smallexample @c ada
26326 function A return Integer;
26327 function B return Integer;
26328 function C return Integer;
26330 function B return Integer is begin return A; end;
26331 function C return Integer is begin return B; end;
26335 function A return Integer is begin return 1; end;
26341 Now the call to @code{C}
26342 at elaboration time in the declaration of @code{X} is correct, because
26343 the body of @code{C} is already elaborated,
26344 and the call to @code{B} within the body of
26345 @code{C} is correct, but the call
26346 to @code{A} within the body of @code{B} is incorrect, because the body
26347 of @code{A} has not been elaborated, so @code{Program_Error}
26348 will be raised on the call to @code{A}.
26349 In this case GNAT will generate a
26350 warning that @code{Program_Error} may be
26351 raised at the point of the call. Let's look at the warning:
26357 2. function A return Integer;
26358 3. function B return Integer;
26359 4. function C return Integer;
26361 6. function B return Integer is begin return A; end;
26363 >>> warning: call to "A" before body is elaborated may
26364 raise Program_Error
26365 >>> warning: "B" called at line 7
26366 >>> warning: "C" called at line 9
26368 7. function C return Integer is begin return B; end;
26370 9. X : Integer := C;
26372 11. function A return Integer is begin return 1; end;
26382 Note that the message here says ``may raise'', instead of the direct case,
26383 where the message says ``will be raised''. That's because whether
26385 actually called depends in general on run-time flow of control.
26386 For example, if the body of @code{B} said
26388 @smallexample @c ada
26391 function B return Integer is
26393 if some-condition-depending-on-input-data then
26404 then we could not know until run time whether the incorrect call to A would
26405 actually occur, so @code{Program_Error} might
26406 or might not be raised. It is possible for a compiler to
26407 do a better job of analyzing bodies, to
26408 determine whether or not @code{Program_Error}
26409 might be raised, but it certainly
26410 couldn't do a perfect job (that would require solving the halting problem
26411 and is provably impossible), and because this is a warning anyway, it does
26412 not seem worth the effort to do the analysis. Cases in which it
26413 would be relevant are rare.
26415 In practice, warnings of either of the forms given
26416 above will usually correspond to
26417 real errors, and should be examined carefully and eliminated.
26418 In the rare case where a warning is bogus, it can be suppressed by any of
26419 the following methods:
26423 Compile with the @option{-gnatws} switch set
26426 Suppress @code{Elaboration_Check} for the called subprogram
26429 Use pragma @code{Warnings_Off} to turn warnings off for the call
26433 For the internal elaboration check case,
26434 GNAT by default generates the
26435 necessary run-time checks to ensure
26436 that @code{Program_Error} is raised if any
26437 call fails an elaboration check. Of course this can only happen if a
26438 warning has been issued as described above. The use of pragma
26439 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
26440 some of these checks, meaning that it may be possible (but is not
26441 guaranteed) for a program to be able to call a subprogram whose body
26442 is not yet elaborated, without raising a @code{Program_Error} exception.
26444 @node Controlling Elaboration in GNAT - External Calls
26445 @section Controlling Elaboration in GNAT - External Calls
26448 The previous section discussed the case in which the execution of a
26449 particular thread of elaboration code occurred entirely within a
26450 single unit. This is the easy case to handle, because a programmer
26451 has direct and total control over the order of elaboration, and
26452 furthermore, checks need only be generated in cases which are rare
26453 and which the compiler can easily detect.
26454 The situation is more complex when separate compilation is taken into account.
26455 Consider the following:
26457 @smallexample @c ada
26461 function Sqrt (Arg : Float) return Float;
26464 package body Math is
26465 function Sqrt (Arg : Float) return Float is
26474 X : Float := Math.Sqrt (0.5);
26487 where @code{Main} is the main program. When this program is executed, the
26488 elaboration code must first be executed, and one of the jobs of the
26489 binder is to determine the order in which the units of a program are
26490 to be elaborated. In this case we have four units: the spec and body
26492 the spec of @code{Stuff} and the body of @code{Main}).
26493 In what order should the four separate sections of elaboration code
26496 There are some restrictions in the order of elaboration that the binder
26497 can choose. In particular, if unit U has a @code{with}
26498 for a package @code{X}, then you
26499 are assured that the spec of @code{X}
26500 is elaborated before U , but you are
26501 not assured that the body of @code{X}
26502 is elaborated before U.
26503 This means that in the above case, the binder is allowed to choose the
26514 but that's not good, because now the call to @code{Math.Sqrt}
26515 that happens during
26516 the elaboration of the @code{Stuff}
26517 spec happens before the body of @code{Math.Sqrt} is
26518 elaborated, and hence causes @code{Program_Error} exception to be raised.
26519 At first glance, one might say that the binder is misbehaving, because
26520 obviously you want to elaborate the body of something you @code{with}
26522 that is not a general rule that can be followed in all cases. Consider
26524 @smallexample @c ada
26532 package body Y is ...
26535 package body X is ...
26541 This is a common arrangement, and, apart from the order of elaboration
26542 problems that might arise in connection with elaboration code, this works fine.
26543 A rule that says that you must first elaborate the body of anything you
26544 @code{with} cannot work in this case:
26545 the body of @code{X} @code{with}'s @code{Y},
26546 which means you would have to
26547 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
26549 you have to elaborate the body of @code{X} first, but ... and we have a
26550 loop that cannot be broken.
26552 It is true that the binder can in many cases guess an order of elaboration
26553 that is unlikely to cause a @code{Program_Error}
26554 exception to be raised, and it tries to do so (in the
26555 above example of @code{Math/Stuff/Spec}, the GNAT binder will
26557 elaborate the body of @code{Math} right after its spec, so all will be well).
26559 However, a program that blindly relies on the binder to be helpful can
26560 get into trouble, as we discussed in the previous sections, so
26562 provides a number of facilities for assisting the programmer in
26563 developing programs that are robust with respect to elaboration order.
26565 @node Default Behavior in GNAT - Ensuring Safety
26566 @section Default Behavior in GNAT - Ensuring Safety
26569 The default behavior in GNAT ensures elaboration safety. In its
26570 default mode GNAT implements the
26571 rule we previously described as the right approach. Let's restate it:
26575 @emph{If a unit has elaboration code that can directly or indirectly make a
26576 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
26577 package in a @code{with}'ed unit, then if the @code{with}'ed unit
26578 does not have pragma @code{Pure} or
26579 @code{Preelaborate}, then the client should have an
26580 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
26582 @emph{In the case of instantiating a generic subprogram, it is always
26583 sufficient to have only an @code{Elaborate} pragma for the
26584 @code{with}'ed unit.}
26588 By following this rule a client is assured that calls and instantiations
26589 can be made without risk of an exception.
26591 In this mode GNAT traces all calls that are potentially made from
26592 elaboration code, and puts in any missing implicit @code{Elaborate}
26593 and @code{Elaborate_All} pragmas.
26594 The advantage of this approach is that no elaboration problems
26595 are possible if the binder can find an elaboration order that is
26596 consistent with these implicit @code{Elaborate} and
26597 @code{Elaborate_All} pragmas. The
26598 disadvantage of this approach is that no such order may exist.
26600 If the binder does not generate any diagnostics, then it means that it has
26601 found an elaboration order that is guaranteed to be safe. However, the binder
26602 may still be relying on implicitly generated @code{Elaborate} and
26603 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
26606 If it is important to guarantee portability, then the compilations should
26609 (warn on elaboration problems) switch. This will cause warning messages
26610 to be generated indicating the missing @code{Elaborate} and
26611 @code{Elaborate_All} pragmas.
26612 Consider the following source program:
26614 @smallexample @c ada
26619 m : integer := k.r;
26626 where it is clear that there
26627 should be a pragma @code{Elaborate_All}
26628 for unit @code{k}. An implicit pragma will be generated, and it is
26629 likely that the binder will be able to honor it. However, if you want
26630 to port this program to some other Ada compiler than GNAT.
26631 it is safer to include the pragma explicitly in the source. If this
26632 unit is compiled with the
26634 switch, then the compiler outputs a warning:
26641 3. m : integer := k.r;
26643 >>> warning: call to "r" may raise Program_Error
26644 >>> warning: missing pragma Elaborate_All for "k"
26652 and these warnings can be used as a guide for supplying manually
26653 the missing pragmas. It is usually a bad idea to use this warning
26654 option during development. That's because it will warn you when
26655 you need to put in a pragma, but cannot warn you when it is time
26656 to take it out. So the use of pragma @code{Elaborate_All} may lead to
26657 unnecessary dependencies and even false circularities.
26659 This default mode is more restrictive than the Ada Reference
26660 Manual, and it is possible to construct programs which will compile
26661 using the dynamic model described there, but will run into a
26662 circularity using the safer static model we have described.
26664 Of course any Ada compiler must be able to operate in a mode
26665 consistent with the requirements of the Ada Reference Manual,
26666 and in particular must have the capability of implementing the
26667 standard dynamic model of elaboration with run-time checks.
26669 In GNAT, this standard mode can be achieved either by the use of
26670 the @option{-gnatE} switch on the compiler (@command{gcc} or
26671 @command{gnatmake}) command, or by the use of the configuration pragma:
26673 @smallexample @c ada
26674 pragma Elaboration_Checks (RM);
26678 Either approach will cause the unit affected to be compiled using the
26679 standard dynamic run-time elaboration checks described in the Ada
26680 Reference Manual. The static model is generally preferable, since it
26681 is clearly safer to rely on compile and link time checks rather than
26682 run-time checks. However, in the case of legacy code, it may be
26683 difficult to meet the requirements of the static model. This
26684 issue is further discussed in
26685 @ref{What to Do If the Default Elaboration Behavior Fails}.
26687 Note that the static model provides a strict subset of the allowed
26688 behavior and programs of the Ada Reference Manual, so if you do
26689 adhere to the static model and no circularities exist,
26690 then you are assured that your program will
26691 work using the dynamic model, providing that you remove any
26692 pragma Elaborate statements from the source.
26694 @node Treatment of Pragma Elaborate
26695 @section Treatment of Pragma Elaborate
26696 @cindex Pragma Elaborate
26699 The use of @code{pragma Elaborate}
26700 should generally be avoided in Ada 95 and Ada 2005 programs,
26701 since there is no guarantee that transitive calls
26702 will be properly handled. Indeed at one point, this pragma was placed
26703 in Annex J (Obsolescent Features), on the grounds that it is never useful.
26705 Now that's a bit restrictive. In practice, the case in which
26706 @code{pragma Elaborate} is useful is when the caller knows that there
26707 are no transitive calls, or that the called unit contains all necessary
26708 transitive @code{pragma Elaborate} statements, and legacy code often
26709 contains such uses.
26711 Strictly speaking the static mode in GNAT should ignore such pragmas,
26712 since there is no assurance at compile time that the necessary safety
26713 conditions are met. In practice, this would cause GNAT to be incompatible
26714 with correctly written Ada 83 code that had all necessary
26715 @code{pragma Elaborate} statements in place. Consequently, we made the
26716 decision that GNAT in its default mode will believe that if it encounters
26717 a @code{pragma Elaborate} then the programmer knows what they are doing,
26718 and it will trust that no elaboration errors can occur.
26720 The result of this decision is two-fold. First to be safe using the
26721 static mode, you should remove all @code{pragma Elaborate} statements.
26722 Second, when fixing circularities in existing code, you can selectively
26723 use @code{pragma Elaborate} statements to convince the static mode of
26724 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
26727 When using the static mode with @option{-gnatwl}, any use of
26728 @code{pragma Elaborate} will generate a warning about possible
26731 @node Elaboration Issues for Library Tasks
26732 @section Elaboration Issues for Library Tasks
26733 @cindex Library tasks, elaboration issues
26734 @cindex Elaboration of library tasks
26737 In this section we examine special elaboration issues that arise for
26738 programs that declare library level tasks.
26740 Generally the model of execution of an Ada program is that all units are
26741 elaborated, and then execution of the program starts. However, the
26742 declaration of library tasks definitely does not fit this model. The
26743 reason for this is that library tasks start as soon as they are declared
26744 (more precisely, as soon as the statement part of the enclosing package
26745 body is reached), that is to say before elaboration
26746 of the program is complete. This means that if such a task calls a
26747 subprogram, or an entry in another task, the callee may or may not be
26748 elaborated yet, and in the standard
26749 Reference Manual model of dynamic elaboration checks, you can even
26750 get timing dependent Program_Error exceptions, since there can be
26751 a race between the elaboration code and the task code.
26753 The static model of elaboration in GNAT seeks to avoid all such
26754 dynamic behavior, by being conservative, and the conservative
26755 approach in this particular case is to assume that all the code
26756 in a task body is potentially executed at elaboration time if
26757 a task is declared at the library level.
26759 This can definitely result in unexpected circularities. Consider
26760 the following example
26762 @smallexample @c ada
26768 type My_Int is new Integer;
26770 function Ident (M : My_Int) return My_Int;
26774 package body Decls is
26775 task body Lib_Task is
26781 function Ident (M : My_Int) return My_Int is
26789 procedure Put_Val (Arg : Decls.My_Int);
26793 package body Utils is
26794 procedure Put_Val (Arg : Decls.My_Int) is
26796 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
26803 Decls.Lib_Task.Start;
26808 If the above example is compiled in the default static elaboration
26809 mode, then a circularity occurs. The circularity comes from the call
26810 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
26811 this call occurs in elaboration code, we need an implicit pragma
26812 @code{Elaborate_All} for @code{Utils}. This means that not only must
26813 the spec and body of @code{Utils} be elaborated before the body
26814 of @code{Decls}, but also the spec and body of any unit that is
26815 @code{with'ed} by the body of @code{Utils} must also be elaborated before
26816 the body of @code{Decls}. This is the transitive implication of
26817 pragma @code{Elaborate_All} and it makes sense, because in general
26818 the body of @code{Put_Val} might have a call to something in a
26819 @code{with'ed} unit.
26821 In this case, the body of Utils (actually its spec) @code{with's}
26822 @code{Decls}. Unfortunately this means that the body of @code{Decls}
26823 must be elaborated before itself, in case there is a call from the
26824 body of @code{Utils}.
26826 Here is the exact chain of events we are worrying about:
26830 In the body of @code{Decls} a call is made from within the body of a library
26831 task to a subprogram in the package @code{Utils}. Since this call may
26832 occur at elaboration time (given that the task is activated at elaboration
26833 time), we have to assume the worst, i.e. that the
26834 call does happen at elaboration time.
26837 This means that the body and spec of @code{Util} must be elaborated before
26838 the body of @code{Decls} so that this call does not cause an access before
26842 Within the body of @code{Util}, specifically within the body of
26843 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
26847 One such @code{with}'ed package is package @code{Decls}, so there
26848 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
26849 In fact there is such a call in this example, but we would have to
26850 assume that there was such a call even if it were not there, since
26851 we are not supposed to write the body of @code{Decls} knowing what
26852 is in the body of @code{Utils}; certainly in the case of the
26853 static elaboration model, the compiler does not know what is in
26854 other bodies and must assume the worst.
26857 This means that the spec and body of @code{Decls} must also be
26858 elaborated before we elaborate the unit containing the call, but
26859 that unit is @code{Decls}! This means that the body of @code{Decls}
26860 must be elaborated before itself, and that's a circularity.
26864 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
26865 the body of @code{Decls} you will get a true Ada Reference Manual
26866 circularity that makes the program illegal.
26868 In practice, we have found that problems with the static model of
26869 elaboration in existing code often arise from library tasks, so
26870 we must address this particular situation.
26872 Note that if we compile and run the program above, using the dynamic model of
26873 elaboration (that is to say use the @option{-gnatE} switch),
26874 then it compiles, binds,
26875 links, and runs, printing the expected result of 2. Therefore in some sense
26876 the circularity here is only apparent, and we need to capture
26877 the properties of this program that distinguish it from other library-level
26878 tasks that have real elaboration problems.
26880 We have four possible answers to this question:
26885 Use the dynamic model of elaboration.
26887 If we use the @option{-gnatE} switch, then as noted above, the program works.
26888 Why is this? If we examine the task body, it is apparent that the task cannot
26890 @code{accept} statement until after elaboration has been completed, because
26891 the corresponding entry call comes from the main program, not earlier.
26892 This is why the dynamic model works here. But that's really giving
26893 up on a precise analysis, and we prefer to take this approach only if we cannot
26895 problem in any other manner. So let us examine two ways to reorganize
26896 the program to avoid the potential elaboration problem.
26899 Split library tasks into separate packages.
26901 Write separate packages, so that library tasks are isolated from
26902 other declarations as much as possible. Let us look at a variation on
26905 @smallexample @c ada
26913 package body Decls1 is
26914 task body Lib_Task is
26922 type My_Int is new Integer;
26923 function Ident (M : My_Int) return My_Int;
26927 package body Decls2 is
26928 function Ident (M : My_Int) return My_Int is
26936 procedure Put_Val (Arg : Decls2.My_Int);
26940 package body Utils is
26941 procedure Put_Val (Arg : Decls2.My_Int) is
26943 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
26950 Decls1.Lib_Task.Start;
26955 All we have done is to split @code{Decls} into two packages, one
26956 containing the library task, and one containing everything else. Now
26957 there is no cycle, and the program compiles, binds, links and executes
26958 using the default static model of elaboration.
26961 Declare separate task types.
26963 A significant part of the problem arises because of the use of the
26964 single task declaration form. This means that the elaboration of
26965 the task type, and the elaboration of the task itself (i.e. the
26966 creation of the task) happen at the same time. A good rule
26967 of style in Ada is to always create explicit task types. By
26968 following the additional step of placing task objects in separate
26969 packages from the task type declaration, many elaboration problems
26970 are avoided. Here is another modified example of the example program:
26972 @smallexample @c ada
26974 task type Lib_Task_Type is
26978 type My_Int is new Integer;
26980 function Ident (M : My_Int) return My_Int;
26984 package body Decls is
26985 task body Lib_Task_Type is
26991 function Ident (M : My_Int) return My_Int is
26999 procedure Put_Val (Arg : Decls.My_Int);
27003 package body Utils is
27004 procedure Put_Val (Arg : Decls.My_Int) is
27006 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
27012 Lib_Task : Decls.Lib_Task_Type;
27018 Declst.Lib_Task.Start;
27023 What we have done here is to replace the @code{task} declaration in
27024 package @code{Decls} with a @code{task type} declaration. Then we
27025 introduce a separate package @code{Declst} to contain the actual
27026 task object. This separates the elaboration issues for
27027 the @code{task type}
27028 declaration, which causes no trouble, from the elaboration issues
27029 of the task object, which is also unproblematic, since it is now independent
27030 of the elaboration of @code{Utils}.
27031 This separation of concerns also corresponds to
27032 a generally sound engineering principle of separating declarations
27033 from instances. This version of the program also compiles, binds, links,
27034 and executes, generating the expected output.
27037 Use No_Entry_Calls_In_Elaboration_Code restriction.
27038 @cindex No_Entry_Calls_In_Elaboration_Code
27040 The previous two approaches described how a program can be restructured
27041 to avoid the special problems caused by library task bodies. in practice,
27042 however, such restructuring may be difficult to apply to existing legacy code,
27043 so we must consider solutions that do not require massive rewriting.
27045 Let us consider more carefully why our original sample program works
27046 under the dynamic model of elaboration. The reason is that the code
27047 in the task body blocks immediately on the @code{accept}
27048 statement. Now of course there is nothing to prohibit elaboration
27049 code from making entry calls (for example from another library level task),
27050 so we cannot tell in isolation that
27051 the task will not execute the accept statement during elaboration.
27053 However, in practice it is very unusual to see elaboration code
27054 make any entry calls, and the pattern of tasks starting
27055 at elaboration time and then immediately blocking on @code{accept} or
27056 @code{select} statements is very common. What this means is that
27057 the compiler is being too pessimistic when it analyzes the
27058 whole package body as though it might be executed at elaboration
27061 If we know that the elaboration code contains no entry calls, (a very safe
27062 assumption most of the time, that could almost be made the default
27063 behavior), then we can compile all units of the program under control
27064 of the following configuration pragma:
27067 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
27071 This pragma can be placed in the @file{gnat.adc} file in the usual
27072 manner. If we take our original unmodified program and compile it
27073 in the presence of a @file{gnat.adc} containing the above pragma,
27074 then once again, we can compile, bind, link, and execute, obtaining
27075 the expected result. In the presence of this pragma, the compiler does
27076 not trace calls in a task body, that appear after the first @code{accept}
27077 or @code{select} statement, and therefore does not report a potential
27078 circularity in the original program.
27080 The compiler will check to the extent it can that the above
27081 restriction is not violated, but it is not always possible to do a
27082 complete check at compile time, so it is important to use this
27083 pragma only if the stated restriction is in fact met, that is to say
27084 no task receives an entry call before elaboration of all units is completed.
27088 @node Mixing Elaboration Models
27089 @section Mixing Elaboration Models
27091 So far, we have assumed that the entire program is either compiled
27092 using the dynamic model or static model, ensuring consistency. It
27093 is possible to mix the two models, but rules have to be followed
27094 if this mixing is done to ensure that elaboration checks are not
27097 The basic rule is that @emph{a unit compiled with the static model cannot
27098 be @code{with'ed} by a unit compiled with the dynamic model}. The
27099 reason for this is that in the static model, a unit assumes that
27100 its clients guarantee to use (the equivalent of) pragma
27101 @code{Elaborate_All} so that no elaboration checks are required
27102 in inner subprograms, and this assumption is violated if the
27103 client is compiled with dynamic checks.
27105 The precise rule is as follows. A unit that is compiled with dynamic
27106 checks can only @code{with} a unit that meets at least one of the
27107 following criteria:
27112 The @code{with'ed} unit is itself compiled with dynamic elaboration
27113 checks (that is with the @option{-gnatE} switch.
27116 The @code{with'ed} unit is an internal GNAT implementation unit from
27117 the System, Interfaces, Ada, or GNAT hierarchies.
27120 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
27123 The @code{with'ing} unit (that is the client) has an explicit pragma
27124 @code{Elaborate_All} for the @code{with'ed} unit.
27129 If this rule is violated, that is if a unit with dynamic elaboration
27130 checks @code{with's} a unit that does not meet one of the above four
27131 criteria, then the binder (@code{gnatbind}) will issue a warning
27132 similar to that in the following example:
27135 warning: "x.ads" has dynamic elaboration checks and with's
27136 warning: "y.ads" which has static elaboration checks
27140 These warnings indicate that the rule has been violated, and that as a result
27141 elaboration checks may be missed in the resulting executable file.
27142 This warning may be suppressed using the @option{-ws} binder switch
27143 in the usual manner.
27145 One useful application of this mixing rule is in the case of a subsystem
27146 which does not itself @code{with} units from the remainder of the
27147 application. In this case, the entire subsystem can be compiled with
27148 dynamic checks to resolve a circularity in the subsystem, while
27149 allowing the main application that uses this subsystem to be compiled
27150 using the more reliable default static model.
27152 @node What to Do If the Default Elaboration Behavior Fails
27153 @section What to Do If the Default Elaboration Behavior Fails
27156 If the binder cannot find an acceptable order, it outputs detailed
27157 diagnostics. For example:
27163 error: elaboration circularity detected
27164 info: "proc (body)" must be elaborated before "pack (body)"
27165 info: reason: Elaborate_All probably needed in unit "pack (body)"
27166 info: recompile "pack (body)" with -gnatwl
27167 info: for full details
27168 info: "proc (body)"
27169 info: is needed by its spec:
27170 info: "proc (spec)"
27171 info: which is withed by:
27172 info: "pack (body)"
27173 info: "pack (body)" must be elaborated before "proc (body)"
27174 info: reason: pragma Elaborate in unit "proc (body)"
27180 In this case we have a cycle that the binder cannot break. On the one
27181 hand, there is an explicit pragma Elaborate in @code{proc} for
27182 @code{pack}. This means that the body of @code{pack} must be elaborated
27183 before the body of @code{proc}. On the other hand, there is elaboration
27184 code in @code{pack} that calls a subprogram in @code{proc}. This means
27185 that for maximum safety, there should really be a pragma
27186 Elaborate_All in @code{pack} for @code{proc} which would require that
27187 the body of @code{proc} be elaborated before the body of
27188 @code{pack}. Clearly both requirements cannot be satisfied.
27189 Faced with a circularity of this kind, you have three different options.
27192 @item Fix the program
27193 The most desirable option from the point of view of long-term maintenance
27194 is to rearrange the program so that the elaboration problems are avoided.
27195 One useful technique is to place the elaboration code into separate
27196 child packages. Another is to move some of the initialization code to
27197 explicitly called subprograms, where the program controls the order
27198 of initialization explicitly. Although this is the most desirable option,
27199 it may be impractical and involve too much modification, especially in
27200 the case of complex legacy code.
27202 @item Perform dynamic checks
27203 If the compilations are done using the
27205 (dynamic elaboration check) switch, then GNAT behaves in a quite different
27206 manner. Dynamic checks are generated for all calls that could possibly result
27207 in raising an exception. With this switch, the compiler does not generate
27208 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
27209 exactly as specified in the @cite{Ada Reference Manual}.
27210 The binder will generate
27211 an executable program that may or may not raise @code{Program_Error}, and then
27212 it is the programmer's job to ensure that it does not raise an exception. Note
27213 that it is important to compile all units with the switch, it cannot be used
27216 @item Suppress checks
27217 The drawback of dynamic checks is that they generate a
27218 significant overhead at run time, both in space and time. If you
27219 are absolutely sure that your program cannot raise any elaboration
27220 exceptions, and you still want to use the dynamic elaboration model,
27221 then you can use the configuration pragma
27222 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
27223 example this pragma could be placed in the @file{gnat.adc} file.
27225 @item Suppress checks selectively
27226 When you know that certain calls or instantiations in elaboration code cannot
27227 possibly lead to an elaboration error, and the binder nevertheless complains
27228 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
27229 elaboration circularities, it is possible to remove those warnings locally and
27230 obtain a program that will bind. Clearly this can be unsafe, and it is the
27231 responsibility of the programmer to make sure that the resulting program has no
27232 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
27233 used with different granularity to suppress warnings and break elaboration
27238 Place the pragma that names the called subprogram in the declarative part
27239 that contains the call.
27242 Place the pragma in the declarative part, without naming an entity. This
27243 disables warnings on all calls in the corresponding declarative region.
27246 Place the pragma in the package spec that declares the called subprogram,
27247 and name the subprogram. This disables warnings on all elaboration calls to
27251 Place the pragma in the package spec that declares the called subprogram,
27252 without naming any entity. This disables warnings on all elaboration calls to
27253 all subprograms declared in this spec.
27255 @item Use Pragma Elaborate
27256 As previously described in section @xref{Treatment of Pragma Elaborate},
27257 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
27258 that no elaboration checks are required on calls to the designated unit.
27259 There may be cases in which the caller knows that no transitive calls
27260 can occur, so that a @code{pragma Elaborate} will be sufficient in a
27261 case where @code{pragma Elaborate_All} would cause a circularity.
27265 These five cases are listed in order of decreasing safety, and therefore
27266 require increasing programmer care in their application. Consider the
27269 @smallexample @c adanocomment
27271 function F1 return Integer;
27276 function F2 return Integer;
27277 function Pure (x : integer) return integer;
27278 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
27279 -- pragma Suppress (Elaboration_Check); -- (4)
27283 package body Pack1 is
27284 function F1 return Integer is
27288 Val : integer := Pack2.Pure (11); -- Elab. call (1)
27291 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
27292 -- pragma Suppress(Elaboration_Check); -- (2)
27294 X1 := Pack2.F2 + 1; -- Elab. call (2)
27299 package body Pack2 is
27300 function F2 return Integer is
27304 function Pure (x : integer) return integer is
27306 return x ** 3 - 3 * x;
27310 with Pack1, Ada.Text_IO;
27313 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
27316 In the absence of any pragmas, an attempt to bind this program produces
27317 the following diagnostics:
27323 error: elaboration circularity detected
27324 info: "pack1 (body)" must be elaborated before "pack1 (body)"
27325 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
27326 info: recompile "pack1 (body)" with -gnatwl for full details
27327 info: "pack1 (body)"
27328 info: must be elaborated along with its spec:
27329 info: "pack1 (spec)"
27330 info: which is withed by:
27331 info: "pack2 (body)"
27332 info: which must be elaborated along with its spec:
27333 info: "pack2 (spec)"
27334 info: which is withed by:
27335 info: "pack1 (body)"
27338 The sources of the circularity are the two calls to @code{Pack2.Pure} and
27339 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
27340 F2 is safe, even though F2 calls F1, because the call appears after the
27341 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
27342 remove the warning on the call. It is also possible to use pragma (2)
27343 because there are no other potentially unsafe calls in the block.
27346 The call to @code{Pure} is safe because this function does not depend on the
27347 state of @code{Pack2}. Therefore any call to this function is safe, and it
27348 is correct to place pragma (3) in the corresponding package spec.
27351 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
27352 warnings on all calls to functions declared therein. Note that this is not
27353 necessarily safe, and requires more detailed examination of the subprogram
27354 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
27355 be already elaborated.
27359 It is hard to generalize on which of these four approaches should be
27360 taken. Obviously if it is possible to fix the program so that the default
27361 treatment works, this is preferable, but this may not always be practical.
27362 It is certainly simple enough to use
27364 but the danger in this case is that, even if the GNAT binder
27365 finds a correct elaboration order, it may not always do so,
27366 and certainly a binder from another Ada compiler might not. A
27367 combination of testing and analysis (for which the warnings generated
27370 switch can be useful) must be used to ensure that the program is free
27371 of errors. One switch that is useful in this testing is the
27372 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
27375 Normally the binder tries to find an order that has the best chance
27376 of avoiding elaboration problems. However, if this switch is used, the binder
27377 plays a devil's advocate role, and tries to choose the order that
27378 has the best chance of failing. If your program works even with this
27379 switch, then it has a better chance of being error free, but this is still
27382 For an example of this approach in action, consider the C-tests (executable
27383 tests) from the ACVC suite. If these are compiled and run with the default
27384 treatment, then all but one of them succeed without generating any error
27385 diagnostics from the binder. However, there is one test that fails, and
27386 this is not surprising, because the whole point of this test is to ensure
27387 that the compiler can handle cases where it is impossible to determine
27388 a correct order statically, and it checks that an exception is indeed
27389 raised at run time.
27391 This one test must be compiled and run using the
27393 switch, and then it passes. Alternatively, the entire suite can
27394 be run using this switch. It is never wrong to run with the dynamic
27395 elaboration switch if your code is correct, and we assume that the
27396 C-tests are indeed correct (it is less efficient, but efficiency is
27397 not a factor in running the ACVC tests.)
27399 @node Elaboration for Access-to-Subprogram Values
27400 @section Elaboration for Access-to-Subprogram Values
27401 @cindex Access-to-subprogram
27404 Access-to-subprogram types (introduced in Ada 95) complicate
27405 the handling of elaboration. The trouble is that it becomes
27406 impossible to tell at compile time which procedure
27407 is being called. This means that it is not possible for the binder
27408 to analyze the elaboration requirements in this case.
27410 If at the point at which the access value is created
27411 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
27412 the body of the subprogram is
27413 known to have been elaborated, then the access value is safe, and its use
27414 does not require a check. This may be achieved by appropriate arrangement
27415 of the order of declarations if the subprogram is in the current unit,
27416 or, if the subprogram is in another unit, by using pragma
27417 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
27418 on the referenced unit.
27420 If the referenced body is not known to have been elaborated at the point
27421 the access value is created, then any use of the access value must do a
27422 dynamic check, and this dynamic check will fail and raise a
27423 @code{Program_Error} exception if the body has not been elaborated yet.
27424 GNAT will generate the necessary checks, and in addition, if the
27426 switch is set, will generate warnings that such checks are required.
27428 The use of dynamic dispatching for tagged types similarly generates
27429 a requirement for dynamic checks, and premature calls to any primitive
27430 operation of a tagged type before the body of the operation has been
27431 elaborated, will result in the raising of @code{Program_Error}.
27433 @node Summary of Procedures for Elaboration Control
27434 @section Summary of Procedures for Elaboration Control
27435 @cindex Elaboration control
27438 First, compile your program with the default options, using none of
27439 the special elaboration control switches. If the binder successfully
27440 binds your program, then you can be confident that, apart from issues
27441 raised by the use of access-to-subprogram types and dynamic dispatching,
27442 the program is free of elaboration errors. If it is important that the
27443 program be portable, then use the
27445 switch to generate warnings about missing @code{Elaborate} or
27446 @code{Elaborate_All} pragmas, and supply the missing pragmas.
27448 If the program fails to bind using the default static elaboration
27449 handling, then you can fix the program to eliminate the binder
27450 message, or recompile the entire program with the
27451 @option{-gnatE} switch to generate dynamic elaboration checks,
27452 and, if you are sure there really are no elaboration problems,
27453 use a global pragma @code{Suppress (Elaboration_Check)}.
27455 @node Other Elaboration Order Considerations
27456 @section Other Elaboration Order Considerations
27458 This section has been entirely concerned with the issue of finding a valid
27459 elaboration order, as defined by the Ada Reference Manual. In a case
27460 where several elaboration orders are valid, the task is to find one
27461 of the possible valid elaboration orders (and the static model in GNAT
27462 will ensure that this is achieved).
27464 The purpose of the elaboration rules in the Ada Reference Manual is to
27465 make sure that no entity is accessed before it has been elaborated. For
27466 a subprogram, this means that the spec and body must have been elaborated
27467 before the subprogram is called. For an object, this means that the object
27468 must have been elaborated before its value is read or written. A violation
27469 of either of these two requirements is an access before elaboration order,
27470 and this section has been all about avoiding such errors.
27472 In the case where more than one order of elaboration is possible, in the
27473 sense that access before elaboration errors are avoided, then any one of
27474 the orders is ``correct'' in the sense that it meets the requirements of
27475 the Ada Reference Manual, and no such error occurs.
27477 However, it may be the case for a given program, that there are
27478 constraints on the order of elaboration that come not from consideration
27479 of avoiding elaboration errors, but rather from extra-lingual logic
27480 requirements. Consider this example:
27482 @smallexample @c ada
27483 with Init_Constants;
27484 package Constants is
27489 package Init_Constants is
27490 procedure P; -- require a body
27491 end Init_Constants;
27494 package body Init_Constants is
27495 procedure P is begin null; end;
27499 end Init_Constants;
27503 Z : Integer := Constants.X + Constants.Y;
27507 with Text_IO; use Text_IO;
27510 Put_Line (Calc.Z'Img);
27515 In this example, there is more than one valid order of elaboration. For
27516 example both the following are correct orders:
27519 Init_Constants spec
27522 Init_Constants body
27527 Init_Constants spec
27528 Init_Constants body
27535 There is no language rule to prefer one or the other, both are correct
27536 from an order of elaboration point of view. But the programmatic effects
27537 of the two orders are very different. In the first, the elaboration routine
27538 of @code{Calc} initializes @code{Z} to zero, and then the main program
27539 runs with this value of zero. But in the second order, the elaboration
27540 routine of @code{Calc} runs after the body of Init_Constants has set
27541 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
27544 One could perhaps by applying pretty clever non-artificial intelligence
27545 to the situation guess that it is more likely that the second order of
27546 elaboration is the one desired, but there is no formal linguistic reason
27547 to prefer one over the other. In fact in this particular case, GNAT will
27548 prefer the second order, because of the rule that bodies are elaborated
27549 as soon as possible, but it's just luck that this is what was wanted
27550 (if indeed the second order was preferred).
27552 If the program cares about the order of elaboration routines in a case like
27553 this, it is important to specify the order required. In this particular
27554 case, that could have been achieved by adding to the spec of Calc:
27556 @smallexample @c ada
27557 pragma Elaborate_All (Constants);
27561 which requires that the body (if any) and spec of @code{Constants},
27562 as well as the body and spec of any unit @code{with}'ed by
27563 @code{Constants} be elaborated before @code{Calc} is elaborated.
27565 Clearly no automatic method can always guess which alternative you require,
27566 and if you are working with legacy code that had constraints of this kind
27567 which were not properly specified by adding @code{Elaborate} or
27568 @code{Elaborate_All} pragmas, then indeed it is possible that two different
27569 compilers can choose different orders.
27571 However, GNAT does attempt to diagnose the common situation where there
27572 are uninitialized variables in the visible part of a package spec, and the
27573 corresponding package body has an elaboration block that directly or
27574 indirectly initialized one or more of these variables. This is the situation
27575 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
27576 a warning that suggests this addition if it detects this situation.
27578 The @code{gnatbind}
27579 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
27580 out problems. This switch causes bodies to be elaborated as late as possible
27581 instead of as early as possible. In the example above, it would have forced
27582 the choice of the first elaboration order. If you get different results
27583 when using this switch, and particularly if one set of results is right,
27584 and one is wrong as far as you are concerned, it shows that you have some
27585 missing @code{Elaborate} pragmas. For the example above, we have the
27589 gnatmake -f -q main
27592 gnatmake -f -q main -bargs -p
27598 It is of course quite unlikely that both these results are correct, so
27599 it is up to you in a case like this to investigate the source of the
27600 difference, by looking at the two elaboration orders that are chosen,
27601 and figuring out which is correct, and then adding the necessary
27602 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
27606 @c *******************************
27607 @node Conditional Compilation
27608 @appendix Conditional Compilation
27609 @c *******************************
27610 @cindex Conditional compilation
27613 It is often necessary to arrange for a single source program
27614 to serve multiple purposes, where it is compiled in different
27615 ways to achieve these different goals. Some examples of the
27616 need for this feature are
27619 @item Adapting a program to a different hardware environment
27620 @item Adapting a program to a different target architecture
27621 @item Turning debugging features on and off
27622 @item Arranging for a program to compile with different compilers
27626 In C, or C++, the typical approach would be to use the preprocessor
27627 that is defined as part of the language. The Ada language does not
27628 contain such a feature. This is not an oversight, but rather a very
27629 deliberate design decision, based on the experience that overuse of
27630 the preprocessing features in C and C++ can result in programs that
27631 are extremely difficult to maintain. For example, if we have ten
27632 switches that can be on or off, this means that there are a thousand
27633 separate programs, any one of which might not even be syntactically
27634 correct, and even if syntactically correct, the resulting program
27635 might not work correctly. Testing all combinations can quickly become
27638 Nevertheless, the need to tailor programs certainly exists, and in
27639 this Appendix we will discuss how this can
27640 be achieved using Ada in general, and GNAT in particular.
27643 * Use of Boolean Constants::
27644 * Debugging - A Special Case::
27645 * Conditionalizing Declarations::
27646 * Use of Alternative Implementations::
27650 @node Use of Boolean Constants
27651 @section Use of Boolean Constants
27654 In the case where the difference is simply which code
27655 sequence is executed, the cleanest solution is to use Boolean
27656 constants to control which code is executed.
27658 @smallexample @c ada
27660 FP_Initialize_Required : constant Boolean := True;
27662 if FP_Initialize_Required then
27669 Not only will the code inside the @code{if} statement not be executed if
27670 the constant Boolean is @code{False}, but it will also be completely
27671 deleted from the program.
27672 However, the code is only deleted after the @code{if} statement
27673 has been checked for syntactic and semantic correctness.
27674 (In contrast, with preprocessors the code is deleted before the
27675 compiler ever gets to see it, so it is not checked until the switch
27677 @cindex Preprocessors (contrasted with conditional compilation)
27679 Typically the Boolean constants will be in a separate package,
27682 @smallexample @c ada
27685 FP_Initialize_Required : constant Boolean := True;
27686 Reset_Available : constant Boolean := False;
27693 The @code{Config} package exists in multiple forms for the various targets,
27694 with an appropriate script selecting the version of @code{Config} needed.
27695 Then any other unit requiring conditional compilation can do a @code{with}
27696 of @code{Config} to make the constants visible.
27699 @node Debugging - A Special Case
27700 @section Debugging - A Special Case
27703 A common use of conditional code is to execute statements (for example
27704 dynamic checks, or output of intermediate results) under control of a
27705 debug switch, so that the debugging behavior can be turned on and off.
27706 This can be done using a Boolean constant to control whether the code
27709 @smallexample @c ada
27712 Put_Line ("got to the first stage!");
27720 @smallexample @c ada
27722 if Debugging and then Temperature > 999.0 then
27723 raise Temperature_Crazy;
27729 Since this is a common case, there are special features to deal with
27730 this in a convenient manner. For the case of tests, Ada 2005 has added
27731 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
27732 @cindex pragma @code{Assert}
27733 on the @code{Assert} pragma that has always been available in GNAT, so this
27734 feature may be used with GNAT even if you are not using Ada 2005 features.
27735 The use of pragma @code{Assert} is described in the
27736 @cite{GNAT Reference Manual}, but as an example, the last test could be written:
27738 @smallexample @c ada
27739 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
27745 @smallexample @c ada
27746 pragma Assert (Temperature <= 999.0);
27750 In both cases, if assertions are active and the temperature is excessive,
27751 the exception @code{Assert_Failure} will be raised, with the given string in
27752 the first case or a string indicating the location of the pragma in the second
27753 case used as the exception message.
27755 You can turn assertions on and off by using the @code{Assertion_Policy}
27757 @cindex pragma @code{Assertion_Policy}
27758 This is an Ada 2005 pragma which is implemented in all modes by
27759 GNAT, but only in the latest versions of GNAT which include Ada 2005
27760 capability. Alternatively, you can use the @option{-gnata} switch
27761 @cindex @option{-gnata} switch
27762 to enable assertions from the command line (this is recognized by all versions
27765 For the example above with the @code{Put_Line}, the GNAT-specific pragma
27766 @code{Debug} can be used:
27767 @cindex pragma @code{Debug}
27769 @smallexample @c ada
27770 pragma Debug (Put_Line ("got to the first stage!"));
27774 If debug pragmas are enabled, the argument, which must be of the form of
27775 a procedure call, is executed (in this case, @code{Put_Line} will be called).
27776 Only one call can be present, but of course a special debugging procedure
27777 containing any code you like can be included in the program and then
27778 called in a pragma @code{Debug} argument as needed.
27780 One advantage of pragma @code{Debug} over the @code{if Debugging then}
27781 construct is that pragma @code{Debug} can appear in declarative contexts,
27782 such as at the very beginning of a procedure, before local declarations have
27785 Debug pragmas are enabled using either the @option{-gnata} switch that also
27786 controls assertions, or with a separate Debug_Policy pragma.
27787 @cindex pragma @code{Debug_Policy}
27788 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
27789 in Ada 95 and Ada 83 programs as well), and is analogous to
27790 pragma @code{Assertion_Policy} to control assertions.
27792 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
27793 and thus they can appear in @file{gnat.adc} if you are not using a
27794 project file, or in the file designated to contain configuration pragmas
27796 They then apply to all subsequent compilations. In practice the use of
27797 the @option{-gnata} switch is often the most convenient method of controlling
27798 the status of these pragmas.
27800 Note that a pragma is not a statement, so in contexts where a statement
27801 sequence is required, you can't just write a pragma on its own. You have
27802 to add a @code{null} statement.
27804 @smallexample @c ada
27807 ... -- some statements
27809 pragma Assert (Num_Cases < 10);
27816 @node Conditionalizing Declarations
27817 @section Conditionalizing Declarations
27820 In some cases, it may be necessary to conditionalize declarations to meet
27821 different requirements. For example we might want a bit string whose length
27822 is set to meet some hardware message requirement.
27824 In some cases, it may be possible to do this using declare blocks controlled
27825 by conditional constants:
27827 @smallexample @c ada
27829 if Small_Machine then
27831 X : Bit_String (1 .. 10);
27837 X : Large_Bit_String (1 .. 1000);
27846 Note that in this approach, both declarations are analyzed by the
27847 compiler so this can only be used where both declarations are legal,
27848 even though one of them will not be used.
27850 Another approach is to define integer constants, e.g. @code{Bits_Per_Word}, or
27851 Boolean constants, e.g. @code{Little_Endian}, and then write declarations
27852 that are parameterized by these constants. For example
27854 @smallexample @c ada
27857 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
27863 If @code{Bits_Per_Word} is set to 32, this generates either
27865 @smallexample @c ada
27868 Field1 at 0 range 0 .. 32;
27874 for the big endian case, or
27876 @smallexample @c ada
27879 Field1 at 0 range 10 .. 32;
27885 for the little endian case. Since a powerful subset of Ada expression
27886 notation is usable for creating static constants, clever use of this
27887 feature can often solve quite difficult problems in conditionalizing
27888 compilation (note incidentally that in Ada 95, the little endian
27889 constant was introduced as @code{System.Default_Bit_Order}, so you do not
27890 need to define this one yourself).
27893 @node Use of Alternative Implementations
27894 @section Use of Alternative Implementations
27897 In some cases, none of the approaches described above are adequate. This
27898 can occur for example if the set of declarations required is radically
27899 different for two different configurations.
27901 In this situation, the official Ada way of dealing with conditionalizing
27902 such code is to write separate units for the different cases. As long as
27903 this does not result in excessive duplication of code, this can be done
27904 without creating maintenance problems. The approach is to share common
27905 code as far as possible, and then isolate the code and declarations
27906 that are different. Subunits are often a convenient method for breaking
27907 out a piece of a unit that is to be conditionalized, with separate files
27908 for different versions of the subunit for different targets, where the
27909 build script selects the right one to give to the compiler.
27910 @cindex Subunits (and conditional compilation)
27912 As an example, consider a situation where a new feature in Ada 2005
27913 allows something to be done in a really nice way. But your code must be able
27914 to compile with an Ada 95 compiler. Conceptually you want to say:
27916 @smallexample @c ada
27919 ... neat Ada 2005 code
27921 ... not quite as neat Ada 95 code
27927 where @code{Ada_2005} is a Boolean constant.
27929 But this won't work when @code{Ada_2005} is set to @code{False},
27930 since the @code{then} clause will be illegal for an Ada 95 compiler.
27931 (Recall that although such unreachable code would eventually be deleted
27932 by the compiler, it still needs to be legal. If it uses features
27933 introduced in Ada 2005, it will be illegal in Ada 95.)
27935 So instead we write
27937 @smallexample @c ada
27938 procedure Insert is separate;
27942 Then we have two files for the subunit @code{Insert}, with the two sets of
27944 If the package containing this is called @code{File_Queries}, then we might
27948 @item @file{file_queries-insert-2005.adb}
27949 @item @file{file_queries-insert-95.adb}
27953 and the build script renames the appropriate file to
27956 file_queries-insert.adb
27960 and then carries out the compilation.
27962 This can also be done with project files' naming schemes. For example:
27964 @smallexample @c project
27965 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
27969 Note also that with project files it is desirable to use a different extension
27970 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
27971 conflict may arise through another commonly used feature: to declare as part
27972 of the project a set of directories containing all the sources obeying the
27973 default naming scheme.
27975 The use of alternative units is certainly feasible in all situations,
27976 and for example the Ada part of the GNAT run-time is conditionalized
27977 based on the target architecture using this approach. As a specific example,
27978 consider the implementation of the AST feature in VMS. There is one
27986 which is the same for all architectures, and three bodies:
27990 used for all non-VMS operating systems
27991 @item s-asthan-vms-alpha.adb
27992 used for VMS on the Alpha
27993 @item s-asthan-vms-ia64.adb
27994 used for VMS on the ia64
27998 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
27999 this operating system feature is not available, and the two remaining
28000 versions interface with the corresponding versions of VMS to provide
28001 VMS-compatible AST handling. The GNAT build script knows the architecture
28002 and operating system, and automatically selects the right version,
28003 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
28005 Another style for arranging alternative implementations is through Ada's
28006 access-to-subprogram facility.
28007 In case some functionality is to be conditionally included,
28008 you can declare an access-to-procedure variable @code{Ref} that is initialized
28009 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
28011 In some library package, set @code{Ref} to @code{Proc'Access} for some
28012 procedure @code{Proc} that performs the relevant processing.
28013 The initialization only occurs if the library package is included in the
28015 The same idea can also be implemented using tagged types and dispatching
28019 @node Preprocessing
28020 @section Preprocessing
28021 @cindex Preprocessing
28024 Although it is quite possible to conditionalize code without the use of
28025 C-style preprocessing, as described earlier in this section, it is
28026 nevertheless convenient in some cases to use the C approach. Moreover,
28027 older Ada compilers have often provided some preprocessing capability,
28028 so legacy code may depend on this approach, even though it is not
28031 To accommodate such use, GNAT provides a preprocessor (modeled to a large
28032 extent on the various preprocessors that have been used
28033 with legacy code on other compilers, to enable easier transition).
28035 The preprocessor may be used in two separate modes. It can be used quite
28036 separately from the compiler, to generate a separate output source file
28037 that is then fed to the compiler as a separate step. This is the
28038 @code{gnatprep} utility, whose use is fully described in
28039 @ref{Preprocessing Using gnatprep}.
28040 @cindex @code{gnatprep}
28042 The preprocessing language allows such constructs as
28046 #if DEBUG or PRIORITY > 4 then
28047 bunch of declarations
28049 completely different bunch of declarations
28055 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
28056 defined either on the command line or in a separate file.
28058 The other way of running the preprocessor is even closer to the C style and
28059 often more convenient. In this approach the preprocessing is integrated into
28060 the compilation process. The compiler is fed the preprocessor input which
28061 includes @code{#if} lines etc, and then the compiler carries out the
28062 preprocessing internally and processes the resulting output.
28063 For more details on this approach, see @ref{Integrated Preprocessing}.
28066 @c *******************************
28067 @node Inline Assembler
28068 @appendix Inline Assembler
28069 @c *******************************
28072 If you need to write low-level software that interacts directly
28073 with the hardware, Ada provides two ways to incorporate assembly
28074 language code into your program. First, you can import and invoke
28075 external routines written in assembly language, an Ada feature fully
28076 supported by GNAT@. However, for small sections of code it may be simpler
28077 or more efficient to include assembly language statements directly
28078 in your Ada source program, using the facilities of the implementation-defined
28079 package @code{System.Machine_Code}, which incorporates the gcc
28080 Inline Assembler. The Inline Assembler approach offers a number of advantages,
28081 including the following:
28084 @item No need to use non-Ada tools
28085 @item Consistent interface over different targets
28086 @item Automatic usage of the proper calling conventions
28087 @item Access to Ada constants and variables
28088 @item Definition of intrinsic routines
28089 @item Possibility of inlining a subprogram comprising assembler code
28090 @item Code optimizer can take Inline Assembler code into account
28093 This chapter presents a series of examples to show you how to use
28094 the Inline Assembler. Although it focuses on the Intel x86,
28095 the general approach applies also to other processors.
28096 It is assumed that you are familiar with Ada
28097 and with assembly language programming.
28100 * Basic Assembler Syntax::
28101 * A Simple Example of Inline Assembler::
28102 * Output Variables in Inline Assembler::
28103 * Input Variables in Inline Assembler::
28104 * Inlining Inline Assembler Code::
28105 * Other Asm Functionality::
28108 @c ---------------------------------------------------------------------------
28109 @node Basic Assembler Syntax
28110 @section Basic Assembler Syntax
28113 The assembler used by GNAT and gcc is based not on the Intel assembly
28114 language, but rather on a language that descends from the AT&T Unix
28115 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
28116 The following table summarizes the main features of @emph{as} syntax
28117 and points out the differences from the Intel conventions.
28118 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
28119 pre-processor) documentation for further information.
28122 @item Register names
28123 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
28125 Intel: No extra punctuation; for example @code{eax}
28127 @item Immediate operand
28128 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
28130 Intel: No extra punctuation; for example @code{4}
28133 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
28135 Intel: No extra punctuation; for example @code{loc}
28137 @item Memory contents
28138 gcc / @emph{as}: No extra punctuation; for example @code{loc}
28140 Intel: Square brackets; for example @code{[loc]}
28142 @item Register contents
28143 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
28145 Intel: Square brackets; for example @code{[eax]}
28147 @item Hexadecimal numbers
28148 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
28150 Intel: Trailing ``h''; for example @code{A0h}
28153 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
28156 Intel: Implicit, deduced by assembler; for example @code{mov}
28158 @item Instruction repetition
28159 gcc / @emph{as}: Split into two lines; for example
28165 Intel: Keep on one line; for example @code{rep stosl}
28167 @item Order of operands
28168 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
28170 Intel: Destination first; for example @code{mov eax, 4}
28173 @c ---------------------------------------------------------------------------
28174 @node A Simple Example of Inline Assembler
28175 @section A Simple Example of Inline Assembler
28178 The following example will generate a single assembly language statement,
28179 @code{nop}, which does nothing. Despite its lack of run-time effect,
28180 the example will be useful in illustrating the basics of
28181 the Inline Assembler facility.
28183 @smallexample @c ada
28185 with System.Machine_Code; use System.Machine_Code;
28186 procedure Nothing is
28193 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
28194 here it takes one parameter, a @emph{template string} that must be a static
28195 expression and that will form the generated instruction.
28196 @code{Asm} may be regarded as a compile-time procedure that parses
28197 the template string and additional parameters (none here),
28198 from which it generates a sequence of assembly language instructions.
28200 The examples in this chapter will illustrate several of the forms
28201 for invoking @code{Asm}; a complete specification of the syntax
28202 is found in the @cite{GNAT Reference Manual}.
28204 Under the standard GNAT conventions, the @code{Nothing} procedure
28205 should be in a file named @file{nothing.adb}.
28206 You can build the executable in the usual way:
28210 However, the interesting aspect of this example is not its run-time behavior
28211 but rather the generated assembly code.
28212 To see this output, invoke the compiler as follows:
28214 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
28216 where the options are:
28220 compile only (no bind or link)
28222 generate assembler listing
28223 @item -fomit-frame-pointer
28224 do not set up separate stack frames
28226 do not add runtime checks
28229 This gives a human-readable assembler version of the code. The resulting
28230 file will have the same name as the Ada source file, but with a @code{.s}
28231 extension. In our example, the file @file{nothing.s} has the following
28236 .file "nothing.adb"
28238 ___gnu_compiled_ada:
28241 .globl __ada_nothing
28253 The assembly code you included is clearly indicated by
28254 the compiler, between the @code{#APP} and @code{#NO_APP}
28255 delimiters. The character before the 'APP' and 'NOAPP'
28256 can differ on different targets. For example, GNU/Linux uses '#APP' while
28257 on NT you will see '/APP'.
28259 If you make a mistake in your assembler code (such as using the
28260 wrong size modifier, or using a wrong operand for the instruction) GNAT
28261 will report this error in a temporary file, which will be deleted when
28262 the compilation is finished. Generating an assembler file will help
28263 in such cases, since you can assemble this file separately using the
28264 @emph{as} assembler that comes with gcc.
28266 Assembling the file using the command
28269 as @file{nothing.s}
28272 will give you error messages whose lines correspond to the assembler
28273 input file, so you can easily find and correct any mistakes you made.
28274 If there are no errors, @emph{as} will generate an object file
28275 @file{nothing.out}.
28277 @c ---------------------------------------------------------------------------
28278 @node Output Variables in Inline Assembler
28279 @section Output Variables in Inline Assembler
28282 The examples in this section, showing how to access the processor flags,
28283 illustrate how to specify the destination operands for assembly language
28286 @smallexample @c ada
28288 with Interfaces; use Interfaces;
28289 with Ada.Text_IO; use Ada.Text_IO;
28290 with System.Machine_Code; use System.Machine_Code;
28291 procedure Get_Flags is
28292 Flags : Unsigned_32;
28295 Asm ("pushfl" & LF & HT & -- push flags on stack
28296 "popl %%eax" & LF & HT & -- load eax with flags
28297 "movl %%eax, %0", -- store flags in variable
28298 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28299 Put_Line ("Flags register:" & Flags'Img);
28304 In order to have a nicely aligned assembly listing, we have separated
28305 multiple assembler statements in the Asm template string with linefeed
28306 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
28307 The resulting section of the assembly output file is:
28314 movl %eax, -40(%ebp)
28319 It would have been legal to write the Asm invocation as:
28322 Asm ("pushfl popl %%eax movl %%eax, %0")
28325 but in the generated assembler file, this would come out as:
28329 pushfl popl %eax movl %eax, -40(%ebp)
28333 which is not so convenient for the human reader.
28335 We use Ada comments
28336 at the end of each line to explain what the assembler instructions
28337 actually do. This is a useful convention.
28339 When writing Inline Assembler instructions, you need to precede each register
28340 and variable name with a percent sign. Since the assembler already requires
28341 a percent sign at the beginning of a register name, you need two consecutive
28342 percent signs for such names in the Asm template string, thus @code{%%eax}.
28343 In the generated assembly code, one of the percent signs will be stripped off.
28345 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
28346 variables: operands you later define using @code{Input} or @code{Output}
28347 parameters to @code{Asm}.
28348 An output variable is illustrated in
28349 the third statement in the Asm template string:
28353 The intent is to store the contents of the eax register in a variable that can
28354 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
28355 necessarily work, since the compiler might optimize by using a register
28356 to hold Flags, and the expansion of the @code{movl} instruction would not be
28357 aware of this optimization. The solution is not to store the result directly
28358 but rather to advise the compiler to choose the correct operand form;
28359 that is the purpose of the @code{%0} output variable.
28361 Information about the output variable is supplied in the @code{Outputs}
28362 parameter to @code{Asm}:
28364 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28367 The output is defined by the @code{Asm_Output} attribute of the target type;
28368 the general format is
28370 Type'Asm_Output (constraint_string, variable_name)
28373 The constraint string directs the compiler how
28374 to store/access the associated variable. In the example
28376 Unsigned_32'Asm_Output ("=m", Flags);
28378 the @code{"m"} (memory) constraint tells the compiler that the variable
28379 @code{Flags} should be stored in a memory variable, thus preventing
28380 the optimizer from keeping it in a register. In contrast,
28382 Unsigned_32'Asm_Output ("=r", Flags);
28384 uses the @code{"r"} (register) constraint, telling the compiler to
28385 store the variable in a register.
28387 If the constraint is preceded by the equal character (@strong{=}), it tells
28388 the compiler that the variable will be used to store data into it.
28390 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
28391 allowing the optimizer to choose whatever it deems best.
28393 There are a fairly large number of constraints, but the ones that are
28394 most useful (for the Intel x86 processor) are the following:
28400 global (i.e. can be stored anywhere)
28418 use one of eax, ebx, ecx or edx
28420 use one of eax, ebx, ecx, edx, esi or edi
28423 The full set of constraints is described in the gcc and @emph{as}
28424 documentation; note that it is possible to combine certain constraints
28425 in one constraint string.
28427 You specify the association of an output variable with an assembler operand
28428 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
28430 @smallexample @c ada
28432 Asm ("pushfl" & LF & HT & -- push flags on stack
28433 "popl %%eax" & LF & HT & -- load eax with flags
28434 "movl %%eax, %0", -- store flags in variable
28435 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28439 @code{%0} will be replaced in the expanded code by the appropriate operand,
28441 the compiler decided for the @code{Flags} variable.
28443 In general, you may have any number of output variables:
28446 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
28448 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
28449 of @code{Asm_Output} attributes
28453 @smallexample @c ada
28455 Asm ("movl %%eax, %0" & LF & HT &
28456 "movl %%ebx, %1" & LF & HT &
28458 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
28459 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
28460 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
28464 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
28465 in the Ada program.
28467 As a variation on the @code{Get_Flags} example, we can use the constraints
28468 string to direct the compiler to store the eax register into the @code{Flags}
28469 variable, instead of including the store instruction explicitly in the
28470 @code{Asm} template string:
28472 @smallexample @c ada
28474 with Interfaces; use Interfaces;
28475 with Ada.Text_IO; use Ada.Text_IO;
28476 with System.Machine_Code; use System.Machine_Code;
28477 procedure Get_Flags_2 is
28478 Flags : Unsigned_32;
28481 Asm ("pushfl" & LF & HT & -- push flags on stack
28482 "popl %%eax", -- save flags in eax
28483 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
28484 Put_Line ("Flags register:" & Flags'Img);
28490 The @code{"a"} constraint tells the compiler that the @code{Flags}
28491 variable will come from the eax register. Here is the resulting code:
28499 movl %eax,-40(%ebp)
28504 The compiler generated the store of eax into Flags after
28505 expanding the assembler code.
28507 Actually, there was no need to pop the flags into the eax register;
28508 more simply, we could just pop the flags directly into the program variable:
28510 @smallexample @c ada
28512 with Interfaces; use Interfaces;
28513 with Ada.Text_IO; use Ada.Text_IO;
28514 with System.Machine_Code; use System.Machine_Code;
28515 procedure Get_Flags_3 is
28516 Flags : Unsigned_32;
28519 Asm ("pushfl" & LF & HT & -- push flags on stack
28520 "pop %0", -- save flags in Flags
28521 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28522 Put_Line ("Flags register:" & Flags'Img);
28527 @c ---------------------------------------------------------------------------
28528 @node Input Variables in Inline Assembler
28529 @section Input Variables in Inline Assembler
28532 The example in this section illustrates how to specify the source operands
28533 for assembly language statements.
28534 The program simply increments its input value by 1:
28536 @smallexample @c ada
28538 with Interfaces; use Interfaces;
28539 with Ada.Text_IO; use Ada.Text_IO;
28540 with System.Machine_Code; use System.Machine_Code;
28541 procedure Increment is
28543 function Incr (Value : Unsigned_32) return Unsigned_32 is
28544 Result : Unsigned_32;
28547 Inputs => Unsigned_32'Asm_Input ("a", Value),
28548 Outputs => Unsigned_32'Asm_Output ("=a", Result));
28552 Value : Unsigned_32;
28556 Put_Line ("Value before is" & Value'Img);
28557 Value := Incr (Value);
28558 Put_Line ("Value after is" & Value'Img);
28563 The @code{Outputs} parameter to @code{Asm} specifies
28564 that the result will be in the eax register and that it is to be stored
28565 in the @code{Result} variable.
28567 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
28568 but with an @code{Asm_Input} attribute.
28569 The @code{"="} constraint, indicating an output value, is not present.
28571 You can have multiple input variables, in the same way that you can have more
28572 than one output variable.
28574 The parameter count (%0, %1) etc, now starts at the first input
28575 statement, and continues with the output statements.
28576 When both parameters use the same variable, the
28577 compiler will treat them as the same %n operand, which is the case here.
28579 Just as the @code{Outputs} parameter causes the register to be stored into the
28580 target variable after execution of the assembler statements, so does the
28581 @code{Inputs} parameter cause its variable to be loaded into the register
28582 before execution of the assembler statements.
28584 Thus the effect of the @code{Asm} invocation is:
28586 @item load the 32-bit value of @code{Value} into eax
28587 @item execute the @code{incl %eax} instruction
28588 @item store the contents of eax into the @code{Result} variable
28591 The resulting assembler file (with @option{-O2} optimization) contains:
28594 _increment__incr.1:
28607 @c ---------------------------------------------------------------------------
28608 @node Inlining Inline Assembler Code
28609 @section Inlining Inline Assembler Code
28612 For a short subprogram such as the @code{Incr} function in the previous
28613 section, the overhead of the call and return (creating / deleting the stack
28614 frame) can be significant, compared to the amount of code in the subprogram
28615 body. A solution is to apply Ada's @code{Inline} pragma to the subprogram,
28616 which directs the compiler to expand invocations of the subprogram at the
28617 point(s) of call, instead of setting up a stack frame for out-of-line calls.
28618 Here is the resulting program:
28620 @smallexample @c ada
28622 with Interfaces; use Interfaces;
28623 with Ada.Text_IO; use Ada.Text_IO;
28624 with System.Machine_Code; use System.Machine_Code;
28625 procedure Increment_2 is
28627 function Incr (Value : Unsigned_32) return Unsigned_32 is
28628 Result : Unsigned_32;
28631 Inputs => Unsigned_32'Asm_Input ("a", Value),
28632 Outputs => Unsigned_32'Asm_Output ("=a", Result));
28635 pragma Inline (Increment);
28637 Value : Unsigned_32;
28641 Put_Line ("Value before is" & Value'Img);
28642 Value := Increment (Value);
28643 Put_Line ("Value after is" & Value'Img);
28648 Compile the program with both optimization (@option{-O2}) and inlining
28649 enabled (@option{-gnatpn} instead of @option{-gnatp}).
28651 The @code{Incr} function is still compiled as usual, but at the
28652 point in @code{Increment} where our function used to be called:
28657 call _increment__incr.1
28662 the code for the function body directly appears:
28675 thus saving the overhead of stack frame setup and an out-of-line call.
28677 @c ---------------------------------------------------------------------------
28678 @node Other Asm Functionality
28679 @section Other @code{Asm} Functionality
28682 This section describes two important parameters to the @code{Asm}
28683 procedure: @code{Clobber}, which identifies register usage;
28684 and @code{Volatile}, which inhibits unwanted optimizations.
28687 * The Clobber Parameter::
28688 * The Volatile Parameter::
28691 @c ---------------------------------------------------------------------------
28692 @node The Clobber Parameter
28693 @subsection The @code{Clobber} Parameter
28696 One of the dangers of intermixing assembly language and a compiled language
28697 such as Ada is that the compiler needs to be aware of which registers are
28698 being used by the assembly code. In some cases, such as the earlier examples,
28699 the constraint string is sufficient to indicate register usage (e.g.,
28701 the eax register). But more generally, the compiler needs an explicit
28702 identification of the registers that are used by the Inline Assembly
28705 Using a register that the compiler doesn't know about
28706 could be a side effect of an instruction (like @code{mull}
28707 storing its result in both eax and edx).
28708 It can also arise from explicit register usage in your
28709 assembly code; for example:
28712 Asm ("movl %0, %%ebx" & LF & HT &
28714 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
28715 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
28719 where the compiler (since it does not analyze the @code{Asm} template string)
28720 does not know you are using the ebx register.
28722 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
28723 to identify the registers that will be used by your assembly code:
28727 Asm ("movl %0, %%ebx" & LF & HT &
28729 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
28730 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28735 The Clobber parameter is a static string expression specifying the
28736 register(s) you are using. Note that register names are @emph{not} prefixed
28737 by a percent sign. Also, if more than one register is used then their names
28738 are separated by commas; e.g., @code{"eax, ebx"}
28740 The @code{Clobber} parameter has several additional uses:
28742 @item Use ``register'' name @code{cc} to indicate that flags might have changed
28743 @item Use ``register'' name @code{memory} if you changed a memory location
28746 @c ---------------------------------------------------------------------------
28747 @node The Volatile Parameter
28748 @subsection The @code{Volatile} Parameter
28749 @cindex Volatile parameter
28752 Compiler optimizations in the presence of Inline Assembler may sometimes have
28753 unwanted effects. For example, when an @code{Asm} invocation with an input
28754 variable is inside a loop, the compiler might move the loading of the input
28755 variable outside the loop, regarding it as a one-time initialization.
28757 If this effect is not desired, you can disable such optimizations by setting
28758 the @code{Volatile} parameter to @code{True}; for example:
28760 @smallexample @c ada
28762 Asm ("movl %0, %%ebx" & LF & HT &
28764 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
28765 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28771 By default, @code{Volatile} is set to @code{False} unless there is no
28772 @code{Outputs} parameter.
28774 Although setting @code{Volatile} to @code{True} prevents unwanted
28775 optimizations, it will also disable other optimizations that might be
28776 important for efficiency. In general, you should set @code{Volatile}
28777 to @code{True} only if the compiler's optimizations have created
28779 @c END OF INLINE ASSEMBLER CHAPTER
28780 @c ===============================
28782 @c ***********************************
28783 @c * Compatibility and Porting Guide *
28784 @c ***********************************
28785 @node Compatibility and Porting Guide
28786 @appendix Compatibility and Porting Guide
28789 This chapter describes the compatibility issues that may arise between
28790 GNAT and other Ada compilation systems (including those for Ada 83),
28791 and shows how GNAT can expedite porting
28792 applications developed in other Ada environments.
28795 * Compatibility with Ada 83::
28796 * Compatibility between Ada 95 and Ada 2005::
28797 * Implementation-dependent characteristics::
28798 * Compatibility with Other Ada Systems::
28799 * Representation Clauses::
28801 @c Brief section is only in non-VMS version
28802 @c Full chapter is in VMS version
28803 * Compatibility with HP Ada 83::
28806 * Transitioning to 64-Bit GNAT for OpenVMS::
28810 @node Compatibility with Ada 83
28811 @section Compatibility with Ada 83
28812 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
28815 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83. In
28816 particular, the design intention was that the difficulties associated
28817 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
28818 that occur when moving from one Ada 83 system to another.
28820 However, there are a number of points at which there are minor
28821 incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains
28822 full details of these issues,
28823 and should be consulted for a complete treatment.
28825 following subsections treat the most likely issues to be encountered.
28828 * Legal Ada 83 programs that are illegal in Ada 95::
28829 * More deterministic semantics::
28830 * Changed semantics::
28831 * Other language compatibility issues::
28834 @node Legal Ada 83 programs that are illegal in Ada 95
28835 @subsection Legal Ada 83 programs that are illegal in Ada 95
28837 Some legal Ada 83 programs are illegal (i.e. they will fail to compile) in
28838 Ada 95 and thus also in Ada 2005:
28841 @item Character literals
28842 Some uses of character literals are ambiguous. Since Ada 95 has introduced
28843 @code{Wide_Character} as a new predefined character type, some uses of
28844 character literals that were legal in Ada 83 are illegal in Ada 95.
28846 @smallexample @c ada
28847 for Char in 'A' .. 'Z' loop ... end loop;
28851 The problem is that @code{'A'} and @code{'Z'} could be from either
28852 @code{Character} or @code{Wide_Character}. The simplest correction
28853 is to make the type explicit; e.g.:
28854 @smallexample @c ada
28855 for Char in Character range 'A' .. 'Z' loop ... end loop;
28858 @item New reserved words
28859 The identifiers @code{abstract}, @code{aliased}, @code{protected},
28860 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
28861 Existing Ada 83 code using any of these identifiers must be edited to
28862 use some alternative name.
28864 @item Freezing rules
28865 The rules in Ada 95 are slightly different with regard to the point at
28866 which entities are frozen, and representation pragmas and clauses are
28867 not permitted past the freeze point. This shows up most typically in
28868 the form of an error message complaining that a representation item
28869 appears too late, and the appropriate corrective action is to move
28870 the item nearer to the declaration of the entity to which it refers.
28872 A particular case is that representation pragmas
28875 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
28877 cannot be applied to a subprogram body. If necessary, a separate subprogram
28878 declaration must be introduced to which the pragma can be applied.
28880 @item Optional bodies for library packages
28881 In Ada 83, a package that did not require a package body was nevertheless
28882 allowed to have one. This lead to certain surprises in compiling large
28883 systems (situations in which the body could be unexpectedly ignored by the
28884 binder). In Ada 95, if a package does not require a body then it is not
28885 permitted to have a body. To fix this problem, simply remove a redundant
28886 body if it is empty, or, if it is non-empty, introduce a dummy declaration
28887 into the spec that makes the body required. One approach is to add a private
28888 part to the package declaration (if necessary), and define a parameterless
28889 procedure called @code{Requires_Body}, which must then be given a dummy
28890 procedure body in the package body, which then becomes required.
28891 Another approach (assuming that this does not introduce elaboration
28892 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
28893 since one effect of this pragma is to require the presence of a package body.
28895 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
28896 In Ada 95, the exception @code{Numeric_Error} is a renaming of
28897 @code{Constraint_Error}.
28898 This means that it is illegal to have separate exception handlers for
28899 the two exceptions. The fix is simply to remove the handler for the
28900 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
28901 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
28903 @item Indefinite subtypes in generics
28904 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
28905 as the actual for a generic formal private type, but then the instantiation
28906 would be illegal if there were any instances of declarations of variables
28907 of this type in the generic body. In Ada 95, to avoid this clear violation
28908 of the methodological principle known as the ``contract model'',
28909 the generic declaration explicitly indicates whether
28910 or not such instantiations are permitted. If a generic formal parameter
28911 has explicit unknown discriminants, indicated by using @code{(<>)} after the
28912 type name, then it can be instantiated with indefinite types, but no
28913 stand-alone variables can be declared of this type. Any attempt to declare
28914 such a variable will result in an illegality at the time the generic is
28915 declared. If the @code{(<>)} notation is not used, then it is illegal
28916 to instantiate the generic with an indefinite type.
28917 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
28918 It will show up as a compile time error, and
28919 the fix is usually simply to add the @code{(<>)} to the generic declaration.
28922 @node More deterministic semantics
28923 @subsection More deterministic semantics
28927 Conversions from real types to integer types round away from 0. In Ada 83
28928 the conversion Integer(2.5) could deliver either 2 or 3 as its value. This
28929 implementation freedom was intended to support unbiased rounding in
28930 statistical applications, but in practice it interfered with portability.
28931 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
28932 is required. Numeric code may be affected by this change in semantics.
28933 Note, though, that this issue is no worse than already existed in Ada 83
28934 when porting code from one vendor to another.
28937 The Real-Time Annex introduces a set of policies that define the behavior of
28938 features that were implementation dependent in Ada 83, such as the order in
28939 which open select branches are executed.
28942 @node Changed semantics
28943 @subsection Changed semantics
28946 The worst kind of incompatibility is one where a program that is legal in
28947 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
28948 possible in Ada 83. Fortunately this is extremely rare, but the one
28949 situation that you should be alert to is the change in the predefined type
28950 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
28953 @item Range of type @code{Character}
28954 The range of @code{Standard.Character} is now the full 256 characters
28955 of Latin-1, whereas in most Ada 83 implementations it was restricted
28956 to 128 characters. Although some of the effects of
28957 this change will be manifest in compile-time rejection of legal
28958 Ada 83 programs it is possible for a working Ada 83 program to have
28959 a different effect in Ada 95, one that was not permitted in Ada 83.
28960 As an example, the expression
28961 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
28962 delivers @code{255} as its value.
28963 In general, you should look at the logic of any
28964 character-processing Ada 83 program and see whether it needs to be adapted
28965 to work correctly with Latin-1. Note that the predefined Ada 95 API has a
28966 character handling package that may be relevant if code needs to be adapted
28967 to account for the additional Latin-1 elements.
28968 The desirable fix is to
28969 modify the program to accommodate the full character set, but in some cases
28970 it may be convenient to define a subtype or derived type of Character that
28971 covers only the restricted range.
28975 @node Other language compatibility issues
28976 @subsection Other language compatibility issues
28979 @item @option{-gnat83} switch
28980 All implementations of GNAT provide a switch that causes GNAT to operate
28981 in Ada 83 mode. In this mode, some but not all compatibility problems
28982 of the type described above are handled automatically. For example, the
28983 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
28984 as identifiers as in Ada 83.
28986 in practice, it is usually advisable to make the necessary modifications
28987 to the program to remove the need for using this switch.
28988 See @ref{Compiling Different Versions of Ada}.
28990 @item Support for removed Ada 83 pragmas and attributes
28991 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
28992 generally because they were replaced by other mechanisms. Ada 95 and Ada 2005
28993 compilers are allowed, but not required, to implement these missing
28994 elements. In contrast with some other compilers, GNAT implements all
28995 such pragmas and attributes, eliminating this compatibility concern. These
28996 include @code{pragma Interface} and the floating point type attributes
28997 (@code{Emax}, @code{Mantissa}, etc.), among other items.
29001 @node Compatibility between Ada 95 and Ada 2005
29002 @section Compatibility between Ada 95 and Ada 2005
29003 @cindex Compatibility between Ada 95 and Ada 2005
29006 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
29007 a number of incompatibilities. Several are enumerated below;
29008 for a complete description please see the
29009 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
29010 @cite{Rationale for Ada 2005}.
29013 @item New reserved words.
29014 The words @code{interface}, @code{overriding} and @code{synchronized} are
29015 reserved in Ada 2005.
29016 A pre-Ada 2005 program that uses any of these as an identifier will be
29019 @item New declarations in predefined packages.
29020 A number of packages in the predefined environment contain new declarations:
29021 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
29022 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
29023 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
29024 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
29025 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
29026 If an Ada 95 program does a @code{with} and @code{use} of any of these
29027 packages, the new declarations may cause name clashes.
29029 @item Access parameters.
29030 A nondispatching subprogram with an access parameter cannot be renamed
29031 as a dispatching operation. This was permitted in Ada 95.
29033 @item Access types, discriminants, and constraints.
29034 Rule changes in this area have led to some incompatibilities; for example,
29035 constrained subtypes of some access types are not permitted in Ada 2005.
29037 @item Aggregates for limited types.
29038 The allowance of aggregates for limited types in Ada 2005 raises the
29039 possibility of ambiguities in legal Ada 95 programs, since additional types
29040 now need to be considered in expression resolution.
29042 @item Fixed-point multiplication and division.
29043 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
29044 were legal in Ada 95 and invoked the predefined versions of these operations,
29046 The ambiguity may be resolved either by applying a type conversion to the
29047 expression, or by explicitly invoking the operation from package
29050 @item Return-by-reference types.
29051 The Ada 95 return-by-reference mechanism has been removed. Instead, the user
29052 can declare a function returning a value from an anonymous access type.
29056 @node Implementation-dependent characteristics
29057 @section Implementation-dependent characteristics
29059 Although the Ada language defines the semantics of each construct as
29060 precisely as practical, in some situations (for example for reasons of
29061 efficiency, or where the effect is heavily dependent on the host or target
29062 platform) the implementation is allowed some freedom. In porting Ada 83
29063 code to GNAT, you need to be aware of whether / how the existing code
29064 exercised such implementation dependencies. Such characteristics fall into
29065 several categories, and GNAT offers specific support in assisting the
29066 transition from certain Ada 83 compilers.
29069 * Implementation-defined pragmas::
29070 * Implementation-defined attributes::
29072 * Elaboration order::
29073 * Target-specific aspects::
29076 @node Implementation-defined pragmas
29077 @subsection Implementation-defined pragmas
29080 Ada compilers are allowed to supplement the language-defined pragmas, and
29081 these are a potential source of non-portability. All GNAT-defined pragmas
29082 are described in the GNAT Reference Manual, and these include several that
29083 are specifically intended to correspond to other vendors' Ada 83 pragmas.
29084 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
29086 compatibility with HP Ada 83, GNAT supplies the pragmas
29087 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
29088 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
29089 and @code{Volatile}.
29090 Other relevant pragmas include @code{External} and @code{Link_With}.
29091 Some vendor-specific
29092 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
29094 avoiding compiler rejection of units that contain such pragmas; they are not
29095 relevant in a GNAT context and hence are not otherwise implemented.
29097 @node Implementation-defined attributes
29098 @subsection Implementation-defined attributes
29100 Analogous to pragmas, the set of attributes may be extended by an
29101 implementation. All GNAT-defined attributes are described in the
29102 @cite{GNAT Reference Manual}, and these include several that are specifically
29104 to correspond to other vendors' Ada 83 attributes. For migrating from VADS,
29105 the attribute @code{VADS_Size} may be useful. For compatibility with HP
29106 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
29110 @subsection Libraries
29112 Vendors may supply libraries to supplement the standard Ada API. If Ada 83
29113 code uses vendor-specific libraries then there are several ways to manage
29114 this in Ada 95 or Ada 2005:
29117 If the source code for the libraries (specifications and bodies) are
29118 available, then the libraries can be migrated in the same way as the
29121 If the source code for the specifications but not the bodies are
29122 available, then you can reimplement the bodies.
29124 Some features introduced by Ada 95 obviate the need for library support. For
29125 example most Ada 83 vendors supplied a package for unsigned integers. The
29126 Ada 95 modular type feature is the preferred way to handle this need, so
29127 instead of migrating or reimplementing the unsigned integer package it may
29128 be preferable to retrofit the application using modular types.
29131 @node Elaboration order
29132 @subsection Elaboration order
29134 The implementation can choose any elaboration order consistent with the unit
29135 dependency relationship. This freedom means that some orders can result in
29136 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
29137 to invoke a subprogram its body has been elaborated, or to instantiate a
29138 generic before the generic body has been elaborated. By default GNAT
29139 attempts to choose a safe order (one that will not encounter access before
29140 elaboration problems) by implicitly inserting @code{Elaborate} or
29141 @code{Elaborate_All} pragmas where
29142 needed. However, this can lead to the creation of elaboration circularities
29143 and a resulting rejection of the program by gnatbind. This issue is
29144 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
29145 In brief, there are several
29146 ways to deal with this situation:
29150 Modify the program to eliminate the circularities, e.g. by moving
29151 elaboration-time code into explicitly-invoked procedures
29153 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
29154 @code{Elaborate} pragmas, and then inhibit the generation of implicit
29155 @code{Elaborate_All}
29156 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
29157 (by selectively suppressing elaboration checks via pragma
29158 @code{Suppress(Elaboration_Check)} when it is safe to do so).
29161 @node Target-specific aspects
29162 @subsection Target-specific aspects
29164 Low-level applications need to deal with machine addresses, data
29165 representations, interfacing with assembler code, and similar issues. If
29166 such an Ada 83 application is being ported to different target hardware (for
29167 example where the byte endianness has changed) then you will need to
29168 carefully examine the program logic; the porting effort will heavily depend
29169 on the robustness of the original design. Moreover, Ada 95 (and thus
29170 Ada 2005) are sometimes
29171 incompatible with typical Ada 83 compiler practices regarding implicit
29172 packing, the meaning of the Size attribute, and the size of access values.
29173 GNAT's approach to these issues is described in @ref{Representation Clauses}.
29175 @node Compatibility with Other Ada Systems
29176 @section Compatibility with Other Ada Systems
29179 If programs avoid the use of implementation dependent and
29180 implementation defined features, as documented in the @cite{Ada
29181 Reference Manual}, there should be a high degree of portability between
29182 GNAT and other Ada systems. The following are specific items which
29183 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
29184 compilers, but do not affect porting code to GNAT@.
29185 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
29186 the following issues may or may not arise for Ada 2005 programs
29187 when other compilers appear.)
29190 @item Ada 83 Pragmas and Attributes
29191 Ada 95 compilers are allowed, but not required, to implement the missing
29192 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
29193 GNAT implements all such pragmas and attributes, eliminating this as
29194 a compatibility concern, but some other Ada 95 compilers reject these
29195 pragmas and attributes.
29197 @item Specialized Needs Annexes
29198 GNAT implements the full set of special needs annexes. At the
29199 current time, it is the only Ada 95 compiler to do so. This means that
29200 programs making use of these features may not be portable to other Ada
29201 95 compilation systems.
29203 @item Representation Clauses
29204 Some other Ada 95 compilers implement only the minimal set of
29205 representation clauses required by the Ada 95 reference manual. GNAT goes
29206 far beyond this minimal set, as described in the next section.
29209 @node Representation Clauses
29210 @section Representation Clauses
29213 The Ada 83 reference manual was quite vague in describing both the minimal
29214 required implementation of representation clauses, and also their precise
29215 effects. Ada 95 (and thus also Ada 2005) are much more explicit, but the
29216 minimal set of capabilities required is still quite limited.
29218 GNAT implements the full required set of capabilities in
29219 Ada 95 and Ada 2005, but also goes much further, and in particular
29220 an effort has been made to be compatible with existing Ada 83 usage to the
29221 greatest extent possible.
29223 A few cases exist in which Ada 83 compiler behavior is incompatible with
29224 the requirements in Ada 95 (and thus also Ada 2005). These are instances of
29225 intentional or accidental dependence on specific implementation dependent
29226 characteristics of these Ada 83 compilers. The following is a list of
29227 the cases most likely to arise in existing Ada 83 code.
29230 @item Implicit Packing
29231 Some Ada 83 compilers allowed a Size specification to cause implicit
29232 packing of an array or record. This could cause expensive implicit
29233 conversions for change of representation in the presence of derived
29234 types, and the Ada design intends to avoid this possibility.
29235 Subsequent AI's were issued to make it clear that such implicit
29236 change of representation in response to a Size clause is inadvisable,
29237 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
29238 Reference Manuals as implementation advice that is followed by GNAT@.
29239 The problem will show up as an error
29240 message rejecting the size clause. The fix is simply to provide
29241 the explicit pragma @code{Pack}, or for more fine tuned control, provide
29242 a Component_Size clause.
29244 @item Meaning of Size Attribute
29245 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
29246 the minimal number of bits required to hold values of the type. For example,
29247 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
29248 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and
29249 some 32 in this situation. This problem will usually show up as a compile
29250 time error, but not always. It is a good idea to check all uses of the
29251 'Size attribute when porting Ada 83 code. The GNAT specific attribute
29252 Object_Size can provide a useful way of duplicating the behavior of
29253 some Ada 83 compiler systems.
29255 @item Size of Access Types
29256 A common assumption in Ada 83 code is that an access type is in fact a pointer,
29257 and that therefore it will be the same size as a System.Address value. This
29258 assumption is true for GNAT in most cases with one exception. For the case of
29259 a pointer to an unconstrained array type (where the bounds may vary from one
29260 value of the access type to another), the default is to use a ``fat pointer'',
29261 which is represented as two separate pointers, one to the bounds, and one to
29262 the array. This representation has a number of advantages, including improved
29263 efficiency. However, it may cause some difficulties in porting existing Ada 83
29264 code which makes the assumption that, for example, pointers fit in 32 bits on
29265 a machine with 32-bit addressing.
29267 To get around this problem, GNAT also permits the use of ``thin pointers'' for
29268 access types in this case (where the designated type is an unconstrained array
29269 type). These thin pointers are indeed the same size as a System.Address value.
29270 To specify a thin pointer, use a size clause for the type, for example:
29272 @smallexample @c ada
29273 type X is access all String;
29274 for X'Size use Standard'Address_Size;
29278 which will cause the type X to be represented using a single pointer.
29279 When using this representation, the bounds are right behind the array.
29280 This representation is slightly less efficient, and does not allow quite
29281 such flexibility in the use of foreign pointers or in using the
29282 Unrestricted_Access attribute to create pointers to non-aliased objects.
29283 But for any standard portable use of the access type it will work in
29284 a functionally correct manner and allow porting of existing code.
29285 Note that another way of forcing a thin pointer representation
29286 is to use a component size clause for the element size in an array,
29287 or a record representation clause for an access field in a record.
29291 @c This brief section is only in the non-VMS version
29292 @c The complete chapter on HP Ada is in the VMS version
29293 @node Compatibility with HP Ada 83
29294 @section Compatibility with HP Ada 83
29297 The VMS version of GNAT fully implements all the pragmas and attributes
29298 provided by HP Ada 83, as well as providing the standard HP Ada 83
29299 libraries, including Starlet. In addition, data layouts and parameter
29300 passing conventions are highly compatible. This means that porting
29301 existing HP Ada 83 code to GNAT in VMS systems should be easier than
29302 most other porting efforts. The following are some of the most
29303 significant differences between GNAT and HP Ada 83.
29306 @item Default floating-point representation
29307 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
29308 it is VMS format. GNAT does implement the necessary pragmas
29309 (Long_Float, Float_Representation) for changing this default.
29312 The package System in GNAT exactly corresponds to the definition in the
29313 Ada 95 reference manual, which means that it excludes many of the
29314 HP Ada 83 extensions. However, a separate package Aux_DEC is provided
29315 that contains the additional definitions, and a special pragma,
29316 Extend_System allows this package to be treated transparently as an
29317 extension of package System.
29320 The definitions provided by Aux_DEC are exactly compatible with those
29321 in the HP Ada 83 version of System, with one exception.
29322 HP Ada provides the following declarations:
29324 @smallexample @c ada
29325 TO_ADDRESS (INTEGER)
29326 TO_ADDRESS (UNSIGNED_LONGWORD)
29327 TO_ADDRESS (@i{universal_integer})
29331 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
29332 an extension to Ada 83 not strictly compatible with the reference manual.
29333 In GNAT, we are constrained to be exactly compatible with the standard,
29334 and this means we cannot provide this capability. In HP Ada 83, the
29335 point of this definition is to deal with a call like:
29337 @smallexample @c ada
29338 TO_ADDRESS (16#12777#);
29342 Normally, according to the Ada 83 standard, one would expect this to be
29343 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
29344 of TO_ADDRESS@. However, in HP Ada 83, there is no ambiguity, since the
29345 definition using @i{universal_integer} takes precedence.
29347 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
29348 is not possible to be 100% compatible. Since there are many programs using
29349 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
29350 to change the name of the function in the UNSIGNED_LONGWORD case, so the
29351 declarations provided in the GNAT version of AUX_Dec are:
29353 @smallexample @c ada
29354 function To_Address (X : Integer) return Address;
29355 pragma Pure_Function (To_Address);
29357 function To_Address_Long (X : Unsigned_Longword)
29359 pragma Pure_Function (To_Address_Long);
29363 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
29364 change the name to TO_ADDRESS_LONG@.
29366 @item Task_Id values
29367 The Task_Id values assigned will be different in the two systems, and GNAT
29368 does not provide a specified value for the Task_Id of the environment task,
29369 which in GNAT is treated like any other declared task.
29373 For full details on these and other less significant compatibility issues,
29374 see appendix E of the HP publication entitled @cite{HP Ada, Technical
29375 Overview and Comparison on HP Platforms}.
29377 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
29378 attributes are recognized, although only a subset of them can sensibly
29379 be implemented. The description of pragmas in the
29380 @cite{GNAT Reference Manual}
29381 indicates whether or not they are applicable to non-VMS systems.
29385 @node Transitioning to 64-Bit GNAT for OpenVMS
29386 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
29389 This section is meant to assist users of pre-2006 @value{EDITION}
29390 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
29391 the version of the GNAT technology supplied in 2006 and later for
29392 OpenVMS on both Alpha and I64.
29395 * Introduction to transitioning::
29396 * Migration of 32 bit code::
29397 * Taking advantage of 64 bit addressing::
29398 * Technical details::
29401 @node Introduction to transitioning
29402 @subsection Introduction
29405 64-bit @value{EDITION} for Open VMS has been designed to meet
29410 Providing a full conforming implementation of Ada 95 and Ada 2005
29413 Allowing maximum backward compatibility, thus easing migration of existing
29417 Supplying a path for exploiting the full 64-bit address range
29421 Ada's strong typing semantics has made it
29422 impractical to have different 32-bit and 64-bit modes. As soon as
29423 one object could possibly be outside the 32-bit address space, this
29424 would make it necessary for the @code{System.Address} type to be 64 bits.
29425 In particular, this would cause inconsistencies if 32-bit code is
29426 called from 64-bit code that raises an exception.
29428 This issue has been resolved by always using 64-bit addressing
29429 at the system level, but allowing for automatic conversions between
29430 32-bit and 64-bit addresses where required. Thus users who
29431 do not currently require 64-bit addressing capabilities, can
29432 recompile their code with only minimal changes (and indeed
29433 if the code is written in portable Ada, with no assumptions about
29434 the size of the @code{Address} type, then no changes at all are necessary).
29436 this approach provides a simple, gradual upgrade path to future
29437 use of larger memories than available for 32-bit systems.
29438 Also, newly written applications or libraries will by default
29439 be fully compatible with future systems exploiting 64-bit
29440 addressing capabilities.
29442 @ref{Migration of 32 bit code}, will focus on porting applications
29443 that do not require more than 2 GB of
29444 addressable memory. This code will be referred to as
29445 @emph{32-bit code}.
29446 For applications intending to exploit the full 64-bit address space,
29447 @ref{Taking advantage of 64 bit addressing},
29448 will consider further changes that may be required.
29449 Such code will be referred to below as @emph{64-bit code}.
29451 @node Migration of 32 bit code
29452 @subsection Migration of 32-bit code
29457 * Unchecked conversions::
29458 * Predefined constants::
29459 * Interfacing with C::
29460 * Experience with source compatibility::
29463 @node Address types
29464 @subsubsection Address types
29467 To solve the problem of mixing 64-bit and 32-bit addressing,
29468 while maintaining maximum backward compatibility, the following
29469 approach has been taken:
29473 @code{System.Address} always has a size of 64 bits
29476 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
29480 Since @code{System.Short_Address} is a subtype of @code{System.Address},
29481 a @code{Short_Address}
29482 may be used where an @code{Address} is required, and vice versa, without
29483 needing explicit type conversions.
29484 By virtue of the Open VMS parameter passing conventions,
29486 and exported subprograms that have 32-bit address parameters are
29487 compatible with those that have 64-bit address parameters.
29488 (See @ref{Making code 64 bit clean} for details.)
29490 The areas that may need attention are those where record types have
29491 been defined that contain components of the type @code{System.Address}, and
29492 where objects of this type are passed to code expecting a record layout with
29495 Different compilers on different platforms cannot be
29496 expected to represent the same type in the same way,
29497 since alignment constraints
29498 and other system-dependent properties affect the compiler's decision.
29499 For that reason, Ada code
29500 generally uses representation clauses to specify the expected
29501 layout where required.
29503 If such a representation clause uses 32 bits for a component having
29504 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
29505 will detect that error and produce a specific diagnostic message.
29506 The developer should then determine whether the representation
29507 should be 64 bits or not and make either of two changes:
29508 change the size to 64 bits and leave the type as @code{System.Address}, or
29509 leave the size as 32 bits and change the type to @code{System.Short_Address}.
29510 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
29511 required in any code setting or accessing the field; the compiler will
29512 automatically perform any needed conversions between address
29516 @subsubsection Access types
29519 By default, objects designated by access values are always
29520 allocated in the 32-bit
29521 address space. Thus legacy code will never contain
29522 any objects that are not addressable with 32-bit addresses, and
29523 the compiler will never raise exceptions as result of mixing
29524 32-bit and 64-bit addresses.
29526 However, the access values themselves are represented in 64 bits, for optimum
29527 performance and future compatibility with 64-bit code. As was
29528 the case with @code{System.Address}, the compiler will give an error message
29529 if an object or record component has a representation clause that
29530 requires the access value to fit in 32 bits. In such a situation,
29531 an explicit size clause for the access type, specifying 32 bits,
29532 will have the desired effect.
29534 General access types (declared with @code{access all}) can never be
29535 32 bits, as values of such types must be able to refer to any object
29536 of the designated type,
29537 including objects residing outside the 32-bit address range.
29538 Existing Ada 83 code will not contain such type definitions,
29539 however, since general access types were introduced in Ada 95.
29541 @node Unchecked conversions
29542 @subsubsection Unchecked conversions
29545 In the case of an @code{Unchecked_Conversion} where the source type is a
29546 64-bit access type or the type @code{System.Address}, and the target
29547 type is a 32-bit type, the compiler will generate a warning.
29548 Even though the generated code will still perform the required
29549 conversions, it is highly recommended in these cases to use
29550 respectively a 32-bit access type or @code{System.Short_Address}
29551 as the source type.
29553 @node Predefined constants
29554 @subsubsection Predefined constants
29557 The following table shows the correspondence between pre-2006 versions of
29558 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
29561 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
29562 @item @b{Constant} @tab @b{Old} @tab @b{New}
29563 @item @code{System.Word_Size} @tab 32 @tab 64
29564 @item @code{System.Memory_Size} @tab 2**32 @tab 2**64
29565 @item @code{System.Short_Memory_Size} @tab 2**32 @tab 2**32
29566 @item @code{System.Address_Size} @tab 32 @tab 64
29570 If you need to refer to the specific
29571 memory size of a 32-bit implementation, instead of the
29572 actual memory size, use @code{System.Short_Memory_Size}
29573 rather than @code{System.Memory_Size}.
29574 Similarly, references to @code{System.Address_Size} may need
29575 to be replaced by @code{System.Short_Address'Size}.
29576 The program @command{gnatfind} may be useful for locating
29577 references to the above constants, so that you can verify that they
29580 @node Interfacing with C
29581 @subsubsection Interfacing with C
29584 In order to minimize the impact of the transition to 64-bit addresses on
29585 legacy programs, some fundamental types in the @code{Interfaces.C}
29586 package hierarchy continue to be represented in 32 bits.
29587 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
29588 This eases integration with the default HP C layout choices, for example
29589 as found in the system routines in @code{DECC$SHR.EXE}.
29590 Because of this implementation choice, the type fully compatible with
29591 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
29592 Depending on the context the compiler will issue a
29593 warning or an error when type @code{Address} is used, alerting the user to a
29594 potential problem. Otherwise 32-bit programs that use
29595 @code{Interfaces.C} should normally not require code modifications
29597 The other issue arising with C interfacing concerns pragma @code{Convention}.
29598 For VMS 64-bit systems, there is an issue of the appropriate default size
29599 of C convention pointers in the absence of an explicit size clause. The HP
29600 C compiler can choose either 32 or 64 bits depending on compiler options.
29601 GNAT chooses 32-bits rather than 64-bits in the default case where no size
29602 clause is given. This proves a better choice for porting 32-bit legacy
29603 applications. In order to have a 64-bit representation, it is necessary to
29604 specify a size representation clause. For example:
29606 @smallexample @c ada
29607 type int_star is access Interfaces.C.int;
29608 pragma Convention(C, int_star);
29609 for int_star'Size use 64; -- Necessary to get 64 and not 32 bits
29612 @node Experience with source compatibility
29613 @subsubsection Experience with source compatibility
29616 The Security Server and STARLET on I64 provide an interesting ``test case''
29617 for source compatibility issues, since it is in such system code
29618 where assumptions about @code{Address} size might be expected to occur.
29619 Indeed, there were a small number of occasions in the Security Server
29620 file @file{jibdef.ads}
29621 where a representation clause for a record type specified
29622 32 bits for a component of type @code{Address}.
29623 All of these errors were detected by the compiler.
29624 The repair was obvious and immediate; to simply replace @code{Address} by
29625 @code{Short_Address}.
29627 In the case of STARLET, there were several record types that should
29628 have had representation clauses but did not. In these record types
29629 there was an implicit assumption that an @code{Address} value occupied
29631 These compiled without error, but their usage resulted in run-time error
29632 returns from STARLET system calls.
29633 Future GNAT technology enhancements may include a tool that detects and flags
29634 these sorts of potential source code porting problems.
29636 @c ****************************************
29637 @node Taking advantage of 64 bit addressing
29638 @subsection Taking advantage of 64-bit addressing
29641 * Making code 64 bit clean::
29642 * Allocating memory from the 64 bit storage pool::
29643 * Restrictions on use of 64 bit objects::
29644 * Using 64 bit storage pools by default::
29645 * General access types::
29646 * STARLET and other predefined libraries::
29649 @node Making code 64 bit clean
29650 @subsubsection Making code 64-bit clean
29653 In order to prevent problems that may occur when (parts of) a
29654 system start using memory outside the 32-bit address range,
29655 we recommend some additional guidelines:
29659 For imported subprograms that take parameters of the
29660 type @code{System.Address}, ensure that these subprograms can
29661 indeed handle 64-bit addresses. If not, or when in doubt,
29662 change the subprogram declaration to specify
29663 @code{System.Short_Address} instead.
29666 Resolve all warnings related to size mismatches in
29667 unchecked conversions. Failing to do so causes
29668 erroneous execution if the source object is outside
29669 the 32-bit address space.
29672 (optional) Explicitly use the 32-bit storage pool
29673 for access types used in a 32-bit context, or use
29674 generic access types where possible
29675 (@pxref{Restrictions on use of 64 bit objects}).
29679 If these rules are followed, the compiler will automatically insert
29680 any necessary checks to ensure that no addresses or access values
29681 passed to 32-bit code ever refer to objects outside the 32-bit
29683 Any attempt to do this will raise @code{Constraint_Error}.
29685 @node Allocating memory from the 64 bit storage pool
29686 @subsubsection Allocating memory from the 64-bit storage pool
29689 For any access type @code{T} that potentially requires memory allocations
29690 beyond the 32-bit address space,
29691 use the following representation clause:
29693 @smallexample @c ada
29694 for T'Storage_Pool use System.Pool_64;
29697 @node Restrictions on use of 64 bit objects
29698 @subsubsection Restrictions on use of 64-bit objects
29701 Taking the address of an object allocated from a 64-bit storage pool,
29702 and then passing this address to a subprogram expecting
29703 @code{System.Short_Address},
29704 or assigning it to a variable of type @code{Short_Address}, will cause
29705 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
29706 (@pxref{Making code 64 bit clean}), or checks are suppressed,
29707 no exception is raised and execution
29708 will become erroneous.
29710 @node Using 64 bit storage pools by default
29711 @subsubsection Using 64-bit storage pools by default
29714 In some cases it may be desirable to have the compiler allocate
29715 from 64-bit storage pools by default. This may be the case for
29716 libraries that are 64-bit clean, but may be used in both 32-bit
29717 and 64-bit contexts. For these cases the following configuration
29718 pragma may be specified:
29720 @smallexample @c ada
29721 pragma Pool_64_Default;
29725 Any code compiled in the context of this pragma will by default
29726 use the @code{System.Pool_64} storage pool. This default may be overridden
29727 for a specific access type @code{T} by the representation clause:
29729 @smallexample @c ada
29730 for T'Storage_Pool use System.Pool_32;
29734 Any object whose address may be passed to a subprogram with a
29735 @code{Short_Address} argument, or assigned to a variable of type
29736 @code{Short_Address}, needs to be allocated from this pool.
29738 @node General access types
29739 @subsubsection General access types
29742 Objects designated by access values from a
29743 general access type (declared with @code{access all}) are never allocated
29744 from a 64-bit storage pool. Code that uses general access types will
29745 accept objects allocated in either 32-bit or 64-bit address spaces,
29746 but never allocate objects outside the 32-bit address space.
29747 Using general access types ensures maximum compatibility with both
29748 32-bit and 64-bit code.
29750 @node STARLET and other predefined libraries
29751 @subsubsection STARLET and other predefined libraries
29754 All code that comes as part of GNAT is 64-bit clean, but the
29755 restrictions given in @ref{Restrictions on use of 64 bit objects},
29756 still apply. Look at the package
29757 specifications to see in which contexts objects allocated
29758 in 64-bit address space are acceptable.
29760 @node Technical details
29761 @subsection Technical details
29764 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
29765 Ada standard with respect to the type of @code{System.Address}. Previous
29766 versions of GNAT Pro have defined this type as private and implemented it as a
29769 In order to allow defining @code{System.Short_Address} as a proper subtype,
29770 and to match the implicit sign extension in parameter passing,
29771 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
29772 visible (i.e., non-private) integer type.
29773 Standard operations on the type, such as the binary operators ``+'', ``-'',
29774 etc., that take @code{Address} operands and return an @code{Address} result,
29775 have been hidden by declaring these
29776 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
29777 ambiguities that would otherwise result from overloading.
29778 (Note that, although @code{Address} is a visible integer type,
29779 good programming practice dictates against exploiting the type's
29780 integer properties such as literals, since this will compromise
29783 Defining @code{Address} as a visible integer type helps achieve
29784 maximum compatibility for existing Ada code,
29785 without sacrificing the capabilities of the 64-bit architecture.
29788 @c ************************************************
29790 @node Microsoft Windows Topics
29791 @appendix Microsoft Windows Topics
29797 This chapter describes topics that are specific to the Microsoft Windows
29798 platforms (NT, 2000, and XP Professional).
29801 * Using GNAT on Windows::
29802 * Using a network installation of GNAT::
29803 * CONSOLE and WINDOWS subsystems::
29804 * Temporary Files::
29805 * Mixed-Language Programming on Windows::
29806 * Windows Calling Conventions::
29807 * Introduction to Dynamic Link Libraries (DLLs)::
29808 * Using DLLs with GNAT::
29809 * Building DLLs with GNAT::
29810 * Building DLLs with GNAT Project files::
29811 * Building DLLs with gnatdll::
29812 * GNAT and Windows Resources::
29813 * Debugging a DLL::
29814 * Setting Stack Size from gnatlink::
29815 * Setting Heap Size from gnatlink::
29818 @node Using GNAT on Windows
29819 @section Using GNAT on Windows
29822 One of the strengths of the GNAT technology is that its tool set
29823 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
29824 @code{gdb} debugger, etc.) is used in the same way regardless of the
29827 On Windows this tool set is complemented by a number of Microsoft-specific
29828 tools that have been provided to facilitate interoperability with Windows
29829 when this is required. With these tools:
29834 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
29838 You can use any Dynamically Linked Library (DLL) in your Ada code (both
29839 relocatable and non-relocatable DLLs are supported).
29842 You can build Ada DLLs for use in other applications. These applications
29843 can be written in a language other than Ada (e.g., C, C++, etc). Again both
29844 relocatable and non-relocatable Ada DLLs are supported.
29847 You can include Windows resources in your Ada application.
29850 You can use or create COM/DCOM objects.
29854 Immediately below are listed all known general GNAT-for-Windows restrictions.
29855 Other restrictions about specific features like Windows Resources and DLLs
29856 are listed in separate sections below.
29861 It is not possible to use @code{GetLastError} and @code{SetLastError}
29862 when tasking, protected records, or exceptions are used. In these
29863 cases, in order to implement Ada semantics, the GNAT run-time system
29864 calls certain Win32 routines that set the last error variable to 0 upon
29865 success. It should be possible to use @code{GetLastError} and
29866 @code{SetLastError} when tasking, protected record, and exception
29867 features are not used, but it is not guaranteed to work.
29870 It is not possible to link against Microsoft libraries except for
29871 import libraries. The library must be built to be compatible with
29872 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
29873 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
29874 not be compatible with the GNAT runtime. Even if the library is
29875 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
29878 When the compilation environment is located on FAT32 drives, users may
29879 experience recompilations of the source files that have not changed if
29880 Daylight Saving Time (DST) state has changed since the last time files
29881 were compiled. NTFS drives do not have this problem.
29884 No components of the GNAT toolset use any entries in the Windows
29885 registry. The only entries that can be created are file associations and
29886 PATH settings, provided the user has chosen to create them at installation
29887 time, as well as some minimal book-keeping information needed to correctly
29888 uninstall or integrate different GNAT products.
29891 @node Using a network installation of GNAT
29892 @section Using a network installation of GNAT
29895 Make sure the system on which GNAT is installed is accessible from the
29896 current machine, i.e. the install location is shared over the network.
29897 Shared resources are accessed on Windows by means of UNC paths, which
29898 have the format @code{\\server\sharename\path}
29900 In order to use such a network installation, simply add the UNC path of the
29901 @file{bin} directory of your GNAT installation in front of your PATH. For
29902 example, if GNAT is installed in @file{\GNAT} directory of a share location
29903 called @file{c-drive} on a machine @file{LOKI}, the following command will
29906 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
29908 Be aware that every compilation using the network installation results in the
29909 transfer of large amounts of data across the network and will likely cause
29910 serious performance penalty.
29912 @node CONSOLE and WINDOWS subsystems
29913 @section CONSOLE and WINDOWS subsystems
29914 @cindex CONSOLE Subsystem
29915 @cindex WINDOWS Subsystem
29919 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
29920 (which is the default subsystem) will always create a console when
29921 launching the application. This is not something desirable when the
29922 application has a Windows GUI. To get rid of this console the
29923 application must be using the @code{WINDOWS} subsystem. To do so
29924 the @option{-mwindows} linker option must be specified.
29927 $ gnatmake winprog -largs -mwindows
29930 @node Temporary Files
29931 @section Temporary Files
29932 @cindex Temporary files
29935 It is possible to control where temporary files gets created by setting
29936 the TMP environment variable. The file will be created:
29939 @item Under the directory pointed to by the TMP environment variable if
29940 this directory exists.
29942 @item Under c:\temp, if the TMP environment variable is not set (or not
29943 pointing to a directory) and if this directory exists.
29945 @item Under the current working directory otherwise.
29949 This allows you to determine exactly where the temporary
29950 file will be created. This is particularly useful in networked
29951 environments where you may not have write access to some
29954 @node Mixed-Language Programming on Windows
29955 @section Mixed-Language Programming on Windows
29958 Developing pure Ada applications on Windows is no different than on
29959 other GNAT-supported platforms. However, when developing or porting an
29960 application that contains a mix of Ada and C/C++, the choice of your
29961 Windows C/C++ development environment conditions your overall
29962 interoperability strategy.
29964 If you use @command{gcc} to compile the non-Ada part of your application,
29965 there are no Windows-specific restrictions that affect the overall
29966 interoperability with your Ada code. If you plan to use
29967 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
29968 the following limitations:
29972 You cannot link your Ada code with an object or library generated with
29973 Microsoft tools if these use the @code{.tls} section (Thread Local
29974 Storage section) since the GNAT linker does not yet support this section.
29977 You cannot link your Ada code with an object or library generated with
29978 Microsoft tools if these use I/O routines other than those provided in
29979 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
29980 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
29981 libraries can cause a conflict with @code{msvcrt.dll} services. For
29982 instance Visual C++ I/O stream routines conflict with those in
29987 If you do want to use the Microsoft tools for your non-Ada code and hit one
29988 of the above limitations, you have two choices:
29992 Encapsulate your non Ada code in a DLL to be linked with your Ada
29993 application. In this case, use the Microsoft or whatever environment to
29994 build the DLL and use GNAT to build your executable
29995 (@pxref{Using DLLs with GNAT}).
29998 Or you can encapsulate your Ada code in a DLL to be linked with the
29999 other part of your application. In this case, use GNAT to build the DLL
30000 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
30001 environment to build your executable.
30004 @node Windows Calling Conventions
30005 @section Windows Calling Conventions
30010 * C Calling Convention::
30011 * Stdcall Calling Convention::
30012 * Win32 Calling Convention::
30013 * DLL Calling Convention::
30017 When a subprogram @code{F} (caller) calls a subprogram @code{G}
30018 (callee), there are several ways to push @code{G}'s parameters on the
30019 stack and there are several possible scenarios to clean up the stack
30020 upon @code{G}'s return. A calling convention is an agreed upon software
30021 protocol whereby the responsibilities between the caller (@code{F}) and
30022 the callee (@code{G}) are clearly defined. Several calling conventions
30023 are available for Windows:
30027 @code{C} (Microsoft defined)
30030 @code{Stdcall} (Microsoft defined)
30033 @code{Win32} (GNAT specific)
30036 @code{DLL} (GNAT specific)
30039 @node C Calling Convention
30040 @subsection @code{C} Calling Convention
30043 This is the default calling convention used when interfacing to C/C++
30044 routines compiled with either @command{gcc} or Microsoft Visual C++.
30046 In the @code{C} calling convention subprogram parameters are pushed on the
30047 stack by the caller from right to left. The caller itself is in charge of
30048 cleaning up the stack after the call. In addition, the name of a routine
30049 with @code{C} calling convention is mangled by adding a leading underscore.
30051 The name to use on the Ada side when importing (or exporting) a routine
30052 with @code{C} calling convention is the name of the routine. For
30053 instance the C function:
30056 int get_val (long);
30060 should be imported from Ada as follows:
30062 @smallexample @c ada
30064 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30065 pragma Import (C, Get_Val, External_Name => "get_val");
30070 Note that in this particular case the @code{External_Name} parameter could
30071 have been omitted since, when missing, this parameter is taken to be the
30072 name of the Ada entity in lower case. When the @code{Link_Name} parameter
30073 is missing, as in the above example, this parameter is set to be the
30074 @code{External_Name} with a leading underscore.
30076 When importing a variable defined in C, you should always use the @code{C}
30077 calling convention unless the object containing the variable is part of a
30078 DLL (in which case you should use the @code{Stdcall} calling
30079 convention, @pxref{Stdcall Calling Convention}).
30081 @node Stdcall Calling Convention
30082 @subsection @code{Stdcall} Calling Convention
30085 This convention, which was the calling convention used for Pascal
30086 programs, is used by Microsoft for all the routines in the Win32 API for
30087 efficiency reasons. It must be used to import any routine for which this
30088 convention was specified.
30090 In the @code{Stdcall} calling convention subprogram parameters are pushed
30091 on the stack by the caller from right to left. The callee (and not the
30092 caller) is in charge of cleaning the stack on routine exit. In addition,
30093 the name of a routine with @code{Stdcall} calling convention is mangled by
30094 adding a leading underscore (as for the @code{C} calling convention) and a
30095 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
30096 bytes) of the parameters passed to the routine.
30098 The name to use on the Ada side when importing a C routine with a
30099 @code{Stdcall} calling convention is the name of the C routine. The leading
30100 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
30101 the compiler. For instance the Win32 function:
30104 @b{APIENTRY} int get_val (long);
30108 should be imported from Ada as follows:
30110 @smallexample @c ada
30112 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30113 pragma Import (Stdcall, Get_Val);
30114 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
30119 As for the @code{C} calling convention, when the @code{External_Name}
30120 parameter is missing, it is taken to be the name of the Ada entity in lower
30121 case. If instead of writing the above import pragma you write:
30123 @smallexample @c ada
30125 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30126 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
30131 then the imported routine is @code{_retrieve_val@@4}. However, if instead
30132 of specifying the @code{External_Name} parameter you specify the
30133 @code{Link_Name} as in the following example:
30135 @smallexample @c ada
30137 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30138 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
30143 then the imported routine is @code{retrieve_val}, that is, there is no
30144 decoration at all. No leading underscore and no Stdcall suffix
30145 @code{@@}@code{@i{nn}}.
30148 This is especially important as in some special cases a DLL's entry
30149 point name lacks a trailing @code{@@}@code{@i{nn}} while the exported
30150 name generated for a call has it.
30153 It is also possible to import variables defined in a DLL by using an
30154 import pragma for a variable. As an example, if a DLL contains a
30155 variable defined as:
30162 then, to access this variable from Ada you should write:
30164 @smallexample @c ada
30166 My_Var : Interfaces.C.int;
30167 pragma Import (Stdcall, My_Var);
30172 Note that to ease building cross-platform bindings this convention
30173 will be handled as a @code{C} calling convention on non Windows platforms.
30175 @node Win32 Calling Convention
30176 @subsection @code{Win32} Calling Convention
30179 This convention, which is GNAT-specific is fully equivalent to the
30180 @code{Stdcall} calling convention described above.
30182 @node DLL Calling Convention
30183 @subsection @code{DLL} Calling Convention
30186 This convention, which is GNAT-specific is fully equivalent to the
30187 @code{Stdcall} calling convention described above.
30189 @node Introduction to Dynamic Link Libraries (DLLs)
30190 @section Introduction to Dynamic Link Libraries (DLLs)
30194 A Dynamically Linked Library (DLL) is a library that can be shared by
30195 several applications running under Windows. A DLL can contain any number of
30196 routines and variables.
30198 One advantage of DLLs is that you can change and enhance them without
30199 forcing all the applications that depend on them to be relinked or
30200 recompiled. However, you should be aware than all calls to DLL routines are
30201 slower since, as you will understand below, such calls are indirect.
30203 To illustrate the remainder of this section, suppose that an application
30204 wants to use the services of a DLL @file{API.dll}. To use the services
30205 provided by @file{API.dll} you must statically link against the DLL or
30206 an import library which contains a jump table with an entry for each
30207 routine and variable exported by the DLL. In the Microsoft world this
30208 import library is called @file{API.lib}. When using GNAT this import
30209 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
30210 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
30212 After you have linked your application with the DLL or the import library
30213 and you run your application, here is what happens:
30217 Your application is loaded into memory.
30220 The DLL @file{API.dll} is mapped into the address space of your
30221 application. This means that:
30225 The DLL will use the stack of the calling thread.
30228 The DLL will use the virtual address space of the calling process.
30231 The DLL will allocate memory from the virtual address space of the calling
30235 Handles (pointers) can be safely exchanged between routines in the DLL
30236 routines and routines in the application using the DLL.
30240 The entries in the jump table (from the import library @file{libAPI.dll.a}
30241 or @file{API.lib} or automatically created when linking against a DLL)
30242 which is part of your application are initialized with the addresses
30243 of the routines and variables in @file{API.dll}.
30246 If present in @file{API.dll}, routines @code{DllMain} or
30247 @code{DllMainCRTStartup} are invoked. These routines typically contain
30248 the initialization code needed for the well-being of the routines and
30249 variables exported by the DLL.
30253 There is an additional point which is worth mentioning. In the Windows
30254 world there are two kind of DLLs: relocatable and non-relocatable
30255 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
30256 in the target application address space. If the addresses of two
30257 non-relocatable DLLs overlap and these happen to be used by the same
30258 application, a conflict will occur and the application will run
30259 incorrectly. Hence, when possible, it is always preferable to use and
30260 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
30261 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
30262 User's Guide) removes the debugging symbols from the DLL but the DLL can
30263 still be relocated.
30265 As a side note, an interesting difference between Microsoft DLLs and
30266 Unix shared libraries, is the fact that on most Unix systems all public
30267 routines are exported by default in a Unix shared library, while under
30268 Windows it is possible (but not required) to list exported routines in
30269 a definition file (@pxref{The Definition File}).
30271 @node Using DLLs with GNAT
30272 @section Using DLLs with GNAT
30275 * Creating an Ada Spec for the DLL Services::
30276 * Creating an Import Library::
30280 To use the services of a DLL, say @file{API.dll}, in your Ada application
30285 The Ada spec for the routines and/or variables you want to access in
30286 @file{API.dll}. If not available this Ada spec must be built from the C/C++
30287 header files provided with the DLL.
30290 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
30291 mentioned an import library is a statically linked library containing the
30292 import table which will be filled at load time to point to the actual
30293 @file{API.dll} routines. Sometimes you don't have an import library for the
30294 DLL you want to use. The following sections will explain how to build
30295 one. Note that this is optional.
30298 The actual DLL, @file{API.dll}.
30302 Once you have all the above, to compile an Ada application that uses the
30303 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
30304 you simply issue the command
30307 $ gnatmake my_ada_app -largs -lAPI
30311 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
30312 tells the GNAT linker to look first for a library named @file{API.lib}
30313 (Microsoft-style name) and if not found for a libraries named
30314 @file{libAPI.dll.a}, @file{API.dll.a} or @file{libAPI.a}.
30315 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
30316 contains the following pragma
30318 @smallexample @c ada
30319 pragma Linker_Options ("-lAPI");
30323 you do not have to add @option{-largs -lAPI} at the end of the
30324 @command{gnatmake} command.
30326 If any one of the items above is missing you will have to create it
30327 yourself. The following sections explain how to do so using as an
30328 example a fictitious DLL called @file{API.dll}.
30330 @node Creating an Ada Spec for the DLL Services
30331 @subsection Creating an Ada Spec for the DLL Services
30334 A DLL typically comes with a C/C++ header file which provides the
30335 definitions of the routines and variables exported by the DLL. The Ada
30336 equivalent of this header file is a package spec that contains definitions
30337 for the imported entities. If the DLL you intend to use does not come with
30338 an Ada spec you have to generate one such spec yourself. For example if
30339 the header file of @file{API.dll} is a file @file{api.h} containing the
30340 following two definitions:
30352 then the equivalent Ada spec could be:
30354 @smallexample @c ada
30357 with Interfaces.C.Strings;
30362 function Get (Str : C.Strings.Chars_Ptr) return C.int;
30365 pragma Import (C, Get);
30366 pragma Import (DLL, Some_Var);
30373 Note that a variable is
30374 @strong{always imported with a Stdcall convention}. A function
30375 can have @code{C} or @code{Stdcall} convention.
30376 (@pxref{Windows Calling Conventions}).
30378 @node Creating an Import Library
30379 @subsection Creating an Import Library
30380 @cindex Import library
30383 * The Definition File::
30384 * GNAT-Style Import Library::
30385 * Microsoft-Style Import Library::
30389 If a Microsoft-style import library @file{API.lib} or a GNAT-style
30390 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
30391 with @file{API.dll} you can skip this section. You can also skip this
30392 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
30393 as in this case it is possible to link directly against the
30394 DLL. Otherwise read on.
30396 @node The Definition File
30397 @subsubsection The Definition File
30398 @cindex Definition file
30402 As previously mentioned, and unlike Unix systems, the list of symbols
30403 that are exported from a DLL must be provided explicitly in Windows.
30404 The main goal of a definition file is precisely that: list the symbols
30405 exported by a DLL. A definition file (usually a file with a @code{.def}
30406 suffix) has the following structure:
30412 [DESCRIPTION @i{string}]
30422 @item LIBRARY @i{name}
30423 This section, which is optional, gives the name of the DLL.
30425 @item DESCRIPTION @i{string}
30426 This section, which is optional, gives a description string that will be
30427 embedded in the import library.
30430 This section gives the list of exported symbols (procedures, functions or
30431 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
30432 section of @file{API.def} looks like:
30446 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
30447 (@pxref{Windows Calling Conventions}) for a Stdcall
30448 calling convention function in the exported symbols list.
30451 There can actually be other sections in a definition file, but these
30452 sections are not relevant to the discussion at hand.
30454 @node GNAT-Style Import Library
30455 @subsubsection GNAT-Style Import Library
30458 To create a static import library from @file{API.dll} with the GNAT tools
30459 you should proceed as follows:
30463 Create the definition file @file{API.def} (@pxref{The Definition File}).
30464 For that use the @code{dll2def} tool as follows:
30467 $ dll2def API.dll > API.def
30471 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
30472 to standard output the list of entry points in the DLL. Note that if
30473 some routines in the DLL have the @code{Stdcall} convention
30474 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
30475 suffix then you'll have to edit @file{api.def} to add it, and specify
30476 @option{-k} to @command{gnatdll} when creating the import library.
30479 Here are some hints to find the right @code{@@}@i{nn} suffix.
30483 If you have the Microsoft import library (.lib), it is possible to get
30484 the right symbols by using Microsoft @code{dumpbin} tool (see the
30485 corresponding Microsoft documentation for further details).
30488 $ dumpbin /exports api.lib
30492 If you have a message about a missing symbol at link time the compiler
30493 tells you what symbol is expected. You just have to go back to the
30494 definition file and add the right suffix.
30498 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
30499 (@pxref{Using gnatdll}) as follows:
30502 $ gnatdll -e API.def -d API.dll
30506 @code{gnatdll} takes as input a definition file @file{API.def} and the
30507 name of the DLL containing the services listed in the definition file
30508 @file{API.dll}. The name of the static import library generated is
30509 computed from the name of the definition file as follows: if the
30510 definition file name is @i{xyz}@code{.def}, the import library name will
30511 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
30512 @option{-e} could have been removed because the name of the definition
30513 file (before the ``@code{.def}'' suffix) is the same as the name of the
30514 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
30517 @node Microsoft-Style Import Library
30518 @subsubsection Microsoft-Style Import Library
30521 With GNAT you can either use a GNAT-style or Microsoft-style import
30522 library. A Microsoft import library is needed only if you plan to make an
30523 Ada DLL available to applications developed with Microsoft
30524 tools (@pxref{Mixed-Language Programming on Windows}).
30526 To create a Microsoft-style import library for @file{API.dll} you
30527 should proceed as follows:
30531 Create the definition file @file{API.def} from the DLL. For this use either
30532 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
30533 tool (see the corresponding Microsoft documentation for further details).
30536 Build the actual import library using Microsoft's @code{lib} utility:
30539 $ lib -machine:IX86 -def:API.def -out:API.lib
30543 If you use the above command the definition file @file{API.def} must
30544 contain a line giving the name of the DLL:
30551 See the Microsoft documentation for further details about the usage of
30555 @node Building DLLs with GNAT
30556 @section Building DLLs with GNAT
30557 @cindex DLLs, building
30560 This section explain how to build DLLs using the GNAT built-in DLL
30561 support. With the following procedure it is straight forward to build
30562 and use DLLs with GNAT.
30566 @item building object files
30568 The first step is to build all objects files that are to be included
30569 into the DLL. This is done by using the standard @command{gnatmake} tool.
30571 @item building the DLL
30573 To build the DLL you must use @command{gcc}'s @option{-shared}
30574 option. It is quite simple to use this method:
30577 $ gcc -shared -o api.dll obj1.o obj2.o ...
30580 It is important to note that in this case all symbols found in the
30581 object files are automatically exported. It is possible to restrict
30582 the set of symbols to export by passing to @command{gcc} a definition
30583 file, @pxref{The Definition File}. For example:
30586 $ gcc -shared -o api.dll api.def obj1.o obj2.o ...
30589 If you use a definition file you must export the elaboration procedures
30590 for every package that required one. Elaboration procedures are named
30591 using the package name followed by "_E".
30593 @item preparing DLL to be used
30595 For the DLL to be used by client programs the bodies must be hidden
30596 from it and the .ali set with read-only attribute. This is very important
30597 otherwise GNAT will recompile all packages and will not actually use
30598 the code in the DLL. For example:
30602 $ copy *.ads *.ali api.dll apilib
30603 $ attrib +R apilib\*.ali
30608 At this point it is possible to use the DLL by directly linking
30609 against it. Note that you must use the GNAT shared runtime when using
30610 GNAT shared libraries. This is achieved by using @option{-shared} binder's
30614 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
30617 @node Building DLLs with GNAT Project files
30618 @section Building DLLs with GNAT Project files
30619 @cindex DLLs, building
30622 There is nothing specific to Windows in the build process.
30623 @pxref{Library Projects}.
30626 Due to a system limitation, it is not possible under Windows to create threads
30627 when inside the @code{DllMain} routine which is used for auto-initialization
30628 of shared libraries, so it is not possible to have library level tasks in SALs.
30630 @node Building DLLs with gnatdll
30631 @section Building DLLs with gnatdll
30632 @cindex DLLs, building
30635 * Limitations When Using Ada DLLs from Ada::
30636 * Exporting Ada Entities::
30637 * Ada DLLs and Elaboration::
30638 * Ada DLLs and Finalization::
30639 * Creating a Spec for Ada DLLs::
30640 * Creating the Definition File::
30645 Note that it is preferred to use the built-in GNAT DLL support
30646 (@pxref{Building DLLs with GNAT}) or GNAT Project files
30647 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
30649 This section explains how to build DLLs containing Ada code using
30650 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
30651 remainder of this section.
30653 The steps required to build an Ada DLL that is to be used by Ada as well as
30654 non-Ada applications are as follows:
30658 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
30659 @code{Stdcall} calling convention to avoid any Ada name mangling for the
30660 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
30661 skip this step if you plan to use the Ada DLL only from Ada applications.
30664 Your Ada code must export an initialization routine which calls the routine
30665 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
30666 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
30667 routine exported by the Ada DLL must be invoked by the clients of the DLL
30668 to initialize the DLL.
30671 When useful, the DLL should also export a finalization routine which calls
30672 routine @code{adafinal} generated by @command{gnatbind} to perform the
30673 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
30674 The finalization routine exported by the Ada DLL must be invoked by the
30675 clients of the DLL when the DLL services are no further needed.
30678 You must provide a spec for the services exported by the Ada DLL in each
30679 of the programming languages to which you plan to make the DLL available.
30682 You must provide a definition file listing the exported entities
30683 (@pxref{The Definition File}).
30686 Finally you must use @code{gnatdll} to produce the DLL and the import
30687 library (@pxref{Using gnatdll}).
30691 Note that a relocatable DLL stripped using the @code{strip}
30692 binutils tool will not be relocatable anymore. To build a DLL without
30693 debug information pass @code{-largs -s} to @code{gnatdll}. This
30694 restriction does not apply to a DLL built using a Library Project.
30695 @pxref{Library Projects}.
30697 @node Limitations When Using Ada DLLs from Ada
30698 @subsection Limitations When Using Ada DLLs from Ada
30701 When using Ada DLLs from Ada applications there is a limitation users
30702 should be aware of. Because on Windows the GNAT run time is not in a DLL of
30703 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
30704 each Ada DLL includes the services of the GNAT run time that are necessary
30705 to the Ada code inside the DLL. As a result, when an Ada program uses an
30706 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
30707 one in the main program.
30709 It is therefore not possible to exchange GNAT run-time objects between the
30710 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
30711 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
30714 It is completely safe to exchange plain elementary, array or record types,
30715 Windows object handles, etc.
30717 @node Exporting Ada Entities
30718 @subsection Exporting Ada Entities
30719 @cindex Export table
30722 Building a DLL is a way to encapsulate a set of services usable from any
30723 application. As a result, the Ada entities exported by a DLL should be
30724 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
30725 any Ada name mangling. As an example here is an Ada package
30726 @code{API}, spec and body, exporting two procedures, a function, and a
30729 @smallexample @c ada
30732 with Interfaces.C; use Interfaces;
30734 Count : C.int := 0;
30735 function Factorial (Val : C.int) return C.int;
30737 procedure Initialize_API;
30738 procedure Finalize_API;
30739 -- Initialization & Finalization routines. More in the next section.
30741 pragma Export (C, Initialize_API);
30742 pragma Export (C, Finalize_API);
30743 pragma Export (C, Count);
30744 pragma Export (C, Factorial);
30750 @smallexample @c ada
30753 package body API is
30754 function Factorial (Val : C.int) return C.int is
30757 Count := Count + 1;
30758 for K in 1 .. Val loop
30764 procedure Initialize_API is
30766 pragma Import (C, Adainit);
30769 end Initialize_API;
30771 procedure Finalize_API is
30772 procedure Adafinal;
30773 pragma Import (C, Adafinal);
30783 If the Ada DLL you are building will only be used by Ada applications
30784 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
30785 convention. As an example, the previous package could be written as
30788 @smallexample @c ada
30792 Count : Integer := 0;
30793 function Factorial (Val : Integer) return Integer;
30795 procedure Initialize_API;
30796 procedure Finalize_API;
30797 -- Initialization and Finalization routines.
30803 @smallexample @c ada
30806 package body API is
30807 function Factorial (Val : Integer) return Integer is
30808 Fact : Integer := 1;
30810 Count := Count + 1;
30811 for K in 1 .. Val loop
30818 -- The remainder of this package body is unchanged.
30825 Note that if you do not export the Ada entities with a @code{C} or
30826 @code{Stdcall} convention you will have to provide the mangled Ada names
30827 in the definition file of the Ada DLL
30828 (@pxref{Creating the Definition File}).
30830 @node Ada DLLs and Elaboration
30831 @subsection Ada DLLs and Elaboration
30832 @cindex DLLs and elaboration
30835 The DLL that you are building contains your Ada code as well as all the
30836 routines in the Ada library that are needed by it. The first thing a
30837 user of your DLL must do is elaborate the Ada code
30838 (@pxref{Elaboration Order Handling in GNAT}).
30840 To achieve this you must export an initialization routine
30841 (@code{Initialize_API} in the previous example), which must be invoked
30842 before using any of the DLL services. This elaboration routine must call
30843 the Ada elaboration routine @code{adainit} generated by the GNAT binder
30844 (@pxref{Binding with Non-Ada Main Programs}). See the body of
30845 @code{Initialize_Api} for an example. Note that the GNAT binder is
30846 automatically invoked during the DLL build process by the @code{gnatdll}
30847 tool (@pxref{Using gnatdll}).
30849 When a DLL is loaded, Windows systematically invokes a routine called
30850 @code{DllMain}. It would therefore be possible to call @code{adainit}
30851 directly from @code{DllMain} without having to provide an explicit
30852 initialization routine. Unfortunately, it is not possible to call
30853 @code{adainit} from the @code{DllMain} if your program has library level
30854 tasks because access to the @code{DllMain} entry point is serialized by
30855 the system (that is, only a single thread can execute ``through'' it at a
30856 time), which means that the GNAT run time will deadlock waiting for the
30857 newly created task to complete its initialization.
30859 @node Ada DLLs and Finalization
30860 @subsection Ada DLLs and Finalization
30861 @cindex DLLs and finalization
30864 When the services of an Ada DLL are no longer needed, the client code should
30865 invoke the DLL finalization routine, if available. The DLL finalization
30866 routine is in charge of releasing all resources acquired by the DLL. In the
30867 case of the Ada code contained in the DLL, this is achieved by calling
30868 routine @code{adafinal} generated by the GNAT binder
30869 (@pxref{Binding with Non-Ada Main Programs}).
30870 See the body of @code{Finalize_Api} for an
30871 example. As already pointed out the GNAT binder is automatically invoked
30872 during the DLL build process by the @code{gnatdll} tool
30873 (@pxref{Using gnatdll}).
30875 @node Creating a Spec for Ada DLLs
30876 @subsection Creating a Spec for Ada DLLs
30879 To use the services exported by the Ada DLL from another programming
30880 language (e.g. C), you have to translate the specs of the exported Ada
30881 entities in that language. For instance in the case of @code{API.dll},
30882 the corresponding C header file could look like:
30887 extern int *_imp__count;
30888 #define count (*_imp__count)
30889 int factorial (int);
30895 It is important to understand that when building an Ada DLL to be used by
30896 other Ada applications, you need two different specs for the packages
30897 contained in the DLL: one for building the DLL and the other for using
30898 the DLL. This is because the @code{DLL} calling convention is needed to
30899 use a variable defined in a DLL, but when building the DLL, the variable
30900 must have either the @code{Ada} or @code{C} calling convention. As an
30901 example consider a DLL comprising the following package @code{API}:
30903 @smallexample @c ada
30907 Count : Integer := 0;
30909 -- Remainder of the package omitted.
30916 After producing a DLL containing package @code{API}, the spec that
30917 must be used to import @code{API.Count} from Ada code outside of the
30920 @smallexample @c ada
30925 pragma Import (DLL, Count);
30931 @node Creating the Definition File
30932 @subsection Creating the Definition File
30935 The definition file is the last file needed to build the DLL. It lists
30936 the exported symbols. As an example, the definition file for a DLL
30937 containing only package @code{API} (where all the entities are exported
30938 with a @code{C} calling convention) is:
30953 If the @code{C} calling convention is missing from package @code{API},
30954 then the definition file contains the mangled Ada names of the above
30955 entities, which in this case are:
30964 api__initialize_api
30969 @node Using gnatdll
30970 @subsection Using @code{gnatdll}
30974 * gnatdll Example::
30975 * gnatdll behind the Scenes::
30980 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
30981 and non-Ada sources that make up your DLL have been compiled.
30982 @code{gnatdll} is actually in charge of two distinct tasks: build the
30983 static import library for the DLL and the actual DLL. The form of the
30984 @code{gnatdll} command is
30988 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
30993 where @i{list-of-files} is a list of ALI and object files. The object
30994 file list must be the exact list of objects corresponding to the non-Ada
30995 sources whose services are to be included in the DLL. The ALI file list
30996 must be the exact list of ALI files for the corresponding Ada sources
30997 whose services are to be included in the DLL. If @i{list-of-files} is
30998 missing, only the static import library is generated.
31001 You may specify any of the following switches to @code{gnatdll}:
31004 @item -a[@var{address}]
31005 @cindex @option{-a} (@code{gnatdll})
31006 Build a non-relocatable DLL at @var{address}. If @var{address} is not
31007 specified the default address @var{0x11000000} will be used. By default,
31008 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
31009 advise the reader to build relocatable DLL.
31011 @item -b @var{address}
31012 @cindex @option{-b} (@code{gnatdll})
31013 Set the relocatable DLL base address. By default the address is
31016 @item -bargs @var{opts}
31017 @cindex @option{-bargs} (@code{gnatdll})
31018 Binder options. Pass @var{opts} to the binder.
31020 @item -d @var{dllfile}
31021 @cindex @option{-d} (@code{gnatdll})
31022 @var{dllfile} is the name of the DLL. This switch must be present for
31023 @code{gnatdll} to do anything. The name of the generated import library is
31024 obtained algorithmically from @var{dllfile} as shown in the following
31025 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
31026 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
31027 by option @option{-e}) is obtained algorithmically from @var{dllfile}
31028 as shown in the following example:
31029 if @var{dllfile} is @code{xyz.dll}, the definition
31030 file used is @code{xyz.def}.
31032 @item -e @var{deffile}
31033 @cindex @option{-e} (@code{gnatdll})
31034 @var{deffile} is the name of the definition file.
31037 @cindex @option{-g} (@code{gnatdll})
31038 Generate debugging information. This information is stored in the object
31039 file and copied from there to the final DLL file by the linker,
31040 where it can be read by the debugger. You must use the
31041 @option{-g} switch if you plan on using the debugger or the symbolic
31045 @cindex @option{-h} (@code{gnatdll})
31046 Help mode. Displays @code{gnatdll} switch usage information.
31049 @cindex @option{-I} (@code{gnatdll})
31050 Direct @code{gnatdll} to search the @var{dir} directory for source and
31051 object files needed to build the DLL.
31052 (@pxref{Search Paths and the Run-Time Library (RTL)}).
31055 @cindex @option{-k} (@code{gnatdll})
31056 Removes the @code{@@}@i{nn} suffix from the import library's exported
31057 names, but keeps them for the link names. You must specify this
31058 option if you want to use a @code{Stdcall} function in a DLL for which
31059 the @code{@@}@i{nn} suffix has been removed. This is the case for most
31060 of the Windows NT DLL for example. This option has no effect when
31061 @option{-n} option is specified.
31063 @item -l @var{file}
31064 @cindex @option{-l} (@code{gnatdll})
31065 The list of ALI and object files used to build the DLL are listed in
31066 @var{file}, instead of being given in the command line. Each line in
31067 @var{file} contains the name of an ALI or object file.
31070 @cindex @option{-n} (@code{gnatdll})
31071 No Import. Do not create the import library.
31074 @cindex @option{-q} (@code{gnatdll})
31075 Quiet mode. Do not display unnecessary messages.
31078 @cindex @option{-v} (@code{gnatdll})
31079 Verbose mode. Display extra information.
31081 @item -largs @var{opts}
31082 @cindex @option{-largs} (@code{gnatdll})
31083 Linker options. Pass @var{opts} to the linker.
31086 @node gnatdll Example
31087 @subsubsection @code{gnatdll} Example
31090 As an example the command to build a relocatable DLL from @file{api.adb}
31091 once @file{api.adb} has been compiled and @file{api.def} created is
31094 $ gnatdll -d api.dll api.ali
31098 The above command creates two files: @file{libapi.dll.a} (the import
31099 library) and @file{api.dll} (the actual DLL). If you want to create
31100 only the DLL, just type:
31103 $ gnatdll -d api.dll -n api.ali
31107 Alternatively if you want to create just the import library, type:
31110 $ gnatdll -d api.dll
31113 @node gnatdll behind the Scenes
31114 @subsubsection @code{gnatdll} behind the Scenes
31117 This section details the steps involved in creating a DLL. @code{gnatdll}
31118 does these steps for you. Unless you are interested in understanding what
31119 goes on behind the scenes, you should skip this section.
31121 We use the previous example of a DLL containing the Ada package @code{API},
31122 to illustrate the steps necessary to build a DLL. The starting point is a
31123 set of objects that will make up the DLL and the corresponding ALI
31124 files. In the case of this example this means that @file{api.o} and
31125 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
31130 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
31131 the information necessary to generate relocation information for the
31137 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
31142 In addition to the base file, the @command{gnatlink} command generates an
31143 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
31144 asks @command{gnatlink} to generate the routines @code{DllMain} and
31145 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
31146 is loaded into memory.
31149 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
31150 export table (@file{api.exp}). The export table contains the relocation
31151 information in a form which can be used during the final link to ensure
31152 that the Windows loader is able to place the DLL anywhere in memory.
31156 $ dlltool --dllname api.dll --def api.def --base-file api.base \
31157 --output-exp api.exp
31162 @code{gnatdll} builds the base file using the new export table. Note that
31163 @command{gnatbind} must be called once again since the binder generated file
31164 has been deleted during the previous call to @command{gnatlink}.
31169 $ gnatlink api -o api.jnk api.exp -mdll
31170 -Wl,--base-file,api.base
31175 @code{gnatdll} builds the new export table using the new base file and
31176 generates the DLL import library @file{libAPI.dll.a}.
31180 $ dlltool --dllname api.dll --def api.def --base-file api.base \
31181 --output-exp api.exp --output-lib libAPI.a
31186 Finally @code{gnatdll} builds the relocatable DLL using the final export
31192 $ gnatlink api api.exp -o api.dll -mdll
31197 @node Using dlltool
31198 @subsubsection Using @code{dlltool}
31201 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
31202 DLLs and static import libraries. This section summarizes the most
31203 common @code{dlltool} switches. The form of the @code{dlltool} command
31207 $ dlltool [@var{switches}]
31211 @code{dlltool} switches include:
31214 @item --base-file @var{basefile}
31215 @cindex @option{--base-file} (@command{dlltool})
31216 Read the base file @var{basefile} generated by the linker. This switch
31217 is used to create a relocatable DLL.
31219 @item --def @var{deffile}
31220 @cindex @option{--def} (@command{dlltool})
31221 Read the definition file.
31223 @item --dllname @var{name}
31224 @cindex @option{--dllname} (@command{dlltool})
31225 Gives the name of the DLL. This switch is used to embed the name of the
31226 DLL in the static import library generated by @code{dlltool} with switch
31227 @option{--output-lib}.
31230 @cindex @option{-k} (@command{dlltool})
31231 Kill @code{@@}@i{nn} from exported names
31232 (@pxref{Windows Calling Conventions}
31233 for a discussion about @code{Stdcall}-style symbols.
31236 @cindex @option{--help} (@command{dlltool})
31237 Prints the @code{dlltool} switches with a concise description.
31239 @item --output-exp @var{exportfile}
31240 @cindex @option{--output-exp} (@command{dlltool})
31241 Generate an export file @var{exportfile}. The export file contains the
31242 export table (list of symbols in the DLL) and is used to create the DLL.
31244 @item --output-lib @i{libfile}
31245 @cindex @option{--output-lib} (@command{dlltool})
31246 Generate a static import library @var{libfile}.
31249 @cindex @option{-v} (@command{dlltool})
31252 @item --as @i{assembler-name}
31253 @cindex @option{--as} (@command{dlltool})
31254 Use @i{assembler-name} as the assembler. The default is @code{as}.
31257 @node GNAT and Windows Resources
31258 @section GNAT and Windows Resources
31259 @cindex Resources, windows
31262 * Building Resources::
31263 * Compiling Resources::
31264 * Using Resources::
31268 Resources are an easy way to add Windows specific objects to your
31269 application. The objects that can be added as resources include:
31298 This section explains how to build, compile and use resources.
31300 @node Building Resources
31301 @subsection Building Resources
31302 @cindex Resources, building
31305 A resource file is an ASCII file. By convention resource files have an
31306 @file{.rc} extension.
31307 The easiest way to build a resource file is to use Microsoft tools
31308 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
31309 @code{dlgedit.exe} to build dialogs.
31310 It is always possible to build an @file{.rc} file yourself by writing a
31313 It is not our objective to explain how to write a resource file. A
31314 complete description of the resource script language can be found in the
31315 Microsoft documentation.
31317 @node Compiling Resources
31318 @subsection Compiling Resources
31321 @cindex Resources, compiling
31324 This section describes how to build a GNAT-compatible (COFF) object file
31325 containing the resources. This is done using the Resource Compiler
31326 @code{windres} as follows:
31329 $ windres -i myres.rc -o myres.o
31333 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
31334 file. You can specify an alternate preprocessor (usually named
31335 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
31336 parameter. A list of all possible options may be obtained by entering
31337 the command @code{windres} @option{--help}.
31339 It is also possible to use the Microsoft resource compiler @code{rc.exe}
31340 to produce a @file{.res} file (binary resource file). See the
31341 corresponding Microsoft documentation for further details. In this case
31342 you need to use @code{windres} to translate the @file{.res} file to a
31343 GNAT-compatible object file as follows:
31346 $ windres -i myres.res -o myres.o
31349 @node Using Resources
31350 @subsection Using Resources
31351 @cindex Resources, using
31354 To include the resource file in your program just add the
31355 GNAT-compatible object file for the resource(s) to the linker
31356 arguments. With @command{gnatmake} this is done by using the @option{-largs}
31360 $ gnatmake myprog -largs myres.o
31363 @node Debugging a DLL
31364 @section Debugging a DLL
31365 @cindex DLL debugging
31368 * Program and DLL Both Built with GCC/GNAT::
31369 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
31373 Debugging a DLL is similar to debugging a standard program. But
31374 we have to deal with two different executable parts: the DLL and the
31375 program that uses it. We have the following four possibilities:
31379 The program and the DLL are built with @code{GCC/GNAT}.
31381 The program is built with foreign tools and the DLL is built with
31384 The program is built with @code{GCC/GNAT} and the DLL is built with
31390 In this section we address only cases one and two above.
31391 There is no point in trying to debug
31392 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
31393 information in it. To do so you must use a debugger compatible with the
31394 tools suite used to build the DLL.
31396 @node Program and DLL Both Built with GCC/GNAT
31397 @subsection Program and DLL Both Built with GCC/GNAT
31400 This is the simplest case. Both the DLL and the program have @code{GDB}
31401 compatible debugging information. It is then possible to break anywhere in
31402 the process. Let's suppose here that the main procedure is named
31403 @code{ada_main} and that in the DLL there is an entry point named
31407 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
31408 program must have been built with the debugging information (see GNAT -g
31409 switch). Here are the step-by-step instructions for debugging it:
31412 @item Launch @code{GDB} on the main program.
31418 @item Start the program and stop at the beginning of the main procedure
31425 This step is required to be able to set a breakpoint inside the DLL. As long
31426 as the program is not run, the DLL is not loaded. This has the
31427 consequence that the DLL debugging information is also not loaded, so it is not
31428 possible to set a breakpoint in the DLL.
31430 @item Set a breakpoint inside the DLL
31433 (gdb) break ada_dll
31440 At this stage a breakpoint is set inside the DLL. From there on
31441 you can use the standard approach to debug the whole program
31442 (@pxref{Running and Debugging Ada Programs}).
31445 @c This used to work, probably because the DLLs were non-relocatable
31446 @c keep this section around until the problem is sorted out.
31448 To break on the @code{DllMain} routine it is not possible to follow
31449 the procedure above. At the time the program stop on @code{ada_main}
31450 the @code{DllMain} routine as already been called. Either you can use
31451 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
31454 @item Launch @code{GDB} on the main program.
31460 @item Load DLL symbols
31463 (gdb) add-sym api.dll
31466 @item Set a breakpoint inside the DLL
31469 (gdb) break ada_dll.adb:45
31472 Note that at this point it is not possible to break using the routine symbol
31473 directly as the program is not yet running. The solution is to break
31474 on the proper line (break in @file{ada_dll.adb} line 45).
31476 @item Start the program
31485 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
31486 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
31489 * Debugging the DLL Directly::
31490 * Attaching to a Running Process::
31494 In this case things are slightly more complex because it is not possible to
31495 start the main program and then break at the beginning to load the DLL and the
31496 associated DLL debugging information. It is not possible to break at the
31497 beginning of the program because there is no @code{GDB} debugging information,
31498 and therefore there is no direct way of getting initial control. This
31499 section addresses this issue by describing some methods that can be used
31500 to break somewhere in the DLL to debug it.
31503 First suppose that the main procedure is named @code{main} (this is for
31504 example some C code built with Microsoft Visual C) and that there is a
31505 DLL named @code{test.dll} containing an Ada entry point named
31509 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
31510 been built with debugging information (see GNAT -g option).
31512 @node Debugging the DLL Directly
31513 @subsubsection Debugging the DLL Directly
31517 Find out the executable starting address
31520 $ objdump --file-header main.exe
31523 The starting address is reported on the last line. For example:
31526 main.exe: file format pei-i386
31527 architecture: i386, flags 0x0000010a:
31528 EXEC_P, HAS_DEBUG, D_PAGED
31529 start address 0x00401010
31533 Launch the debugger on the executable.
31540 Set a breakpoint at the starting address, and launch the program.
31543 $ (gdb) break *0x00401010
31547 The program will stop at the given address.
31550 Set a breakpoint on a DLL subroutine.
31553 (gdb) break ada_dll.adb:45
31556 Or if you want to break using a symbol on the DLL, you need first to
31557 select the Ada language (language used by the DLL).
31560 (gdb) set language ada
31561 (gdb) break ada_dll
31565 Continue the program.
31572 This will run the program until it reaches the breakpoint that has been
31573 set. From that point you can use the standard way to debug a program
31574 as described in (@pxref{Running and Debugging Ada Programs}).
31579 It is also possible to debug the DLL by attaching to a running process.
31581 @node Attaching to a Running Process
31582 @subsubsection Attaching to a Running Process
31583 @cindex DLL debugging, attach to process
31586 With @code{GDB} it is always possible to debug a running process by
31587 attaching to it. It is possible to debug a DLL this way. The limitation
31588 of this approach is that the DLL must run long enough to perform the
31589 attach operation. It may be useful for instance to insert a time wasting
31590 loop in the code of the DLL to meet this criterion.
31594 @item Launch the main program @file{main.exe}.
31600 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
31601 that the process PID for @file{main.exe} is 208.
31609 @item Attach to the running process to be debugged.
31615 @item Load the process debugging information.
31618 (gdb) symbol-file main.exe
31621 @item Break somewhere in the DLL.
31624 (gdb) break ada_dll
31627 @item Continue process execution.
31636 This last step will resume the process execution, and stop at
31637 the breakpoint we have set. From there you can use the standard
31638 approach to debug a program as described in
31639 (@pxref{Running and Debugging Ada Programs}).
31641 @node Setting Stack Size from gnatlink
31642 @section Setting Stack Size from @command{gnatlink}
31645 It is possible to specify the program stack size at link time. On modern
31646 versions of Windows, starting with XP, this is mostly useful to set the size of
31647 the main stack (environment task). The other task stacks are set with pragma
31648 Storage_Size or with the @command{gnatbind -d} command.
31650 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
31651 reserve size of individual tasks, the link-time stack size applies to all
31652 tasks, and pragma Storage_Size has no effect.
31653 In particular, Stack Overflow checks are made against this
31654 link-time specified size.
31656 This setting can be done with
31657 @command{gnatlink} using either:
31661 @item using @option{-Xlinker} linker option
31664 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
31667 This sets the stack reserve size to 0x10000 bytes and the stack commit
31668 size to 0x1000 bytes.
31670 @item using @option{-Wl} linker option
31673 $ gnatlink hello -Wl,--stack=0x1000000
31676 This sets the stack reserve size to 0x1000000 bytes. Note that with
31677 @option{-Wl} option it is not possible to set the stack commit size
31678 because the coma is a separator for this option.
31682 @node Setting Heap Size from gnatlink
31683 @section Setting Heap Size from @command{gnatlink}
31686 Under Windows systems, it is possible to specify the program heap size from
31687 @command{gnatlink} using either:
31691 @item using @option{-Xlinker} linker option
31694 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
31697 This sets the heap reserve size to 0x10000 bytes and the heap commit
31698 size to 0x1000 bytes.
31700 @item using @option{-Wl} linker option
31703 $ gnatlink hello -Wl,--heap=0x1000000
31706 This sets the heap reserve size to 0x1000000 bytes. Note that with
31707 @option{-Wl} option it is not possible to set the heap commit size
31708 because the coma is a separator for this option.
31714 @c **********************************
31715 @c * GNU Free Documentation License *
31716 @c **********************************
31718 @c GNU Free Documentation License
31720 @node Index,,GNU Free Documentation License, Top
31726 @c Put table of contents at end, otherwise it precedes the "title page" in
31727 @c the .txt version
31728 @c Edit the pdf file to move the contents to the beginning, after the title