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
122 Permission is granted to copy, distribute and/or modify this document
123 under the terms of the GNU Free Documentation License, Version 1.2
124 or any later version published by the Free Software Foundation;
125 with the Invariant Sections being ``GNU Free Documentation License'', with the
126 Front-Cover Texts being
127 ``@value{EDITION} User's Guide'',
128 and with no Back-Cover Texts.
129 A copy of the license is included in the section entitled
130 ``GNU Free Documentation License''.
134 @title @value{EDITION} User's Guide
138 @titlefont{@i{@value{PLATFORM}}}
144 @subtitle GNAT, The GNU Ada Compiler
149 @vskip 0pt plus 1filll
156 @node Top, About This Guide, (dir), (dir)
157 @top @value{EDITION} User's Guide
160 @value{EDITION} User's Guide @value{PLATFORM}
163 GNAT, The GNU Ada Compiler@*
164 GCC version @value{version-GCC}@*
171 * Getting Started with GNAT::
172 * The GNAT Compilation Model::
173 * Compiling Using gcc::
174 * Binding Using gnatbind::
175 * Linking Using gnatlink::
176 * The GNAT Make Program gnatmake::
177 * Improving Performance::
178 * Renaming Files Using gnatchop::
179 * Configuration Pragmas::
180 * Handling Arbitrary File Naming Conventions Using gnatname::
181 * GNAT Project Manager::
182 * The Cross-Referencing Tools gnatxref and gnatfind::
183 * The GNAT Pretty-Printer gnatpp::
184 * The GNAT Metric Tool gnatmetric::
185 * File Name Krunching Using gnatkr::
186 * Preprocessing Using gnatprep::
188 * The GNAT Run-Time Library Builder gnatlbr::
190 * The GNAT Library Browser gnatls::
191 * Cleaning Up Using gnatclean::
193 * GNAT and Libraries::
194 * Using the GNU make Utility::
196 * Memory Management Issues::
197 * Stack Related Facilities::
198 * Verifying Properties Using gnatcheck::
199 * Creating Sample Bodies Using gnatstub::
200 * Other Utility Programs::
201 * Running and Debugging Ada Programs::
203 * Compatibility with HP Ada::
205 * Platform-Specific Information for the Run-Time Libraries::
206 * Example of Binder Output File::
207 * Elaboration Order Handling in GNAT::
208 * Conditional Compilation::
210 * Compatibility and Porting Guide::
212 * Microsoft Windows Topics::
214 * GNU Free Documentation License::
217 --- The Detailed Node Listing ---
221 * What This Guide Contains::
222 * What You Should Know before Reading This Guide::
223 * Related Information::
226 Getting Started with GNAT
229 * Running a Simple Ada Program::
230 * Running a Program with Multiple Units::
231 * Using the gnatmake Utility::
233 * Editing with Emacs::
236 * Introduction to GPS::
239 The GNAT Compilation Model
241 * Source Representation::
242 * Foreign Language Representation::
243 * File Naming Rules::
244 * Using Other File Names::
245 * Alternative File Naming Schemes::
246 * Generating Object Files::
247 * Source Dependencies::
248 * The Ada Library Information Files::
249 * Binding an Ada Program::
250 * Mixed Language Programming::
252 * Building Mixed Ada & C++ Programs::
253 * Comparison between GNAT and C/C++ Compilation Models::
255 * Comparison between GNAT and Conventional Ada Library Models::
257 * Placement of temporary files::
260 Foreign Language Representation
263 * Other 8-Bit Codes::
264 * Wide Character Encodings::
266 Compiling Ada Programs With gcc
268 * Compiling Programs::
270 * Search Paths and the Run-Time Library (RTL)::
271 * Order of Compilation Issues::
276 * Output and Error Message Control::
277 * Warning Message Control::
278 * Debugging and Assertion Control::
279 * Validity Checking::
282 * Using gcc for Syntax Checking::
283 * Using gcc for Semantic Checking::
284 * Compiling Different Versions of Ada::
285 * Character Set Control::
286 * File Naming Control::
287 * Subprogram Inlining Control::
288 * Auxiliary Output Control::
289 * Debugging Control::
290 * Exception Handling Control::
291 * Units to Sources Mapping Files::
292 * Integrated Preprocessing::
297 Binding Ada Programs With gnatbind
300 * Switches for gnatbind::
301 * Command-Line Access::
302 * Search Paths for gnatbind::
303 * Examples of gnatbind Usage::
305 Switches for gnatbind
307 * Consistency-Checking Modes::
308 * Binder Error Message Control::
309 * Elaboration Control::
311 * Binding with Non-Ada Main Programs::
312 * Binding Programs with No Main Subprogram::
314 Linking Using gnatlink
317 * Switches for gnatlink::
319 The GNAT Make Program gnatmake
322 * Switches for gnatmake::
323 * Mode Switches for gnatmake::
324 * Notes on the Command Line::
325 * How gnatmake Works::
326 * Examples of gnatmake Usage::
328 Improving Performance
329 * Performance Considerations::
330 * Reducing Size of Ada Executables with gnatelim::
331 * Reducing Size of Executables with unused subprogram/data elimination::
333 Performance Considerations
334 * Controlling Run-Time Checks::
335 * Use of Restrictions::
336 * Optimization Levels::
337 * Debugging Optimized Code::
338 * Inlining of Subprograms::
339 * Other Optimization Switches::
340 * Optimization and Strict Aliasing::
342 * Coverage Analysis::
345 Reducing Size of Ada Executables with gnatelim
348 * Correcting the List of Eliminate Pragmas::
349 * Making Your Executables Smaller::
350 * Summary of the gnatelim Usage Cycle::
352 Reducing Size of Executables with unused subprogram/data elimination
353 * About unused subprogram/data elimination::
354 * Compilation options::
356 Renaming Files Using gnatchop
358 * Handling Files with Multiple Units::
359 * Operating gnatchop in Compilation Mode::
360 * Command Line for gnatchop::
361 * Switches for gnatchop::
362 * Examples of gnatchop Usage::
364 Configuration Pragmas
366 * Handling of Configuration Pragmas::
367 * The Configuration Pragmas Files::
369 Handling Arbitrary File Naming Conventions Using gnatname
371 * Arbitrary File Naming Conventions::
373 * Switches for gnatname::
374 * Examples of gnatname Usage::
379 * Examples of Project Files::
380 * Project File Syntax::
381 * Objects and Sources in Project Files::
382 * Importing Projects::
383 * Project Extension::
384 * Project Hierarchy Extension::
385 * External References in Project Files::
386 * Packages in Project Files::
387 * Variables from Imported Projects::
390 * Stand-alone Library Projects::
391 * Switches Related to Project Files::
392 * Tools Supporting Project Files::
393 * An Extended Example::
394 * Project File Complete Syntax::
396 The Cross-Referencing Tools gnatxref and gnatfind
398 * gnatxref Switches::
399 * gnatfind Switches::
400 * Project Files for gnatxref and gnatfind::
401 * Regular Expressions in gnatfind and gnatxref::
402 * Examples of gnatxref Usage::
403 * Examples of gnatfind Usage::
405 The GNAT Pretty-Printer gnatpp
407 * Switches for gnatpp::
410 The GNAT Metrics Tool gnatmetric
412 * Switches for gnatmetric::
414 File Name Krunching Using gnatkr
419 * Examples of gnatkr Usage::
421 Preprocessing Using gnatprep
423 * Switches for gnatprep::
424 * Form of Definitions File::
425 * Form of Input Text for gnatprep::
428 The GNAT Run-Time Library Builder gnatlbr
431 * Switches for gnatlbr::
432 * Examples of gnatlbr Usage::
435 The GNAT Library Browser gnatls
438 * Switches for gnatls::
439 * Examples of gnatls Usage::
441 Cleaning Up Using gnatclean
443 * Running gnatclean::
444 * Switches for gnatclean::
445 @c * Examples of gnatclean Usage::
451 * Introduction to Libraries in GNAT::
452 * General Ada Libraries::
453 * Stand-alone Ada Libraries::
454 * Rebuilding the GNAT Run-Time Library::
456 Using the GNU make Utility
458 * Using gnatmake in a Makefile::
459 * Automatically Creating a List of Directories::
460 * Generating the Command Line Switches::
461 * Overcoming Command Line Length Limits::
464 Memory Management Issues
466 * Some Useful Memory Pools::
467 * The GNAT Debug Pool Facility::
472 Stack Related Facilities
474 * Stack Overflow Checking::
475 * Static Stack Usage Analysis::
476 * Dynamic Stack Usage Analysis::
478 Some Useful Memory Pools
480 The GNAT Debug Pool Facility
486 * Switches for gnatmem::
487 * Example of gnatmem Usage::
490 Verifying Properties Using gnatcheck
492 * Format of the Report File::
493 * General gnatcheck Switches::
494 * gnatcheck Rule Options::
495 * Adding the Results of Compiler Checks to gnatcheck Output::
496 * Project-Wide Checks::
499 Sample Bodies Using gnatstub
502 * Switches for gnatstub::
504 Other Utility Programs
506 * Using Other Utility Programs with GNAT::
507 * The External Symbol Naming Scheme of GNAT::
508 * Converting Ada Files to html with gnathtml::
510 Running and Debugging Ada Programs
512 * The GNAT Debugger GDB::
514 * Introduction to GDB Commands::
515 * Using Ada Expressions::
516 * Calling User-Defined Subprograms::
517 * Using the Next Command in a Function::
520 * Debugging Generic Units::
521 * GNAT Abnormal Termination or Failure to Terminate::
522 * Naming Conventions for GNAT Source Files::
523 * Getting Internal Debugging Information::
531 Compatibility with HP Ada
533 * Ada Language Compatibility::
534 * Differences in the Definition of Package System::
535 * Language-Related Features::
536 * The Package STANDARD::
537 * The Package SYSTEM::
538 * Tasking and Task-Related Features::
539 * Pragmas and Pragma-Related Features::
540 * Library of Predefined Units::
542 * Main Program Definition::
543 * Implementation-Defined Attributes::
544 * Compiler and Run-Time Interfacing::
545 * Program Compilation and Library Management::
547 * Implementation Limits::
548 * Tools and Utilities::
550 Language-Related Features
552 * Integer Types and Representations::
553 * Floating-Point Types and Representations::
554 * Pragmas Float_Representation and Long_Float::
555 * Fixed-Point Types and Representations::
556 * Record and Array Component Alignment::
558 * Other Representation Clauses::
560 Tasking and Task-Related Features
562 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
563 * Assigning Task IDs::
564 * Task IDs and Delays::
565 * Task-Related Pragmas::
566 * Scheduling and Task Priority::
568 * External Interrupts::
570 Pragmas and Pragma-Related Features
572 * Restrictions on the Pragma INLINE::
573 * Restrictions on the Pragma INTERFACE::
574 * Restrictions on the Pragma SYSTEM_NAME::
576 Library of Predefined Units
578 * Changes to DECLIB::
582 * Shared Libraries and Options Files::
586 Platform-Specific Information for the Run-Time Libraries
588 * Summary of Run-Time Configurations::
589 * Specifying a Run-Time Library::
590 * Choosing the Scheduling Policy::
591 * Solaris-Specific Considerations::
592 * Linux-Specific Considerations::
593 * AIX-Specific Considerations::
595 Example of Binder Output File
597 Elaboration Order Handling in GNAT
600 * Checking the Elaboration Order::
601 * Controlling the Elaboration Order::
602 * Controlling Elaboration in GNAT - Internal Calls::
603 * Controlling Elaboration in GNAT - External Calls::
604 * Default Behavior in GNAT - Ensuring Safety::
605 * Treatment of Pragma Elaborate::
606 * Elaboration Issues for Library Tasks::
607 * Mixing Elaboration Models::
608 * What to Do If the Default Elaboration Behavior Fails::
609 * Elaboration for Access-to-Subprogram Values::
610 * Summary of Procedures for Elaboration Control::
611 * Other Elaboration Order Considerations::
613 Conditional Compilation
614 * Use of Boolean Constants::
615 * Debugging - A Special Case::
616 * Conditionalizing Declarations::
617 * Use of Alternative Implementations::
622 * Basic Assembler Syntax::
623 * A Simple Example of Inline Assembler::
624 * Output Variables in Inline Assembler::
625 * Input Variables in Inline Assembler::
626 * Inlining Inline Assembler Code::
627 * Other Asm Functionality::
629 Compatibility and Porting Guide
631 * Compatibility with Ada 83::
632 * Compatibility between Ada 95 and Ada 2005::
633 * Implementation-dependent characteristics::
635 @c This brief section is only in the non-VMS version
636 @c The complete chapter on HP Ada issues is in the VMS version
637 * Compatibility with HP Ada 83::
639 * Compatibility with Other Ada Systems::
640 * Representation Clauses::
642 * Transitioning to 64-Bit GNAT for OpenVMS::
646 Microsoft Windows Topics
648 * Using GNAT on Windows::
649 * CONSOLE and WINDOWS subsystems::
651 * Mixed-Language Programming on Windows::
652 * Windows Calling Conventions::
653 * Introduction to Dynamic Link Libraries (DLLs)::
654 * Using DLLs with GNAT::
655 * Building DLLs with GNAT::
656 * GNAT and Windows Resources::
658 * Setting Stack Size from gnatlink::
659 * Setting Heap Size from gnatlink::
666 @node About This Guide
667 @unnumbered About This Guide
671 This guide describes the use of @value{EDITION},
672 a compiler and software development toolset for the full Ada
673 programming language, implemented on OpenVMS for HP's Alpha and
674 Integrity server (I64) platforms.
677 This guide describes the use of @value{EDITION},
678 a compiler and software development
679 toolset for the full Ada programming language.
681 It documents the features of the compiler and tools, and explains
682 how to use them to build Ada applications.
684 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
685 Ada 83 compatibility mode.
686 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
687 but you can override with a compiler switch
688 (@pxref{Compiling Different Versions of Ada})
689 to explicitly specify the language version.
690 Throughout this manual, references to ``Ada'' without a year suffix
691 apply to both the Ada 95 and Ada 2005 versions of the language.
695 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
696 ``GNAT'' in the remainder of this document.
703 * What This Guide Contains::
704 * What You Should Know before Reading This Guide::
705 * Related Information::
709 @node What This Guide Contains
710 @unnumberedsec What This Guide Contains
713 This guide contains the following chapters:
717 @ref{Getting Started with GNAT}, describes how to get started compiling
718 and running Ada programs with the GNAT Ada programming environment.
720 @ref{The GNAT Compilation Model}, describes the compilation model used
724 @ref{Compiling Using gcc}, describes how to compile
725 Ada programs with @command{gcc}, the Ada compiler.
728 @ref{Binding Using gnatbind}, describes how to
729 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
733 @ref{Linking Using gnatlink},
734 describes @command{gnatlink}, a
735 program that provides for linking using the GNAT run-time library to
736 construct a program. @command{gnatlink} can also incorporate foreign language
737 object units into the executable.
740 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
741 utility that automatically determines the set of sources
742 needed by an Ada compilation unit, and executes the necessary compilations
746 @ref{Improving Performance}, shows various techniques for making your
747 Ada program run faster or take less space.
748 It discusses the effect of the compiler's optimization switch and
749 also describes the @command{gnatelim} tool and unused subprogram/data
753 @ref{Renaming Files Using gnatchop}, describes
754 @code{gnatchop}, a utility that allows you to preprocess a file that
755 contains Ada source code, and split it into one or more new files, one
756 for each compilation unit.
759 @ref{Configuration Pragmas}, describes the configuration pragmas
763 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
764 shows how to override the default GNAT file naming conventions,
765 either for an individual unit or globally.
768 @ref{GNAT Project Manager}, describes how to use project files
769 to organize large projects.
772 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
773 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
774 way to navigate through sources.
777 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
778 version of an Ada source file with control over casing, indentation,
779 comment placement, and other elements of program presentation style.
782 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
783 metrics for an Ada source file, such as the number of types and subprograms,
784 and assorted complexity measures.
787 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
788 file name krunching utility, used to handle shortened
789 file names on operating systems with a limit on the length of names.
792 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
793 preprocessor utility that allows a single source file to be used to
794 generate multiple or parameterized source files by means of macro
799 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
800 a tool for rebuilding the GNAT run time with user-supplied
801 configuration pragmas.
805 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
806 utility that displays information about compiled units, including dependences
807 on the corresponding sources files, and consistency of compilations.
810 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
811 to delete files that are produced by the compiler, binder and linker.
815 @ref{GNAT and Libraries}, describes the process of creating and using
816 Libraries with GNAT. It also describes how to recompile the GNAT run-time
820 @ref{Using the GNU make Utility}, describes some techniques for using
821 the GNAT toolset in Makefiles.
825 @ref{Memory Management Issues}, describes some useful predefined storage pools
826 and in particular the GNAT Debug Pool facility, which helps detect incorrect
829 It also describes @command{gnatmem}, a utility that monitors dynamic
830 allocation and deallocation and helps detect ``memory leaks''.
834 @ref{Stack Related Facilities}, describes some useful tools associated with
835 stack checking and analysis.
838 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
839 a utility that checks Ada code against a set of rules.
842 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
843 a utility that generates empty but compilable bodies for library units.
846 @ref{Other Utility Programs}, discusses several other GNAT utilities,
847 including @code{gnathtml}.
850 @ref{Running and Debugging Ada Programs}, describes how to run and debug
855 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
856 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
857 developed by Digital Equipment Corporation and currently supported by HP.}
858 for OpenVMS Alpha. This product was formerly known as DEC Ada,
861 historical compatibility reasons, the relevant libraries still use the
866 @ref{Platform-Specific Information for the Run-Time Libraries},
867 describes the various run-time
868 libraries supported by GNAT on various platforms and explains how to
869 choose a particular library.
872 @ref{Example of Binder Output File}, shows the source code for the binder
873 output file for a sample program.
876 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
877 you deal with elaboration order issues.
880 @ref{Conditional Compilation}, describes how to model conditional compilation,
881 both with Ada in general and with GNAT facilities in particular.
884 @ref{Inline Assembler}, shows how to use the inline assembly facility
888 @ref{Compatibility and Porting Guide}, contains sections on compatibility
889 of GNAT with other Ada development environments (including Ada 83 systems),
890 to assist in porting code from those environments.
894 @ref{Microsoft Windows Topics}, presents information relevant to the
895 Microsoft Windows platform.
899 @c *************************************************
900 @node What You Should Know before Reading This Guide
901 @c *************************************************
902 @unnumberedsec What You Should Know before Reading This Guide
904 @cindex Ada 95 Language Reference Manual
905 @cindex Ada 2005 Language Reference Manual
907 This guide assumes a basic familiarity with the Ada 95 language, as
908 described in the International Standard ANSI/ISO/IEC-8652:1995, January
910 It does not require knowledge of the new features introduced by Ada 2005,
911 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
913 Both reference manuals are included in the GNAT documentation
916 @node Related Information
917 @unnumberedsec Related Information
920 For further information about related tools, refer to the following
925 @cite{GNAT Reference Manual}, which contains all reference
926 material for the GNAT implementation of Ada.
930 @cite{Using the GNAT Programming Studio}, which describes the GPS
931 Integrated Development Environment.
934 @cite{GNAT Programming Studio Tutorial}, which introduces the
935 main GPS features through examples.
939 @cite{Ada 95 Reference Manual}, which contains reference
940 material for the Ada 95 programming language.
943 @cite{Ada 2005 Reference Manual}, which contains reference
944 material for the Ada 2005 programming language.
947 @cite{Debugging with GDB}
949 , located in the GNU:[DOCS] directory,
951 contains all details on the use of the GNU source-level debugger.
954 @cite{GNU Emacs Manual}
956 , located in the GNU:[DOCS] directory if the EMACS kit is installed,
958 contains full information on the extensible editor and programming
965 @unnumberedsec Conventions
967 @cindex Typographical conventions
970 Following are examples of the typographical and graphic conventions used
975 @code{Functions}, @code{utility program names}, @code{standard names},
982 @file{File Names}, @file{button names}, and @file{field names}.
991 [optional information or parameters]
994 Examples are described by text
996 and then shown this way.
1001 Commands that are entered by the user are preceded in this manual by the
1002 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1003 uses this sequence as a prompt, then the commands will appear exactly as
1004 you see them in the manual. If your system uses some other prompt, then
1005 the command will appear with the @code{$} replaced by whatever prompt
1006 character you are using.
1009 Full file names are shown with the ``@code{/}'' character
1010 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1011 If you are using GNAT on a Windows platform, please note that
1012 the ``@code{\}'' character should be used instead.
1015 @c ****************************
1016 @node Getting Started with GNAT
1017 @chapter Getting Started with GNAT
1020 This chapter describes some simple ways of using GNAT to build
1021 executable Ada programs.
1023 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1024 show how to use the command line environment.
1025 @ref{Introduction to GPS}, provides a brief
1026 introduction to the GNAT Programming Studio, a visually-oriented
1027 Integrated Development Environment for GNAT.
1028 GPS offers a graphical ``look and feel'', support for development in
1029 other programming languages, comprehensive browsing features, and
1030 many other capabilities.
1031 For information on GPS please refer to
1032 @cite{Using the GNAT Programming Studio}.
1037 * Running a Simple Ada Program::
1038 * Running a Program with Multiple Units::
1039 * Using the gnatmake Utility::
1041 * Editing with Emacs::
1044 * Introduction to GPS::
1049 @section Running GNAT
1052 Three steps are needed to create an executable file from an Ada source
1057 The source file(s) must be compiled.
1059 The file(s) must be bound using the GNAT binder.
1061 All appropriate object files must be linked to produce an executable.
1065 All three steps are most commonly handled by using the @command{gnatmake}
1066 utility program that, given the name of the main program, automatically
1067 performs the necessary compilation, binding and linking steps.
1069 @node Running a Simple Ada Program
1070 @section Running a Simple Ada Program
1073 Any text editor may be used to prepare an Ada program.
1075 used, the optional Ada mode may be helpful in laying out the program.)
1077 program text is a normal text file. We will assume in our initial
1078 example that you have used your editor to prepare the following
1079 standard format text file:
1081 @smallexample @c ada
1083 with Ada.Text_IO; use Ada.Text_IO;
1086 Put_Line ("Hello WORLD!");
1092 This file should be named @file{hello.adb}.
1093 With the normal default file naming conventions, GNAT requires
1095 contain a single compilation unit whose file name is the
1097 with periods replaced by hyphens; the
1098 extension is @file{ads} for a
1099 spec and @file{adb} for a body.
1100 You can override this default file naming convention by use of the
1101 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1102 Alternatively, if you want to rename your files according to this default
1103 convention, which is probably more convenient if you will be using GNAT
1104 for all your compilations, then the @code{gnatchop} utility
1105 can be used to generate correctly-named source files
1106 (@pxref{Renaming Files Using gnatchop}).
1108 You can compile the program using the following command (@code{$} is used
1109 as the command prompt in the examples in this document):
1116 @command{gcc} is the command used to run the compiler. This compiler is
1117 capable of compiling programs in several languages, including Ada and
1118 C. It assumes that you have given it an Ada program if the file extension is
1119 either @file{.ads} or @file{.adb}, and it will then call
1120 the GNAT compiler to compile the specified file.
1123 The @option{-c} switch is required. It tells @command{gcc} to only do a
1124 compilation. (For C programs, @command{gcc} can also do linking, but this
1125 capability is not used directly for Ada programs, so the @option{-c}
1126 switch must always be present.)
1129 This compile command generates a file
1130 @file{hello.o}, which is the object
1131 file corresponding to your Ada program. It also generates
1132 an ``Ada Library Information'' file @file{hello.ali},
1133 which contains additional information used to check
1134 that an Ada program is consistent.
1135 To build an executable file,
1136 use @code{gnatbind} to bind the program
1137 and @command{gnatlink} to link it. The
1138 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1139 @file{ALI} file, but the default extension of @file{.ali} can
1140 be omitted. This means that in the most common case, the argument
1141 is simply the name of the main program:
1149 A simpler method of carrying out these steps is to use
1151 a master program that invokes all the required
1152 compilation, binding and linking tools in the correct order. In particular,
1153 @command{gnatmake} automatically recompiles any sources that have been
1154 modified since they were last compiled, or sources that depend
1155 on such modified sources, so that ``version skew'' is avoided.
1156 @cindex Version skew (avoided by @command{gnatmake})
1159 $ gnatmake hello.adb
1163 The result is an executable program called @file{hello}, which can be
1171 assuming that the current directory is on the search path
1172 for executable programs.
1175 and, if all has gone well, you will see
1182 appear in response to this command.
1184 @c ****************************************
1185 @node Running a Program with Multiple Units
1186 @section Running a Program with Multiple Units
1189 Consider a slightly more complicated example that has three files: a
1190 main program, and the spec and body of a package:
1192 @smallexample @c ada
1195 package Greetings is
1200 with Ada.Text_IO; use Ada.Text_IO;
1201 package body Greetings is
1204 Put_Line ("Hello WORLD!");
1207 procedure Goodbye is
1209 Put_Line ("Goodbye WORLD!");
1226 Following the one-unit-per-file rule, place this program in the
1227 following three separate files:
1231 spec of package @code{Greetings}
1234 body of package @code{Greetings}
1237 body of main program
1241 To build an executable version of
1242 this program, we could use four separate steps to compile, bind, and link
1243 the program, as follows:
1247 $ gcc -c greetings.adb
1253 Note that there is no required order of compilation when using GNAT.
1254 In particular it is perfectly fine to compile the main program first.
1255 Also, it is not necessary to compile package specs in the case where
1256 there is an accompanying body; you only need to compile the body. If you want
1257 to submit these files to the compiler for semantic checking and not code
1258 generation, then use the
1259 @option{-gnatc} switch:
1262 $ gcc -c greetings.ads -gnatc
1266 Although the compilation can be done in separate steps as in the
1267 above example, in practice it is almost always more convenient
1268 to use the @command{gnatmake} tool. All you need to know in this case
1269 is the name of the main program's source file. The effect of the above four
1270 commands can be achieved with a single one:
1273 $ gnatmake gmain.adb
1277 In the next section we discuss the advantages of using @command{gnatmake} in
1280 @c *****************************
1281 @node Using the gnatmake Utility
1282 @section Using the @command{gnatmake} Utility
1285 If you work on a program by compiling single components at a time using
1286 @command{gcc}, you typically keep track of the units you modify. In order to
1287 build a consistent system, you compile not only these units, but also any
1288 units that depend on the units you have modified.
1289 For example, in the preceding case,
1290 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1291 you edit @file{greetings.ads}, you must recompile both
1292 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1293 units that depend on @file{greetings.ads}.
1295 @code{gnatbind} will warn you if you forget one of these compilation
1296 steps, so that it is impossible to generate an inconsistent program as a
1297 result of forgetting to do a compilation. Nevertheless it is tedious and
1298 error-prone to keep track of dependencies among units.
1299 One approach to handle the dependency-bookkeeping is to use a
1300 makefile. However, makefiles present maintenance problems of their own:
1301 if the dependencies change as you change the program, you must make
1302 sure that the makefile is kept up-to-date manually, which is also an
1303 error-prone process.
1305 The @command{gnatmake} utility takes care of these details automatically.
1306 Invoke it using either one of the following forms:
1309 $ gnatmake gmain.adb
1310 $ gnatmake ^gmain^GMAIN^
1314 The argument is the name of the file containing the main program;
1315 you may omit the extension. @command{gnatmake}
1316 examines the environment, automatically recompiles any files that need
1317 recompiling, and binds and links the resulting set of object files,
1318 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1319 In a large program, it
1320 can be extremely helpful to use @command{gnatmake}, because working out by hand
1321 what needs to be recompiled can be difficult.
1323 Note that @command{gnatmake}
1324 takes into account all the Ada rules that
1325 establish dependencies among units. These include dependencies that result
1326 from inlining subprogram bodies, and from
1327 generic instantiation. Unlike some other
1328 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1329 found by the compiler on a previous compilation, which may possibly
1330 be wrong when sources change. @command{gnatmake} determines the exact set of
1331 dependencies from scratch each time it is run.
1334 @node Editing with Emacs
1335 @section Editing with Emacs
1339 Emacs is an extensible self-documenting text editor that is available in a
1340 separate VMSINSTAL kit.
1342 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1343 click on the Emacs Help menu and run the Emacs Tutorial.
1344 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1345 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1347 Documentation on Emacs and other tools is available in Emacs under the
1348 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1349 use the middle mouse button to select a topic (e.g. Emacs).
1351 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1352 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1353 get to the Emacs manual.
1354 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1357 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1358 which is sufficiently extensible to provide for a complete programming
1359 environment and shell for the sophisticated user.
1363 @node Introduction to GPS
1364 @section Introduction to GPS
1365 @cindex GPS (GNAT Programming Studio)
1366 @cindex GNAT Programming Studio (GPS)
1368 Although the command line interface (@command{gnatmake}, etc.) alone
1369 is sufficient, a graphical Interactive Development
1370 Environment can make it easier for you to compose, navigate, and debug
1371 programs. This section describes the main features of GPS
1372 (``GNAT Programming Studio''), the GNAT graphical IDE.
1373 You will see how to use GPS to build and debug an executable, and
1374 you will also learn some of the basics of the GNAT ``project'' facility.
1376 GPS enables you to do much more than is presented here;
1377 e.g., you can produce a call graph, interface to a third-party
1378 Version Control System, and inspect the generated assembly language
1380 Indeed, GPS also supports languages other than Ada.
1381 Such additional information, and an explanation of all of the GPS menu
1382 items. may be found in the on-line help, which includes
1383 a user's guide and a tutorial (these are also accessible from the GNAT
1387 * Building a New Program with GPS::
1388 * Simple Debugging with GPS::
1391 @node Building a New Program with GPS
1392 @subsection Building a New Program with GPS
1394 GPS invokes the GNAT compilation tools using information
1395 contained in a @emph{project} (also known as a @emph{project file}):
1396 a collection of properties such
1397 as source directories, identities of main subprograms, tool switches, etc.,
1398 and their associated values.
1399 See @ref{GNAT Project Manager} for details.
1400 In order to run GPS, you will need to either create a new project
1401 or else open an existing one.
1403 This section will explain how you can use GPS to create a project,
1404 to associate Ada source files with a project, and to build and run
1408 @item @emph{Creating a project}
1410 Invoke GPS, either from the command line or the platform's IDE.
1411 After it starts, GPS will display a ``Welcome'' screen with three
1416 @code{Start with default project in directory}
1419 @code{Create new project with wizard}
1422 @code{Open existing project}
1426 Select @code{Create new project with wizard} and press @code{OK}.
1427 A new window will appear. In the text box labeled with
1428 @code{Enter the name of the project to create}, type @file{sample}
1429 as the project name.
1430 In the next box, browse to choose the directory in which you
1431 would like to create the project file.
1432 After selecting an appropriate directory, press @code{Forward}.
1434 A window will appear with the title
1435 @code{Version Control System Configuration}.
1436 Simply press @code{Forward}.
1438 A window will appear with the title
1439 @code{Please select the source directories for this project}.
1440 The directory that you specified for the project file will be selected
1441 by default as the one to use for sources; simply press @code{Forward}.
1443 A window will appear with the title
1444 @code{Please select the build directory for this project}.
1445 The directory that you specified for the project file will be selected
1446 by default for object files and executables;
1447 simply press @code{Forward}.
1449 A window will appear with the title
1450 @code{Please select the main units for this project}.
1451 You will supply this information later, after creating the source file.
1452 Simply press @code{Forward} for now.
1454 A window will appear with the title
1455 @code{Please select the switches to build the project}.
1456 Press @code{Apply}. This will create a project file named
1457 @file{sample.prj} in the directory that you had specified.
1459 @item @emph{Creating and saving the source file}
1461 After you create the new project, a GPS window will appear, which is
1462 partitioned into two main sections:
1466 A @emph{Workspace area}, initially greyed out, which you will use for
1467 creating and editing source files
1470 Directly below, a @emph{Messages area}, which initially displays a
1471 ``Welcome'' message.
1472 (If the Messages area is not visible, drag its border upward to expand it.)
1476 Select @code{File} on the menu bar, and then the @code{New} command.
1477 The Workspace area will become white, and you can now
1478 enter the source program explicitly.
1479 Type the following text
1481 @smallexample @c ada
1483 with Ada.Text_IO; use Ada.Text_IO;
1486 Put_Line("Hello from GPS!");
1492 Select @code{File}, then @code{Save As}, and enter the source file name
1494 The file will be saved in the same directory you specified as the
1495 location of the default project file.
1497 @item @emph{Updating the project file}
1499 You need to add the new source file to the project.
1501 the @code{Project} menu and then @code{Edit project properties}.
1502 Click the @code{Main files} tab on the left, and then the
1504 Choose @file{hello.adb} from the list, and press @code{Open}.
1505 The project settings window will reflect this action.
1508 @item @emph{Building and running the program}
1510 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1511 and select @file{hello.adb}.
1512 The Messages window will display the resulting invocations of @command{gcc},
1513 @command{gnatbind}, and @command{gnatlink}
1514 (reflecting the default switch settings from the
1515 project file that you created) and then a ``successful compilation/build''
1518 To run the program, choose the @code{Build} menu, then @code{Run}, and
1519 select @command{hello}.
1520 An @emph{Arguments Selection} window will appear.
1521 There are no command line arguments, so just click @code{OK}.
1523 The Messages window will now display the program's output (the string
1524 @code{Hello from GPS}), and at the bottom of the GPS window a status
1525 update is displayed (@code{Run: hello}).
1526 Close the GPS window (or select @code{File}, then @code{Exit}) to
1527 terminate this GPS session.
1530 @node Simple Debugging with GPS
1531 @subsection Simple Debugging with GPS
1533 This section illustrates basic debugging techniques (setting breakpoints,
1534 examining/modifying variables, single stepping).
1537 @item @emph{Opening a project}
1539 Start GPS and select @code{Open existing project}; browse to
1540 specify the project file @file{sample.prj} that you had created in the
1543 @item @emph{Creating a source file}
1545 Select @code{File}, then @code{New}, and type in the following program:
1547 @smallexample @c ada
1549 with Ada.Text_IO; use Ada.Text_IO;
1550 procedure Example is
1551 Line : String (1..80);
1554 Put_Line("Type a line of text at each prompt; an empty line to exit");
1558 Put_Line (Line (1..N) );
1566 Select @code{File}, then @code{Save as}, and enter the file name
1569 @item @emph{Updating the project file}
1571 Add @code{Example} as a new main unit for the project:
1574 Select @code{Project}, then @code{Edit Project Properties}.
1577 Select the @code{Main files} tab, click @code{Add}, then
1578 select the file @file{example.adb} from the list, and
1580 You will see the file name appear in the list of main units
1586 @item @emph{Building/running the executable}
1588 To build the executable
1589 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1591 Run the program to see its effect (in the Messages area).
1592 Each line that you enter is displayed; an empty line will
1593 cause the loop to exit and the program to terminate.
1595 @item @emph{Debugging the program}
1597 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1598 which are required for debugging, are on by default when you create
1600 Thus unless you intentionally remove these settings, you will be able
1601 to debug any program that you develop using GPS.
1604 @item @emph{Initializing}
1606 Select @code{Debug}, then @code{Initialize}, then @file{example}
1608 @item @emph{Setting a breakpoint}
1610 After performing the initialization step, you will observe a small
1611 icon to the right of each line number.
1612 This serves as a toggle for breakpoints; clicking the icon will
1613 set a breakpoint at the corresponding line (the icon will change to
1614 a red circle with an ``x''), and clicking it again
1615 will remove the breakpoint / reset the icon.
1617 For purposes of this example, set a breakpoint at line 10 (the
1618 statement @code{Put_Line@ (Line@ (1..N));}
1620 @item @emph{Starting program execution}
1622 Select @code{Debug}, then @code{Run}. When the
1623 @code{Program Arguments} window appears, click @code{OK}.
1624 A console window will appear; enter some line of text,
1625 e.g. @code{abcde}, at the prompt.
1626 The program will pause execution when it gets to the
1627 breakpoint, and the corresponding line is highlighted.
1629 @item @emph{Examining a variable}
1631 Move the mouse over one of the occurrences of the variable @code{N}.
1632 You will see the value (5) displayed, in ``tool tip'' fashion.
1633 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1634 You will see information about @code{N} appear in the @code{Debugger Data}
1635 pane, showing the value as 5.
1637 @item @emph{Assigning a new value to a variable}
1639 Right click on the @code{N} in the @code{Debugger Data} pane, and
1640 select @code{Set value of N}.
1641 When the input window appears, enter the value @code{4} and click
1643 This value does not automatically appear in the @code{Debugger Data}
1644 pane; to see it, right click again on the @code{N} in the
1645 @code{Debugger Data} pane and select @code{Update value}.
1646 The new value, 4, will appear in red.
1648 @item @emph{Single stepping}
1650 Select @code{Debug}, then @code{Next}.
1651 This will cause the next statement to be executed, in this case the
1652 call of @code{Put_Line} with the string slice.
1653 Notice in the console window that the displayed string is simply
1654 @code{abcd} and not @code{abcde} which you had entered.
1655 This is because the upper bound of the slice is now 4 rather than 5.
1657 @item @emph{Removing a breakpoint}
1659 Toggle the breakpoint icon at line 10.
1661 @item @emph{Resuming execution from a breakpoint}
1663 Select @code{Debug}, then @code{Continue}.
1664 The program will reach the next iteration of the loop, and
1665 wait for input after displaying the prompt.
1666 This time, just hit the @kbd{Enter} key.
1667 The value of @code{N} will be 0, and the program will terminate.
1668 The console window will disappear.
1673 @node The GNAT Compilation Model
1674 @chapter The GNAT Compilation Model
1675 @cindex GNAT compilation model
1676 @cindex Compilation model
1679 * Source Representation::
1680 * Foreign Language Representation::
1681 * File Naming Rules::
1682 * Using Other File Names::
1683 * Alternative File Naming Schemes::
1684 * Generating Object Files::
1685 * Source Dependencies::
1686 * The Ada Library Information Files::
1687 * Binding an Ada Program::
1688 * Mixed Language Programming::
1690 * Building Mixed Ada & C++ Programs::
1691 * Comparison between GNAT and C/C++ Compilation Models::
1693 * Comparison between GNAT and Conventional Ada Library Models::
1695 * Placement of temporary files::
1700 This chapter describes the compilation model used by GNAT. Although
1701 similar to that used by other languages, such as C and C++, this model
1702 is substantially different from the traditional Ada compilation models,
1703 which are based on a library. The model is initially described without
1704 reference to the library-based model. If you have not previously used an
1705 Ada compiler, you need only read the first part of this chapter. The
1706 last section describes and discusses the differences between the GNAT
1707 model and the traditional Ada compiler models. If you have used other
1708 Ada compilers, this section will help you to understand those
1709 differences, and the advantages of the GNAT model.
1711 @node Source Representation
1712 @section Source Representation
1716 Ada source programs are represented in standard text files, using
1717 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1718 7-bit ASCII set, plus additional characters used for
1719 representing foreign languages (@pxref{Foreign Language Representation}
1720 for support of non-USA character sets). The format effector characters
1721 are represented using their standard ASCII encodings, as follows:
1726 Vertical tab, @code{16#0B#}
1730 Horizontal tab, @code{16#09#}
1734 Carriage return, @code{16#0D#}
1738 Line feed, @code{16#0A#}
1742 Form feed, @code{16#0C#}
1746 Source files are in standard text file format. In addition, GNAT will
1747 recognize a wide variety of stream formats, in which the end of
1748 physical lines is marked by any of the following sequences:
1749 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1750 in accommodating files that are imported from other operating systems.
1752 @cindex End of source file
1753 @cindex Source file, end
1755 The end of a source file is normally represented by the physical end of
1756 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1757 recognized as signalling the end of the source file. Again, this is
1758 provided for compatibility with other operating systems where this
1759 code is used to represent the end of file.
1761 Each file contains a single Ada compilation unit, including any pragmas
1762 associated with the unit. For example, this means you must place a
1763 package declaration (a package @dfn{spec}) and the corresponding body in
1764 separate files. An Ada @dfn{compilation} (which is a sequence of
1765 compilation units) is represented using a sequence of files. Similarly,
1766 you will place each subunit or child unit in a separate file.
1768 @node Foreign Language Representation
1769 @section Foreign Language Representation
1772 GNAT supports the standard character sets defined in Ada as well as
1773 several other non-standard character sets for use in localized versions
1774 of the compiler (@pxref{Character Set Control}).
1777 * Other 8-Bit Codes::
1778 * Wide Character Encodings::
1786 The basic character set is Latin-1. This character set is defined by ISO
1787 standard 8859, part 1. The lower half (character codes @code{16#00#}
1788 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1789 is used to represent additional characters. These include extended letters
1790 used by European languages, such as French accents, the vowels with umlauts
1791 used in German, and the extra letter A-ring used in Swedish.
1793 @findex Ada.Characters.Latin_1
1794 For a complete list of Latin-1 codes and their encodings, see the source
1795 file of library unit @code{Ada.Characters.Latin_1} in file
1796 @file{a-chlat1.ads}.
1797 You may use any of these extended characters freely in character or
1798 string literals. In addition, the extended characters that represent
1799 letters can be used in identifiers.
1801 @node Other 8-Bit Codes
1802 @subsection Other 8-Bit Codes
1805 GNAT also supports several other 8-bit coding schemes:
1808 @item ISO 8859-2 (Latin-2)
1811 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1814 @item ISO 8859-3 (Latin-3)
1817 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1820 @item ISO 8859-4 (Latin-4)
1823 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1826 @item ISO 8859-5 (Cyrillic)
1829 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1830 lowercase equivalence.
1832 @item ISO 8859-15 (Latin-9)
1835 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1836 lowercase equivalence
1838 @item IBM PC (code page 437)
1839 @cindex code page 437
1840 This code page is the normal default for PCs in the U.S. It corresponds
1841 to the original IBM PC character set. This set has some, but not all, of
1842 the extended Latin-1 letters, but these letters do not have the same
1843 encoding as Latin-1. In this mode, these letters are allowed in
1844 identifiers with uppercase and lowercase equivalence.
1846 @item IBM PC (code page 850)
1847 @cindex code page 850
1848 This code page is a modification of 437 extended to include all the
1849 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1850 mode, all these letters are allowed in identifiers with uppercase and
1851 lowercase equivalence.
1853 @item Full Upper 8-bit
1854 Any character in the range 80-FF allowed in identifiers, and all are
1855 considered distinct. In other words, there are no uppercase and lowercase
1856 equivalences in this range. This is useful in conjunction with
1857 certain encoding schemes used for some foreign character sets (e.g.
1858 the typical method of representing Chinese characters on the PC).
1861 No upper-half characters in the range 80-FF are allowed in identifiers.
1862 This gives Ada 83 compatibility for identifier names.
1866 For precise data on the encodings permitted, and the uppercase and lowercase
1867 equivalences that are recognized, see the file @file{csets.adb} in
1868 the GNAT compiler sources. You will need to obtain a full source release
1869 of GNAT to obtain this file.
1871 @node Wide Character Encodings
1872 @subsection Wide Character Encodings
1875 GNAT allows wide character codes to appear in character and string
1876 literals, and also optionally in identifiers, by means of the following
1877 possible encoding schemes:
1882 In this encoding, a wide character is represented by the following five
1890 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1891 characters (using uppercase letters) of the wide character code. For
1892 example, ESC A345 is used to represent the wide character with code
1894 This scheme is compatible with use of the full Wide_Character set.
1896 @item Upper-Half Coding
1897 @cindex Upper-Half Coding
1898 The wide character with encoding @code{16#abcd#} where the upper bit is on
1899 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1900 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1901 character, but is not required to be in the upper half. This method can
1902 be also used for shift-JIS or EUC, where the internal coding matches the
1905 @item Shift JIS Coding
1906 @cindex Shift JIS Coding
1907 A wide character is represented by a two-character sequence,
1909 @code{16#cd#}, with the restrictions described for upper-half encoding as
1910 described above. The internal character code is the corresponding JIS
1911 character according to the standard algorithm for Shift-JIS
1912 conversion. Only characters defined in the JIS code set table can be
1913 used with this encoding method.
1917 A wide character is represented by a two-character sequence
1919 @code{16#cd#}, with both characters being in the upper half. The internal
1920 character code is the corresponding JIS character according to the EUC
1921 encoding algorithm. Only characters defined in the JIS code set table
1922 can be used with this encoding method.
1925 A wide character is represented using
1926 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1927 10646-1/Am.2. Depending on the character value, the representation
1928 is a one, two, or three byte sequence:
1933 16#0000#-16#007f#: 2#0xxxxxxx#
1934 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
1935 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
1940 where the xxx bits correspond to the left-padded bits of the
1941 16-bit character value. Note that all lower half ASCII characters
1942 are represented as ASCII bytes and all upper half characters and
1943 other wide characters are represented as sequences of upper-half
1944 (The full UTF-8 scheme allows for encoding 31-bit characters as
1945 6-byte sequences, but in this implementation, all UTF-8 sequences
1946 of four or more bytes length will be treated as illegal).
1947 @item Brackets Coding
1948 In this encoding, a wide character is represented by the following eight
1956 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1957 characters (using uppercase letters) of the wide character code. For
1958 example, [``A345''] is used to represent the wide character with code
1959 @code{16#A345#}. It is also possible (though not required) to use the
1960 Brackets coding for upper half characters. For example, the code
1961 @code{16#A3#} can be represented as @code{[``A3'']}.
1963 This scheme is compatible with use of the full Wide_Character set,
1964 and is also the method used for wide character encoding in the standard
1965 ACVC (Ada Compiler Validation Capability) test suite distributions.
1970 Note: Some of these coding schemes do not permit the full use of the
1971 Ada character set. For example, neither Shift JIS, nor EUC allow the
1972 use of the upper half of the Latin-1 set.
1974 @node File Naming Rules
1975 @section File Naming Rules
1978 The default file name is determined by the name of the unit that the
1979 file contains. The name is formed by taking the full expanded name of
1980 the unit and replacing the separating dots with hyphens and using
1981 ^lowercase^uppercase^ for all letters.
1983 An exception arises if the file name generated by the above rules starts
1984 with one of the characters
1991 and the second character is a
1992 minus. In this case, the character ^tilde^dollar sign^ is used in place
1993 of the minus. The reason for this special rule is to avoid clashes with
1994 the standard names for child units of the packages System, Ada,
1995 Interfaces, and GNAT, which use the prefixes
2004 The file extension is @file{.ads} for a spec and
2005 @file{.adb} for a body. The following list shows some
2006 examples of these rules.
2013 @item arith_functions.ads
2014 Arith_Functions (package spec)
2015 @item arith_functions.adb
2016 Arith_Functions (package body)
2018 Func.Spec (child package spec)
2020 Func.Spec (child package body)
2022 Sub (subunit of Main)
2023 @item ^a~bad.adb^A$BAD.ADB^
2024 A.Bad (child package body)
2028 Following these rules can result in excessively long
2029 file names if corresponding
2030 unit names are long (for example, if child units or subunits are
2031 heavily nested). An option is available to shorten such long file names
2032 (called file name ``krunching''). This may be particularly useful when
2033 programs being developed with GNAT are to be used on operating systems
2034 with limited file name lengths. @xref{Using gnatkr}.
2036 Of course, no file shortening algorithm can guarantee uniqueness over
2037 all possible unit names; if file name krunching is used, it is your
2038 responsibility to ensure no name clashes occur. Alternatively you
2039 can specify the exact file names that you want used, as described
2040 in the next section. Finally, if your Ada programs are migrating from a
2041 compiler with a different naming convention, you can use the gnatchop
2042 utility to produce source files that follow the GNAT naming conventions.
2043 (For details @pxref{Renaming Files Using gnatchop}.)
2045 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2046 systems, case is not significant. So for example on @code{Windows XP}
2047 if the canonical name is @code{main-sub.adb}, you can use the file name
2048 @code{Main-Sub.adb} instead. However, case is significant for other
2049 operating systems, so for example, if you want to use other than
2050 canonically cased file names on a Unix system, you need to follow
2051 the procedures described in the next section.
2053 @node Using Other File Names
2054 @section Using Other File Names
2058 In the previous section, we have described the default rules used by
2059 GNAT to determine the file name in which a given unit resides. It is
2060 often convenient to follow these default rules, and if you follow them,
2061 the compiler knows without being explicitly told where to find all
2064 However, in some cases, particularly when a program is imported from
2065 another Ada compiler environment, it may be more convenient for the
2066 programmer to specify which file names contain which units. GNAT allows
2067 arbitrary file names to be used by means of the Source_File_Name pragma.
2068 The form of this pragma is as shown in the following examples:
2069 @cindex Source_File_Name pragma
2071 @smallexample @c ada
2073 pragma Source_File_Name (My_Utilities.Stacks,
2074 Spec_File_Name => "myutilst_a.ada");
2075 pragma Source_File_name (My_Utilities.Stacks,
2076 Body_File_Name => "myutilst.ada");
2081 As shown in this example, the first argument for the pragma is the unit
2082 name (in this example a child unit). The second argument has the form
2083 of a named association. The identifier
2084 indicates whether the file name is for a spec or a body;
2085 the file name itself is given by a string literal.
2087 The source file name pragma is a configuration pragma, which means that
2088 normally it will be placed in the @file{gnat.adc}
2089 file used to hold configuration
2090 pragmas that apply to a complete compilation environment.
2091 For more details on how the @file{gnat.adc} file is created and used
2092 see @ref{Handling of Configuration Pragmas}.
2093 @cindex @file{gnat.adc}
2096 GNAT allows completely arbitrary file names to be specified using the
2097 source file name pragma. However, if the file name specified has an
2098 extension other than @file{.ads} or @file{.adb} it is necessary to use
2099 a special syntax when compiling the file. The name in this case must be
2100 preceded by the special sequence @code{-x} followed by a space and the name
2101 of the language, here @code{ada}, as in:
2104 $ gcc -c -x ada peculiar_file_name.sim
2109 @command{gnatmake} handles non-standard file names in the usual manner (the
2110 non-standard file name for the main program is simply used as the
2111 argument to gnatmake). Note that if the extension is also non-standard,
2112 then it must be included in the gnatmake command, it may not be omitted.
2114 @node Alternative File Naming Schemes
2115 @section Alternative File Naming Schemes
2116 @cindex File naming schemes, alternative
2119 In the previous section, we described the use of the @code{Source_File_Name}
2120 pragma to allow arbitrary names to be assigned to individual source files.
2121 However, this approach requires one pragma for each file, and especially in
2122 large systems can result in very long @file{gnat.adc} files, and also create
2123 a maintenance problem.
2125 GNAT also provides a facility for specifying systematic file naming schemes
2126 other than the standard default naming scheme previously described. An
2127 alternative scheme for naming is specified by the use of
2128 @code{Source_File_Name} pragmas having the following format:
2129 @cindex Source_File_Name pragma
2131 @smallexample @c ada
2132 pragma Source_File_Name (
2133 Spec_File_Name => FILE_NAME_PATTERN
2134 [,Casing => CASING_SPEC]
2135 [,Dot_Replacement => STRING_LITERAL]);
2137 pragma Source_File_Name (
2138 Body_File_Name => FILE_NAME_PATTERN
2139 [,Casing => CASING_SPEC]
2140 [,Dot_Replacement => STRING_LITERAL]);
2142 pragma Source_File_Name (
2143 Subunit_File_Name => FILE_NAME_PATTERN
2144 [,Casing => CASING_SPEC]
2145 [,Dot_Replacement => STRING_LITERAL]);
2147 FILE_NAME_PATTERN ::= STRING_LITERAL
2148 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2152 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2153 It contains a single asterisk character, and the unit name is substituted
2154 systematically for this asterisk. The optional parameter
2155 @code{Casing} indicates
2156 whether the unit name is to be all upper-case letters, all lower-case letters,
2157 or mixed-case. If no
2158 @code{Casing} parameter is used, then the default is all
2159 ^lower-case^upper-case^.
2161 The optional @code{Dot_Replacement} string is used to replace any periods
2162 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2163 argument is used then separating dots appear unchanged in the resulting
2165 Although the above syntax indicates that the
2166 @code{Casing} argument must appear
2167 before the @code{Dot_Replacement} argument, but it
2168 is also permissible to write these arguments in the opposite order.
2170 As indicated, it is possible to specify different naming schemes for
2171 bodies, specs, and subunits. Quite often the rule for subunits is the
2172 same as the rule for bodies, in which case, there is no need to give
2173 a separate @code{Subunit_File_Name} rule, and in this case the
2174 @code{Body_File_name} rule is used for subunits as well.
2176 The separate rule for subunits can also be used to implement the rather
2177 unusual case of a compilation environment (e.g. a single directory) which
2178 contains a subunit and a child unit with the same unit name. Although
2179 both units cannot appear in the same partition, the Ada Reference Manual
2180 allows (but does not require) the possibility of the two units coexisting
2181 in the same environment.
2183 The file name translation works in the following steps:
2188 If there is a specific @code{Source_File_Name} pragma for the given unit,
2189 then this is always used, and any general pattern rules are ignored.
2192 If there is a pattern type @code{Source_File_Name} pragma that applies to
2193 the unit, then the resulting file name will be used if the file exists. If
2194 more than one pattern matches, the latest one will be tried first, and the
2195 first attempt resulting in a reference to a file that exists will be used.
2198 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2199 for which the corresponding file exists, then the standard GNAT default
2200 naming rules are used.
2205 As an example of the use of this mechanism, consider a commonly used scheme
2206 in which file names are all lower case, with separating periods copied
2207 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2208 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2211 @smallexample @c ada
2212 pragma Source_File_Name
2213 (Spec_File_Name => "*.1.ada");
2214 pragma Source_File_Name
2215 (Body_File_Name => "*.2.ada");
2219 The default GNAT scheme is actually implemented by providing the following
2220 default pragmas internally:
2222 @smallexample @c ada
2223 pragma Source_File_Name
2224 (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2225 pragma Source_File_Name
2226 (Body_File_Name => "*.adb", Dot_Replacement => "-");
2230 Our final example implements a scheme typically used with one of the
2231 Ada 83 compilers, where the separator character for subunits was ``__''
2232 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2233 by adding @file{.ADA}, and subunits by
2234 adding @file{.SEP}. All file names were
2235 upper case. Child units were not present of course since this was an
2236 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2237 the same double underscore separator for child units.
2239 @smallexample @c ada
2240 pragma Source_File_Name
2241 (Spec_File_Name => "*_.ADA",
2242 Dot_Replacement => "__",
2243 Casing = Uppercase);
2244 pragma Source_File_Name
2245 (Body_File_Name => "*.ADA",
2246 Dot_Replacement => "__",
2247 Casing = Uppercase);
2248 pragma Source_File_Name
2249 (Subunit_File_Name => "*.SEP",
2250 Dot_Replacement => "__",
2251 Casing = Uppercase);
2254 @node Generating Object Files
2255 @section Generating Object Files
2258 An Ada program consists of a set of source files, and the first step in
2259 compiling the program is to generate the corresponding object files.
2260 These are generated by compiling a subset of these source files.
2261 The files you need to compile are the following:
2265 If a package spec has no body, compile the package spec to produce the
2266 object file for the package.
2269 If a package has both a spec and a body, compile the body to produce the
2270 object file for the package. The source file for the package spec need
2271 not be compiled in this case because there is only one object file, which
2272 contains the code for both the spec and body of the package.
2275 For a subprogram, compile the subprogram body to produce the object file
2276 for the subprogram. The spec, if one is present, is as usual in a
2277 separate file, and need not be compiled.
2281 In the case of subunits, only compile the parent unit. A single object
2282 file is generated for the entire subunit tree, which includes all the
2286 Compile child units independently of their parent units
2287 (though, of course, the spec of all the ancestor unit must be present in order
2288 to compile a child unit).
2292 Compile generic units in the same manner as any other units. The object
2293 files in this case are small dummy files that contain at most the
2294 flag used for elaboration checking. This is because GNAT always handles generic
2295 instantiation by means of macro expansion. However, it is still necessary to
2296 compile generic units, for dependency checking and elaboration purposes.
2300 The preceding rules describe the set of files that must be compiled to
2301 generate the object files for a program. Each object file has the same
2302 name as the corresponding source file, except that the extension is
2305 You may wish to compile other files for the purpose of checking their
2306 syntactic and semantic correctness. For example, in the case where a
2307 package has a separate spec and body, you would not normally compile the
2308 spec. However, it is convenient in practice to compile the spec to make
2309 sure it is error-free before compiling clients of this spec, because such
2310 compilations will fail if there is an error in the spec.
2312 GNAT provides an option for compiling such files purely for the
2313 purposes of checking correctness; such compilations are not required as
2314 part of the process of building a program. To compile a file in this
2315 checking mode, use the @option{-gnatc} switch.
2317 @node Source Dependencies
2318 @section Source Dependencies
2321 A given object file clearly depends on the source file which is compiled
2322 to produce it. Here we are using @dfn{depends} in the sense of a typical
2323 @code{make} utility; in other words, an object file depends on a source
2324 file if changes to the source file require the object file to be
2326 In addition to this basic dependency, a given object may depend on
2327 additional source files as follows:
2331 If a file being compiled @code{with}'s a unit @var{X}, the object file
2332 depends on the file containing the spec of unit @var{X}. This includes
2333 files that are @code{with}'ed implicitly either because they are parents
2334 of @code{with}'ed child units or they are run-time units required by the
2335 language constructs used in a particular unit.
2338 If a file being compiled instantiates a library level generic unit, the
2339 object file depends on both the spec and body files for this generic
2343 If a file being compiled instantiates a generic unit defined within a
2344 package, the object file depends on the body file for the package as
2345 well as the spec file.
2349 @cindex @option{-gnatn} switch
2350 If a file being compiled contains a call to a subprogram for which
2351 pragma @code{Inline} applies and inlining is activated with the
2352 @option{-gnatn} switch, the object file depends on the file containing the
2353 body of this subprogram as well as on the file containing the spec. Note
2354 that for inlining to actually occur as a result of the use of this switch,
2355 it is necessary to compile in optimizing mode.
2357 @cindex @option{-gnatN} switch
2358 The use of @option{-gnatN} activates a more extensive inlining optimization
2359 that is performed by the front end of the compiler. This inlining does
2360 not require that the code generation be optimized. Like @option{-gnatn},
2361 the use of this switch generates additional dependencies.
2363 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
2364 to specify both options.
2367 If an object file @file{O} depends on the proper body of a subunit through
2368 inlining or instantiation, it depends on the parent unit of the subunit.
2369 This means that any modification of the parent unit or one of its subunits
2370 affects the compilation of @file{O}.
2373 The object file for a parent unit depends on all its subunit body files.
2376 The previous two rules meant that for purposes of computing dependencies and
2377 recompilation, a body and all its subunits are treated as an indivisible whole.
2380 These rules are applied transitively: if unit @code{A} @code{with}'s
2381 unit @code{B}, whose elaboration calls an inlined procedure in package
2382 @code{C}, the object file for unit @code{A} will depend on the body of
2383 @code{C}, in file @file{c.adb}.
2385 The set of dependent files described by these rules includes all the
2386 files on which the unit is semantically dependent, as dictated by the
2387 Ada language standard. However, it is a superset of what the
2388 standard describes, because it includes generic, inline, and subunit
2391 An object file must be recreated by recompiling the corresponding source
2392 file if any of the source files on which it depends are modified. For
2393 example, if the @code{make} utility is used to control compilation,
2394 the rule for an Ada object file must mention all the source files on
2395 which the object file depends, according to the above definition.
2396 The determination of the necessary
2397 recompilations is done automatically when one uses @command{gnatmake}.
2400 @node The Ada Library Information Files
2401 @section The Ada Library Information Files
2402 @cindex Ada Library Information files
2403 @cindex @file{ALI} files
2406 Each compilation actually generates two output files. The first of these
2407 is the normal object file that has a @file{.o} extension. The second is a
2408 text file containing full dependency information. It has the same
2409 name as the source file, but an @file{.ali} extension.
2410 This file is known as the Ada Library Information (@file{ALI}) file.
2411 The following information is contained in the @file{ALI} file.
2415 Version information (indicates which version of GNAT was used to compile
2416 the unit(s) in question)
2419 Main program information (including priority and time slice settings,
2420 as well as the wide character encoding used during compilation).
2423 List of arguments used in the @command{gcc} command for the compilation
2426 Attributes of the unit, including configuration pragmas used, an indication
2427 of whether the compilation was successful, exception model used etc.
2430 A list of relevant restrictions applying to the unit (used for consistency)
2434 Categorization information (e.g. use of pragma @code{Pure}).
2437 Information on all @code{with}'ed units, including presence of
2438 @code{Elaborate} or @code{Elaborate_All} pragmas.
2441 Information from any @code{Linker_Options} pragmas used in the unit
2444 Information on the use of @code{Body_Version} or @code{Version}
2445 attributes in the unit.
2448 Dependency information. This is a list of files, together with
2449 time stamp and checksum information. These are files on which
2450 the unit depends in the sense that recompilation is required
2451 if any of these units are modified.
2454 Cross-reference data. Contains information on all entities referenced
2455 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2456 provide cross-reference information.
2461 For a full detailed description of the format of the @file{ALI} file,
2462 see the source of the body of unit @code{Lib.Writ}, contained in file
2463 @file{lib-writ.adb} in the GNAT compiler sources.
2465 @node Binding an Ada Program
2466 @section Binding an Ada Program
2469 When using languages such as C and C++, once the source files have been
2470 compiled the only remaining step in building an executable program
2471 is linking the object modules together. This means that it is possible to
2472 link an inconsistent version of a program, in which two units have
2473 included different versions of the same header.
2475 The rules of Ada do not permit such an inconsistent program to be built.
2476 For example, if two clients have different versions of the same package,
2477 it is illegal to build a program containing these two clients.
2478 These rules are enforced by the GNAT binder, which also determines an
2479 elaboration order consistent with the Ada rules.
2481 The GNAT binder is run after all the object files for a program have
2482 been created. It is given the name of the main program unit, and from
2483 this it determines the set of units required by the program, by reading the
2484 corresponding ALI files. It generates error messages if the program is
2485 inconsistent or if no valid order of elaboration exists.
2487 If no errors are detected, the binder produces a main program, in Ada by
2488 default, that contains calls to the elaboration procedures of those
2489 compilation unit that require them, followed by
2490 a call to the main program. This Ada program is compiled to generate the
2491 object file for the main program. The name of
2492 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2493 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2496 Finally, the linker is used to build the resulting executable program,
2497 using the object from the main program from the bind step as well as the
2498 object files for the Ada units of the program.
2500 @node Mixed Language Programming
2501 @section Mixed Language Programming
2502 @cindex Mixed Language Programming
2505 This section describes how to develop a mixed-language program,
2506 specifically one that comprises units in both Ada and C.
2509 * Interfacing to C::
2510 * Calling Conventions::
2513 @node Interfacing to C
2514 @subsection Interfacing to C
2516 Interfacing Ada with a foreign language such as C involves using
2517 compiler directives to import and/or export entity definitions in each
2518 language---using @code{extern} statements in C, for instance, and the
2519 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2520 A full treatment of these topics is provided in Appendix B, section 1
2521 of the Ada Reference Manual.
2523 There are two ways to build a program using GNAT that contains some Ada
2524 sources and some foreign language sources, depending on whether or not
2525 the main subprogram is written in Ada. Here is a source example with
2526 the main subprogram in Ada:
2532 void print_num (int num)
2534 printf ("num is %d.\n", num);
2540 /* num_from_Ada is declared in my_main.adb */
2541 extern int num_from_Ada;
2545 return num_from_Ada;
2549 @smallexample @c ada
2551 procedure My_Main is
2553 -- Declare then export an Integer entity called num_from_Ada
2554 My_Num : Integer := 10;
2555 pragma Export (C, My_Num, "num_from_Ada");
2557 -- Declare an Ada function spec for Get_Num, then use
2558 -- C function get_num for the implementation.
2559 function Get_Num return Integer;
2560 pragma Import (C, Get_Num, "get_num");
2562 -- Declare an Ada procedure spec for Print_Num, then use
2563 -- C function print_num for the implementation.
2564 procedure Print_Num (Num : Integer);
2565 pragma Import (C, Print_Num, "print_num");
2568 Print_Num (Get_Num);
2574 To build this example, first compile the foreign language files to
2575 generate object files:
2577 ^gcc -c file1.c^gcc -c FILE1.C^
2578 ^gcc -c file2.c^gcc -c FILE2.C^
2582 Then, compile the Ada units to produce a set of object files and ALI
2585 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2589 Run the Ada binder on the Ada main program:
2591 gnatbind my_main.ali
2595 Link the Ada main program, the Ada objects and the other language
2598 gnatlink my_main.ali file1.o file2.o
2602 The last three steps can be grouped in a single command:
2604 gnatmake my_main.adb -largs file1.o file2.o
2607 @cindex Binder output file
2609 If the main program is in a language other than Ada, then you may have
2610 more than one entry point into the Ada subsystem. You must use a special
2611 binder option to generate callable routines that initialize and
2612 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2613 Calls to the initialization and finalization routines must be inserted
2614 in the main program, or some other appropriate point in the code. The
2615 call to initialize the Ada units must occur before the first Ada
2616 subprogram is called, and the call to finalize the Ada units must occur
2617 after the last Ada subprogram returns. The binder will place the
2618 initialization and finalization subprograms into the
2619 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2620 sources. To illustrate, we have the following example:
2624 extern void adainit (void);
2625 extern void adafinal (void);
2626 extern int add (int, int);
2627 extern int sub (int, int);
2629 int main (int argc, char *argv[])
2635 /* Should print "21 + 7 = 28" */
2636 printf ("%d + %d = %d\n", a, b, add (a, b));
2637 /* Should print "21 - 7 = 14" */
2638 printf ("%d - %d = %d\n", a, b, sub (a, b));
2644 @smallexample @c ada
2647 function Add (A, B : Integer) return Integer;
2648 pragma Export (C, Add, "add");
2652 package body Unit1 is
2653 function Add (A, B : Integer) return Integer is
2661 function Sub (A, B : Integer) return Integer;
2662 pragma Export (C, Sub, "sub");
2666 package body Unit2 is
2667 function Sub (A, B : Integer) return Integer is
2676 The build procedure for this application is similar to the last
2677 example's. First, compile the foreign language files to generate object
2680 ^gcc -c main.c^gcc -c main.c^
2684 Next, compile the Ada units to produce a set of object files and ALI
2687 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2688 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2692 Run the Ada binder on every generated ALI file. Make sure to use the
2693 @option{-n} option to specify a foreign main program:
2695 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2699 Link the Ada main program, the Ada objects and the foreign language
2700 objects. You need only list the last ALI file here:
2702 gnatlink unit2.ali main.o -o exec_file
2705 This procedure yields a binary executable called @file{exec_file}.
2709 Depending on the circumstances (for example when your non-Ada main object
2710 does not provide symbol @code{main}), you may also need to instruct the
2711 GNAT linker not to include the standard startup objects by passing the
2712 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2714 @node Calling Conventions
2715 @subsection Calling Conventions
2716 @cindex Foreign Languages
2717 @cindex Calling Conventions
2718 GNAT follows standard calling sequence conventions and will thus interface
2719 to any other language that also follows these conventions. The following
2720 Convention identifiers are recognized by GNAT:
2723 @cindex Interfacing to Ada
2724 @cindex Other Ada compilers
2725 @cindex Convention Ada
2727 This indicates that the standard Ada calling sequence will be
2728 used and all Ada data items may be passed without any limitations in the
2729 case where GNAT is used to generate both the caller and callee. It is also
2730 possible to mix GNAT generated code and code generated by another Ada
2731 compiler. In this case, the data types should be restricted to simple
2732 cases, including primitive types. Whether complex data types can be passed
2733 depends on the situation. Probably it is safe to pass simple arrays, such
2734 as arrays of integers or floats. Records may or may not work, depending
2735 on whether both compilers lay them out identically. Complex structures
2736 involving variant records, access parameters, tasks, or protected types,
2737 are unlikely to be able to be passed.
2739 Note that in the case of GNAT running
2740 on a platform that supports HP Ada 83, a higher degree of compatibility
2741 can be guaranteed, and in particular records are layed out in an identical
2742 manner in the two compilers. Note also that if output from two different
2743 compilers is mixed, the program is responsible for dealing with elaboration
2744 issues. Probably the safest approach is to write the main program in the
2745 version of Ada other than GNAT, so that it takes care of its own elaboration
2746 requirements, and then call the GNAT-generated adainit procedure to ensure
2747 elaboration of the GNAT components. Consult the documentation of the other
2748 Ada compiler for further details on elaboration.
2750 However, it is not possible to mix the tasking run time of GNAT and
2751 HP Ada 83, All the tasking operations must either be entirely within
2752 GNAT compiled sections of the program, or entirely within HP Ada 83
2753 compiled sections of the program.
2755 @cindex Interfacing to Assembly
2756 @cindex Convention Assembler
2758 Specifies assembler as the convention. In practice this has the
2759 same effect as convention Ada (but is not equivalent in the sense of being
2760 considered the same convention).
2762 @cindex Convention Asm
2765 Equivalent to Assembler.
2767 @cindex Interfacing to COBOL
2768 @cindex Convention COBOL
2771 Data will be passed according to the conventions described
2772 in section B.4 of the Ada Reference Manual.
2775 @cindex Interfacing to C
2776 @cindex Convention C
2778 Data will be passed according to the conventions described
2779 in section B.3 of the Ada Reference Manual.
2781 A note on interfacing to a C ``varargs'' function:
2782 @findex C varargs function
2783 @cindex Interfacing to C varargs function
2784 @cindex varargs function interfaces
2788 In C, @code{varargs} allows a function to take a variable number of
2789 arguments. There is no direct equivalent in this to Ada. One
2790 approach that can be used is to create a C wrapper for each
2791 different profile and then interface to this C wrapper. For
2792 example, to print an @code{int} value using @code{printf},
2793 create a C function @code{printfi} that takes two arguments, a
2794 pointer to a string and an int, and calls @code{printf}.
2795 Then in the Ada program, use pragma @code{Import} to
2796 interface to @code{printfi}.
2799 It may work on some platforms to directly interface to
2800 a @code{varargs} function by providing a specific Ada profile
2801 for a particular call. However, this does not work on
2802 all platforms, since there is no guarantee that the
2803 calling sequence for a two argument normal C function
2804 is the same as for calling a @code{varargs} C function with
2805 the same two arguments.
2808 @cindex Convention Default
2813 @cindex Convention External
2820 @cindex Interfacing to C++
2821 @cindex Convention C++
2822 @item C_Plus_Plus (or CPP)
2823 This stands for C++. For most purposes this is identical to C.
2824 See the separate description of the specialized GNAT pragmas relating to
2825 C++ interfacing for further details.
2829 @cindex Interfacing to Fortran
2830 @cindex Convention Fortran
2832 Data will be passed according to the conventions described
2833 in section B.5 of the Ada Reference Manual.
2836 This applies to an intrinsic operation, as defined in the Ada
2837 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2838 this means that the body of the subprogram is provided by the compiler itself,
2839 usually by means of an efficient code sequence, and that the user does not
2840 supply an explicit body for it. In an application program, the pragma can
2841 only be applied to the following two sets of names, which the GNAT compiler
2846 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2847 Shift_Right_Arithmetic. The corresponding subprogram declaration must have
2848 two formal parameters. The
2849 first one must be a signed integer type or a modular type with a binary
2850 modulus, and the second parameter must be of type Natural.
2851 The return type must be the same as the type of the first argument. The size
2852 of this type can only be 8, 16, 32, or 64.
2853 @item binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2854 The corresponding operator declaration must have parameters and result type
2855 that have the same root numeric type (for example, all three are long_float
2856 types). This simplifies the definition of operations that use type checking
2857 to perform dimensional checks:
2859 @smallexample @c ada
2860 type Distance is new Long_Float;
2861 type Time is new Long_Float;
2862 type Velocity is new Long_Float;
2863 function "/" (D : Distance; T : Time)
2865 pragma Import (Intrinsic, "/");
2869 This common idiom is often programmed with a generic definition and an
2870 explicit body. The pragma makes it simpler to introduce such declarations.
2871 It incurs no overhead in compilation time or code size, because it is
2872 implemented as a single machine instruction.
2878 @cindex Convention Stdcall
2880 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2881 and specifies that the @code{Stdcall} calling sequence will be used,
2882 as defined by the NT API. Nevertheless, to ease building
2883 cross-platform bindings this convention will be handled as a @code{C} calling
2884 convention on non Windows platforms.
2887 @cindex Convention DLL
2889 This is equivalent to @code{Stdcall}.
2892 @cindex Convention Win32
2894 This is equivalent to @code{Stdcall}.
2898 @cindex Convention Stubbed
2900 This is a special convention that indicates that the compiler
2901 should provide a stub body that raises @code{Program_Error}.
2905 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2906 that can be used to parametrize conventions and allow additional synonyms
2907 to be specified. For example if you have legacy code in which the convention
2908 identifier Fortran77 was used for Fortran, you can use the configuration
2911 @smallexample @c ada
2912 pragma Convention_Identifier (Fortran77, Fortran);
2916 And from now on the identifier Fortran77 may be used as a convention
2917 identifier (for example in an @code{Import} pragma) with the same
2921 @node Building Mixed Ada & C++ Programs
2922 @section Building Mixed Ada and C++ Programs
2925 A programmer inexperienced with mixed-language development may find that
2926 building an application containing both Ada and C++ code can be a
2927 challenge. This section gives a few
2928 hints that should make this task easier. The first section addresses
2929 the differences between interfacing with C and interfacing with C++.
2931 looks into the delicate problem of linking the complete application from
2932 its Ada and C++ parts. The last section gives some hints on how the GNAT
2933 run-time library can be adapted in order to allow inter-language dispatching
2934 with a new C++ compiler.
2937 * Interfacing to C++::
2938 * Linking a Mixed C++ & Ada Program::
2939 * A Simple Example::
2940 * Interfacing with C++ at the Class Level::
2943 @node Interfacing to C++
2944 @subsection Interfacing to C++
2947 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2948 generating code that is compatible with the G++ Application Binary
2949 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2952 Interfacing can be done at 3 levels: simple data, subprograms, and
2953 classes. In the first two cases, GNAT offers a specific @var{Convention
2954 C_Plus_Plus} (or @var{CPP}) that behaves exactly like @var{Convention C}.
2955 Usually, C++ mangles the names of subprograms, and currently, GNAT does
2956 not provide any help to solve the demangling problem. This problem can be
2957 addressed in two ways:
2960 by modifying the C++ code in order to force a C convention using
2961 the @code{extern "C"} syntax.
2964 by figuring out the mangled name and use it as the Link_Name argument of
2969 Interfacing at the class level can be achieved by using the GNAT specific
2970 pragmas such as @code{CPP_Constructor}. See the GNAT Reference Manual for
2971 additional information.
2973 @node Linking a Mixed C++ & Ada Program
2974 @subsection Linking a Mixed C++ & Ada Program
2977 Usually the linker of the C++ development system must be used to link
2978 mixed applications because most C++ systems will resolve elaboration
2979 issues (such as calling constructors on global class instances)
2980 transparently during the link phase. GNAT has been adapted to ease the
2981 use of a foreign linker for the last phase. Three cases can be
2986 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
2987 The C++ linker can simply be called by using the C++ specific driver
2988 called @code{c++}. Note that this setup is not very common because it
2989 may involve recompiling the whole GCC tree from sources, which makes it
2990 harder to upgrade the compilation system for one language without
2991 destabilizing the other.
2996 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
3000 Using GNAT and G++ from two different GCC installations: If both
3001 compilers are on the PATH, the previous method may be used. It is
3002 important to note that environment variables such as C_INCLUDE_PATH,
3003 GCC_EXEC_PREFIX, BINUTILS_ROOT, and GCC_ROOT will affect both compilers
3004 at the same time and may make one of the two compilers operate
3005 improperly if set during invocation of the wrong compiler. It is also
3006 very important that the linker uses the proper @file{libgcc.a} GCC
3007 library -- that is, the one from the C++ compiler installation. The
3008 implicit link command as suggested in the gnatmake command from the
3009 former example can be replaced by an explicit link command with the
3010 full-verbosity option in order to verify which library is used:
3013 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3015 If there is a problem due to interfering environment variables, it can
3016 be worked around by using an intermediate script. The following example
3017 shows the proper script to use when GNAT has not been installed at its
3018 default location and g++ has been installed at its default location:
3026 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3030 Using a non-GNU C++ compiler: The commands previously described can be
3031 used to insure that the C++ linker is used. Nonetheless, you need to add
3032 a few more parameters to the link command line, depending on the exception
3035 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3036 to the libgcc libraries are required:
3041 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3042 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3045 Where CC is the name of the non-GNU C++ compiler.
3047 If the @code{zero cost} exception mechanism is used, and the platform
3048 supports automatic registration of exception tables (e.g. Solaris or IRIX),
3049 paths to more objects are required:
3054 CC `gcc -print-file-name=crtbegin.o` $* \
3055 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3056 `gcc -print-file-name=crtend.o`
3057 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3060 If the @code{zero cost} exception mechanism is used, and the platform
3061 doesn't support automatic registration of exception tables (e.g. HP-UX,
3062 Tru64 or AIX), the simple approach described above will not work and
3063 a pre-linking phase using GNAT will be necessary.
3067 @node A Simple Example
3068 @subsection A Simple Example
3070 The following example, provided as part of the GNAT examples, shows how
3071 to achieve procedural interfacing between Ada and C++ in both
3072 directions. The C++ class A has two methods. The first method is exported
3073 to Ada by the means of an extern C wrapper function. The second method
3074 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3075 a limited record with a layout comparable to the C++ class. The Ada
3076 subprogram, in turn, calls the C++ method. So, starting from the C++
3077 main program, the process passes back and forth between the two
3081 Here are the compilation commands:
3083 $ gnatmake -c simple_cpp_interface
3086 $ gnatbind -n simple_cpp_interface
3087 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3088 -lstdc++ ex7.o cpp_main.o
3092 Here are the corresponding sources:
3100 void adainit (void);
3101 void adafinal (void);
3102 void method1 (A *t);
3124 class A : public Origin @{
3126 void method1 (void);
3127 void method2 (int v);
3137 extern "C" @{ void ada_method2 (A *t, int v);@}
3139 void A::method1 (void)
3142 printf ("in A::method1, a_value = %d \n",a_value);
3146 void A::method2 (int v)
3148 ada_method2 (this, v);
3149 printf ("in A::method2, a_value = %d \n",a_value);
3156 printf ("in A::A, a_value = %d \n",a_value);
3160 @smallexample @c ada
3162 package body Simple_Cpp_Interface is
3164 procedure Ada_Method2 (This : in out A; V : Integer) is
3170 end Simple_Cpp_Interface;
3173 package Simple_Cpp_Interface is
3176 Vptr : System.Address;
3180 pragma Convention (C, A);
3182 procedure Method1 (This : in out A);
3183 pragma Import (C, Method1);
3185 procedure Ada_Method2 (This : in out A; V : Integer);
3186 pragma Export (C, Ada_Method2);
3188 end Simple_Cpp_Interface;
3191 @node Interfacing with C++ at the Class Level
3192 @subsection Interfacing with C++ at the Class Level
3194 In this section we demonstrate the GNAT features for interfacing with
3195 C++ by means of an example making use of Ada 2005 abstract interface
3196 types. This example consists of a classification of animals; classes
3197 have been used to model our main classification of animals, and
3198 interfaces provide support for the management of secondary
3199 classifications. We first demonstrate a case in which the types and
3200 constructors are defined on the C++ side and imported from the Ada
3201 side, and latter the reverse case.
3203 The root of our derivation will be the @code{Animal} class, with a
3204 single private attribute (the @code{Age} of the animal) and two public
3205 primitives to set and get the value of this attribute.
3210 @b{virtual} void Set_Age (int New_Age);
3211 @b{virtual} int Age ();
3217 Abstract interface types are defined in C++ by means of classes with pure
3218 virtual functions and no data members. In our example we will use two
3219 interfaces that provide support for the common management of @code{Carnivore}
3220 and @code{Domestic} animals:
3223 @b{class} Carnivore @{
3225 @b{virtual} int Number_Of_Teeth () = 0;
3228 @b{class} Domestic @{
3230 @b{virtual void} Set_Owner (char* Name) = 0;
3234 Using these declarations, we can now say that a @code{Dog} is an animal that is
3235 both Carnivore and Domestic, that is:
3238 @b{class} Dog : Animal, Carnivore, Domestic @{
3240 @b{virtual} int Number_Of_Teeth ();
3241 @b{virtual} void Set_Owner (char* Name);
3243 Dog(); // Constructor
3250 In the following examples we will assume that the previous declarations are
3251 located in a file named @code{animals.h}. The following package demonstrates
3252 how to import these C++ declarations from the Ada side:
3254 @smallexample @c ada
3255 with Interfaces.C.Strings; use Interfaces.C.Strings;
3257 type Carnivore is interface;
3258 pragma Convention (C_Plus_Plus, Carnivore);
3259 function Number_Of_Teeth (X : Carnivore)
3260 return Natural is abstract;
3262 type Domestic is interface;
3263 pragma Convention (C_Plus_Plus, Set_Owner);
3265 (X : in out Domestic;
3266 Name : Chars_Ptr) is abstract;
3268 type Animal is tagged record
3271 pragma Import (C_Plus_Plus, Animal);
3273 procedure Set_Age (X : in out Animal; Age : Integer);
3274 pragma Import (C_Plus_Plus, Set_Age);
3276 function Age (X : Animal) return Integer;
3277 pragma Import (C_Plus_Plus, Age);
3279 type Dog is new Animal and Carnivore and Domestic with record
3280 Tooth_Count : Natural;
3281 Owner : String (1 .. 30);
3283 pragma Import (C_Plus_Plus, Dog);
3285 function Number_Of_Teeth (A : Dog) return Integer;
3286 pragma Import (C_Plus_Plus, Number_Of_Teeth);
3288 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3289 pragma Import (C_Plus_Plus, Set_Owner);
3291 function New_Dog return Dog'Class;
3292 pragma CPP_Constructor (New_Dog);
3293 pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3297 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3298 interfacing with these C++ classes is easy. The only requirement is that all
3299 the primitives and components must be declared exactly in the same order in
3302 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3303 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3304 the arguments to the called primitives will be the same as for C++. For the
3305 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3306 to indicate that they have been defined on the C++ side; this is required
3307 because the dispatch table associated with these tagged types will be built
3308 in the C++ side and therefore will not contain the predefined Ada primitives
3309 which Ada would otherwise expect.
3311 As the reader can see there is no need to indicate the C++ mangled names
3312 associated with each subprogram because it is assumed that all the calls to
3313 these primitives will be dispatching calls. The only exception is the
3314 constructor, which must be registered with the compiler by means of
3315 @code{pragma CPP_Constructor} and needs to provide its associated C++
3316 mangled name because the Ada compiler generates direct calls to it.
3318 With the above packages we can now declare objects of type Dog on the Ada side
3319 and dispatch calls to the corresponding subprograms on the C++ side. We can
3320 also extend the tagged type Dog with further fields and primitives, and
3321 override some of its C++ primitives on the Ada side. For example, here we have
3322 a type derivation defined on the Ada side that inherits all the dispatching
3323 primitives of the ancestor from the C++ side.
3326 @b{with} Animals; @b{use} Animals;
3327 @b{package} Vaccinated_Animals @b{is}
3328 @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3329 @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3330 @b{end} Vaccinated_Animals;
3333 It is important to note that, because of the ABI compatibility, the programmer
3334 does not need to add any further information to indicate either the object
3335 layout or the dispatch table entry associated with each dispatching operation.
3337 Now let us define all the types and constructors on the Ada side and export
3338 them to C++, using the same hierarchy of our previous example:
3340 @smallexample @c ada
3341 with Interfaces.C.Strings;
3342 use Interfaces.C.Strings;
3344 type Carnivore is interface;
3345 pragma Convention (C_Plus_Plus, Carnivore);
3346 function Number_Of_Teeth (X : Carnivore)
3347 return Natural is abstract;
3349 type Domestic is interface;
3350 pragma Convention (C_Plus_Plus, Set_Owner);
3352 (X : in out Domestic;
3353 Name : Chars_Ptr) is abstract;
3355 type Animal is tagged record
3358 pragma Convention (C_Plus_Plus, Animal);
3360 procedure Set_Age (X : in out Animal; Age : Integer);
3361 pragma Export (C_Plus_Plus, Set_Age);
3363 function Age (X : Animal) return Integer;
3364 pragma Export (C_Plus_Plus, Age);
3366 type Dog is new Animal and Carnivore and Domestic with record
3367 Tooth_Count : Natural;
3368 Owner : String (1 .. 30);
3370 pragma Convention (C_Plus_Plus, Dog);
3372 function Number_Of_Teeth (A : Dog) return Integer;
3373 pragma Export (C_Plus_Plus, Number_Of_Teeth);
3375 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3376 pragma Export (C_Plus_Plus, Set_Owner);
3378 function New_Dog return Dog'Class;
3379 pragma Export (C_Plus_Plus, New_Dog);
3383 Compared with our previous example the only difference is the use of
3384 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3385 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3386 nothing else to be done; as explained above, the only requirement is that all
3387 the primitives and components are declared in exactly the same order.
3389 For completeness, let us see a brief C++ main program that uses the
3390 declarations available in @code{animals.h} (presented in our first example) to
3391 import and use the declarations from the Ada side, properly initializing and
3392 finalizing the Ada run-time system along the way:
3395 @b{#include} "animals.h"
3396 @b{#include} <iostream>
3397 @b{using namespace} std;
3399 void Check_Carnivore (Carnivore *obj) @{ ... @}
3400 void Check_Domestic (Domestic *obj) @{ ... @}
3401 void Check_Animal (Animal *obj) @{ ... @}
3402 void Check_Dog (Dog *obj) @{ ... @}
3405 void adainit (void);
3406 void adafinal (void);
3412 Dog *obj = new_dog(); // Ada constructor
3413 Check_Carnivore (obj); // Check secondary DT
3414 Check_Domestic (obj); // Check secondary DT
3415 Check_Animal (obj); // Check primary DT
3416 Check_Dog (obj); // Check primary DT
3421 adainit (); test(); adafinal ();
3426 @node Comparison between GNAT and C/C++ Compilation Models
3427 @section Comparison between GNAT and C/C++ Compilation Models
3430 The GNAT model of compilation is close to the C and C++ models. You can
3431 think of Ada specs as corresponding to header files in C. As in C, you
3432 don't need to compile specs; they are compiled when they are used. The
3433 Ada @code{with} is similar in effect to the @code{#include} of a C
3436 One notable difference is that, in Ada, you may compile specs separately
3437 to check them for semantic and syntactic accuracy. This is not always
3438 possible with C headers because they are fragments of programs that have
3439 less specific syntactic or semantic rules.
3441 The other major difference is the requirement for running the binder,
3442 which performs two important functions. First, it checks for
3443 consistency. In C or C++, the only defense against assembling
3444 inconsistent programs lies outside the compiler, in a makefile, for
3445 example. The binder satisfies the Ada requirement that it be impossible
3446 to construct an inconsistent program when the compiler is used in normal
3449 @cindex Elaboration order control
3450 The other important function of the binder is to deal with elaboration
3451 issues. There are also elaboration issues in C++ that are handled
3452 automatically. This automatic handling has the advantage of being
3453 simpler to use, but the C++ programmer has no control over elaboration.
3454 Where @code{gnatbind} might complain there was no valid order of
3455 elaboration, a C++ compiler would simply construct a program that
3456 malfunctioned at run time.
3459 @node Comparison between GNAT and Conventional Ada Library Models
3460 @section Comparison between GNAT and Conventional Ada Library Models
3463 This section is intended for Ada programmers who have
3464 used an Ada compiler implementing the traditional Ada library
3465 model, as described in the Ada Reference Manual.
3467 @cindex GNAT library
3468 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3469 source files themselves acts as the library. Compiling Ada programs does
3470 not generate any centralized information, but rather an object file and
3471 a ALI file, which are of interest only to the binder and linker.
3472 In a traditional system, the compiler reads information not only from
3473 the source file being compiled, but also from the centralized library.
3474 This means that the effect of a compilation depends on what has been
3475 previously compiled. In particular:
3479 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3480 to the version of the unit most recently compiled into the library.
3483 Inlining is effective only if the necessary body has already been
3484 compiled into the library.
3487 Compiling a unit may obsolete other units in the library.
3491 In GNAT, compiling one unit never affects the compilation of any other
3492 units because the compiler reads only source files. Only changes to source
3493 files can affect the results of a compilation. In particular:
3497 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3498 to the source version of the unit that is currently accessible to the
3503 Inlining requires the appropriate source files for the package or
3504 subprogram bodies to be available to the compiler. Inlining is always
3505 effective, independent of the order in which units are complied.
3508 Compiling a unit never affects any other compilations. The editing of
3509 sources may cause previous compilations to be out of date if they
3510 depended on the source file being modified.
3514 The most important result of these differences is that order of compilation
3515 is never significant in GNAT. There is no situation in which one is
3516 required to do one compilation before another. What shows up as order of
3517 compilation requirements in the traditional Ada library becomes, in
3518 GNAT, simple source dependencies; in other words, there is only a set
3519 of rules saying what source files must be present when a file is
3523 @node Placement of temporary files
3524 @section Placement of temporary files
3525 @cindex Temporary files (user control over placement)
3528 GNAT creates temporary files in the directory designated by the environment
3529 variable @env{TMPDIR}.
3530 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3531 for detailed information on how environment variables are resolved.
3532 For most users the easiest way to make use of this feature is to simply
3533 define @env{TMPDIR} as a job level logical name).
3534 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3535 for compiler temporary files, then you can include something like the
3536 following command in your @file{LOGIN.COM} file:
3539 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3543 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3544 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3545 designated by @env{TEMP}.
3546 If none of these environment variables are defined then GNAT uses the
3547 directory designated by the logical name @code{SYS$SCRATCH:}
3548 (by default the user's home directory). If all else fails
3549 GNAT uses the current directory for temporary files.
3552 @c *************************
3553 @node Compiling Using gcc
3554 @chapter Compiling Using @command{gcc}
3557 This chapter discusses how to compile Ada programs using the @command{gcc}
3558 command. It also describes the set of switches
3559 that can be used to control the behavior of the compiler.
3561 * Compiling Programs::
3562 * Switches for gcc::
3563 * Search Paths and the Run-Time Library (RTL)::
3564 * Order of Compilation Issues::
3568 @node Compiling Programs
3569 @section Compiling Programs
3572 The first step in creating an executable program is to compile the units
3573 of the program using the @command{gcc} command. You must compile the
3578 the body file (@file{.adb}) for a library level subprogram or generic
3582 the spec file (@file{.ads}) for a library level package or generic
3583 package that has no body
3586 the body file (@file{.adb}) for a library level package
3587 or generic package that has a body
3592 You need @emph{not} compile the following files
3597 the spec of a library unit which has a body
3604 because they are compiled as part of compiling related units. GNAT
3606 when the corresponding body is compiled, and subunits when the parent is
3609 @cindex cannot generate code
3610 If you attempt to compile any of these files, you will get one of the
3611 following error messages (where fff is the name of the file you compiled):
3614 cannot generate code for file @var{fff} (package spec)
3615 to check package spec, use -gnatc
3617 cannot generate code for file @var{fff} (missing subunits)
3618 to check parent unit, use -gnatc
3620 cannot generate code for file @var{fff} (subprogram spec)
3621 to check subprogram spec, use -gnatc
3623 cannot generate code for file @var{fff} (subunit)
3624 to check subunit, use -gnatc
3628 As indicated by the above error messages, if you want to submit
3629 one of these files to the compiler to check for correct semantics
3630 without generating code, then use the @option{-gnatc} switch.
3632 The basic command for compiling a file containing an Ada unit is
3635 $ gcc -c [@var{switches}] @file{file name}
3639 where @var{file name} is the name of the Ada file (usually
3641 @file{.ads} for a spec or @file{.adb} for a body).
3644 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3646 The result of a successful compilation is an object file, which has the
3647 same name as the source file but an extension of @file{.o} and an Ada
3648 Library Information (ALI) file, which also has the same name as the
3649 source file, but with @file{.ali} as the extension. GNAT creates these
3650 two output files in the current directory, but you may specify a source
3651 file in any directory using an absolute or relative path specification
3652 containing the directory information.
3655 @command{gcc} is actually a driver program that looks at the extensions of
3656 the file arguments and loads the appropriate compiler. For example, the
3657 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3658 These programs are in directories known to the driver program (in some
3659 configurations via environment variables you set), but need not be in
3660 your path. The @command{gcc} driver also calls the assembler and any other
3661 utilities needed to complete the generation of the required object
3664 It is possible to supply several file names on the same @command{gcc}
3665 command. This causes @command{gcc} to call the appropriate compiler for
3666 each file. For example, the following command lists three separate
3667 files to be compiled:
3670 $ gcc -c x.adb y.adb z.c
3674 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3675 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3676 The compiler generates three object files @file{x.o}, @file{y.o} and
3677 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3678 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3681 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3684 @node Switches for gcc
3685 @section Switches for @command{gcc}
3688 The @command{gcc} command accepts switches that control the
3689 compilation process. These switches are fully described in this section.
3690 First we briefly list all the switches, in alphabetical order, then we
3691 describe the switches in more detail in functionally grouped sections.
3693 More switches exist for GCC than those documented here, especially
3694 for specific targets. However, their use is not recommended as
3695 they may change code generation in ways that are incompatible with
3696 the Ada run-time library, or can cause inconsistencies between
3700 * Output and Error Message Control::
3701 * Warning Message Control::
3702 * Debugging and Assertion Control::
3703 * Validity Checking::
3706 * Using gcc for Syntax Checking::
3707 * Using gcc for Semantic Checking::
3708 * Compiling Different Versions of Ada::
3709 * Character Set Control::
3710 * File Naming Control::
3711 * Subprogram Inlining Control::
3712 * Auxiliary Output Control::
3713 * Debugging Control::
3714 * Exception Handling Control::
3715 * Units to Sources Mapping Files::
3716 * Integrated Preprocessing::
3717 * Code Generation Control::
3726 @cindex @option{-b} (@command{gcc})
3727 @item -b @var{target}
3728 Compile your program to run on @var{target}, which is the name of a
3729 system configuration. You must have a GNAT cross-compiler built if
3730 @var{target} is not the same as your host system.
3733 @cindex @option{-B} (@command{gcc})
3734 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3735 from @var{dir} instead of the default location. Only use this switch
3736 when multiple versions of the GNAT compiler are available. See the
3737 @command{gcc} manual page for further details. You would normally use the
3738 @option{-b} or @option{-V} switch instead.
3741 @cindex @option{-c} (@command{gcc})
3742 Compile. Always use this switch when compiling Ada programs.
3744 Note: for some other languages when using @command{gcc}, notably in
3745 the case of C and C++, it is possible to use
3746 use @command{gcc} without a @option{-c} switch to
3747 compile and link in one step. In the case of GNAT, you
3748 cannot use this approach, because the binder must be run
3749 and @command{gcc} cannot be used to run the GNAT binder.
3753 @cindex @option{-fno-inline} (@command{gcc})
3754 Suppresses all back-end inlining, even if other optimization or inlining
3756 This includes suppression of inlining that results
3757 from the use of the pragma @code{Inline_Always}.
3758 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3759 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3760 effect if this switch is present.
3762 @item -fno-strict-aliasing
3763 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3764 Causes the compiler to avoid assumptions regarding non-aliasing
3765 of objects of different types. See
3766 @ref{Optimization and Strict Aliasing} for details.
3769 @cindex @option{-fstack-check} (@command{gcc})
3770 Activates stack checking.
3771 See @ref{Stack Overflow Checking} for details.
3774 @cindex @option{-fstack-usage} (@command{gcc})
3775 Makes the compiler output stack usage information for the program, on a
3776 per-function basis. See @ref{Static Stack Usage Analysis} for details.
3778 @item -fcallgraph-info[=su]
3779 @cindex @option{-fcallgraph-info} (@command{gcc})
3780 Makes the compiler output callgraph information for the program, on a
3781 per-file basis. The information is generated in the VCG format. It can
3782 be decorated with stack-usage per-node information.
3785 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3786 Generate debugging information. This information is stored in the object
3787 file and copied from there to the final executable file by the linker,
3788 where it can be read by the debugger. You must use the
3789 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3792 @cindex @option{-gnat83} (@command{gcc})
3793 Enforce Ada 83 restrictions.
3796 @cindex @option{-gnat95} (@command{gcc})
3797 Enforce Ada 95 restrictions.
3800 @cindex @option{-gnat05} (@command{gcc})
3801 Allow full Ada 2005 features.
3804 @cindex @option{-gnata} (@command{gcc})
3805 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3806 activated. Note that these pragmas can also be controlled using the
3807 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3810 @cindex @option{-gnatA} (@command{gcc})
3811 Avoid processing @file{gnat.adc}. If a gnat.adc file is present,
3815 @cindex @option{-gnatb} (@command{gcc})
3816 Generate brief messages to @file{stderr} even if verbose mode set.
3819 @cindex @option{-gnatc} (@command{gcc})
3820 Check syntax and semantics only (no code generation attempted).
3823 @cindex @option{-gnatd} (@command{gcc})
3824 Specify debug options for the compiler. The string of characters after
3825 the @option{-gnatd} specify the specific debug options. The possible
3826 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3827 compiler source file @file{debug.adb} for details of the implemented
3828 debug options. Certain debug options are relevant to applications
3829 programmers, and these are documented at appropriate points in this
3833 @cindex @option{-gnatD} (@command{gcc})
3834 Create expanded source files for source level debugging. This switch
3835 also suppress generation of cross-reference information
3836 (see @option{-gnatx}).
3838 @item -gnatec=@var{path}
3839 @cindex @option{-gnatec} (@command{gcc})
3840 Specify a configuration pragma file
3842 (the equal sign is optional)
3844 (@pxref{The Configuration Pragmas Files}).
3846 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
3847 @cindex @option{-gnateD} (@command{gcc})
3848 Defines a symbol, associated with value, for preprocessing.
3849 (@pxref{Integrated Preprocessing}).
3852 @cindex @option{-gnatef} (@command{gcc})
3853 Display full source path name in brief error messages.
3855 @item -gnatem=@var{path}
3856 @cindex @option{-gnatem} (@command{gcc})
3857 Specify a mapping file
3859 (the equal sign is optional)
3861 (@pxref{Units to Sources Mapping Files}).
3863 @item -gnatep=@var{file}
3864 @cindex @option{-gnatep} (@command{gcc})
3865 Specify a preprocessing data file
3867 (the equal sign is optional)
3869 (@pxref{Integrated Preprocessing}).
3872 @cindex @option{-gnatE} (@command{gcc})
3873 Full dynamic elaboration checks.
3876 @cindex @option{-gnatf} (@command{gcc})
3877 Full errors. Multiple errors per line, all undefined references, do not
3878 attempt to suppress cascaded errors.
3881 @cindex @option{-gnatF} (@command{gcc})
3882 Externals names are folded to all uppercase.
3884 @item ^-gnatg^/GNAT_INTERNAL^
3885 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
3886 Internal GNAT implementation mode. This should not be used for
3887 applications programs, it is intended only for use by the compiler
3888 and its run-time library. For documentation, see the GNAT sources.
3889 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
3890 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
3891 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
3892 so that all standard warnings and all standard style options are turned on.
3893 All warnings and style error messages are treated as errors.
3896 @cindex @option{-gnatG} (@command{gcc})
3897 List generated expanded code in source form.
3899 @item ^-gnath^/HELP^
3900 @cindex @option{^-gnath^/HELP^} (@command{gcc})
3901 Output usage information. The output is written to @file{stdout}.
3903 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3904 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
3905 Identifier character set
3907 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3909 For details of the possible selections for @var{c},
3910 see @ref{Character Set Control}.
3912 @item ^-gnatI^/IGNORE_REP_CLAUSES^
3913 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
3914 Ignore representation clauses. When this switch is used, all
3915 representation clauses are treated as comments. This is useful
3916 when initially porting code where you want to ignore rep clause
3917 problems, and also for compiling foreign code (particularly
3921 @cindex @option{-gnatjnn} (@command{gcc})
3922 Reformat error messages to fit on nn character lines
3924 @item -gnatk=@var{n}
3925 @cindex @option{-gnatk} (@command{gcc})
3926 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3929 @cindex @option{-gnatl} (@command{gcc})
3930 Output full source listing with embedded error messages.
3933 @cindex @option{-gnatL} (@command{gcc})
3934 Used in conjunction with -gnatG or -gnatD to intersperse original
3935 source lines (as comment lines with line numbers) in the expanded
3938 @item -gnatm=@var{n}
3939 @cindex @option{-gnatm} (@command{gcc})
3940 Limit number of detected error or warning messages to @var{n}
3941 where @var{n} is in the range 1..999_999. The default setting if
3942 no switch is given is 9999. Compilation is terminated if this
3943 limit is exceeded. The equal sign here is optional.
3946 @cindex @option{-gnatn} (@command{gcc})
3947 Activate inlining for subprograms for which
3948 pragma @code{inline} is specified. This inlining is performed
3949 by the GCC back-end.
3952 @cindex @option{-gnatN} (@command{gcc})
3953 Activate front end inlining for subprograms for which
3954 pragma @code{Inline} is specified. This inlining is performed
3955 by the front end and will be visible in the
3956 @option{-gnatG} output.
3957 In some cases, this has proved more effective than the back end
3958 inlining resulting from the use of
3961 @option{-gnatN} automatically implies
3962 @option{-gnatn} so it is not necessary
3963 to specify both options. There are a few cases that the back-end inlining
3964 catches that cannot be dealt with in the front-end.
3967 @cindex @option{-gnato} (@command{gcc})
3968 Enable numeric overflow checking (which is not normally enabled by
3969 default). Not that division by zero is a separate check that is not
3970 controlled by this switch (division by zero checking is on by default).
3973 @cindex @option{-gnatp} (@command{gcc})
3974 Suppress all checks.
3977 @cindex @option{-gnatP} (@command{gcc})
3978 Enable polling. This is required on some systems (notably Windows NT) to
3979 obtain asynchronous abort and asynchronous transfer of control capability.
3980 See the description of pragma Polling in the GNAT Reference Manual for
3984 @cindex @option{-gnatq} (@command{gcc})
3985 Don't quit; try semantics, even if parse errors.
3988 @cindex @option{-gnatQ} (@command{gcc})
3989 Don't quit; generate @file{ALI} and tree files even if illegalities.
3991 @item ^-gnatR[0/1/2/3[s]]^/REPRESENTATION_INFO^
3992 @cindex @option{-gnatR} (@command{gcc})
3993 Output representation information for declared types and objects.
3996 @cindex @option{-gnats} (@command{gcc})
4000 @cindex @option{-gnatS} (@command{gcc})
4001 Print package Standard.
4004 @cindex @option{-gnatt} (@command{gcc})
4005 Generate tree output file.
4007 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4008 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4009 All compiler tables start at @var{nnn} times usual starting size.
4012 @cindex @option{-gnatu} (@command{gcc})
4013 List units for this compilation.
4016 @cindex @option{-gnatU} (@command{gcc})
4017 Tag all error messages with the unique string ``error:''
4020 @cindex @option{-gnatv} (@command{gcc})
4021 Verbose mode. Full error output with source lines to @file{stdout}.
4024 @cindex @option{-gnatV} (@command{gcc})
4025 Control level of validity checking. See separate section describing
4028 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}[,...])^
4029 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4031 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4032 the exact warnings that
4033 are enabled or disabled (@pxref{Warning Message Control}).
4035 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4036 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4037 Wide character encoding method
4039 (@var{e}=n/h/u/s/e/8).
4042 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4046 @cindex @option{-gnatx} (@command{gcc})
4047 Suppress generation of cross-reference information.
4049 @item ^-gnaty^/STYLE_CHECKS=(option,option..)^
4050 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4051 Enable built-in style checks (@pxref{Style Checking}).
4053 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4054 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4055 Distribution stub generation and compilation
4057 (@var{m}=r/c for receiver/caller stubs).
4060 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4061 to be generated and compiled).
4064 @item ^-I^/SEARCH=^@var{dir}
4065 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4067 Direct GNAT to search the @var{dir} directory for source files needed by
4068 the current compilation
4069 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4071 @item ^-I-^/NOCURRENT_DIRECTORY^
4072 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4074 Except for the source file named in the command line, do not look for source
4075 files in the directory containing the source file named in the command line
4076 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4080 @cindex @option{-mbig-switch} (@command{gcc})
4081 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4082 This standard gcc switch causes the compiler to use larger offsets in its
4083 jump table representation for @code{case} statements.
4084 This may result in less efficient code, but is sometimes necessary
4085 (for example on HP-UX targets)
4086 @cindex HP-UX and @option{-mbig-switch} option
4087 in order to compile large and/or nested @code{case} statements.
4090 @cindex @option{-o} (@command{gcc})
4091 This switch is used in @command{gcc} to redirect the generated object file
4092 and its associated ALI file. Beware of this switch with GNAT, because it may
4093 cause the object file and ALI file to have different names which in turn
4094 may confuse the binder and the linker.
4098 @cindex @option{-nostdinc} (@command{gcc})
4099 Inhibit the search of the default location for the GNAT Run Time
4100 Library (RTL) source files.
4103 @cindex @option{-nostdlib} (@command{gcc})
4104 Inhibit the search of the default location for the GNAT Run Time
4105 Library (RTL) ALI files.
4109 @cindex @option{-O} (@command{gcc})
4110 @var{n} controls the optimization level.
4114 No optimization, the default setting if no @option{-O} appears
4117 Normal optimization, the default if you specify @option{-O} without
4118 an operand. A good compromise between code quality and compilation
4122 Extensive optimization, may improve execution time, possibly at the cost of
4123 substantially increased compilation time.
4126 Same as @option{-O2}, and also includes inline expansion for small subprograms
4130 Optimize space usage
4134 See also @ref{Optimization Levels}.
4139 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4140 Equivalent to @option{/OPTIMIZE=NONE}.
4141 This is the default behavior in the absence of an @option{/OPTIMIZE}
4144 @item /OPTIMIZE[=(keyword[,...])]
4145 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4146 Selects the level of optimization for your program. The supported
4147 keywords are as follows:
4150 Perform most optimizations, including those that
4152 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4153 without keyword options.
4156 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4159 Perform some optimizations, but omit ones that are costly.
4162 Same as @code{SOME}.
4165 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4166 automatic inlining of small subprograms within a unit
4169 Try to unroll loops. This keyword may be specified together with
4170 any keyword above other than @code{NONE}. Loop unrolling
4171 usually, but not always, improves the performance of programs.
4174 Optimize space usage
4178 See also @ref{Optimization Levels}.
4182 @item -pass-exit-codes
4183 @cindex @option{-pass-exit-codes} (@command{gcc})
4184 Catch exit codes from the compiler and use the most meaningful as
4188 @item --RTS=@var{rts-path}
4189 @cindex @option{--RTS} (@command{gcc})
4190 Specifies the default location of the runtime library. Same meaning as the
4191 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4194 @cindex @option{^-S^/ASM^} (@command{gcc})
4195 ^Used in place of @option{-c} to^Used to^
4196 cause the assembler source file to be
4197 generated, using @file{^.s^.S^} as the extension,
4198 instead of the object file.
4199 This may be useful if you need to examine the generated assembly code.
4201 @item ^-fverbose-asm^/VERBOSE_ASM^
4202 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4203 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4204 to cause the generated assembly code file to be annotated with variable
4205 names, making it significantly easier to follow.
4208 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4209 Show commands generated by the @command{gcc} driver. Normally used only for
4210 debugging purposes or if you need to be sure what version of the
4211 compiler you are executing.
4215 @cindex @option{-V} (@command{gcc})
4216 Execute @var{ver} version of the compiler. This is the @command{gcc}
4217 version, not the GNAT version.
4220 @item ^-w^/NO_BACK_END_WARNINGS^
4221 @cindex @option{-w} (@command{gcc})
4222 Turn off warnings generated by the back end of the compiler. Use of
4223 this switch also causes the default for front end warnings to be set
4224 to suppress (as though @option{-gnatws} had appeared at the start of
4230 @c Combining qualifiers does not work on VMS
4231 You may combine a sequence of GNAT switches into a single switch. For
4232 example, the combined switch
4234 @cindex Combining GNAT switches
4240 is equivalent to specifying the following sequence of switches:
4243 -gnato -gnatf -gnati3
4248 The following restrictions apply to the combination of switches
4253 The switch @option{-gnatc} if combined with other switches must come
4254 first in the string.
4257 The switch @option{-gnats} if combined with other switches must come
4258 first in the string.
4262 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4263 may not be combined with any other switches.
4267 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4268 switch), then all further characters in the switch are interpreted
4269 as style modifiers (see description of @option{-gnaty}).
4272 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4273 switch), then all further characters in the switch are interpreted
4274 as debug flags (see description of @option{-gnatd}).
4277 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4278 switch), then all further characters in the switch are interpreted
4279 as warning mode modifiers (see description of @option{-gnatw}).
4282 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4283 switch), then all further characters in the switch are interpreted
4284 as validity checking options (see description of @option{-gnatV}).
4288 @node Output and Error Message Control
4289 @subsection Output and Error Message Control
4293 The standard default format for error messages is called ``brief format''.
4294 Brief format messages are written to @file{stderr} (the standard error
4295 file) and have the following form:
4298 e.adb:3:04: Incorrect spelling of keyword "function"
4299 e.adb:4:20: ";" should be "is"
4303 The first integer after the file name is the line number in the file,
4304 and the second integer is the column number within the line.
4306 @code{GPS} can parse the error messages
4307 and point to the referenced character.
4309 The following switches provide control over the error message
4315 @cindex @option{-gnatv} (@command{gcc})
4318 The v stands for verbose.
4320 The effect of this setting is to write long-format error
4321 messages to @file{stdout} (the standard output file.
4322 The same program compiled with the
4323 @option{-gnatv} switch would generate:
4327 3. funcion X (Q : Integer)
4329 >>> Incorrect spelling of keyword "function"
4332 >>> ";" should be "is"
4337 The vertical bar indicates the location of the error, and the @samp{>>>}
4338 prefix can be used to search for error messages. When this switch is
4339 used the only source lines output are those with errors.
4342 @cindex @option{-gnatl} (@command{gcc})
4344 The @code{l} stands for list.
4346 This switch causes a full listing of
4347 the file to be generated. In the case where a body is
4348 compiled, the corresponding spec is also listed, along
4349 with any subunits. Typical output from compiling a package
4350 body @file{p.adb} might look like:
4352 @smallexample @c ada
4356 1. package body p is
4358 3. procedure a is separate;
4369 2. pragma Elaborate_Body
4393 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4394 standard output is redirected, a brief summary is written to
4395 @file{stderr} (standard error) giving the number of error messages and
4396 warning messages generated.
4398 @item -^gnatl^OUTPUT_FILE^=file
4399 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4400 This has the same effect as @code{-gnatl} except that the output is
4401 written to a file instead of to standard output. If the given name
4402 @file{fname} does not start with a period, then it is the full name
4403 of the file to be written. If @file{fname} is an extension, it is
4404 appended to the name of the file being compiled. For example, if
4405 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4406 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4409 @cindex @option{-gnatU} (@command{gcc})
4410 This switch forces all error messages to be preceded by the unique
4411 string ``error:''. This means that error messages take a few more
4412 characters in space, but allows easy searching for and identification
4416 @cindex @option{-gnatb} (@command{gcc})
4418 The @code{b} stands for brief.
4420 This switch causes GNAT to generate the
4421 brief format error messages to @file{stderr} (the standard error
4422 file) as well as the verbose
4423 format message or full listing (which as usual is written to
4424 @file{stdout} (the standard output file).
4426 @item -gnatm=@var{n}
4427 @cindex @option{-gnatm} (@command{gcc})
4429 The @code{m} stands for maximum.
4431 @var{n} is a decimal integer in the
4432 range of 1 to 999 and limits the number of error messages to be
4433 generated. For example, using @option{-gnatm2} might yield
4436 e.adb:3:04: Incorrect spelling of keyword "function"
4437 e.adb:5:35: missing ".."
4438 fatal error: maximum errors reached
4439 compilation abandoned
4443 Note that the equal sign is optional, so the switches
4444 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4447 @cindex @option{-gnatf} (@command{gcc})
4448 @cindex Error messages, suppressing
4450 The @code{f} stands for full.
4452 Normally, the compiler suppresses error messages that are likely to be
4453 redundant. This switch causes all error
4454 messages to be generated. In particular, in the case of
4455 references to undefined variables. If a given variable is referenced
4456 several times, the normal format of messages is
4458 e.adb:7:07: "V" is undefined (more references follow)
4462 where the parenthetical comment warns that there are additional
4463 references to the variable @code{V}. Compiling the same program with the
4464 @option{-gnatf} switch yields
4467 e.adb:7:07: "V" is undefined
4468 e.adb:8:07: "V" is undefined
4469 e.adb:8:12: "V" is undefined
4470 e.adb:8:16: "V" is undefined
4471 e.adb:9:07: "V" is undefined
4472 e.adb:9:12: "V" is undefined
4476 The @option{-gnatf} switch also generates additional information for
4477 some error messages. Some examples are:
4481 Full details on entities not available in high integrity mode
4483 Details on possibly non-portable unchecked conversion
4485 List possible interpretations for ambiguous calls
4487 Additional details on incorrect parameters
4491 @cindex @option{-gnatjnn} (@command{gcc})
4492 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4493 with continuation lines are treated as though the continuation lines were
4494 separate messages (and so a warning with two continuation lines counts as
4495 three warnings, and is listed as three separate messages).
4497 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4498 messages are output in a different manner. A message and all its continuation
4499 lines are treated as a unit, and count as only one warning or message in the
4500 statistics totals. Furthermore, the message is reformatted so that no line
4501 is longer than nn characters.
4504 @cindex @option{-gnatq} (@command{gcc})
4506 The @code{q} stands for quit (really ``don't quit'').
4508 In normal operation mode, the compiler first parses the program and
4509 determines if there are any syntax errors. If there are, appropriate
4510 error messages are generated and compilation is immediately terminated.
4512 GNAT to continue with semantic analysis even if syntax errors have been
4513 found. This may enable the detection of more errors in a single run. On
4514 the other hand, the semantic analyzer is more likely to encounter some
4515 internal fatal error when given a syntactically invalid tree.
4518 @cindex @option{-gnatQ} (@command{gcc})
4519 In normal operation mode, the @file{ALI} file is not generated if any
4520 illegalities are detected in the program. The use of @option{-gnatQ} forces
4521 generation of the @file{ALI} file. This file is marked as being in
4522 error, so it cannot be used for binding purposes, but it does contain
4523 reasonably complete cross-reference information, and thus may be useful
4524 for use by tools (e.g. semantic browsing tools or integrated development
4525 environments) that are driven from the @file{ALI} file. This switch
4526 implies @option{-gnatq}, since the semantic phase must be run to get a
4527 meaningful ALI file.
4529 In addition, if @option{-gnatt} is also specified, then the tree file is
4530 generated even if there are illegalities. It may be useful in this case
4531 to also specify @option{-gnatq} to ensure that full semantic processing
4532 occurs. The resulting tree file can be processed by ASIS, for the purpose
4533 of providing partial information about illegal units, but if the error
4534 causes the tree to be badly malformed, then ASIS may crash during the
4537 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4538 being in error, @command{gnatmake} will attempt to recompile the source when it
4539 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4541 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4542 since ALI files are never generated if @option{-gnats} is set.
4546 @node Warning Message Control
4547 @subsection Warning Message Control
4548 @cindex Warning messages
4550 In addition to error messages, which correspond to illegalities as defined
4551 in the Ada Reference Manual, the compiler detects two kinds of warning
4554 First, the compiler considers some constructs suspicious and generates a
4555 warning message to alert you to a possible error. Second, if the
4556 compiler detects a situation that is sure to raise an exception at
4557 run time, it generates a warning message. The following shows an example
4558 of warning messages:
4560 e.adb:4:24: warning: creation of object may raise Storage_Error
4561 e.adb:10:17: warning: static value out of range
4562 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4566 GNAT considers a large number of situations as appropriate
4567 for the generation of warning messages. As always, warnings are not
4568 definite indications of errors. For example, if you do an out-of-range
4569 assignment with the deliberate intention of raising a
4570 @code{Constraint_Error} exception, then the warning that may be
4571 issued does not indicate an error. Some of the situations for which GNAT
4572 issues warnings (at least some of the time) are given in the following
4573 list. This list is not complete, and new warnings are often added to
4574 subsequent versions of GNAT. The list is intended to give a general idea
4575 of the kinds of warnings that are generated.
4579 Possible infinitely recursive calls
4582 Out-of-range values being assigned
4585 Possible order of elaboration problems
4588 Assertions (pragma Assert) that are sure to fail
4594 Address clauses with possibly unaligned values, or where an attempt is
4595 made to overlay a smaller variable with a larger one.
4598 Fixed-point type declarations with a null range
4601 Direct_IO or Sequential_IO instantiated with a type that has access values
4604 Variables that are never assigned a value
4607 Variables that are referenced before being initialized
4610 Task entries with no corresponding @code{accept} statement
4613 Duplicate accepts for the same task entry in a @code{select}
4616 Objects that take too much storage
4619 Unchecked conversion between types of differing sizes
4622 Missing @code{return} statement along some execution path in a function
4625 Incorrect (unrecognized) pragmas
4628 Incorrect external names
4631 Allocation from empty storage pool
4634 Potentially blocking operation in protected type
4637 Suspicious parenthesization of expressions
4640 Mismatching bounds in an aggregate
4643 Attempt to return local value by reference
4646 Premature instantiation of a generic body
4649 Attempt to pack aliased components
4652 Out of bounds array subscripts
4655 Wrong length on string assignment
4658 Violations of style rules if style checking is enabled
4661 Unused @code{with} clauses
4664 @code{Bit_Order} usage that does not have any effect
4667 @code{Standard.Duration} used to resolve universal fixed expression
4670 Dereference of possibly null value
4673 Declaration that is likely to cause storage error
4676 Internal GNAT unit @code{with}'ed by application unit
4679 Values known to be out of range at compile time
4682 Unreferenced labels and variables
4685 Address overlays that could clobber memory
4688 Unexpected initialization when address clause present
4691 Bad alignment for address clause
4694 Useless type conversions
4697 Redundant assignment statements and other redundant constructs
4700 Useless exception handlers
4703 Accidental hiding of name by child unit
4706 Access before elaboration detected at compile time
4709 A range in a @code{for} loop that is known to be null or might be null
4714 The following section lists compiler switches that are available
4715 to control the handling of warning messages. It is also possible
4716 to exercise much finer control over what warnings are issued and
4717 suppressed using the GNAT pragma Warnings, which is documented
4718 in the GNAT Reference manual.
4723 @emph{Activate all optional errors.}
4724 @cindex @option{-gnatwa} (@command{gcc})
4725 This switch activates most optional warning messages, see remaining list
4726 in this section for details on optional warning messages that can be
4727 individually controlled. The warnings that are not turned on by this
4729 @option{-gnatwd} (implicit dereferencing),
4730 @option{-gnatwh} (hiding),
4731 @option{-gnatwl} (elaboration warnings),
4732 @option{-gnatw.o} (warn on values set by out parameters ignored)
4733 and @option{-gnatwt} (tracking of deleted conditional code).
4734 All other optional warnings are turned on.
4737 @emph{Suppress all optional errors.}
4738 @cindex @option{-gnatwA} (@command{gcc})
4739 This switch suppresses all optional warning messages, see remaining list
4740 in this section for details on optional warning messages that can be
4741 individually controlled.
4744 @emph{Activate warnings on failing assertions.}
4745 @cindex @option{-gnatw.a} (@command{gcc})
4746 @cindex Assert failures
4747 This switch activates warnings for assertions where the compiler can tell at
4748 compile time that the assertion will fail. Note that this warning is given
4749 even if assertions are disabled. The default is that such warnings are
4753 @emph{Suppress warnings on failing assertions.}
4754 @cindex @option{-gnatw.A} (@command{gcc})
4755 @cindex Assert failures
4756 This switch suppresses warnings for assertions where the compiler can tell at
4757 compile time that the assertion will fail.
4760 @emph{Activate warnings on bad fixed values.}
4761 @cindex @option{-gnatwb} (@command{gcc})
4762 @cindex Bad fixed values
4763 @cindex Fixed-point Small value
4765 This switch activates warnings for static fixed-point expressions whose
4766 value is not an exact multiple of Small. Such values are implementation
4767 dependent, since an implementation is free to choose either of the multiples
4768 that surround the value. GNAT always chooses the closer one, but this is not
4769 required behavior, and it is better to specify a value that is an exact
4770 multiple, ensuring predictable execution. The default is that such warnings
4774 @emph{Suppress warnings on bad fixed values.}
4775 @cindex @option{-gnatwB} (@command{gcc})
4776 This switch suppresses warnings for static fixed-point expressions whose
4777 value is not an exact multiple of Small.
4780 @emph{Activate warnings on conditionals.}
4781 @cindex @option{-gnatwc} (@command{gcc})
4782 @cindex Conditionals, constant
4783 This switch activates warnings for conditional expressions used in
4784 tests that are known to be True or False at compile time. The default
4785 is that such warnings are not generated.
4786 Note that this warning does
4787 not get issued for the use of boolean variables or constants whose
4788 values are known at compile time, since this is a standard technique
4789 for conditional compilation in Ada, and this would generate too many
4790 false positive warnings.
4792 This warning option also activates a special test for comparisons using
4793 the operators ``>='' and`` <=''.
4794 If the compiler can tell that only the equality condition is possible,
4795 then it will warn that the ``>'' or ``<'' part of the test
4796 is useless and that the operator could be replaced by ``=''.
4797 An example would be comparing a @code{Natural} variable <= 0.
4799 This warning option also generates warnings if
4800 one or both tests is optimized away in a membership test for integer
4801 values if the result can be determined at compile time. Range tests on
4802 enumeration types are not included, since it is common for such tests
4803 to include an end point.
4805 This warning can also be turned on using @option{-gnatwa}.
4808 @emph{Suppress warnings on conditionals.}
4809 @cindex @option{-gnatwC} (@command{gcc})
4810 This switch suppresses warnings for conditional expressions used in
4811 tests that are known to be True or False at compile time.
4814 @emph{Activate warnings on missing component clauses.}
4815 @cindex @option{-gnatw.c} (@command{gcc})
4816 @cindex Component clause, missing
4817 This switch activates warnings for record components where a record
4818 representation clause is present and has component clauses for the
4819 majority, but not all, of the components. A warning is given for each
4820 component for which no component clause is present.
4822 This warning can also be turned on using @option{-gnatwa}.
4825 @emph{Suppress warnings on missing component clauses.}
4826 @cindex @option{-gnatwC} (@command{gcc})
4827 This switch suppresses warnings for record components that are
4828 missing a component clause in the situation described above.
4831 @emph{Activate warnings on implicit dereferencing.}
4832 @cindex @option{-gnatwd} (@command{gcc})
4833 If this switch is set, then the use of a prefix of an access type
4834 in an indexed component, slice, or selected component without an
4835 explicit @code{.all} will generate a warning. With this warning
4836 enabled, access checks occur only at points where an explicit
4837 @code{.all} appears in the source code (assuming no warnings are
4838 generated as a result of this switch). The default is that such
4839 warnings are not generated.
4840 Note that @option{-gnatwa} does not affect the setting of
4841 this warning option.
4844 @emph{Suppress warnings on implicit dereferencing.}
4845 @cindex @option{-gnatwD} (@command{gcc})
4846 @cindex Implicit dereferencing
4847 @cindex Dereferencing, implicit
4848 This switch suppresses warnings for implicit dereferences in
4849 indexed components, slices, and selected components.
4852 @emph{Treat warnings as errors.}
4853 @cindex @option{-gnatwe} (@command{gcc})
4854 @cindex Warnings, treat as error
4855 This switch causes warning messages to be treated as errors.
4856 The warning string still appears, but the warning messages are counted
4857 as errors, and prevent the generation of an object file.
4860 @emph{Activate warnings on unreferenced formals.}
4861 @cindex @option{-gnatwf} (@command{gcc})
4862 @cindex Formals, unreferenced
4863 This switch causes a warning to be generated if a formal parameter
4864 is not referenced in the body of the subprogram. This warning can
4865 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
4866 default is that these warnings are not generated.
4869 @emph{Suppress warnings on unreferenced formals.}
4870 @cindex @option{-gnatwF} (@command{gcc})
4871 This switch suppresses warnings for unreferenced formal
4872 parameters. Note that the
4873 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4874 effect of warning on unreferenced entities other than subprogram
4878 @emph{Activate warnings on unrecognized pragmas.}
4879 @cindex @option{-gnatwg} (@command{gcc})
4880 @cindex Pragmas, unrecognized
4881 This switch causes a warning to be generated if an unrecognized
4882 pragma is encountered. Apart from issuing this warning, the
4883 pragma is ignored and has no effect. This warning can
4884 also be turned on using @option{-gnatwa}. The default
4885 is that such warnings are issued (satisfying the Ada Reference
4886 Manual requirement that such warnings appear).
4889 @emph{Suppress warnings on unrecognized pragmas.}
4890 @cindex @option{-gnatwG} (@command{gcc})
4891 This switch suppresses warnings for unrecognized pragmas.
4894 @emph{Activate warnings on hiding.}
4895 @cindex @option{-gnatwh} (@command{gcc})
4896 @cindex Hiding of Declarations
4897 This switch activates warnings on hiding declarations.
4898 A declaration is considered hiding
4899 if it is for a non-overloadable entity, and it declares an entity with the
4900 same name as some other entity that is directly or use-visible. The default
4901 is that such warnings are not generated.
4902 Note that @option{-gnatwa} does not affect the setting of this warning option.
4905 @emph{Suppress warnings on hiding.}
4906 @cindex @option{-gnatwH} (@command{gcc})
4907 This switch suppresses warnings on hiding declarations.
4910 @emph{Activate warnings on implementation units.}
4911 @cindex @option{-gnatwi} (@command{gcc})
4912 This switch activates warnings for a @code{with} of an internal GNAT
4913 implementation unit, defined as any unit from the @code{Ada},
4914 @code{Interfaces}, @code{GNAT},
4915 ^^@code{DEC},^ or @code{System}
4916 hierarchies that is not
4917 documented in either the Ada Reference Manual or the GNAT
4918 Programmer's Reference Manual. Such units are intended only
4919 for internal implementation purposes and should not be @code{with}'ed
4920 by user programs. The default is that such warnings are generated
4921 This warning can also be turned on using @option{-gnatwa}.
4924 @emph{Disable warnings on implementation units.}
4925 @cindex @option{-gnatwI} (@command{gcc})
4926 This switch disables warnings for a @code{with} of an internal GNAT
4927 implementation unit.
4930 @emph{Activate warnings on obsolescent features (Annex J).}
4931 @cindex @option{-gnatwj} (@command{gcc})
4932 @cindex Features, obsolescent
4933 @cindex Obsolescent features
4934 If this warning option is activated, then warnings are generated for
4935 calls to subprograms marked with @code{pragma Obsolescent} and
4936 for use of features in Annex J of the Ada Reference Manual. In the
4937 case of Annex J, not all features are flagged. In particular use
4938 of the renamed packages (like @code{Text_IO}) and use of package
4939 @code{ASCII} are not flagged, since these are very common and
4940 would generate many annoying positive warnings. The default is that
4941 such warnings are not generated. This warning is also turned on by
4942 the use of @option{-gnatwa}.
4944 In addition to the above cases, warnings are also generated for
4945 GNAT features that have been provided in past versions but which
4946 have been superseded (typically by features in the new Ada standard).
4947 For example, @code{pragma Ravenscar} will be flagged since its
4948 function is replaced by @code{pragma Profile(Ravenscar)}.
4950 Note that this warning option functions differently from the
4951 restriction @code{No_Obsolescent_Features} in two respects.
4952 First, the restriction applies only to annex J features.
4953 Second, the restriction does flag uses of package @code{ASCII}.
4956 @emph{Suppress warnings on obsolescent features (Annex J).}
4957 @cindex @option{-gnatwJ} (@command{gcc})
4958 This switch disables warnings on use of obsolescent features.
4961 @emph{Activate warnings on variables that could be constants.}
4962 @cindex @option{-gnatwk} (@command{gcc})
4963 This switch activates warnings for variables that are initialized but
4964 never modified, and then could be declared constants. The default is that
4965 such warnings are not given.
4966 This warning can also be turned on using @option{-gnatwa}.
4969 @emph{Suppress warnings on variables that could be constants.}
4970 @cindex @option{-gnatwK} (@command{gcc})
4971 This switch disables warnings on variables that could be declared constants.
4974 @emph{Activate warnings for missing elaboration pragmas.}
4975 @cindex @option{-gnatwl} (@command{gcc})
4976 @cindex Elaboration, warnings
4977 This switch activates warnings on missing
4978 @code{Elaborate_All} and @code{Elaborate} pragmas.
4979 See the section in this guide on elaboration checking for details on
4980 when such pragmas should be used. Warnings are also generated if you
4981 are using the static mode of elaboration, and a @code{pragma Elaborate}
4982 is encountered. The default is that such warnings
4984 This warning is not automatically turned on by the use of @option{-gnatwa}.
4987 @emph{Suppress warnings for missing elaboration pragmas.}
4988 @cindex @option{-gnatwL} (@command{gcc})
4989 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
4990 See the section in this guide on elaboration checking for details on
4991 when such pragmas should be used.
4994 @emph{Activate warnings on modified but unreferenced variables.}
4995 @cindex @option{-gnatwm} (@command{gcc})
4996 This switch activates warnings for variables that are assigned (using
4997 an initialization value or with one or more assignment statements) but
4998 whose value is never read. The warning is suppressed for volatile
4999 variables and also for variables that are renamings of other variables
5000 or for which an address clause is given.
5001 This warning can also be turned on using @option{-gnatwa}.
5002 The default is that these warnings are not given.
5005 @emph{Disable warnings on modified but unreferenced variables.}
5006 @cindex @option{-gnatwM} (@command{gcc})
5007 This switch disables warnings for variables that are assigned or
5008 initialized, but never read.
5011 @emph{Set normal warnings mode.}
5012 @cindex @option{-gnatwn} (@command{gcc})
5013 This switch sets normal warning mode, in which enabled warnings are
5014 issued and treated as warnings rather than errors. This is the default
5015 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5016 an explicit @option{-gnatws} or
5017 @option{-gnatwe}. It also cancels the effect of the
5018 implicit @option{-gnatwe} that is activated by the
5019 use of @option{-gnatg}.
5022 @emph{Activate warnings on address clause overlays.}
5023 @cindex @option{-gnatwo} (@command{gcc})
5024 @cindex Address Clauses, warnings
5025 This switch activates warnings for possibly unintended initialization
5026 effects of defining address clauses that cause one variable to overlap
5027 another. The default is that such warnings are generated.
5028 This warning can also be turned on using @option{-gnatwa}.
5031 @emph{Suppress warnings on address clause overlays.}
5032 @cindex @option{-gnatwO} (@command{gcc})
5033 This switch suppresses warnings on possibly unintended initialization
5034 effects of defining address clauses that cause one variable to overlap
5038 @emph{Activate warnings on modified but unreferenced out parameters.}
5039 @cindex @option{-gnatw.o} (@command{gcc})
5040 This switch activates warnings for variables that are modified by using
5041 them as actuals for a call to a procedure with an out mode formal, where
5042 the resulting assigned value is never read. It is applicable in the case
5043 where there is more than one out mode formal. If there is only one out
5044 mode formal, the warning is issued by default (controlled by -gnatwu).
5045 The warning is suppressed for volatile
5046 variables and also for variables that are renamings of other variables
5047 or for which an address clause is given.
5048 The default is that these warnings are not given. Note that this warning
5049 is not included in -gnatwa, it must be activated explicitly.
5052 @emph{Disable warnings on modified but unreferenced out parameters.}
5053 @cindex @option{-gnatw.O} (@command{gcc})
5054 This switch suppresses warnings for variables that are modified by using
5055 them as actuals for a call to a procedure with an out mode formal, where
5056 the resulting assigned value is never read.
5059 @emph{Activate warnings on ineffective pragma Inlines.}
5060 @cindex @option{-gnatwp} (@command{gcc})
5061 @cindex Inlining, warnings
5062 This switch activates warnings for failure of front end inlining
5063 (activated by @option{-gnatN}) to inline a particular call. There are
5064 many reasons for not being able to inline a call, including most
5065 commonly that the call is too complex to inline. The default is
5066 that such warnings are not given.
5067 This warning can also be turned on using @option{-gnatwa}.
5068 Warnings on ineffective inlining by the gcc back-end can be activated
5069 separately, using the gcc switch -Winline.
5072 @emph{Suppress warnings on ineffective pragma Inlines.}
5073 @cindex @option{-gnatwP} (@command{gcc})
5074 This switch suppresses warnings on ineffective pragma Inlines. If the
5075 inlining mechanism cannot inline a call, it will simply ignore the
5079 @emph{Activate warnings on questionable missing parentheses.}
5080 @cindex @option{-gnatwq} (@command{gcc})
5081 @cindex Parentheses, warnings
5082 This switch activates warnings for cases where parentheses are not used and
5083 the result is potential ambiguity from a readers point of view. For example
5084 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5085 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5086 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5087 follow the rule of always parenthesizing to make the association clear, and
5088 this warning switch warns if such parentheses are not present. The default
5089 is that these warnings are given.
5090 This warning can also be turned on using @option{-gnatwa}.
5093 @emph{Suppress warnings on questionable missing parentheses.}
5094 @cindex @option{-gnatwQ} (@command{gcc})
5095 This switch suppresses warnings for cases where the association is not
5096 clear and the use of parentheses is preferred.
5099 @emph{Activate warnings on redundant constructs.}
5100 @cindex @option{-gnatwr} (@command{gcc})
5101 This switch activates warnings for redundant constructs. The following
5102 is the current list of constructs regarded as redundant:
5106 Assignment of an item to itself.
5108 Type conversion that converts an expression to its own type.
5110 Use of the attribute @code{Base} where @code{typ'Base} is the same
5113 Use of pragma @code{Pack} when all components are placed by a record
5114 representation clause.
5116 Exception handler containing only a reraise statement (raise with no
5117 operand) which has no effect.
5119 Use of the operator abs on an operand that is known at compile time
5122 Comparison of boolean expressions to an explicit True value.
5125 This warning can also be turned on using @option{-gnatwa}.
5126 The default is that warnings for redundant constructs are not given.
5129 @emph{Suppress warnings on redundant constructs.}
5130 @cindex @option{-gnatwR} (@command{gcc})
5131 This switch suppresses warnings for redundant constructs.
5134 @emph{Suppress all warnings.}
5135 @cindex @option{-gnatws} (@command{gcc})
5136 This switch completely suppresses the
5137 output of all warning messages from the GNAT front end.
5138 Note that it does not suppress warnings from the @command{gcc} back end.
5139 To suppress these back end warnings as well, use the switch @option{-w}
5140 in addition to @option{-gnatws}.
5143 @emph{Activate warnings for tracking of deleted conditional code.}
5144 @cindex @option{-gnatwt} (@command{gcc})
5145 @cindex Deactivated code, warnings
5146 @cindex Deleted code, warnings
5147 This switch activates warnings for tracking of code in conditionals (IF and
5148 CASE statements) that is detected to be dead code which cannot be executed, and
5149 which is removed by the front end. This warning is off by default, and is not
5150 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5151 useful for detecting deactivated code in certified applications.
5154 @emph{Suppress warnings for tracking of deleted conditional code.}
5155 @cindex @option{-gnatwT} (@command{gcc})
5156 This switch suppresses warnings for tracking of deleted conditional code.
5159 @emph{Activate warnings on unused entities.}
5160 @cindex @option{-gnatwu} (@command{gcc})
5161 This switch activates warnings to be generated for entities that
5162 are declared but not referenced, and for units that are @code{with}'ed
5164 referenced. In the case of packages, a warning is also generated if
5165 no entities in the package are referenced. This means that if the package
5166 is referenced but the only references are in @code{use}
5167 clauses or @code{renames}
5168 declarations, a warning is still generated. A warning is also generated
5169 for a generic package that is @code{with}'ed but never instantiated.
5170 In the case where a package or subprogram body is compiled, and there
5171 is a @code{with} on the corresponding spec
5172 that is only referenced in the body,
5173 a warning is also generated, noting that the
5174 @code{with} can be moved to the body. The default is that
5175 such warnings are not generated.
5176 This switch also activates warnings on unreferenced formals
5177 (it includes the effect of @option{-gnatwf}).
5178 This warning can also be turned on using @option{-gnatwa}.
5181 @emph{Suppress warnings on unused entities.}
5182 @cindex @option{-gnatwU} (@command{gcc})
5183 This switch suppresses warnings for unused entities and packages.
5184 It also turns off warnings on unreferenced formals (and thus includes
5185 the effect of @option{-gnatwF}).
5188 @emph{Activate warnings on unassigned variables.}
5189 @cindex @option{-gnatwv} (@command{gcc})
5190 @cindex Unassigned variable warnings
5191 This switch activates warnings for access to variables which
5192 may not be properly initialized. The default is that
5193 such warnings are generated.
5194 This warning can also be turned on using @option{-gnatwa}.
5197 @emph{Suppress warnings on unassigned variables.}
5198 @cindex @option{-gnatwV} (@command{gcc})
5199 This switch suppresses warnings for access to variables which
5200 may not be properly initialized.
5201 For variables of a composite type, the warning can also be suppressed in
5202 Ada 2005 by using a default initialization with a box. For example, if
5203 Table is an array of records whose components are only partially uninitialized,
5204 then the following code:
5206 @smallexample @c ada
5207 Tab : Table := (others => <>);
5210 will suppress warnings on subsequent statements that access components
5214 @emph{Activate warnings on wrong low bound assumption.}
5215 @cindex @option{-gnatww} (@command{gcc})
5216 @cindex String indexing warnings
5217 This switch activates warnings for indexing an unconstrained string parameter
5218 with a literal or S'Length. This is a case where the code is assuming that the
5219 low bound is one, which is in general not true (for example when a slice is
5220 passed). The default is that such warnings are generated.
5221 This warning can also be turned on using @option{-gnatwa}.
5224 @emph{Suppress warnings on wrong low bound assumption.}
5225 @cindex @option{-gnatwW} (@command{gcc})
5226 This switch activates warnings for indexing an unconstrained string parameter
5227 with a literal or S'Length. This warning can also be suppressed by providing
5228 an Assert pragma that checks the low bound, for example:
5230 @smallexample @c ada
5231 procedure K (S : String) is
5232 pragma Assert (S'First = 1);
5237 @emph{Activate warnings on Export/Import pragmas.}
5238 @cindex @option{-gnatwx} (@command{gcc})
5239 @cindex Export/Import pragma warnings
5240 This switch activates warnings on Export/Import pragmas when
5241 the compiler detects a possible conflict between the Ada and
5242 foreign language calling sequences. For example, the use of
5243 default parameters in a convention C procedure is dubious
5244 because the C compiler cannot supply the proper default, so
5245 a warning is issued. The default is that such warnings are
5247 This warning can also be turned on using @option{-gnatwa}.
5250 @emph{Suppress warnings on Export/Import pragmas.}
5251 @cindex @option{-gnatwX} (@command{gcc})
5252 This switch suppresses warnings on Export/Import pragmas.
5253 The sense of this is that you are telling the compiler that
5254 you know what you are doing in writing the pragma, and it
5255 should not complain at you.
5258 @emph{Activate warnings for No_Exception_Propagation mode.}
5259 @cindex @option{-gnatwm} (@command{gcc})
5260 This switch activates warnings for exception usage when pragma Restrictions
5261 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5262 explicit exception raises which are not covered by a local handler, and for
5263 exception handlers which do not cover a local raise. The default is that these
5264 warnings are not given.
5267 @emph{Disable warnings for No_Exception_Propagation mode.}
5268 This switch disables warnings for exception usage when pragma Restrictions
5269 (No_Exception_Propagation) is in effect.
5272 @emph{Activate warnings for Ada 2005 compatibility issues.}
5273 @cindex @option{-gnatwy} (@command{gcc})
5274 @cindex Ada 2005 compatibility issues warnings
5275 For the most part Ada 2005 is upwards compatible with Ada 95,
5276 but there are some exceptions (for example the fact that
5277 @code{interface} is now a reserved word in Ada 2005). This
5278 switch activates several warnings to help in identifying
5279 and correcting such incompatibilities. The default is that
5280 these warnings are generated. Note that at one point Ada 2005
5281 was called Ada 0Y, hence the choice of character.
5282 This warning can also be turned on using @option{-gnatwa}.
5285 @emph{Disable warnings for Ada 2005 compatibility issues.}
5286 @cindex @option{-gnatwY} (@command{gcc})
5287 @cindex Ada 2005 compatibility issues warnings
5288 This switch suppresses several warnings intended to help in identifying
5289 incompatibilities between Ada 95 and Ada 2005.
5292 @emph{Activate warnings on unchecked conversions.}
5293 @cindex @option{-gnatwz} (@command{gcc})
5294 @cindex Unchecked_Conversion warnings
5295 This switch activates warnings for unchecked conversions
5296 where the types are known at compile time to have different
5298 is that such warnings are generated.
5299 This warning can also be turned on using @option{-gnatwa}.
5302 @emph{Suppress warnings on unchecked conversions.}
5303 @cindex @option{-gnatwZ} (@command{gcc})
5304 This switch suppresses warnings for unchecked conversions
5305 where the types are known at compile time to have different
5308 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5309 @cindex @option{-Wuninitialized}
5310 The warnings controlled by the @option{-gnatw} switch are generated by the
5311 front end of the compiler. In some cases, the @option{^gcc^GCC^} back end
5312 can provide additional warnings. One such useful warning is provided by
5313 @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^}. This must be used in
5314 conjunction with turning on optimization mode. This causes the flow
5315 analysis circuits of the back end optimizer to output additional
5316 warnings about uninitialized variables.
5318 @item ^-w^/NO_BACK_END_WARNINGS^
5320 This switch suppresses warnings from the @option{^gcc^GCC^} back end. The
5321 code generator detects a number of warning situations that are missed
5322 by the @option{GNAT} front end, and this switch can be used to suppress them.
5323 The use of this switch also sets the default front end warning mode to
5324 @option{-gnatws}, that is, front end warnings suppressed as well.
5330 A string of warning parameters can be used in the same parameter. For example:
5337 will turn on all optional warnings except for elaboration pragma warnings,
5338 and also specify that warnings should be treated as errors.
5340 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5365 @node Debugging and Assertion Control
5366 @subsection Debugging and Assertion Control
5370 @cindex @option{-gnata} (@command{gcc})
5376 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5377 are ignored. This switch, where @samp{a} stands for assert, causes
5378 @code{Assert} and @code{Debug} pragmas to be activated.
5380 The pragmas have the form:
5384 @b{pragma} Assert (@var{Boolean-expression} [,
5385 @var{static-string-expression}])
5386 @b{pragma} Debug (@var{procedure call})
5391 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5392 If the result is @code{True}, the pragma has no effect (other than
5393 possible side effects from evaluating the expression). If the result is
5394 @code{False}, the exception @code{Assert_Failure} declared in the package
5395 @code{System.Assertions} is
5396 raised (passing @var{static-string-expression}, if present, as the
5397 message associated with the exception). If no string expression is
5398 given the default is a string giving the file name and line number
5401 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5402 @code{pragma Debug} may appear within a declaration sequence, allowing
5403 debugging procedures to be called between declarations.
5406 @item /DEBUG[=debug-level]
5408 Specifies how much debugging information is to be included in
5409 the resulting object file where 'debug-level' is one of the following:
5412 Include both debugger symbol records and traceback
5414 This is the default setting.
5416 Include both debugger symbol records and traceback in
5419 Excludes both debugger symbol records and traceback
5420 the object file. Same as /NODEBUG.
5422 Includes only debugger symbol records in the object
5423 file. Note that this doesn't include traceback information.
5428 @node Validity Checking
5429 @subsection Validity Checking
5430 @findex Validity Checking
5433 The Ada Reference Manual has specific requirements for checking
5434 for invalid values. In particular, RM 13.9.1 requires that the
5435 evaluation of invalid values (for example from unchecked conversions),
5436 not result in erroneous execution. In GNAT, the result of such an
5437 evaluation in normal default mode is to either use the value
5438 unmodified, or to raise Constraint_Error in those cases where use
5439 of the unmodified value would cause erroneous execution. The cases
5440 where unmodified values might lead to erroneous execution are case
5441 statements (where a wild jump might result from an invalid value),
5442 and subscripts on the left hand side (where memory corruption could
5443 occur as a result of an invalid value).
5445 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5448 The @code{x} argument is a string of letters that
5449 indicate validity checks that are performed or not performed in addition
5450 to the default checks described above.
5453 The options allowed for this qualifier
5454 indicate validity checks that are performed or not performed in addition
5455 to the default checks described above.
5461 @emph{All validity checks.}
5462 @cindex @option{-gnatVa} (@command{gcc})
5463 All validity checks are turned on.
5465 That is, @option{-gnatVa} is
5466 equivalent to @option{gnatVcdfimorst}.
5470 @emph{Validity checks for copies.}
5471 @cindex @option{-gnatVc} (@command{gcc})
5472 The right hand side of assignments, and the initializing values of
5473 object declarations are validity checked.
5476 @emph{Default (RM) validity checks.}
5477 @cindex @option{-gnatVd} (@command{gcc})
5478 Some validity checks are done by default following normal Ada semantics
5480 A check is done in case statements that the expression is within the range
5481 of the subtype. If it is not, Constraint_Error is raised.
5482 For assignments to array components, a check is done that the expression used
5483 as index is within the range. If it is not, Constraint_Error is raised.
5484 Both these validity checks may be turned off using switch @option{-gnatVD}.
5485 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5486 switch @option{-gnatVd} will leave the checks turned on.
5487 Switch @option{-gnatVD} should be used only if you are sure that all such
5488 expressions have valid values. If you use this switch and invalid values
5489 are present, then the program is erroneous, and wild jumps or memory
5490 overwriting may occur.
5493 @emph{Validity checks for elementary components.}
5494 @cindex @option{-gnatVe} (@command{gcc})
5495 In the absence of this switch, assignments to record or array components are
5496 not validity checked, even if validity checks for assignments generally
5497 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5498 require valid data, but assignment of individual components does. So for
5499 example, there is a difference between copying the elements of an array with a
5500 slice assignment, compared to assigning element by element in a loop. This
5501 switch allows you to turn off validity checking for components, even when they
5502 are assigned component by component.
5505 @emph{Validity checks for floating-point values.}
5506 @cindex @option{-gnatVf} (@command{gcc})
5507 In the absence of this switch, validity checking occurs only for discrete
5508 values. If @option{-gnatVf} is specified, then validity checking also applies
5509 for floating-point values, and NaNs and infinities are considered invalid,
5510 as well as out of range values for constrained types. Note that this means
5511 that standard IEEE infinity mode is not allowed. The exact contexts
5512 in which floating-point values are checked depends on the setting of other
5513 options. For example,
5514 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5515 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5516 (the order does not matter) specifies that floating-point parameters of mode
5517 @code{in} should be validity checked.
5520 @emph{Validity checks for @code{in} mode parameters}
5521 @cindex @option{-gnatVi} (@command{gcc})
5522 Arguments for parameters of mode @code{in} are validity checked in function
5523 and procedure calls at the point of call.
5526 @emph{Validity checks for @code{in out} mode parameters.}
5527 @cindex @option{-gnatVm} (@command{gcc})
5528 Arguments for parameters of mode @code{in out} are validity checked in
5529 procedure calls at the point of call. The @code{'m'} here stands for
5530 modify, since this concerns parameters that can be modified by the call.
5531 Note that there is no specific option to test @code{out} parameters,
5532 but any reference within the subprogram will be tested in the usual
5533 manner, and if an invalid value is copied back, any reference to it
5534 will be subject to validity checking.
5537 @emph{No validity checks.}
5538 @cindex @option{-gnatVn} (@command{gcc})
5539 This switch turns off all validity checking, including the default checking
5540 for case statements and left hand side subscripts. Note that the use of
5541 the switch @option{-gnatp} suppresses all run-time checks, including
5542 validity checks, and thus implies @option{-gnatVn}. When this switch
5543 is used, it cancels any other @option{-gnatV} previously issued.
5546 @emph{Validity checks for operator and attribute operands.}
5547 @cindex @option{-gnatVo} (@command{gcc})
5548 Arguments for predefined operators and attributes are validity checked.
5549 This includes all operators in package @code{Standard},
5550 the shift operators defined as intrinsic in package @code{Interfaces}
5551 and operands for attributes such as @code{Pos}. Checks are also made
5552 on individual component values for composite comparisons, and on the
5553 expressions in type conversions and qualified expressions. Checks are
5554 also made on explicit ranges using .. (e.g. slices, loops etc).
5557 @emph{Validity checks for parameters.}
5558 @cindex @option{-gnatVp} (@command{gcc})
5559 This controls the treatment of parameters within a subprogram (as opposed
5560 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5561 of parameters on a call. If either of these call options is used, then
5562 normally an assumption is made within a subprogram that the input arguments
5563 have been validity checking at the point of call, and do not need checking
5564 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5565 is not made, and parameters are not assumed to be valid, so their validity
5566 will be checked (or rechecked) within the subprogram.
5569 @emph{Validity checks for function returns.}
5570 @cindex @option{-gnatVr} (@command{gcc})
5571 The expression in @code{return} statements in functions is validity
5575 @emph{Validity checks for subscripts.}
5576 @cindex @option{-gnatVs} (@command{gcc})
5577 All subscripts expressions are checked for validity, whether they appear
5578 on the right side or left side (in default mode only left side subscripts
5579 are validity checked).
5582 @emph{Validity checks for tests.}
5583 @cindex @option{-gnatVt} (@command{gcc})
5584 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5585 statements are checked, as well as guard expressions in entry calls.
5590 The @option{-gnatV} switch may be followed by
5591 ^a string of letters^a list of options^
5592 to turn on a series of validity checking options.
5594 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5595 specifies that in addition to the default validity checking, copies and
5596 function return expressions are to be validity checked.
5597 In order to make it easier
5598 to specify the desired combination of effects,
5600 the upper case letters @code{CDFIMORST} may
5601 be used to turn off the corresponding lower case option.
5604 the prefix @code{NO} on an option turns off the corresponding validity
5607 @item @code{NOCOPIES}
5608 @item @code{NODEFAULT}
5609 @item @code{NOFLOATS}
5610 @item @code{NOIN_PARAMS}
5611 @item @code{NOMOD_PARAMS}
5612 @item @code{NOOPERANDS}
5613 @item @code{NORETURNS}
5614 @item @code{NOSUBSCRIPTS}
5615 @item @code{NOTESTS}
5619 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5620 turns on all validity checking options except for
5621 checking of @code{@b{in out}} procedure arguments.
5623 The specification of additional validity checking generates extra code (and
5624 in the case of @option{-gnatVa} the code expansion can be substantial.
5625 However, these additional checks can be very useful in detecting
5626 uninitialized variables, incorrect use of unchecked conversion, and other
5627 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5628 is useful in conjunction with the extra validity checking, since this
5629 ensures that wherever possible uninitialized variables have invalid values.
5631 See also the pragma @code{Validity_Checks} which allows modification of
5632 the validity checking mode at the program source level, and also allows for
5633 temporary disabling of validity checks.
5635 @node Style Checking
5636 @subsection Style Checking
5637 @findex Style checking
5640 The @option{-gnaty^x^(option,option,...)^} switch
5641 @cindex @option{-gnaty} (@command{gcc})
5642 causes the compiler to
5643 enforce specified style rules. A limited set of style rules has been used
5644 in writing the GNAT sources themselves. This switch allows user programs
5645 to activate all or some of these checks. If the source program fails a
5646 specified style check, an appropriate warning message is given, preceded by
5647 the character sequence ``(style)''.
5649 @code{(option,option,...)} is a sequence of keywords
5652 The string @var{x} is a sequence of letters or digits
5654 indicating the particular style
5655 checks to be performed. The following checks are defined:
5660 @emph{Specify indentation level.}
5661 If a digit from 1-9 appears
5662 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5663 then proper indentation is checked, with the digit indicating the
5664 indentation level required.
5665 The general style of required indentation is as specified by
5666 the examples in the Ada Reference Manual. Full line comments must be
5667 aligned with the @code{--} starting on a column that is a multiple of
5668 the alignment level, or they may be aligned the same way as the following
5669 non-blank line (this is useful when full line comments appear in the middle
5673 @emph{Check attribute casing.}
5674 If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty}
5675 then attribute names, including the case of keywords such as @code{digits}
5676 used as attributes names, must be written in mixed case, that is, the
5677 initial letter and any letter following an underscore must be uppercase.
5678 All other letters must be lowercase.
5680 @item ^A^ARRAY_INDEXES^
5681 @emph{Use of array index numbers in array attributes.}
5682 If the ^letter A^word ARRAY_INDEXES^ appears in the string after
5683 @option{-gnaty} then when using the array attributes First, Last, Range,
5684 or Length, the index number must be omitted for one-dimensional arrays
5685 and is required for multi-dimensional arrays.
5688 @emph{Blanks not allowed at statement end.}
5689 If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then
5690 trailing blanks are not allowed at the end of statements. The purpose of this
5691 rule, together with h (no horizontal tabs), is to enforce a canonical format
5692 for the use of blanks to separate source tokens.
5695 @emph{Check comments.}
5696 If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty}
5697 then comments must meet the following set of rules:
5702 The ``@code{--}'' that starts the column must either start in column one,
5703 or else at least one blank must precede this sequence.
5706 Comments that follow other tokens on a line must have at least one blank
5707 following the ``@code{--}'' at the start of the comment.
5710 Full line comments must have two blanks following the ``@code{--}'' that
5711 starts the comment, with the following exceptions.
5714 A line consisting only of the ``@code{--}'' characters, possibly preceded
5715 by blanks is permitted.
5718 A comment starting with ``@code{--x}'' where @code{x} is a special character
5720 This allows proper processing of the output generated by specialized tools
5721 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5723 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5724 special character is defined as being in one of the ASCII ranges
5725 @code{16#21#..16#2F#} or @code{16#3A#..16#3F#}.
5726 Note that this usage is not permitted
5727 in GNAT implementation units (i.e. when @option{-gnatg} is used).
5730 A line consisting entirely of minus signs, possibly preceded by blanks, is
5731 permitted. This allows the construction of box comments where lines of minus
5732 signs are used to form the top and bottom of the box.
5735 A comment that starts and ends with ``@code{--}'' is permitted as long as at
5736 least one blank follows the initial ``@code{--}''. Together with the preceding
5737 rule, this allows the construction of box comments, as shown in the following
5740 ---------------------------
5741 -- This is a box comment --
5742 -- with two text lines. --
5743 ---------------------------
5747 @item ^d^DOS_LINE_ENDINGS^
5748 @emph{Check no DOS line terminators present.}
5749 If the ^letter d^word DOS_LINE_ENDINGS^ appears in the string after
5750 @option{-gnaty} then all lines must be terminated by a single ASCII.LF
5751 character (in particular the DOS line terminator sequence CR/LF is not
5755 @emph{Check end/exit labels.}
5756 If the ^letter e^word END^ appears in the string after @option{-gnaty} then
5757 optional labels on @code{end} statements ending subprograms and on
5758 @code{exit} statements exiting named loops, are required to be present.
5761 @emph{No form feeds or vertical tabs.}
5762 If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then
5763 neither form feeds nor vertical tab characters are permitted
5767 @emph{GNAT style mode}
5768 If the ^letter g^word GNAT^ appears in the string after @option{-gnaty} then
5769 the set of style check switches is set to match that used by the GNAT sources.
5770 This may be useful when developing code that is eventually intended to be
5771 incorporated into GNAT. For further details, see GNAT sources.
5774 @emph{No horizontal tabs.}
5775 If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then
5776 horizontal tab characters are not permitted in the source text.
5777 Together with the b (no blanks at end of line) check, this
5778 enforces a canonical form for the use of blanks to separate
5782 @emph{Check if-then layout.}
5783 If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty},
5784 then the keyword @code{then} must appear either on the same
5785 line as corresponding @code{if}, or on a line on its own, lined
5786 up under the @code{if} with at least one non-blank line in between
5787 containing all or part of the condition to be tested.
5790 @emph{check mode IN keywords}
5791 If the ^letter I (upper case)^word IN_MODE^ appears in the string
5792 after @option{-gnaty} then mode @code{in} (the default mode) is not
5793 allowed to be given explicitly. @code{in out} is fine,
5794 but not @code{in} on its own.
5797 @emph{Check keyword casing.}
5798 If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then
5799 all keywords must be in lower case (with the exception of keywords
5800 such as @code{digits} used as attribute names to which this check
5804 @emph{Check layout.}
5805 If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then
5806 layout of statement and declaration constructs must follow the
5807 recommendations in the Ada Reference Manual, as indicated by the
5808 form of the syntax rules. For example an @code{else} keyword must
5809 be lined up with the corresponding @code{if} keyword.
5811 There are two respects in which the style rule enforced by this check
5812 option are more liberal than those in the Ada Reference Manual. First
5813 in the case of record declarations, it is permissible to put the
5814 @code{record} keyword on the same line as the @code{type} keyword, and
5815 then the @code{end} in @code{end record} must line up under @code{type}.
5816 This is also permitted when the type declaration is split on two lines.
5817 For example, any of the following three layouts is acceptable:
5819 @smallexample @c ada
5842 Second, in the case of a block statement, a permitted alternative
5843 is to put the block label on the same line as the @code{declare} or
5844 @code{begin} keyword, and then line the @code{end} keyword up under
5845 the block label. For example both the following are permitted:
5847 @smallexample @c ada
5865 The same alternative format is allowed for loops. For example, both of
5866 the following are permitted:
5868 @smallexample @c ada
5870 Clear : while J < 10 loop
5881 @item ^Lnnn^MAX_NESTING=nnn^
5882 @emph{Set maximum nesting level}
5883 If the sequence ^Lnnn^MAX_NESTING=nnn^, where nnn is a decimal number in
5884 the range 0-999, appears in the string after @option{-gnaty} then the
5885 maximum level of nesting of constructs (including subprograms, loops,
5886 blocks, packages, and conditionals) may not exceed the given value. A
5887 value of zero disconnects this style check.
5889 @item ^m^LINE_LENGTH^
5890 @emph{Check maximum line length.}
5891 If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty}
5892 then the length of source lines must not exceed 79 characters, including
5893 any trailing blanks. The value of 79 allows convenient display on an
5894 80 character wide device or window, allowing for possible special
5895 treatment of 80 character lines. Note that this count is of
5896 characters in the source text. This means that a tab character counts
5897 as one character in this count but a wide character sequence counts as
5898 a single character (however many bytes are needed in the encoding).
5900 @item ^Mnnn^MAX_LENGTH=nnn^
5901 @emph{Set maximum line length.}
5902 If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in
5903 the string after @option{-gnaty} then the length of lines must not exceed the
5904 given value. The maximum value that can be specified is 32767.
5906 @item ^n^STANDARD_CASING^
5907 @emph{Check casing of entities in Standard.}
5908 If the ^letter n^word STANDARD_CASING^ appears in the string
5909 after @option{-gnaty} then any identifier from Standard must be cased
5910 to match the presentation in the Ada Reference Manual (for example,
5911 @code{Integer} and @code{ASCII.NUL}).
5913 @item ^o^ORDERED_SUBPROGRAMS^
5914 @emph{Check order of subprogram bodies.}
5915 If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string
5916 after @option{-gnaty} then all subprogram bodies in a given scope
5917 (e.g. a package body) must be in alphabetical order. The ordering
5918 rule uses normal Ada rules for comparing strings, ignoring casing
5919 of letters, except that if there is a trailing numeric suffix, then
5920 the value of this suffix is used in the ordering (e.g. Junk2 comes
5924 @emph{Check pragma casing.}
5925 If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then
5926 pragma names must be written in mixed case, that is, the
5927 initial letter and any letter following an underscore must be uppercase.
5928 All other letters must be lowercase.
5930 @item ^r^REFERENCES^
5931 @emph{Check references.}
5932 If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty}
5933 then all identifier references must be cased in the same way as the
5934 corresponding declaration. No specific casing style is imposed on
5935 identifiers. The only requirement is for consistency of references
5938 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
5939 @emph{Check no statements after THEN/ELSE.}
5940 If the ^letter S^word STATEMENTS_AFTER_THEN_ELSE^ appears in the
5941 string after @option{-gnaty} then it is not permitted to write any
5942 statements on the same line as a THEN OR ELSE keyword following the
5943 keyword in an IF statement. OR ELSE and AND THEN are not affected,
5944 and a special exception allows a pragma to appear after ELSE.
5947 @emph{Check separate specs.}
5948 If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then
5949 separate declarations (``specs'') are required for subprograms (a
5950 body is not allowed to serve as its own declaration). The only
5951 exception is that parameterless library level procedures are
5952 not required to have a separate declaration. This exception covers
5953 the most frequent form of main program procedures.
5956 @emph{Check token spacing.}
5957 If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then
5958 the following token spacing rules are enforced:
5963 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
5966 The token @code{=>} must be surrounded by spaces.
5969 The token @code{<>} must be preceded by a space or a left parenthesis.
5972 Binary operators other than @code{**} must be surrounded by spaces.
5973 There is no restriction on the layout of the @code{**} binary operator.
5976 Colon must be surrounded by spaces.
5979 Colon-equal (assignment, initialization) must be surrounded by spaces.
5982 Comma must be the first non-blank character on the line, or be
5983 immediately preceded by a non-blank character, and must be followed
5987 If the token preceding a left parenthesis ends with a letter or digit, then
5988 a space must separate the two tokens.
5991 A right parenthesis must either be the first non-blank character on
5992 a line, or it must be preceded by a non-blank character.
5995 A semicolon must not be preceded by a space, and must not be followed by
5996 a non-blank character.
5999 A unary plus or minus may not be followed by a space.
6002 A vertical bar must be surrounded by spaces.
6005 @item ^u^UNNECESSARY_BLANK_LINES^
6006 @emph{Check unnecessary blank lines.}
6007 Check for unnecessary blank lines. A blank line is considered
6008 unnecessary if it appears at the end of the file, or if more than
6009 one blank line occurs in sequence.
6011 @item ^x^XTRA_PARENS^
6012 @emph{Check extra parentheses.}
6013 Check for the use of an unnecessary extra level of parentheses (C-style)
6014 around conditions in @code{if} statements, @code{while} statements and
6015 @code{exit} statements.
6020 In the above rules, appearing in column one is always permitted, that is,
6021 counts as meeting either a requirement for a required preceding space,
6022 or as meeting a requirement for no preceding space.
6024 Appearing at the end of a line is also always permitted, that is, counts
6025 as meeting either a requirement for a following space, or as meeting
6026 a requirement for no following space.
6029 If any of these style rules is violated, a message is generated giving
6030 details on the violation. The initial characters of such messages are
6031 always ``@code{(style)}''. Note that these messages are treated as warning
6032 messages, so they normally do not prevent the generation of an object
6033 file. The @option{-gnatwe} switch can be used to treat warning messages,
6034 including style messages, as fatal errors.
6038 @option{-gnaty} on its own (that is not
6039 followed by any letters or digits),
6040 is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6041 options enabled with the exception of @option{-gnatyo},
6042 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6045 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6046 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6047 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6049 an indentation level of 3 is set. This is similar to the standard
6050 checking option that is used for the GNAT sources.
6059 clears any previously set style checks.
6061 @node Run-Time Checks
6062 @subsection Run-Time Checks
6063 @cindex Division by zero
6064 @cindex Access before elaboration
6065 @cindex Checks, division by zero
6066 @cindex Checks, access before elaboration
6067 @cindex Checks, stack overflow checking
6070 If you compile with the default options, GNAT will insert many run-time
6071 checks into the compiled code, including code that performs range
6072 checking against constraints, but not arithmetic overflow checking for
6073 integer operations (including division by zero), checks for access
6074 before elaboration on subprogram calls, or stack overflow checking. All
6075 other run-time checks, as required by the Ada Reference Manual, are
6076 generated by default. The following @command{gcc} switches refine this
6082 @cindex @option{-gnatp} (@command{gcc})
6083 @cindex Suppressing checks
6084 @cindex Checks, suppressing
6086 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
6087 had been present in the source. Validity checks are also suppressed (in
6088 other words @option{-gnatp} also implies @option{-gnatVn}.
6089 Use this switch to improve the performance
6090 of the code at the expense of safety in the presence of invalid data or
6094 @cindex @option{-gnato} (@command{gcc})
6095 @cindex Overflow checks
6096 @cindex Check, overflow
6097 Enables overflow checking for integer operations.
6098 This causes GNAT to generate slower and larger executable
6099 programs by adding code to check for overflow (resulting in raising
6100 @code{Constraint_Error} as required by standard Ada
6101 semantics). These overflow checks correspond to situations in which
6102 the true value of the result of an operation may be outside the base
6103 range of the result type. The following example shows the distinction:
6105 @smallexample @c ada
6106 X1 : Integer := Integer'Last;
6107 X2 : Integer range 1 .. 5 := 5;
6108 X3 : Integer := Integer'Last;
6109 X4 : Integer range 1 .. 5 := 5;
6110 F : Float := 2.0E+20;
6119 Here the first addition results in a value that is outside the base range
6120 of Integer, and hence requires an overflow check for detection of the
6121 constraint error. Thus the first assignment to @code{X1} raises a
6122 @code{Constraint_Error} exception only if @option{-gnato} is set.
6124 The second increment operation results in a violation
6125 of the explicit range constraint, and such range checks are always
6126 performed (unless specifically suppressed with a pragma @code{suppress}
6127 or the use of @option{-gnatp}).
6129 The two conversions of @code{F} both result in values that are outside
6130 the base range of type @code{Integer} and thus will raise
6131 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6132 The fact that the result of the second conversion is assigned to
6133 variable @code{X4} with a restricted range is irrelevant, since the problem
6134 is in the conversion, not the assignment.
6136 Basically the rule is that in the default mode (@option{-gnato} not
6137 used), the generated code assures that all integer variables stay
6138 within their declared ranges, or within the base range if there is
6139 no declared range. This prevents any serious problems like indexes
6140 out of range for array operations.
6142 What is not checked in default mode is an overflow that results in
6143 an in-range, but incorrect value. In the above example, the assignments
6144 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6145 range of the target variable, but the result is wrong in the sense that
6146 it is too large to be represented correctly. Typically the assignment
6147 to @code{X1} will result in wrap around to the largest negative number.
6148 The conversions of @code{F} will result in some @code{Integer} value
6149 and if that integer value is out of the @code{X4} range then the
6150 subsequent assignment would generate an exception.
6152 @findex Machine_Overflows
6153 Note that the @option{-gnato} switch does not affect the code generated
6154 for any floating-point operations; it applies only to integer
6156 For floating-point, GNAT has the @code{Machine_Overflows}
6157 attribute set to @code{False} and the normal mode of operation is to
6158 generate IEEE NaN and infinite values on overflow or invalid operations
6159 (such as dividing 0.0 by 0.0).
6161 The reason that we distinguish overflow checking from other kinds of
6162 range constraint checking is that a failure of an overflow check can
6163 generate an incorrect value, but cannot cause erroneous behavior. This
6164 is unlike the situation with a constraint check on an array subscript,
6165 where failure to perform the check can result in random memory description,
6166 or the range check on a case statement, where failure to perform the check
6167 can cause a wild jump.
6169 Note again that @option{-gnato} is off by default, so overflow checking is
6170 not performed in default mode. This means that out of the box, with the
6171 default settings, GNAT does not do all the checks expected from the
6172 language description in the Ada Reference Manual. If you want all constraint
6173 checks to be performed, as described in this Manual, then you must
6174 explicitly use the -gnato switch either on the @command{gnatmake} or
6175 @command{gcc} command.
6178 @cindex @option{-gnatE} (@command{gcc})
6179 @cindex Elaboration checks
6180 @cindex Check, elaboration
6181 Enables dynamic checks for access-before-elaboration
6182 on subprogram calls and generic instantiations.
6183 For full details of the effect and use of this switch,
6184 @xref{Compiling Using gcc}.
6187 @cindex @option{-fstack-check} (@command{gcc})
6188 @cindex Stack Overflow Checking
6189 @cindex Checks, stack overflow checking
6190 Activates stack overflow checking. For full details of the effect and use of
6191 this switch see @ref{Stack Overflow Checking}.
6196 The setting of these switches only controls the default setting of the
6197 checks. You may modify them using either @code{Suppress} (to remove
6198 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6201 @node Using gcc for Syntax Checking
6202 @subsection Using @command{gcc} for Syntax Checking
6205 @cindex @option{-gnats} (@command{gcc})
6209 The @code{s} stands for ``syntax''.
6212 Run GNAT in syntax checking only mode. For
6213 example, the command
6216 $ gcc -c -gnats x.adb
6220 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6221 series of files in a single command
6223 , and can use wild cards to specify such a group of files.
6224 Note that you must specify the @option{-c} (compile
6225 only) flag in addition to the @option{-gnats} flag.
6228 You may use other switches in conjunction with @option{-gnats}. In
6229 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6230 format of any generated error messages.
6232 When the source file is empty or contains only empty lines and/or comments,
6233 the output is a warning:
6236 $ gcc -c -gnats -x ada toto.txt
6237 toto.txt:1:01: warning: empty file, contains no compilation units
6241 Otherwise, the output is simply the error messages, if any. No object file or
6242 ALI file is generated by a syntax-only compilation. Also, no units other
6243 than the one specified are accessed. For example, if a unit @code{X}
6244 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6245 check only mode does not access the source file containing unit
6248 @cindex Multiple units, syntax checking
6249 Normally, GNAT allows only a single unit in a source file. However, this
6250 restriction does not apply in syntax-check-only mode, and it is possible
6251 to check a file containing multiple compilation units concatenated
6252 together. This is primarily used by the @code{gnatchop} utility
6253 (@pxref{Renaming Files Using gnatchop}).
6256 @node Using gcc for Semantic Checking
6257 @subsection Using @command{gcc} for Semantic Checking
6260 @cindex @option{-gnatc} (@command{gcc})
6264 The @code{c} stands for ``check''.
6266 Causes the compiler to operate in semantic check mode,
6267 with full checking for all illegalities specified in the
6268 Ada Reference Manual, but without generation of any object code
6269 (no object file is generated).
6271 Because dependent files must be accessed, you must follow the GNAT
6272 semantic restrictions on file structuring to operate in this mode:
6276 The needed source files must be accessible
6277 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6280 Each file must contain only one compilation unit.
6283 The file name and unit name must match (@pxref{File Naming Rules}).
6286 The output consists of error messages as appropriate. No object file is
6287 generated. An @file{ALI} file is generated for use in the context of
6288 cross-reference tools, but this file is marked as not being suitable
6289 for binding (since no object file is generated).
6290 The checking corresponds exactly to the notion of
6291 legality in the Ada Reference Manual.
6293 Any unit can be compiled in semantics-checking-only mode, including
6294 units that would not normally be compiled (subunits,
6295 and specifications where a separate body is present).
6298 @node Compiling Different Versions of Ada
6299 @subsection Compiling Different Versions of Ada
6302 The switches described in this section allow you to explicitly specify
6303 the version of the Ada language that your programs are written in.
6304 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6305 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6306 indicate Ada 83 compatibility mode.
6309 @cindex Compatibility with Ada 83
6311 @item -gnat83 (Ada 83 Compatibility Mode)
6312 @cindex @option{-gnat83} (@command{gcc})
6313 @cindex ACVC, Ada 83 tests
6317 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6318 specifies that the program is to be compiled in Ada 83 mode. With
6319 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6320 semantics where this can be done easily.
6321 It is not possible to guarantee this switch does a perfect
6322 job; some subtle tests, such as are
6323 found in earlier ACVC tests (and that have been removed from the ACATS suite
6324 for Ada 95), might not compile correctly.
6325 Nevertheless, this switch may be useful in some circumstances, for example
6326 where, due to contractual reasons, existing code needs to be maintained
6327 using only Ada 83 features.
6329 With few exceptions (most notably the need to use @code{<>} on
6330 @cindex Generic formal parameters
6331 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6332 reserved words, and the use of packages
6333 with optional bodies), it is not necessary to specify the
6334 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6335 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6336 a correct Ada 83 program is usually also a correct program
6337 in these later versions of the language standard.
6338 For further information, please refer to @ref{Compatibility and Porting Guide}.
6340 @item -gnat95 (Ada 95 mode)
6341 @cindex @option{-gnat95} (@command{gcc})
6345 This switch directs the compiler to implement the Ada 95 version of the
6347 Since Ada 95 is almost completely upwards
6348 compatible with Ada 83, Ada 83 programs may generally be compiled using
6349 this switch (see the description of the @option{-gnat83} switch for further
6350 information about Ada 83 mode).
6351 If an Ada 2005 program is compiled in Ada 95 mode,
6352 uses of the new Ada 2005 features will cause error
6353 messages or warnings.
6355 This switch also can be used to cancel the effect of a previous
6356 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6358 @item -gnat05 (Ada 2005 mode)
6359 @cindex @option{-gnat05} (@command{gcc})
6360 @cindex Ada 2005 mode
6363 This switch directs the compiler to implement the Ada 2005 version of the
6365 Since Ada 2005 is almost completely upwards
6366 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6367 may generally be compiled using this switch (see the description of the
6368 @option{-gnat83} and @option{-gnat95} switches for further
6371 For information about the approved ``Ada Issues'' that have been incorporated
6372 into Ada 2005, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6373 Included with GNAT releases is a file @file{features-ada0y} that describes
6374 the set of implemented Ada 2005 features.
6378 @node Character Set Control
6379 @subsection Character Set Control
6381 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6382 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6385 Normally GNAT recognizes the Latin-1 character set in source program
6386 identifiers, as described in the Ada Reference Manual.
6388 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6389 single character ^^or word^ indicating the character set, as follows:
6393 ISO 8859-1 (Latin-1) identifiers
6396 ISO 8859-2 (Latin-2) letters allowed in identifiers
6399 ISO 8859-3 (Latin-3) letters allowed in identifiers
6402 ISO 8859-4 (Latin-4) letters allowed in identifiers
6405 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6408 ISO 8859-15 (Latin-9) letters allowed in identifiers
6411 IBM PC letters (code page 437) allowed in identifiers
6414 IBM PC letters (code page 850) allowed in identifiers
6416 @item ^f^FULL_UPPER^
6417 Full upper-half codes allowed in identifiers
6420 No upper-half codes allowed in identifiers
6423 Wide-character codes (that is, codes greater than 255)
6424 allowed in identifiers
6427 @xref{Foreign Language Representation}, for full details on the
6428 implementation of these character sets.
6430 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6431 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6432 Specify the method of encoding for wide characters.
6433 @var{e} is one of the following:
6438 Hex encoding (brackets coding also recognized)
6441 Upper half encoding (brackets encoding also recognized)
6444 Shift/JIS encoding (brackets encoding also recognized)
6447 EUC encoding (brackets encoding also recognized)
6450 UTF-8 encoding (brackets encoding also recognized)
6453 Brackets encoding only (default value)
6455 For full details on these encoding
6456 methods see @ref{Wide Character Encodings}.
6457 Note that brackets coding is always accepted, even if one of the other
6458 options is specified, so for example @option{-gnatW8} specifies that both
6459 brackets and UTF-8 encodings will be recognized. The units that are
6460 with'ed directly or indirectly will be scanned using the specified
6461 representation scheme, and so if one of the non-brackets scheme is
6462 used, it must be used consistently throughout the program. However,
6463 since brackets encoding is always recognized, it may be conveniently
6464 used in standard libraries, allowing these libraries to be used with
6465 any of the available coding schemes.
6468 If no @option{-gnatW?} parameter is present, then the default
6469 representation is normally Brackets encoding only. However, if the
6470 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6471 byte order mark or BOM for UTF-8), then these three characters are
6472 skipped and the default representation for the file is set to UTF-8.
6474 Note that the wide character representation that is specified (explicitly
6475 or by default) for the main program also acts as the default encoding used
6476 for Wide_Text_IO files if not specifically overridden by a WCEM form
6480 @node File Naming Control
6481 @subsection File Naming Control
6484 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6485 @cindex @option{-gnatk} (@command{gcc})
6486 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6487 1-999, indicates the maximum allowable length of a file name (not
6488 including the @file{.ads} or @file{.adb} extension). The default is not
6489 to enable file name krunching.
6491 For the source file naming rules, @xref{File Naming Rules}.
6494 @node Subprogram Inlining Control
6495 @subsection Subprogram Inlining Control
6500 @cindex @option{-gnatn} (@command{gcc})
6502 The @code{n} here is intended to suggest the first syllable of the
6505 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6506 inlining to actually occur, optimization must be enabled. To enable
6507 inlining of subprograms specified by pragma @code{Inline},
6508 you must also specify this switch.
6509 In the absence of this switch, GNAT does not attempt
6510 inlining and does not need to access the bodies of
6511 subprograms for which @code{pragma Inline} is specified if they are not
6512 in the current unit.
6514 If you specify this switch the compiler will access these bodies,
6515 creating an extra source dependency for the resulting object file, and
6516 where possible, the call will be inlined.
6517 For further details on when inlining is possible
6518 see @ref{Inlining of Subprograms}.
6521 @cindex @option{-gnatN} (@command{gcc})
6522 The front end inlining activated by this switch is generally more extensive,
6523 and quite often more effective than the standard @option{-gnatn} inlining mode.
6524 It will also generate additional dependencies.
6526 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
6527 to specify both options.
6530 @node Auxiliary Output Control
6531 @subsection Auxiliary Output Control
6535 @cindex @option{-gnatt} (@command{gcc})
6536 @cindex Writing internal trees
6537 @cindex Internal trees, writing to file
6538 Causes GNAT to write the internal tree for a unit to a file (with the
6539 extension @file{.adt}.
6540 This not normally required, but is used by separate analysis tools.
6542 these tools do the necessary compilations automatically, so you should
6543 not have to specify this switch in normal operation.
6546 @cindex @option{-gnatu} (@command{gcc})
6547 Print a list of units required by this compilation on @file{stdout}.
6548 The listing includes all units on which the unit being compiled depends
6549 either directly or indirectly.
6552 @item -pass-exit-codes
6553 @cindex @option{-pass-exit-codes} (@command{gcc})
6554 If this switch is not used, the exit code returned by @command{gcc} when
6555 compiling multiple files indicates whether all source files have
6556 been successfully used to generate object files or not.
6558 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
6559 exit status and allows an integrated development environment to better
6560 react to a compilation failure. Those exit status are:
6564 There was an error in at least one source file.
6566 At least one source file did not generate an object file.
6568 The compiler died unexpectedly (internal error for example).
6570 An object file has been generated for every source file.
6575 @node Debugging Control
6576 @subsection Debugging Control
6580 @cindex Debugging options
6583 @cindex @option{-gnatd} (@command{gcc})
6584 Activate internal debugging switches. @var{x} is a letter or digit, or
6585 string of letters or digits, which specifies the type of debugging
6586 outputs desired. Normally these are used only for internal development
6587 or system debugging purposes. You can find full documentation for these
6588 switches in the body of the @code{Debug} unit in the compiler source
6589 file @file{debug.adb}.
6593 @cindex @option{-gnatG} (@command{gcc})
6594 This switch causes the compiler to generate auxiliary output containing
6595 a pseudo-source listing of the generated expanded code. Like most Ada
6596 compilers, GNAT works by first transforming the high level Ada code into
6597 lower level constructs. For example, tasking operations are transformed
6598 into calls to the tasking run-time routines. A unique capability of GNAT
6599 is to list this expanded code in a form very close to normal Ada source.
6600 This is very useful in understanding the implications of various Ada
6601 usage on the efficiency of the generated code. There are many cases in
6602 Ada (e.g. the use of controlled types), where simple Ada statements can
6603 generate a lot of run-time code. By using @option{-gnatG} you can identify
6604 these cases, and consider whether it may be desirable to modify the coding
6605 approach to improve efficiency.
6607 The format of the output is very similar to standard Ada source, and is
6608 easily understood by an Ada programmer. The following special syntactic
6609 additions correspond to low level features used in the generated code that
6610 do not have any exact analogies in pure Ada source form. The following
6611 is a partial list of these special constructions. See the specification
6612 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6614 If the switch @option{-gnatL} is used in conjunction with
6615 @cindex @option{-gnatL} (@command{gcc})
6616 @option{-gnatG}, then the original source lines are interspersed
6617 in the expanded source (as comment lines with the original line number).
6620 @item new @var{xxx} [storage_pool = @var{yyy}]
6621 Shows the storage pool being used for an allocator.
6623 @item at end @var{procedure-name};
6624 Shows the finalization (cleanup) procedure for a scope.
6626 @item (if @var{expr} then @var{expr} else @var{expr})
6627 Conditional expression equivalent to the @code{x?y:z} construction in C.
6629 @item @var{target}^^^(@var{source})
6630 A conversion with floating-point truncation instead of rounding.
6632 @item @var{target}?(@var{source})
6633 A conversion that bypasses normal Ada semantic checking. In particular
6634 enumeration types and fixed-point types are treated simply as integers.
6636 @item @var{target}?^^^(@var{source})
6637 Combines the above two cases.
6639 @item @var{x} #/ @var{y}
6640 @itemx @var{x} #mod @var{y}
6641 @itemx @var{x} #* @var{y}
6642 @itemx @var{x} #rem @var{y}
6643 A division or multiplication of fixed-point values which are treated as
6644 integers without any kind of scaling.
6646 @item free @var{expr} [storage_pool = @var{xxx}]
6647 Shows the storage pool associated with a @code{free} statement.
6649 @item [subtype or type declaration]
6650 Used to list an equivalent declaration for an internally generated
6651 type that is referenced elsewhere in the listing.
6653 @item freeze @var{type-name} [@var{actions}]
6654 Shows the point at which @var{type-name} is frozen, with possible
6655 associated actions to be performed at the freeze point.
6657 @item reference @var{itype}
6658 Reference (and hence definition) to internal type @var{itype}.
6660 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6661 Intrinsic function call.
6663 @item @var{label-name} : label
6664 Declaration of label @var{labelname}.
6666 @item #$ @var{subprogram-name}
6667 An implicit call to a run-time support routine
6668 (to meet the requirement of H.3.1(9) in a
6671 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
6672 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6673 @var{expr}, but handled more efficiently).
6675 @item [constraint_error]
6676 Raise the @code{Constraint_Error} exception.
6678 @item @var{expression}'reference
6679 A pointer to the result of evaluating @var{expression}.
6681 @item @var{target-type}!(@var{source-expression})
6682 An unchecked conversion of @var{source-expression} to @var{target-type}.
6684 @item [@var{numerator}/@var{denominator}]
6685 Used to represent internal real literals (that) have no exact
6686 representation in base 2-16 (for example, the result of compile time
6687 evaluation of the expression 1.0/27.0).
6691 @cindex @option{-gnatD} (@command{gcc})
6692 When used in conjunction with @option{-gnatG}, this switch causes
6693 the expanded source, as described above for
6694 @option{-gnatG} to be written to files with names
6695 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6696 instead of to the standard output file. For
6697 example, if the source file name is @file{hello.adb}, then a file
6698 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written. The debugging
6699 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
6700 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6701 you to do source level debugging using the generated code which is
6702 sometimes useful for complex code, for example to find out exactly
6703 which part of a complex construction raised an exception. This switch
6704 also suppress generation of cross-reference information (see
6705 @option{-gnatx}) since otherwise the cross-reference information
6706 would refer to the @file{^.dg^.DG^} file, which would cause
6707 confusion since this is not the original source file.
6709 Note that @option{-gnatD} actually implies @option{-gnatG}
6710 automatically, so it is not necessary to give both options.
6711 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6713 If the switch @option{-gnatL} is used in conjunction with
6714 @cindex @option{-gnatL} (@command{gcc})
6715 @option{-gnatDG}, then the original source lines are interspersed
6716 in the expanded source (as comment lines with the original line number).
6719 @item -gnatR[0|1|2|3[s]]
6720 @cindex @option{-gnatR} (@command{gcc})
6721 This switch controls output from the compiler of a listing showing
6722 representation information for declared types and objects. For
6723 @option{-gnatR0}, no information is output (equivalent to omitting
6724 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6725 so @option{-gnatR} with no parameter has the same effect), size and alignment
6726 information is listed for declared array and record types. For
6727 @option{-gnatR2}, size and alignment information is listed for all
6728 declared types and objects. Finally @code{-gnatR3} includes symbolic
6729 expressions for values that are computed at run time for
6730 variant records. These symbolic expressions have a mostly obvious
6731 format with #n being used to represent the value of the n'th
6732 discriminant. See source files @file{repinfo.ads/adb} in the
6733 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6734 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
6735 the output is to a file with the name @file{^file.rep^file_REP^} where
6736 file is the name of the corresponding source file.
6739 @item /REPRESENTATION_INFO
6740 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
6741 This qualifier controls output from the compiler of a listing showing
6742 representation information for declared types and objects. For
6743 @option{/REPRESENTATION_INFO=NONE}, no information is output
6744 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6745 @option{/REPRESENTATION_INFO} without option is equivalent to
6746 @option{/REPRESENTATION_INFO=ARRAYS}.
6747 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6748 information is listed for declared array and record types. For
6749 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6750 is listed for all expression information for values that are computed
6751 at run time for variant records. These symbolic expressions have a mostly
6752 obvious format with #n being used to represent the value of the n'th
6753 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6754 @code{GNAT} sources for full details on the format of
6755 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6756 If _FILE is added at the end of an option
6757 (e.g. @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6758 then the output is to a file with the name @file{file_REP} where
6759 file is the name of the corresponding source file.
6761 Note that it is possible for record components to have zero size. In
6762 this case, the component clause uses an obvious extension of permitted
6763 Ada syntax, for example @code{at 0 range 0 .. -1}.
6765 Representation information requires that code be generated (since it is the
6766 code generator that lays out complex data structures). If an attempt is made
6767 to output representation information when no code is generated, for example
6768 when a subunit is compiled on its own, then no information can be generated
6769 and the compiler outputs a message to this effect.
6772 @cindex @option{-gnatS} (@command{gcc})
6773 The use of the switch @option{-gnatS} for an
6774 Ada compilation will cause the compiler to output a
6775 representation of package Standard in a form very
6776 close to standard Ada. It is not quite possible to
6777 do this entirely in standard Ada (since new
6778 numeric base types cannot be created in standard
6779 Ada), but the output is easily
6780 readable to any Ada programmer, and is useful to
6781 determine the characteristics of target dependent
6782 types in package Standard.
6785 @cindex @option{-gnatx} (@command{gcc})
6786 Normally the compiler generates full cross-referencing information in
6787 the @file{ALI} file. This information is used by a number of tools,
6788 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
6789 suppresses this information. This saves some space and may slightly
6790 speed up compilation, but means that these tools cannot be used.
6793 @node Exception Handling Control
6794 @subsection Exception Handling Control
6797 GNAT uses two methods for handling exceptions at run-time. The
6798 @code{setjmp/longjmp} method saves the context when entering
6799 a frame with an exception handler. Then when an exception is
6800 raised, the context can be restored immediately, without the
6801 need for tracing stack frames. This method provides very fast
6802 exception propagation, but introduces significant overhead for
6803 the use of exception handlers, even if no exception is raised.
6805 The other approach is called ``zero cost'' exception handling.
6806 With this method, the compiler builds static tables to describe
6807 the exception ranges. No dynamic code is required when entering
6808 a frame containing an exception handler. When an exception is
6809 raised, the tables are used to control a back trace of the
6810 subprogram invocation stack to locate the required exception
6811 handler. This method has considerably poorer performance for
6812 the propagation of exceptions, but there is no overhead for
6813 exception handlers if no exception is raised. Note that in this
6814 mode and in the context of mixed Ada and C/C++ programming,
6815 to propagate an exception through a C/C++ code, the C/C++ code
6816 must be compiled with the @option{-funwind-tables} GCC's
6819 The following switches may be used to control which of the
6820 two exception handling methods is used.
6826 @cindex @option{--RTS=sjlj} (@command{gnatmake})
6827 This switch causes the setjmp/longjmp run-time (when available) to be used
6828 for exception handling. If the default
6829 mechanism for the target is zero cost exceptions, then
6830 this switch can be used to modify this default, and must be
6831 used for all units in the partition.
6832 This option is rarely used. One case in which it may be
6833 advantageous is if you have an application where exception
6834 raising is common and the overall performance of the
6835 application is improved by favoring exception propagation.
6838 @cindex @option{--RTS=zcx} (@command{gnatmake})
6839 @cindex Zero Cost Exceptions
6840 This switch causes the zero cost approach to be used
6841 for exception handling. If this is the default mechanism for the
6842 target (see below), then this switch is unneeded. If the default
6843 mechanism for the target is setjmp/longjmp exceptions, then
6844 this switch can be used to modify this default, and must be
6845 used for all units in the partition.
6846 This option can only be used if the zero cost approach
6847 is available for the target in use, otherwise it will generate an error.
6851 The same option @option{--RTS} must be used both for @command{gcc}
6852 and @command{gnatbind}. Passing this option to @command{gnatmake}
6853 (@pxref{Switches for gnatmake}) will ensure the required consistency
6854 through the compilation and binding steps.
6856 @node Units to Sources Mapping Files
6857 @subsection Units to Sources Mapping Files
6861 @item -gnatem^^=^@var{path}
6862 @cindex @option{-gnatem} (@command{gcc})
6863 A mapping file is a way to communicate to the compiler two mappings:
6864 from unit names to file names (without any directory information) and from
6865 file names to path names (with full directory information). These mappings
6866 are used by the compiler to short-circuit the path search.
6868 The use of mapping files is not required for correct operation of the
6869 compiler, but mapping files can improve efficiency, particularly when
6870 sources are read over a slow network connection. In normal operation,
6871 you need not be concerned with the format or use of mapping files,
6872 and the @option{-gnatem} switch is not a switch that you would use
6873 explicitly. it is intended only for use by automatic tools such as
6874 @command{gnatmake} running under the project file facility. The
6875 description here of the format of mapping files is provided
6876 for completeness and for possible use by other tools.
6878 A mapping file is a sequence of sets of three lines. In each set,
6879 the first line is the unit name, in lower case, with ``@code{%s}''
6881 specifications and ``@code{%b}'' appended for bodies; the second line is the
6882 file name; and the third line is the path name.
6888 /gnat/project1/sources/main.2.ada
6891 When the switch @option{-gnatem} is specified, the compiler will create
6892 in memory the two mappings from the specified file. If there is any problem
6893 (non existent file, truncated file or duplicate entries), no mapping
6896 Several @option{-gnatem} switches may be specified; however, only the last
6897 one on the command line will be taken into account.
6899 When using a project file, @command{gnatmake} create a temporary mapping file
6900 and communicates it to the compiler using this switch.
6904 @node Integrated Preprocessing
6905 @subsection Integrated Preprocessing
6908 GNAT sources may be preprocessed immediately before compilation.
6909 In this case, the actual
6910 text of the source is not the text of the source file, but is derived from it
6911 through a process called preprocessing. Integrated preprocessing is specified
6912 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
6913 indicates, through a text file, the preprocessing data to be used.
6914 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
6917 Note that when integrated preprocessing is used, the output from the
6918 preprocessor is not written to any external file. Instead it is passed
6919 internally to the compiler. If you need to preserve the result of
6920 preprocessing in a file, then you should use @command{gnatprep}
6921 to perform the desired preprocessing in stand-alone mode.
6924 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
6925 used when Integrated Preprocessing is used. The reason is that preprocessing
6926 with another Preprocessing Data file without changing the sources will
6927 not trigger recompilation without this switch.
6930 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
6931 always trigger recompilation for sources that are preprocessed,
6932 because @command{gnatmake} cannot compute the checksum of the source after
6936 The actual preprocessing function is described in details in section
6937 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
6938 preprocessing is triggered and parameterized.
6942 @item -gnatep=@var{file}
6943 @cindex @option{-gnatep} (@command{gcc})
6944 This switch indicates to the compiler the file name (without directory
6945 information) of the preprocessor data file to use. The preprocessor data file
6946 should be found in the source directories.
6949 A preprocessing data file is a text file with significant lines indicating
6950 how should be preprocessed either a specific source or all sources not
6951 mentioned in other lines. A significant line is a non empty, non comment line.
6952 Comments are similar to Ada comments.
6955 Each significant line starts with either a literal string or the character '*'.
6956 A literal string is the file name (without directory information) of the source
6957 to preprocess. A character '*' indicates the preprocessing for all the sources
6958 that are not specified explicitly on other lines (order of the lines is not
6959 significant). It is an error to have two lines with the same file name or two
6960 lines starting with the character '*'.
6963 After the file name or the character '*', another optional literal string
6964 indicating the file name of the definition file to be used for preprocessing
6965 (@pxref{Form of Definitions File}). The definition files are found by the
6966 compiler in one of the source directories. In some cases, when compiling
6967 a source in a directory other than the current directory, if the definition
6968 file is in the current directory, it may be necessary to add the current
6969 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
6970 the compiler would not find the definition file.
6973 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
6974 be found. Those ^switches^switches^ are:
6979 Causes both preprocessor lines and the lines deleted by
6980 preprocessing to be replaced by blank lines, preserving the line number.
6981 This ^switch^switch^ is always implied; however, if specified after @option{-c}
6982 it cancels the effect of @option{-c}.
6985 Causes both preprocessor lines and the lines deleted
6986 by preprocessing to be retained as comments marked
6987 with the special string ``@code{--! }''.
6989 @item -Dsymbol=value
6990 Define or redefine a symbol, associated with value. A symbol is an Ada
6991 identifier, or an Ada reserved word, with the exception of @code{if},
6992 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6993 @code{value} is either a literal string, an Ada identifier or any Ada reserved
6994 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
6995 same name defined in a definition file.
6998 Causes a sorted list of symbol names and values to be
6999 listed on the standard output file.
7002 Causes undefined symbols to be treated as having the value @code{FALSE}
7004 of a preprocessor test. In the absence of this option, an undefined symbol in
7005 a @code{#if} or @code{#elsif} test will be treated as an error.
7010 Examples of valid lines in a preprocessor data file:
7013 "toto.adb" "prep.def" -u
7014 -- preprocess "toto.adb", using definition file "prep.def",
7015 -- undefined symbol are False.
7018 -- preprocess all other sources without a definition file;
7019 -- suppressed lined are commented; symbol VERSION has the value V101.
7021 "titi.adb" "prep2.def" -s
7022 -- preprocess "titi.adb", using definition file "prep2.def";
7023 -- list all symbols with their values.
7026 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
7027 @cindex @option{-gnateD} (@command{gcc})
7028 Define or redefine a preprocessing symbol, associated with value. If no value
7029 is given on the command line, then the value of the symbol is @code{True}.
7030 A symbol is an identifier, following normal Ada (case-insensitive)
7031 rules for its syntax, and value is any sequence (including an empty sequence)
7032 of characters from the set (letters, digits, period, underline).
7033 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7034 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7037 A symbol declared with this ^switch^switch^ on the command line replaces a
7038 symbol with the same name either in a definition file or specified with a
7039 ^switch^switch^ -D in the preprocessor data file.
7042 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7046 @node Code Generation Control
7047 @subsection Code Generation Control
7051 The GCC technology provides a wide range of target dependent
7052 @option{-m} switches for controlling
7053 details of code generation with respect to different versions of
7054 architectures. This includes variations in instruction sets (e.g.
7055 different members of the power pc family), and different requirements
7056 for optimal arrangement of instructions (e.g. different members of
7057 the x86 family). The list of available @option{-m} switches may be
7058 found in the GCC documentation.
7060 Use of these @option{-m} switches may in some cases result in improved
7063 The GNAT Pro technology is tested and qualified without any
7064 @option{-m} switches,
7065 so generally the most reliable approach is to avoid the use of these
7066 switches. However, we generally expect most of these switches to work
7067 successfully with GNAT Pro, and many customers have reported successful
7068 use of these options.
7070 Our general advice is to avoid the use of @option{-m} switches unless
7071 special needs lead to requirements in this area. In particular,
7072 there is no point in using @option{-m} switches to improve performance
7073 unless you actually see a performance improvement.
7077 @subsection Return Codes
7078 @cindex Return Codes
7079 @cindex @option{/RETURN_CODES=VMS}
7082 On VMS, GNAT compiled programs return POSIX-style codes by default,
7083 e.g. @option{/RETURN_CODES=POSIX}.
7085 To enable VMS style return codes, use GNAT BIND and LINK with the option
7086 @option{/RETURN_CODES=VMS}. For example:
7089 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7090 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7094 Programs built with /RETURN_CODES=VMS are suitable to be called in
7095 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7096 are suitable for spawning with appropriate GNAT RTL routines.
7100 @node Search Paths and the Run-Time Library (RTL)
7101 @section Search Paths and the Run-Time Library (RTL)
7104 With the GNAT source-based library system, the compiler must be able to
7105 find source files for units that are needed by the unit being compiled.
7106 Search paths are used to guide this process.
7108 The compiler compiles one source file whose name must be given
7109 explicitly on the command line. In other words, no searching is done
7110 for this file. To find all other source files that are needed (the most
7111 common being the specs of units), the compiler examines the following
7112 directories, in the following order:
7116 The directory containing the source file of the main unit being compiled
7117 (the file name on the command line).
7120 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7121 @command{gcc} command line, in the order given.
7124 @findex ADA_PRJ_INCLUDE_FILE
7125 Each of the directories listed in the text file whose name is given
7126 by the @code{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7129 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7130 driver when project files are used. It should not normally be set
7134 @findex ADA_INCLUDE_PATH
7135 Each of the directories listed in the value of the
7136 @code{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7138 Construct this value
7139 exactly as the @code{PATH} environment variable: a list of directory
7140 names separated by colons (semicolons when working with the NT version).
7143 Normally, define this value as a logical name containing a comma separated
7144 list of directory names.
7146 This variable can also be defined by means of an environment string
7147 (an argument to the HP C exec* set of functions).
7151 DEFINE ANOTHER_PATH FOO:[BAG]
7152 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7155 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7156 first, followed by the standard Ada
7157 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7158 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7159 (Text_IO, Sequential_IO, etc)
7160 instead of the standard Ada packages. Thus, in order to get the standard Ada
7161 packages by default, ADA_INCLUDE_PATH must be redefined.
7165 The content of the @file{ada_source_path} file which is part of the GNAT
7166 installation tree and is used to store standard libraries such as the
7167 GNAT Run Time Library (RTL) source files.
7169 @ref{Installing a library}
7174 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7175 inhibits the use of the directory
7176 containing the source file named in the command line. You can still
7177 have this directory on your search path, but in this case it must be
7178 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7180 Specifying the switch @option{-nostdinc}
7181 inhibits the search of the default location for the GNAT Run Time
7182 Library (RTL) source files.
7184 The compiler outputs its object files and ALI files in the current
7187 Caution: The object file can be redirected with the @option{-o} switch;
7188 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7189 so the @file{ALI} file will not go to the right place. Therefore, you should
7190 avoid using the @option{-o} switch.
7194 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7195 children make up the GNAT RTL, together with the simple @code{System.IO}
7196 package used in the @code{"Hello World"} example. The sources for these units
7197 are needed by the compiler and are kept together in one directory. Not
7198 all of the bodies are needed, but all of the sources are kept together
7199 anyway. In a normal installation, you need not specify these directory
7200 names when compiling or binding. Either the environment variables or
7201 the built-in defaults cause these files to be found.
7203 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7204 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7205 consisting of child units of @code{GNAT}. This is a collection of generally
7206 useful types, subprograms, etc. See the @cite{GNAT Reference Manual} for
7209 Besides simplifying access to the RTL, a major use of search paths is
7210 in compiling sources from multiple directories. This can make
7211 development environments much more flexible.
7213 @node Order of Compilation Issues
7214 @section Order of Compilation Issues
7217 If, in our earlier example, there was a spec for the @code{hello}
7218 procedure, it would be contained in the file @file{hello.ads}; yet this
7219 file would not have to be explicitly compiled. This is the result of the
7220 model we chose to implement library management. Some of the consequences
7221 of this model are as follows:
7225 There is no point in compiling specs (except for package
7226 specs with no bodies) because these are compiled as needed by clients. If
7227 you attempt a useless compilation, you will receive an error message.
7228 It is also useless to compile subunits because they are compiled as needed
7232 There are no order of compilation requirements: performing a
7233 compilation never obsoletes anything. The only way you can obsolete
7234 something and require recompilations is to modify one of the
7235 source files on which it depends.
7238 There is no library as such, apart from the ALI files
7239 (@pxref{The Ada Library Information Files}, for information on the format
7240 of these files). For now we find it convenient to create separate ALI files,
7241 but eventually the information therein may be incorporated into the object
7245 When you compile a unit, the source files for the specs of all units
7246 that it @code{with}'s, all its subunits, and the bodies of any generics it
7247 instantiates must be available (reachable by the search-paths mechanism
7248 described above), or you will receive a fatal error message.
7255 The following are some typical Ada compilation command line examples:
7258 @item $ gcc -c xyz.adb
7259 Compile body in file @file{xyz.adb} with all default options.
7262 @item $ gcc -c -O2 -gnata xyz-def.adb
7265 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7268 Compile the child unit package in file @file{xyz-def.adb} with extensive
7269 optimizations, and pragma @code{Assert}/@code{Debug} statements
7272 @item $ gcc -c -gnatc abc-def.adb
7273 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7277 @node Binding Using gnatbind
7278 @chapter Binding Using @code{gnatbind}
7282 * Running gnatbind::
7283 * Switches for gnatbind::
7284 * Command-Line Access::
7285 * Search Paths for gnatbind::
7286 * Examples of gnatbind Usage::
7290 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7291 to bind compiled GNAT objects.
7293 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7294 driver (see @ref{The GNAT Driver and Project Files}).
7296 The @code{gnatbind} program performs four separate functions:
7300 Checks that a program is consistent, in accordance with the rules in
7301 Chapter 10 of the Ada Reference Manual. In particular, error
7302 messages are generated if a program uses inconsistent versions of a
7306 Checks that an acceptable order of elaboration exists for the program
7307 and issues an error message if it cannot find an order of elaboration
7308 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7311 Generates a main program incorporating the given elaboration order.
7312 This program is a small Ada package (body and spec) that
7313 must be subsequently compiled
7314 using the GNAT compiler. The necessary compilation step is usually
7315 performed automatically by @command{gnatlink}. The two most important
7316 functions of this program
7317 are to call the elaboration routines of units in an appropriate order
7318 and to call the main program.
7321 Determines the set of object files required by the given main program.
7322 This information is output in the forms of comments in the generated program,
7323 to be read by the @command{gnatlink} utility used to link the Ada application.
7326 @node Running gnatbind
7327 @section Running @code{gnatbind}
7330 The form of the @code{gnatbind} command is
7333 $ gnatbind [@i{switches}] @i{mainprog}[.ali] [@i{switches}]
7337 where @file{@i{mainprog}.adb} is the Ada file containing the main program
7338 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
7339 package in two files whose names are
7340 @file{b~@i{mainprog}.ads}, and @file{b~@i{mainprog}.adb}.
7341 For example, if given the
7342 parameter @file{hello.ali}, for a main program contained in file
7343 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7344 and @file{b~hello.adb}.
7346 When doing consistency checking, the binder takes into consideration
7347 any source files it can locate. For example, if the binder determines
7348 that the given main program requires the package @code{Pack}, whose
7350 file is @file{pack.ali} and whose corresponding source spec file is
7351 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7352 (using the same search path conventions as previously described for the
7353 @command{gcc} command). If it can locate this source file, it checks that
7355 or source checksums of the source and its references to in @file{ALI} files
7356 match. In other words, any @file{ALI} files that mentions this spec must have
7357 resulted from compiling this version of the source file (or in the case
7358 where the source checksums match, a version close enough that the
7359 difference does not matter).
7361 @cindex Source files, use by binder
7362 The effect of this consistency checking, which includes source files, is
7363 that the binder ensures that the program is consistent with the latest
7364 version of the source files that can be located at bind time. Editing a
7365 source file without compiling files that depend on the source file cause
7366 error messages to be generated by the binder.
7368 For example, suppose you have a main program @file{hello.adb} and a
7369 package @code{P}, from file @file{p.ads} and you perform the following
7374 Enter @code{gcc -c hello.adb} to compile the main program.
7377 Enter @code{gcc -c p.ads} to compile package @code{P}.
7380 Edit file @file{p.ads}.
7383 Enter @code{gnatbind hello}.
7387 At this point, the file @file{p.ali} contains an out-of-date time stamp
7388 because the file @file{p.ads} has been edited. The attempt at binding
7389 fails, and the binder generates the following error messages:
7392 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7393 error: "p.ads" has been modified and must be recompiled
7397 Now both files must be recompiled as indicated, and then the bind can
7398 succeed, generating a main program. You need not normally be concerned
7399 with the contents of this file, but for reference purposes a sample
7400 binder output file is given in @ref{Example of Binder Output File}.
7402 In most normal usage, the default mode of @command{gnatbind} which is to
7403 generate the main package in Ada, as described in the previous section.
7404 In particular, this means that any Ada programmer can read and understand
7405 the generated main program. It can also be debugged just like any other
7406 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7407 @command{gnatbind} and @command{gnatlink}.
7409 However for some purposes it may be convenient to generate the main
7410 program in C rather than Ada. This may for example be helpful when you
7411 are generating a mixed language program with the main program in C. The
7412 GNAT compiler itself is an example.
7413 The use of the @option{^-C^/BIND_FILE=C^} switch
7414 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7415 be generated in C (and compiled using the gnu C compiler).
7417 @node Switches for gnatbind
7418 @section Switches for @command{gnatbind}
7421 The following switches are available with @code{gnatbind}; details will
7422 be presented in subsequent sections.
7425 * Consistency-Checking Modes::
7426 * Binder Error Message Control::
7427 * Elaboration Control::
7429 * Binding with Non-Ada Main Programs::
7430 * Binding Programs with No Main Subprogram::
7437 @cindex @option{--version} @command{gnatbind}
7438 Display Copyright and version, then exit disregarding all other options.
7441 @cindex @option{--help} @command{gnatbind}
7442 If @option{--version} was not used, display usage, then exit disregarding
7446 @cindex @option{-a} @command{gnatbind}
7447 Indicates that, if supported by the platform, the adainit procedure should
7448 be treated as an initialisation routine by the linker (a constructor). This
7449 is intended to be used by the Project Manager to automatically initialize
7450 shared Stand-Alone Libraries.
7452 @item ^-aO^/OBJECT_SEARCH^
7453 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7454 Specify directory to be searched for ALI files.
7456 @item ^-aI^/SOURCE_SEARCH^
7457 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7458 Specify directory to be searched for source file.
7460 @item ^-A^/BIND_FILE=ADA^
7461 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
7462 Generate binder program in Ada (default)
7464 @item ^-b^/REPORT_ERRORS=BRIEF^
7465 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
7466 Generate brief messages to @file{stderr} even if verbose mode set.
7468 @item ^-c^/NOOUTPUT^
7469 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
7470 Check only, no generation of binder output file.
7472 @item ^-C^/BIND_FILE=C^
7473 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
7474 Generate binder program in C
7476 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}[k|m]
7477 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}[k|m]} (@command{gnatbind})
7478 This switch can be used to change the default task stack size value
7479 to a specified size @var{nn}, which is expressed in bytes by default, or
7480 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7482 In the absence of a [k|m] suffix, this switch is equivalent, in effect,
7483 to completing all task specs with
7484 @smallexample @c ada
7485 pragma Storage_Size (nn);
7487 When they do not already have such a pragma.
7489 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}[k|m]
7490 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
7491 This switch can be used to change the default secondary stack size value
7492 to a specified size @var{nn}, which is expressed in bytes by default, or
7493 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7496 The secondary stack is used to deal with functions that return a variable
7497 sized result, for example a function returning an unconstrained
7498 String. There are two ways in which this secondary stack is allocated.
7500 For most targets, the secondary stack is growing on demand and is allocated
7501 as a chain of blocks in the heap. The -D option is not very
7502 relevant. It only give some control over the size of the allocated
7503 blocks (whose size is the minimum of the default secondary stack size value,
7504 and the actual size needed for the current allocation request).
7506 For certain targets, notably VxWorks 653,
7507 the secondary stack is allocated by carving off a fixed ratio chunk of the
7508 primary task stack. The -D option is used to define the
7509 size of the environment task's secondary stack.
7511 @item ^-e^/ELABORATION_DEPENDENCIES^
7512 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
7513 Output complete list of elaboration-order dependencies.
7515 @item ^-E^/STORE_TRACEBACKS^
7516 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
7517 Store tracebacks in exception occurrences when the target supports it.
7518 This is the default with the zero cost exception mechanism.
7520 @c The following may get moved to an appendix
7521 This option is currently supported on the following targets:
7522 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
7524 See also the packages @code{GNAT.Traceback} and
7525 @code{GNAT.Traceback.Symbolic} for more information.
7527 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
7528 @command{gcc} option.
7531 @item ^-F^/FORCE_ELABS_FLAGS^
7532 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
7533 Force the checks of elaboration flags. @command{gnatbind} does not normally
7534 generate checks of elaboration flags for the main executable, except when
7535 a Stand-Alone Library is used. However, there are cases when this cannot be
7536 detected by gnatbind. An example is importing an interface of a Stand-Alone
7537 Library through a pragma Import and only specifying through a linker switch
7538 this Stand-Alone Library. This switch is used to guarantee that elaboration
7539 flag checks are generated.
7542 @cindex @option{^-h^/HELP^} (@command{gnatbind})
7543 Output usage (help) information
7546 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7547 Specify directory to be searched for source and ALI files.
7549 @item ^-I-^/NOCURRENT_DIRECTORY^
7550 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
7551 Do not look for sources in the current directory where @code{gnatbind} was
7552 invoked, and do not look for ALI files in the directory containing the
7553 ALI file named in the @code{gnatbind} command line.
7555 @item ^-l^/ORDER_OF_ELABORATION^
7556 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
7557 Output chosen elaboration order.
7559 @item ^-Lxxx^/BUILD_LIBRARY=xxx^
7560 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
7561 Bind the units for library building. In this case the adainit and
7562 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
7563 are renamed to ^xxxinit^XXXINIT^ and
7564 ^xxxfinal^XXXFINAL^.
7565 Implies ^-n^/NOCOMPILE^.
7567 (@xref{GNAT and Libraries}, for more details.)
7570 On OpenVMS, these init and final procedures are exported in uppercase
7571 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
7572 the init procedure will be "TOTOINIT" and the exported name of the final
7573 procedure will be "TOTOFINAL".
7576 @item ^-Mxyz^/RENAME_MAIN=xyz^
7577 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
7578 Rename generated main program from main to xyz. This option is
7579 supported on cross environments only.
7581 @item ^-m^/ERROR_LIMIT=^@var{n}
7582 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
7583 Limit number of detected errors to @var{n}, where @var{n} is
7584 in the range 1..999_999. The default value if no switch is
7585 given is 9999. Binding is terminated if the limit is exceeded.
7587 Furthermore, under Windows, the sources pointed to by the libraries path
7588 set in the registry are not searched for.
7592 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7596 @cindex @option{-nostdinc} (@command{gnatbind})
7597 Do not look for sources in the system default directory.
7600 @cindex @option{-nostdlib} (@command{gnatbind})
7601 Do not look for library files in the system default directory.
7603 @item --RTS=@var{rts-path}
7604 @cindex @option{--RTS} (@code{gnatbind})
7605 Specifies the default location of the runtime library. Same meaning as the
7606 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
7608 @item ^-o ^/OUTPUT=^@var{file}
7609 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7610 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7611 Note that if this option is used, then linking must be done manually,
7612 gnatlink cannot be used.
7614 @item ^-O^/OBJECT_LIST^
7615 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7618 @item ^-p^/PESSIMISTIC_ELABORATION^
7619 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7620 Pessimistic (worst-case) elaboration order
7623 @cindex @option{^-R^-R^} (@command{gnatbind})
7624 Output closure source list.
7626 @item ^-s^/READ_SOURCES=ALL^
7627 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7628 Require all source files to be present.
7630 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7631 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7632 Specifies the value to be used when detecting uninitialized scalar
7633 objects with pragma Initialize_Scalars.
7634 The @var{xxx} ^string specified with the switch^option^ may be either
7636 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7637 @item ``@option{^lo^LOW^}'' for the lowest possible value
7638 @item ``@option{^hi^HIGH^}'' for the highest possible value
7639 @item ``@option{xx}'' for a value consisting of repeated bytes with the
7640 value 16#xx# (i.e. xx is a string of two hexadecimal digits).
7643 In addition, you can specify @option{-Sev} to indicate that the value is
7644 to be set at run time. In this case, the program will look for an environment
7645 @cindex GNAT_INIT_SCALARS
7646 variable of the form @code{GNAT_INIT_SCALARS=xx}, where xx is one
7647 of @option{in/lo/hi/xx} with the same meanings as above.
7648 If no environment variable is found, or if it does not have a valid value,
7649 then the default is @option{in} (invalid values).
7653 @cindex @option{-static} (@code{gnatbind})
7654 Link against a static GNAT run time.
7657 @cindex @option{-shared} (@code{gnatbind})
7658 Link against a shared GNAT run time when available.
7661 @item ^-t^/NOTIME_STAMP_CHECK^
7662 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7663 Tolerate time stamp and other consistency errors
7665 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7666 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7667 Set the time slice value to @var{n} milliseconds. If the system supports
7668 the specification of a specific time slice value, then the indicated value
7669 is used. If the system does not support specific time slice values, but
7670 does support some general notion of round-robin scheduling, then any
7671 nonzero value will activate round-robin scheduling.
7673 A value of zero is treated specially. It turns off time
7674 slicing, and in addition, indicates to the tasking run time that the
7675 semantics should match as closely as possible the Annex D
7676 requirements of the Ada RM, and in particular sets the default
7677 scheduling policy to @code{FIFO_Within_Priorities}.
7679 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
7680 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
7681 Enable dynamic stack usage, with @var{n} results stored and displayed
7682 at program termination. A result is generated when a task
7683 terminates. Results that can't be stored are displayed on the fly, at
7684 task termination. This option is currently not supported on Itanium
7685 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
7687 @item ^-v^/REPORT_ERRORS=VERBOSE^
7688 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7689 Verbose mode. Write error messages, header, summary output to
7694 @cindex @option{-w} (@code{gnatbind})
7695 Warning mode (@var{x}=s/e for suppress/treat as error)
7699 @item /WARNINGS=NORMAL
7700 @cindex @option{/WARNINGS} (@code{gnatbind})
7701 Normal warnings mode. Warnings are issued but ignored
7703 @item /WARNINGS=SUPPRESS
7704 @cindex @option{/WARNINGS} (@code{gnatbind})
7705 All warning messages are suppressed
7707 @item /WARNINGS=ERROR
7708 @cindex @option{/WARNINGS} (@code{gnatbind})
7709 Warning messages are treated as fatal errors
7712 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
7713 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
7714 Override default wide character encoding for standard Text_IO files.
7716 @item ^-x^/READ_SOURCES=NONE^
7717 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7718 Exclude source files (check object consistency only).
7721 @item /READ_SOURCES=AVAILABLE
7722 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7723 Default mode, in which sources are checked for consistency only if
7727 @item ^-y^/ENABLE_LEAP_SECONDS^
7728 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
7729 Enable leap seconds support in @code{Ada.Calendar} and its children.
7731 @item ^-z^/ZERO_MAIN^
7732 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7738 You may obtain this listing of switches by running @code{gnatbind} with
7742 @node Consistency-Checking Modes
7743 @subsection Consistency-Checking Modes
7746 As described earlier, by default @code{gnatbind} checks
7747 that object files are consistent with one another and are consistent
7748 with any source files it can locate. The following switches control binder
7753 @item ^-s^/READ_SOURCES=ALL^
7754 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
7755 Require source files to be present. In this mode, the binder must be
7756 able to locate all source files that are referenced, in order to check
7757 their consistency. In normal mode, if a source file cannot be located it
7758 is simply ignored. If you specify this switch, a missing source
7761 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
7762 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
7763 Override default wide character encoding for standard Text_IO files.
7764 Normally the default wide character encoding method used for standard
7765 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
7766 the main source input (see description of switch
7767 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
7768 use of this switch for the binder (which has the same set of
7769 possible arguments) overrides this default as specified.
7771 @item ^-x^/READ_SOURCES=NONE^
7772 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
7773 Exclude source files. In this mode, the binder only checks that ALI
7774 files are consistent with one another. Source files are not accessed.
7775 The binder runs faster in this mode, and there is still a guarantee that
7776 the resulting program is self-consistent.
7777 If a source file has been edited since it was last compiled, and you
7778 specify this switch, the binder will not detect that the object
7779 file is out of date with respect to the source file. Note that this is the
7780 mode that is automatically used by @command{gnatmake} because in this
7781 case the checking against sources has already been performed by
7782 @command{gnatmake} in the course of compilation (i.e. before binding).
7785 @item /READ_SOURCES=AVAILABLE
7786 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
7787 This is the default mode in which source files are checked if they are
7788 available, and ignored if they are not available.
7792 @node Binder Error Message Control
7793 @subsection Binder Error Message Control
7796 The following switches provide control over the generation of error
7797 messages from the binder:
7801 @item ^-v^/REPORT_ERRORS=VERBOSE^
7802 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7803 Verbose mode. In the normal mode, brief error messages are generated to
7804 @file{stderr}. If this switch is present, a header is written
7805 to @file{stdout} and any error messages are directed to @file{stdout}.
7806 All that is written to @file{stderr} is a brief summary message.
7808 @item ^-b^/REPORT_ERRORS=BRIEF^
7809 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
7810 Generate brief error messages to @file{stderr} even if verbose mode is
7811 specified. This is relevant only when used with the
7812 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
7816 @cindex @option{-m} (@code{gnatbind})
7817 Limits the number of error messages to @var{n}, a decimal integer in the
7818 range 1-999. The binder terminates immediately if this limit is reached.
7821 @cindex @option{-M} (@code{gnatbind})
7822 Renames the generated main program from @code{main} to @code{xxx}.
7823 This is useful in the case of some cross-building environments, where
7824 the actual main program is separate from the one generated
7828 @item ^-ws^/WARNINGS=SUPPRESS^
7829 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
7831 Suppress all warning messages.
7833 @item ^-we^/WARNINGS=ERROR^
7834 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
7835 Treat any warning messages as fatal errors.
7838 @item /WARNINGS=NORMAL
7839 Standard mode with warnings generated, but warnings do not get treated
7843 @item ^-t^/NOTIME_STAMP_CHECK^
7844 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7845 @cindex Time stamp checks, in binder
7846 @cindex Binder consistency checks
7847 @cindex Consistency checks, in binder
7848 The binder performs a number of consistency checks including:
7852 Check that time stamps of a given source unit are consistent
7854 Check that checksums of a given source unit are consistent
7856 Check that consistent versions of @code{GNAT} were used for compilation
7858 Check consistency of configuration pragmas as required
7862 Normally failure of such checks, in accordance with the consistency
7863 requirements of the Ada Reference Manual, causes error messages to be
7864 generated which abort the binder and prevent the output of a binder
7865 file and subsequent link to obtain an executable.
7867 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
7868 into warnings, so that
7869 binding and linking can continue to completion even in the presence of such
7870 errors. The result may be a failed link (due to missing symbols), or a
7871 non-functional executable which has undefined semantics.
7872 @emph{This means that
7873 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
7877 @node Elaboration Control
7878 @subsection Elaboration Control
7881 The following switches provide additional control over the elaboration
7882 order. For full details see @ref{Elaboration Order Handling in GNAT}.
7885 @item ^-p^/PESSIMISTIC_ELABORATION^
7886 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
7887 Normally the binder attempts to choose an elaboration order that is
7888 likely to minimize the likelihood of an elaboration order error resulting
7889 in raising a @code{Program_Error} exception. This switch reverses the
7890 action of the binder, and requests that it deliberately choose an order
7891 that is likely to maximize the likelihood of an elaboration error.
7892 This is useful in ensuring portability and avoiding dependence on
7893 accidental fortuitous elaboration ordering.
7895 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
7897 elaboration checking is used (@option{-gnatE} switch used for compilation).
7898 This is because in the default static elaboration mode, all necessary
7899 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
7900 These implicit pragmas are still respected by the binder in
7901 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
7902 safe elaboration order is assured.
7905 @node Output Control
7906 @subsection Output Control
7909 The following switches allow additional control over the output
7910 generated by the binder.
7915 @item ^-A^/BIND_FILE=ADA^
7916 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
7917 Generate binder program in Ada (default). The binder program is named
7918 @file{b~@var{mainprog}.adb} by default. This can be changed with
7919 @option{^-o^/OUTPUT^} @code{gnatbind} option.
7921 @item ^-c^/NOOUTPUT^
7922 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
7923 Check only. Do not generate the binder output file. In this mode the
7924 binder performs all error checks but does not generate an output file.
7926 @item ^-C^/BIND_FILE=C^
7927 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
7928 Generate binder program in C. The binder program is named
7929 @file{b_@var{mainprog}.c}.
7930 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
7933 @item ^-e^/ELABORATION_DEPENDENCIES^
7934 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
7935 Output complete list of elaboration-order dependencies, showing the
7936 reason for each dependency. This output can be rather extensive but may
7937 be useful in diagnosing problems with elaboration order. The output is
7938 written to @file{stdout}.
7941 @cindex @option{^-h^/HELP^} (@code{gnatbind})
7942 Output usage information. The output is written to @file{stdout}.
7944 @item ^-K^/LINKER_OPTION_LIST^
7945 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
7946 Output linker options to @file{stdout}. Includes library search paths,
7947 contents of pragmas Ident and Linker_Options, and libraries added
7950 @item ^-l^/ORDER_OF_ELABORATION^
7951 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
7952 Output chosen elaboration order. The output is written to @file{stdout}.
7954 @item ^-O^/OBJECT_LIST^
7955 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
7956 Output full names of all the object files that must be linked to provide
7957 the Ada component of the program. The output is written to @file{stdout}.
7958 This list includes the files explicitly supplied and referenced by the user
7959 as well as implicitly referenced run-time unit files. The latter are
7960 omitted if the corresponding units reside in shared libraries. The
7961 directory names for the run-time units depend on the system configuration.
7963 @item ^-o ^/OUTPUT=^@var{file}
7964 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
7965 Set name of output file to @var{file} instead of the normal
7966 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
7967 binder generated body filename. In C mode you would normally give
7968 @var{file} an extension of @file{.c} because it will be a C source program.
7969 Note that if this option is used, then linking must be done manually.
7970 It is not possible to use gnatlink in this case, since it cannot locate
7973 @item ^-r^/RESTRICTION_LIST^
7974 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
7975 Generate list of @code{pragma Restrictions} that could be applied to
7976 the current unit. This is useful for code audit purposes, and also may
7977 be used to improve code generation in some cases.
7981 @node Binding with Non-Ada Main Programs
7982 @subsection Binding with Non-Ada Main Programs
7985 In our description so far we have assumed that the main
7986 program is in Ada, and that the task of the binder is to generate a
7987 corresponding function @code{main} that invokes this Ada main
7988 program. GNAT also supports the building of executable programs where
7989 the main program is not in Ada, but some of the called routines are
7990 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
7991 The following switch is used in this situation:
7995 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
7996 No main program. The main program is not in Ada.
8000 In this case, most of the functions of the binder are still required,
8001 but instead of generating a main program, the binder generates a file
8002 containing the following callable routines:
8007 You must call this routine to initialize the Ada part of the program by
8008 calling the necessary elaboration routines. A call to @code{adainit} is
8009 required before the first call to an Ada subprogram.
8011 Note that it is assumed that the basic execution environment must be setup
8012 to be appropriate for Ada execution at the point where the first Ada
8013 subprogram is called. In particular, if the Ada code will do any
8014 floating-point operations, then the FPU must be setup in an appropriate
8015 manner. For the case of the x86, for example, full precision mode is
8016 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8017 that the FPU is in the right state.
8021 You must call this routine to perform any library-level finalization
8022 required by the Ada subprograms. A call to @code{adafinal} is required
8023 after the last call to an Ada subprogram, and before the program
8028 If the @option{^-n^/NOMAIN^} switch
8029 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8030 @cindex Binder, multiple input files
8031 is given, more than one ALI file may appear on
8032 the command line for @code{gnatbind}. The normal @dfn{closure}
8033 calculation is performed for each of the specified units. Calculating
8034 the closure means finding out the set of units involved by tracing
8035 @code{with} references. The reason it is necessary to be able to
8036 specify more than one ALI file is that a given program may invoke two or
8037 more quite separate groups of Ada units.
8039 The binder takes the name of its output file from the last specified ALI
8040 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8041 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8042 The output is an Ada unit in source form that can
8043 be compiled with GNAT unless the -C switch is used in which case the
8044 output is a C source file, which must be compiled using the C compiler.
8045 This compilation occurs automatically as part of the @command{gnatlink}
8048 Currently the GNAT run time requires a FPU using 80 bits mode
8049 precision. Under targets where this is not the default it is required to
8050 call GNAT.Float_Control.Reset before using floating point numbers (this
8051 include float computation, float input and output) in the Ada code. A
8052 side effect is that this could be the wrong mode for the foreign code
8053 where floating point computation could be broken after this call.
8055 @node Binding Programs with No Main Subprogram
8056 @subsection Binding Programs with No Main Subprogram
8059 It is possible to have an Ada program which does not have a main
8060 subprogram. This program will call the elaboration routines of all the
8061 packages, then the finalization routines.
8063 The following switch is used to bind programs organized in this manner:
8066 @item ^-z^/ZERO_MAIN^
8067 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8068 Normally the binder checks that the unit name given on the command line
8069 corresponds to a suitable main subprogram. When this switch is used,
8070 a list of ALI files can be given, and the execution of the program
8071 consists of elaboration of these units in an appropriate order. Note
8072 that the default wide character encoding method for standard Text_IO
8073 files is always set to Brackets if this switch is set (you can use
8075 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8078 @node Command-Line Access
8079 @section Command-Line Access
8082 The package @code{Ada.Command_Line} provides access to the command-line
8083 arguments and program name. In order for this interface to operate
8084 correctly, the two variables
8096 are declared in one of the GNAT library routines. These variables must
8097 be set from the actual @code{argc} and @code{argv} values passed to the
8098 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8099 generates the C main program to automatically set these variables.
8100 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8101 set these variables. If they are not set, the procedures in
8102 @code{Ada.Command_Line} will not be available, and any attempt to use
8103 them will raise @code{Constraint_Error}. If command line access is
8104 required, your main program must set @code{gnat_argc} and
8105 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8108 @node Search Paths for gnatbind
8109 @section Search Paths for @code{gnatbind}
8112 The binder takes the name of an ALI file as its argument and needs to
8113 locate source files as well as other ALI files to verify object consistency.
8115 For source files, it follows exactly the same search rules as @command{gcc}
8116 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8117 directories searched are:
8121 The directory containing the ALI file named in the command line, unless
8122 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8125 All directories specified by @option{^-I^/SEARCH^}
8126 switches on the @code{gnatbind}
8127 command line, in the order given.
8130 @findex ADA_PRJ_OBJECTS_FILE
8131 Each of the directories listed in the text file whose name is given
8132 by the @code{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8135 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8136 driver when project files are used. It should not normally be set
8140 @findex ADA_OBJECTS_PATH
8141 Each of the directories listed in the value of the
8142 @code{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8144 Construct this value
8145 exactly as the @code{PATH} environment variable: a list of directory
8146 names separated by colons (semicolons when working with the NT version
8150 Normally, define this value as a logical name containing a comma separated
8151 list of directory names.
8153 This variable can also be defined by means of an environment string
8154 (an argument to the HP C exec* set of functions).
8158 DEFINE ANOTHER_PATH FOO:[BAG]
8159 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8162 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8163 first, followed by the standard Ada
8164 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8165 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8166 (Text_IO, Sequential_IO, etc)
8167 instead of the standard Ada packages. Thus, in order to get the standard Ada
8168 packages by default, ADA_OBJECTS_PATH must be redefined.
8172 The content of the @file{ada_object_path} file which is part of the GNAT
8173 installation tree and is used to store standard libraries such as the
8174 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8177 @ref{Installing a library}
8182 In the binder the switch @option{^-I^/SEARCH^}
8183 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8184 is used to specify both source and
8185 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8186 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8187 instead if you want to specify
8188 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8189 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8190 if you want to specify library paths
8191 only. This means that for the binder
8192 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8193 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8194 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8195 The binder generates the bind file (a C language source file) in the
8196 current working directory.
8202 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8203 children make up the GNAT Run-Time Library, together with the package
8204 GNAT and its children, which contain a set of useful additional
8205 library functions provided by GNAT. The sources for these units are
8206 needed by the compiler and are kept together in one directory. The ALI
8207 files and object files generated by compiling the RTL are needed by the
8208 binder and the linker and are kept together in one directory, typically
8209 different from the directory containing the sources. In a normal
8210 installation, you need not specify these directory names when compiling
8211 or binding. Either the environment variables or the built-in defaults
8212 cause these files to be found.
8214 Besides simplifying access to the RTL, a major use of search paths is
8215 in compiling sources from multiple directories. This can make
8216 development environments much more flexible.
8218 @node Examples of gnatbind Usage
8219 @section Examples of @code{gnatbind} Usage
8222 This section contains a number of examples of using the GNAT binding
8223 utility @code{gnatbind}.
8226 @item gnatbind hello
8227 The main program @code{Hello} (source program in @file{hello.adb}) is
8228 bound using the standard switch settings. The generated main program is
8229 @file{b~hello.adb}. This is the normal, default use of the binder.
8232 @item gnatbind hello -o mainprog.adb
8235 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8237 The main program @code{Hello} (source program in @file{hello.adb}) is
8238 bound using the standard switch settings. The generated main program is
8239 @file{mainprog.adb} with the associated spec in
8240 @file{mainprog.ads}. Note that you must specify the body here not the
8241 spec, in the case where the output is in Ada. Note that if this option
8242 is used, then linking must be done manually, since gnatlink will not
8243 be able to find the generated file.
8246 @item gnatbind main -C -o mainprog.c -x
8249 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
8251 The main program @code{Main} (source program in
8252 @file{main.adb}) is bound, excluding source files from the
8253 consistency checking, generating
8254 the file @file{mainprog.c}.
8257 @item gnatbind -x main_program -C -o mainprog.c
8258 This command is exactly the same as the previous example. Switches may
8259 appear anywhere in the command line, and single letter switches may be
8260 combined into a single switch.
8264 @item gnatbind -n math dbase -C -o ada-control.c
8267 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
8269 The main program is in a language other than Ada, but calls to
8270 subprograms in packages @code{Math} and @code{Dbase} appear. This call
8271 to @code{gnatbind} generates the file @file{ada-control.c} containing
8272 the @code{adainit} and @code{adafinal} routines to be called before and
8273 after accessing the Ada units.
8276 @c ------------------------------------
8277 @node Linking Using gnatlink
8278 @chapter Linking Using @command{gnatlink}
8279 @c ------------------------------------
8283 This chapter discusses @command{gnatlink}, a tool that links
8284 an Ada program and builds an executable file. This utility
8285 invokes the system linker ^(via the @command{gcc} command)^^
8286 with a correct list of object files and library references.
8287 @command{gnatlink} automatically determines the list of files and
8288 references for the Ada part of a program. It uses the binder file
8289 generated by the @command{gnatbind} to determine this list.
8291 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8292 driver (see @ref{The GNAT Driver and Project Files}).
8295 * Running gnatlink::
8296 * Switches for gnatlink::
8299 @node Running gnatlink
8300 @section Running @command{gnatlink}
8303 The form of the @command{gnatlink} command is
8306 $ gnatlink [@var{switches}] @var{mainprog}[.ali]
8307 [@var{non-Ada objects}] [@var{linker options}]
8311 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8313 or linker options) may be in any order, provided that no non-Ada object may
8314 be mistaken for a main @file{ALI} file.
8315 Any file name @file{F} without the @file{.ali}
8316 extension will be taken as the main @file{ALI} file if a file exists
8317 whose name is the concatenation of @file{F} and @file{.ali}.
8320 @file{@var{mainprog}.ali} references the ALI file of the main program.
8321 The @file{.ali} extension of this file can be omitted. From this
8322 reference, @command{gnatlink} locates the corresponding binder file
8323 @file{b~@var{mainprog}.adb} and, using the information in this file along
8324 with the list of non-Ada objects and linker options, constructs a
8325 linker command file to create the executable.
8327 The arguments other than the @command{gnatlink} switches and the main
8328 @file{ALI} file are passed to the linker uninterpreted.
8329 They typically include the names of
8330 object files for units written in other languages than Ada and any library
8331 references required to resolve references in any of these foreign language
8332 units, or in @code{Import} pragmas in any Ada units.
8334 @var{linker options} is an optional list of linker specific
8336 The default linker called by gnatlink is @var{gcc} which in
8337 turn calls the appropriate system linker.
8338 Standard options for the linker such as @option{-lmy_lib} or
8339 @option{-Ldir} can be added as is.
8340 For options that are not recognized by
8341 @var{gcc} as linker options, use the @var{gcc} switches @option{-Xlinker} or
8343 Refer to the GCC documentation for
8344 details. Here is an example showing how to generate a linker map:
8347 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8350 Using @var{linker options} it is possible to set the program stack and
8353 See @ref{Setting Stack Size from gnatlink} and
8354 @ref{Setting Heap Size from gnatlink}.
8357 @command{gnatlink} determines the list of objects required by the Ada
8358 program and prepends them to the list of objects passed to the linker.
8359 @command{gnatlink} also gathers any arguments set by the use of
8360 @code{pragma Linker_Options} and adds them to the list of arguments
8361 presented to the linker.
8364 @command{gnatlink} accepts the following types of extra files on the command
8365 line: objects (.OBJ), libraries (.OLB), sharable images (.EXE), and
8366 options files (.OPT). These are recognized and handled according to their
8370 @node Switches for gnatlink
8371 @section Switches for @command{gnatlink}
8374 The following switches are available with the @command{gnatlink} utility:
8380 @cindex @option{--version} @command{gnatlink}
8381 Display Copyright and version, then exit disregarding all other options.
8384 @cindex @option{--help} @command{gnatlink}
8385 If @option{--version} was not used, display usage, then exit disregarding
8388 @item ^-A^/BIND_FILE=ADA^
8389 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
8390 The binder has generated code in Ada. This is the default.
8392 @item ^-C^/BIND_FILE=C^
8393 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
8394 If instead of generating a file in Ada, the binder has generated one in
8395 C, then the linker needs to know about it. Use this switch to signal
8396 to @command{gnatlink} that the binder has generated C code rather than
8399 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8400 @cindex Command line length
8401 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8402 On some targets, the command line length is limited, and @command{gnatlink}
8403 will generate a separate file for the linker if the list of object files
8405 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8406 to be generated even if
8407 the limit is not exceeded. This is useful in some cases to deal with
8408 special situations where the command line length is exceeded.
8411 @cindex Debugging information, including
8412 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8413 The option to include debugging information causes the Ada bind file (in
8414 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8415 @option{^-g^/DEBUG^}.
8416 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8417 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8418 Without @option{^-g^/DEBUG^}, the binder removes these files by
8419 default. The same procedure apply if a C bind file was generated using
8420 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8421 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8423 @item ^-n^/NOCOMPILE^
8424 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8425 Do not compile the file generated by the binder. This may be used when
8426 a link is rerun with different options, but there is no need to recompile
8430 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8431 Causes additional information to be output, including a full list of the
8432 included object files. This switch option is most useful when you want
8433 to see what set of object files are being used in the link step.
8435 @item ^-v -v^/VERBOSE/VERBOSE^
8436 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8437 Very verbose mode. Requests that the compiler operate in verbose mode when
8438 it compiles the binder file, and that the system linker run in verbose mode.
8440 @item ^-o ^/EXECUTABLE=^@var{exec-name}
8441 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
8442 @var{exec-name} specifies an alternate name for the generated
8443 executable program. If this switch is omitted, the executable has the same
8444 name as the main unit. For example, @code{gnatlink try.ali} creates
8445 an executable called @file{^try^TRY.EXE^}.
8448 @item -b @var{target}
8449 @cindex @option{-b} (@command{gnatlink})
8450 Compile your program to run on @var{target}, which is the name of a
8451 system configuration. You must have a GNAT cross-compiler built if
8452 @var{target} is not the same as your host system.
8455 @cindex @option{-B} (@command{gnatlink})
8456 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8457 from @var{dir} instead of the default location. Only use this switch
8458 when multiple versions of the GNAT compiler are available. See the
8459 @command{gcc} manual page for further details. You would normally use the
8460 @option{-b} or @option{-V} switch instead.
8462 @item --GCC=@var{compiler_name}
8463 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8464 Program used for compiling the binder file. The default is
8465 @command{gcc}. You need to use quotes around @var{compiler_name} if
8466 @code{compiler_name} contains spaces or other separator characters.
8467 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8468 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8469 inserted after your command name. Thus in the above example the compiler
8470 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8471 A limitation of this syntax is that the name and path name of the executable
8472 itself must not include any embedded spaces. If several
8473 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
8474 is taken into account. However, all the additional switches are also taken
8476 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8477 @option{--GCC="bar -x -y -z -t"}.
8479 @item --LINK=@var{name}
8480 @cindex @option{--LINK=} (@command{gnatlink})
8481 @var{name} is the name of the linker to be invoked. This is especially
8482 useful in mixed language programs since languages such as C++ require
8483 their own linker to be used. When this switch is omitted, the default
8484 name for the linker is @command{gcc}. When this switch is used, the
8485 specified linker is called instead of @command{gcc} with exactly the same
8486 parameters that would have been passed to @command{gcc} so if the desired
8487 linker requires different parameters it is necessary to use a wrapper
8488 script that massages the parameters before invoking the real linker. It
8489 may be useful to control the exact invocation by using the verbose
8495 @item /DEBUG=TRACEBACK
8496 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
8497 This qualifier causes sufficient information to be included in the
8498 executable file to allow a traceback, but does not include the full
8499 symbol information needed by the debugger.
8501 @item /IDENTIFICATION="<string>"
8502 @code{"<string>"} specifies the string to be stored in the image file
8503 identification field in the image header.
8504 It overrides any pragma @code{Ident} specified string.
8506 @item /NOINHIBIT-EXEC
8507 Generate the executable file even if there are linker warnings.
8509 @item /NOSTART_FILES
8510 Don't link in the object file containing the ``main'' transfer address.
8511 Used when linking with a foreign language main program compiled with an
8515 Prefer linking with object libraries over sharable images, even without
8521 @node The GNAT Make Program gnatmake
8522 @chapter The GNAT Make Program @command{gnatmake}
8526 * Running gnatmake::
8527 * Switches for gnatmake::
8528 * Mode Switches for gnatmake::
8529 * Notes on the Command Line::
8530 * How gnatmake Works::
8531 * Examples of gnatmake Usage::
8534 A typical development cycle when working on an Ada program consists of
8535 the following steps:
8539 Edit some sources to fix bugs.
8545 Compile all sources affected.
8555 The third step can be tricky, because not only do the modified files
8556 @cindex Dependency rules
8557 have to be compiled, but any files depending on these files must also be
8558 recompiled. The dependency rules in Ada can be quite complex, especially
8559 in the presence of overloading, @code{use} clauses, generics and inlined
8562 @command{gnatmake} automatically takes care of the third and fourth steps
8563 of this process. It determines which sources need to be compiled,
8564 compiles them, and binds and links the resulting object files.
8566 Unlike some other Ada make programs, the dependencies are always
8567 accurately recomputed from the new sources. The source based approach of
8568 the GNAT compilation model makes this possible. This means that if
8569 changes to the source program cause corresponding changes in
8570 dependencies, they will always be tracked exactly correctly by
8573 @node Running gnatmake
8574 @section Running @command{gnatmake}
8577 The usual form of the @command{gnatmake} command is
8580 $ gnatmake [@var{switches}] @var{file_name}
8581 [@var{file_names}] [@var{mode_switches}]
8585 The only required argument is one @var{file_name}, which specifies
8586 a compilation unit that is a main program. Several @var{file_names} can be
8587 specified: this will result in several executables being built.
8588 If @code{switches} are present, they can be placed before the first
8589 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8590 If @var{mode_switches} are present, they must always be placed after
8591 the last @var{file_name} and all @code{switches}.
8593 If you are using standard file extensions (.adb and .ads), then the
8594 extension may be omitted from the @var{file_name} arguments. However, if
8595 you are using non-standard extensions, then it is required that the
8596 extension be given. A relative or absolute directory path can be
8597 specified in a @var{file_name}, in which case, the input source file will
8598 be searched for in the specified directory only. Otherwise, the input
8599 source file will first be searched in the directory where
8600 @command{gnatmake} was invoked and if it is not found, it will be search on
8601 the source path of the compiler as described in
8602 @ref{Search Paths and the Run-Time Library (RTL)}.
8604 All @command{gnatmake} output (except when you specify
8605 @option{^-M^/DEPENDENCIES_LIST^}) is to
8606 @file{stderr}. The output produced by the
8607 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8610 @node Switches for gnatmake
8611 @section Switches for @command{gnatmake}
8614 You may specify any of the following switches to @command{gnatmake}:
8620 @cindex @option{--version} @command{gnatmake}
8621 Display Copyright and version, then exit disregarding all other options.
8624 @cindex @option{--help} @command{gnatmake}
8625 If @option{--version} was not used, display usage, then exit disregarding
8629 @item --GCC=@var{compiler_name}
8630 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
8631 Program used for compiling. The default is `@command{gcc}'. You need to use
8632 quotes around @var{compiler_name} if @code{compiler_name} contains
8633 spaces or other separator characters. As an example @option{--GCC="foo -x
8634 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
8635 compiler. A limitation of this syntax is that the name and path name of
8636 the executable itself must not include any embedded spaces. Note that
8637 switch @option{-c} is always inserted after your command name. Thus in the
8638 above example the compiler command that will be used by @command{gnatmake}
8639 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
8640 used, only the last @var{compiler_name} is taken into account. However,
8641 all the additional switches are also taken into account. Thus,
8642 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8643 @option{--GCC="bar -x -y -z -t"}.
8645 @item --GNATBIND=@var{binder_name}
8646 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
8647 Program used for binding. The default is `@code{gnatbind}'. You need to
8648 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8649 or other separator characters. As an example @option{--GNATBIND="bar -x
8650 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
8651 binder. Binder switches that are normally appended by @command{gnatmake}
8652 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8653 A limitation of this syntax is that the name and path name of the executable
8654 itself must not include any embedded spaces.
8656 @item --GNATLINK=@var{linker_name}
8657 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
8658 Program used for linking. The default is `@command{gnatlink}'. You need to
8659 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8660 or other separator characters. As an example @option{--GNATLINK="lan -x
8661 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
8662 linker. Linker switches that are normally appended by @command{gnatmake} to
8663 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
8664 A limitation of this syntax is that the name and path name of the executable
8665 itself must not include any embedded spaces.
8669 @item ^-a^/ALL_FILES^
8670 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
8671 Consider all files in the make process, even the GNAT internal system
8672 files (for example, the predefined Ada library files), as well as any
8673 locked files. Locked files are files whose ALI file is write-protected.
8675 @command{gnatmake} does not check these files,
8676 because the assumption is that the GNAT internal files are properly up
8677 to date, and also that any write protected ALI files have been properly
8678 installed. Note that if there is an installation problem, such that one
8679 of these files is not up to date, it will be properly caught by the
8681 You may have to specify this switch if you are working on GNAT
8682 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8683 in conjunction with @option{^-f^/FORCE_COMPILE^}
8684 if you need to recompile an entire application,
8685 including run-time files, using special configuration pragmas,
8686 such as a @code{Normalize_Scalars} pragma.
8689 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8692 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8695 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8698 @item ^-b^/ACTIONS=BIND^
8699 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
8700 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8701 compilation and binding, but no link.
8702 Can be combined with @option{^-l^/ACTIONS=LINK^}
8703 to do binding and linking. When not combined with
8704 @option{^-c^/ACTIONS=COMPILE^}
8705 all the units in the closure of the main program must have been previously
8706 compiled and must be up to date. The root unit specified by @var{file_name}
8707 may be given without extension, with the source extension or, if no GNAT
8708 Project File is specified, with the ALI file extension.
8710 @item ^-c^/ACTIONS=COMPILE^
8711 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
8712 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8713 is also specified. Do not perform linking, except if both
8714 @option{^-b^/ACTIONS=BIND^} and
8715 @option{^-l^/ACTIONS=LINK^} are also specified.
8716 If the root unit specified by @var{file_name} is not a main unit, this is the
8717 default. Otherwise @command{gnatmake} will attempt binding and linking
8718 unless all objects are up to date and the executable is more recent than
8722 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
8723 Use a temporary mapping file. A mapping file is a way to communicate to the
8724 compiler two mappings: from unit names to file names (without any directory
8725 information) and from file names to path names (with full directory
8726 information). These mappings are used by the compiler to short-circuit the path
8727 search. When @command{gnatmake} is invoked with this switch, it will create
8728 a temporary mapping file, initially populated by the project manager,
8729 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8730 Each invocation of the compiler will add the newly accessed sources to the
8731 mapping file. This will improve the source search during the next invocation
8734 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8735 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
8736 Use a specific mapping file. The file, specified as a path name (absolute or
8737 relative) by this switch, should already exist, otherwise the switch is
8738 ineffective. The specified mapping file will be communicated to the compiler.
8739 This switch is not compatible with a project file
8740 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8741 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8743 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
8744 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
8745 Put all object files and ALI file in directory @var{dir}.
8746 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
8747 and ALI files go in the current working directory.
8749 This switch cannot be used when using a project file.
8753 @cindex @option{-eL} (@command{gnatmake})
8754 Follow all symbolic links when processing project files.
8757 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
8758 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
8759 Output the commands for the compiler, the binder and the linker
8760 on ^standard output^SYS$OUTPUT^,
8761 instead of ^standard error^SYS$ERROR^.
8763 @item ^-f^/FORCE_COMPILE^
8764 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
8765 Force recompilations. Recompile all sources, even though some object
8766 files may be up to date, but don't recompile predefined or GNAT internal
8767 files or locked files (files with a write-protected ALI file),
8768 unless the @option{^-a^/ALL_FILES^} switch is also specified.
8770 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
8771 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
8772 When using project files, if some errors or warnings are detected during
8773 parsing and verbose mode is not in effect (no use of switch
8774 ^-v^/VERBOSE^), then error lines start with the full path name of the project
8775 file, rather than its simple file name.
8778 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
8779 Enable debugging. This switch is simply passed to the compiler and to the
8782 @item ^-i^/IN_PLACE^
8783 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
8784 In normal mode, @command{gnatmake} compiles all object files and ALI files
8785 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
8786 then instead object files and ALI files that already exist are overwritten
8787 in place. This means that once a large project is organized into separate
8788 directories in the desired manner, then @command{gnatmake} will automatically
8789 maintain and update this organization. If no ALI files are found on the
8790 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
8791 the new object and ALI files are created in the
8792 directory containing the source being compiled. If another organization
8793 is desired, where objects and sources are kept in different directories,
8794 a useful technique is to create dummy ALI files in the desired directories.
8795 When detecting such a dummy file, @command{gnatmake} will be forced to
8796 recompile the corresponding source file, and it will be put the resulting
8797 object and ALI files in the directory where it found the dummy file.
8799 @item ^-j^/PROCESSES=^@var{n}
8800 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
8801 @cindex Parallel make
8802 Use @var{n} processes to carry out the (re)compilations. On a
8803 multiprocessor machine compilations will occur in parallel. In the
8804 event of compilation errors, messages from various compilations might
8805 get interspersed (but @command{gnatmake} will give you the full ordered
8806 list of failing compiles at the end). If this is problematic, rerun
8807 the make process with n set to 1 to get a clean list of messages.
8809 @item ^-k^/CONTINUE_ON_ERROR^
8810 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
8811 Keep going. Continue as much as possible after a compilation error. To
8812 ease the programmer's task in case of compilation errors, the list of
8813 sources for which the compile fails is given when @command{gnatmake}
8816 If @command{gnatmake} is invoked with several @file{file_names} and with this
8817 switch, if there are compilation errors when building an executable,
8818 @command{gnatmake} will not attempt to build the following executables.
8820 @item ^-l^/ACTIONS=LINK^
8821 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
8822 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
8823 and linking. Linking will not be performed if combined with
8824 @option{^-c^/ACTIONS=COMPILE^}
8825 but not with @option{^-b^/ACTIONS=BIND^}.
8826 When not combined with @option{^-b^/ACTIONS=BIND^}
8827 all the units in the closure of the main program must have been previously
8828 compiled and must be up to date, and the main program needs to have been bound.
8829 The root unit specified by @var{file_name}
8830 may be given without extension, with the source extension or, if no GNAT
8831 Project File is specified, with the ALI file extension.
8833 @item ^-m^/MINIMAL_RECOMPILATION^
8834 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
8835 Specify that the minimum necessary amount of recompilations
8836 be performed. In this mode @command{gnatmake} ignores time
8837 stamp differences when the only
8838 modifications to a source file consist in adding/removing comments,
8839 empty lines, spaces or tabs. This means that if you have changed the
8840 comments in a source file or have simply reformatted it, using this
8841 switch will tell gnatmake not to recompile files that depend on it
8842 (provided other sources on which these files depend have undergone no
8843 semantic modifications). Note that the debugging information may be
8844 out of date with respect to the sources if the @option{-m} switch causes
8845 a compilation to be switched, so the use of this switch represents a
8846 trade-off between compilation time and accurate debugging information.
8848 @item ^-M^/DEPENDENCIES_LIST^
8849 @cindex Dependencies, producing list
8850 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
8851 Check if all objects are up to date. If they are, output the object
8852 dependences to @file{stdout} in a form that can be directly exploited in
8853 a @file{Makefile}. By default, each source file is prefixed with its
8854 (relative or absolute) directory name. This name is whatever you
8855 specified in the various @option{^-aI^/SOURCE_SEARCH^}
8856 and @option{^-I^/SEARCH^} switches. If you use
8857 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
8858 @option{^-q^/QUIET^}
8859 (see below), only the source file names,
8860 without relative paths, are output. If you just specify the
8861 @option{^-M^/DEPENDENCIES_LIST^}
8862 switch, dependencies of the GNAT internal system files are omitted. This
8863 is typically what you want. If you also specify
8864 the @option{^-a^/ALL_FILES^} switch,
8865 dependencies of the GNAT internal files are also listed. Note that
8866 dependencies of the objects in external Ada libraries (see switch
8867 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
8870 @item ^-n^/DO_OBJECT_CHECK^
8871 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
8872 Don't compile, bind, or link. Checks if all objects are up to date.
8873 If they are not, the full name of the first file that needs to be
8874 recompiled is printed.
8875 Repeated use of this option, followed by compiling the indicated source
8876 file, will eventually result in recompiling all required units.
8878 @item ^-o ^/EXECUTABLE=^@var{exec_name}
8879 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
8880 Output executable name. The name of the final executable program will be
8881 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
8882 name for the executable will be the name of the input file in appropriate form
8883 for an executable file on the host system.
8885 This switch cannot be used when invoking @command{gnatmake} with several
8888 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
8889 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
8890 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
8891 automatically missing object directories, library directories and exec
8894 @item ^-P^/PROJECT_FILE=^@var{project}
8895 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
8896 Use project file @var{project}. Only one such switch can be used.
8897 @xref{gnatmake and Project Files}.
8900 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
8901 Quiet. When this flag is not set, the commands carried out by
8902 @command{gnatmake} are displayed.
8904 @item ^-s^/SWITCH_CHECK/^
8905 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
8906 Recompile if compiler switches have changed since last compilation.
8907 All compiler switches but -I and -o are taken into account in the
8909 orders between different ``first letter'' switches are ignored, but
8910 orders between same switches are taken into account. For example,
8911 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
8912 is equivalent to @option{-O -g}.
8914 This switch is recommended when Integrated Preprocessing is used.
8917 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
8918 Unique. Recompile at most the main files. It implies -c. Combined with
8919 -f, it is equivalent to calling the compiler directly. Note that using
8920 ^-u^/UNIQUE^ with a project file and no main has a special meaning
8921 (@pxref{Project Files and Main Subprograms}).
8923 @item ^-U^/ALL_PROJECTS^
8924 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
8925 When used without a project file or with one or several mains on the command
8926 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
8927 on the command line, all sources of all project files are checked and compiled
8928 if not up to date, and libraries are rebuilt, if necessary.
8931 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
8932 Verbose. Display the reason for all recompilations @command{gnatmake}
8933 decides are necessary, with the highest verbosity level.
8935 @item ^-vl^/LOW_VERBOSITY^
8936 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
8937 Verbosity level Low. Display fewer lines than in verbosity Medium.
8939 @item ^-vm^/MEDIUM_VERBOSITY^
8940 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
8941 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
8943 @item ^-vh^/HIGH_VERBOSITY^
8944 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
8945 Verbosity level High. Equivalent to ^-v^/REASONS^.
8947 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
8948 Indicate the verbosity of the parsing of GNAT project files.
8949 @xref{Switches Related to Project Files}.
8951 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
8952 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
8953 Indicate that sources that are not part of any Project File may be compiled.
8954 Normally, when using Project Files, only sources that are part of a Project
8955 File may be compile. When this switch is used, a source outside of all Project
8956 Files may be compiled. The ALI file and the object file will be put in the
8957 object directory of the main Project. The compilation switches used will only
8958 be those specified on the command line.
8960 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
8961 Indicate that external variable @var{name} has the value @var{value}.
8962 The Project Manager will use this value for occurrences of
8963 @code{external(name)} when parsing the project file.
8964 @xref{Switches Related to Project Files}.
8967 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
8968 No main subprogram. Bind and link the program even if the unit name
8969 given on the command line is a package name. The resulting executable
8970 will execute the elaboration routines of the package and its closure,
8971 then the finalization routines.
8976 @item @command{gcc} @asis{switches}
8978 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
8979 is passed to @command{gcc} (e.g. @option{-O}, @option{-gnato,} etc.)
8982 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
8983 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
8984 automatically treated as a compiler switch, and passed on to all
8985 compilations that are carried out.
8990 Source and library search path switches:
8994 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
8995 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
8996 When looking for source files also look in directory @var{dir}.
8997 The order in which source files search is undertaken is
8998 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9000 @item ^-aL^/SKIP_MISSING=^@var{dir}
9001 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9002 Consider @var{dir} as being an externally provided Ada library.
9003 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9004 files have been located in directory @var{dir}. This allows you to have
9005 missing bodies for the units in @var{dir} and to ignore out of date bodies
9006 for the same units. You still need to specify
9007 the location of the specs for these units by using the switches
9008 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9009 or @option{^-I^/SEARCH=^@var{dir}}.
9010 Note: this switch is provided for compatibility with previous versions
9011 of @command{gnatmake}. The easier method of causing standard libraries
9012 to be excluded from consideration is to write-protect the corresponding
9015 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9016 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9017 When searching for library and object files, look in directory
9018 @var{dir}. The order in which library files are searched is described in
9019 @ref{Search Paths for gnatbind}.
9021 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9022 @cindex Search paths, for @command{gnatmake}
9023 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9024 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9025 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9027 @item ^-I^/SEARCH=^@var{dir}
9028 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9029 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9030 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9032 @item ^-I-^/NOCURRENT_DIRECTORY^
9033 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9034 @cindex Source files, suppressing search
9035 Do not look for source files in the directory containing the source
9036 file named in the command line.
9037 Do not look for ALI or object files in the directory
9038 where @command{gnatmake} was invoked.
9040 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9041 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9042 @cindex Linker libraries
9043 Add directory @var{dir} to the list of directories in which the linker
9044 will search for libraries. This is equivalent to
9045 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9047 Furthermore, under Windows, the sources pointed to by the libraries path
9048 set in the registry are not searched for.
9052 @cindex @option{-nostdinc} (@command{gnatmake})
9053 Do not look for source files in the system default directory.
9056 @cindex @option{-nostdlib} (@command{gnatmake})
9057 Do not look for library files in the system default directory.
9059 @item --RTS=@var{rts-path}
9060 @cindex @option{--RTS} (@command{gnatmake})
9061 Specifies the default location of the runtime library. GNAT looks for the
9063 in the following directories, and stops as soon as a valid runtime is found
9064 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9065 @file{ada_object_path} present):
9068 @item <current directory>/$rts_path
9070 @item <default-search-dir>/$rts_path
9072 @item <default-search-dir>/rts-$rts_path
9076 The selected path is handled like a normal RTS path.
9080 @node Mode Switches for gnatmake
9081 @section Mode Switches for @command{gnatmake}
9084 The mode switches (referred to as @code{mode_switches}) allow the
9085 inclusion of switches that are to be passed to the compiler itself, the
9086 binder or the linker. The effect of a mode switch is to cause all
9087 subsequent switches up to the end of the switch list, or up to the next
9088 mode switch, to be interpreted as switches to be passed on to the
9089 designated component of GNAT.
9093 @item -cargs @var{switches}
9094 @cindex @option{-cargs} (@command{gnatmake})
9095 Compiler switches. Here @var{switches} is a list of switches
9096 that are valid switches for @command{gcc}. They will be passed on to
9097 all compile steps performed by @command{gnatmake}.
9099 @item -bargs @var{switches}
9100 @cindex @option{-bargs} (@command{gnatmake})
9101 Binder switches. Here @var{switches} is a list of switches
9102 that are valid switches for @code{gnatbind}. They will be passed on to
9103 all bind steps performed by @command{gnatmake}.
9105 @item -largs @var{switches}
9106 @cindex @option{-largs} (@command{gnatmake})
9107 Linker switches. Here @var{switches} is a list of switches
9108 that are valid switches for @command{gnatlink}. They will be passed on to
9109 all link steps performed by @command{gnatmake}.
9111 @item -margs @var{switches}
9112 @cindex @option{-margs} (@command{gnatmake})
9113 Make switches. The switches are directly interpreted by @command{gnatmake},
9114 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9118 @node Notes on the Command Line
9119 @section Notes on the Command Line
9122 This section contains some additional useful notes on the operation
9123 of the @command{gnatmake} command.
9127 @cindex Recompilation, by @command{gnatmake}
9128 If @command{gnatmake} finds no ALI files, it recompiles the main program
9129 and all other units required by the main program.
9130 This means that @command{gnatmake}
9131 can be used for the initial compile, as well as during subsequent steps of
9132 the development cycle.
9135 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9136 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9137 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9141 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9142 is used to specify both source and
9143 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9144 instead if you just want to specify
9145 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9146 if you want to specify library paths
9150 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9151 This may conveniently be used to exclude standard libraries from
9152 consideration and in particular it means that the use of the
9153 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9154 unless @option{^-a^/ALL_FILES^} is also specified.
9157 @command{gnatmake} has been designed to make the use of Ada libraries
9158 particularly convenient. Assume you have an Ada library organized
9159 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9160 of your Ada compilation units,
9161 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9162 specs of these units, but no bodies. Then to compile a unit
9163 stored in @code{main.adb}, which uses this Ada library you would just type
9167 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
9170 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9171 /SKIP_MISSING=@i{[OBJ_DIR]} main
9176 Using @command{gnatmake} along with the
9177 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9178 switch provides a mechanism for avoiding unnecessary recompilations. Using
9180 you can update the comments/format of your
9181 source files without having to recompile everything. Note, however, that
9182 adding or deleting lines in a source files may render its debugging
9183 info obsolete. If the file in question is a spec, the impact is rather
9184 limited, as that debugging info will only be useful during the
9185 elaboration phase of your program. For bodies the impact can be more
9186 significant. In all events, your debugger will warn you if a source file
9187 is more recent than the corresponding object, and alert you to the fact
9188 that the debugging information may be out of date.
9191 @node How gnatmake Works
9192 @section How @command{gnatmake} Works
9195 Generally @command{gnatmake} automatically performs all necessary
9196 recompilations and you don't need to worry about how it works. However,
9197 it may be useful to have some basic understanding of the @command{gnatmake}
9198 approach and in particular to understand how it uses the results of
9199 previous compilations without incorrectly depending on them.
9201 First a definition: an object file is considered @dfn{up to date} if the
9202 corresponding ALI file exists and if all the source files listed in the
9203 dependency section of this ALI file have time stamps matching those in
9204 the ALI file. This means that neither the source file itself nor any
9205 files that it depends on have been modified, and hence there is no need
9206 to recompile this file.
9208 @command{gnatmake} works by first checking if the specified main unit is up
9209 to date. If so, no compilations are required for the main unit. If not,
9210 @command{gnatmake} compiles the main program to build a new ALI file that
9211 reflects the latest sources. Then the ALI file of the main unit is
9212 examined to find all the source files on which the main program depends,
9213 and @command{gnatmake} recursively applies the above procedure on all these
9216 This process ensures that @command{gnatmake} only trusts the dependencies
9217 in an existing ALI file if they are known to be correct. Otherwise it
9218 always recompiles to determine a new, guaranteed accurate set of
9219 dependencies. As a result the program is compiled ``upside down'' from what may
9220 be more familiar as the required order of compilation in some other Ada
9221 systems. In particular, clients are compiled before the units on which
9222 they depend. The ability of GNAT to compile in any order is critical in
9223 allowing an order of compilation to be chosen that guarantees that
9224 @command{gnatmake} will recompute a correct set of new dependencies if
9227 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9228 imported by several of the executables, it will be recompiled at most once.
9230 Note: when using non-standard naming conventions
9231 (@pxref{Using Other File Names}), changing through a configuration pragmas
9232 file the version of a source and invoking @command{gnatmake} to recompile may
9233 have no effect, if the previous version of the source is still accessible
9234 by @command{gnatmake}. It may be necessary to use the switch
9235 ^-f^/FORCE_COMPILE^.
9237 @node Examples of gnatmake Usage
9238 @section Examples of @command{gnatmake} Usage
9241 @item gnatmake hello.adb
9242 Compile all files necessary to bind and link the main program
9243 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9244 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9246 @item gnatmake main1 main2 main3
9247 Compile all files necessary to bind and link the main programs
9248 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9249 (containing unit @code{Main2}) and @file{main3.adb}
9250 (containing unit @code{Main3}) and bind and link the resulting object files
9251 to generate three executable files @file{^main1^MAIN1.EXE^},
9252 @file{^main2^MAIN2.EXE^}
9253 and @file{^main3^MAIN3.EXE^}.
9256 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9260 @item gnatmake Main_Unit /QUIET
9261 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9262 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9264 Compile all files necessary to bind and link the main program unit
9265 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9266 be done with optimization level 2 and the order of elaboration will be
9267 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9268 displaying commands it is executing.
9271 @c *************************
9272 @node Improving Performance
9273 @chapter Improving Performance
9274 @cindex Improving performance
9277 This chapter presents several topics related to program performance.
9278 It first describes some of the tradeoffs that need to be considered
9279 and some of the techniques for making your program run faster.
9280 It then documents the @command{gnatelim} tool and unused subprogram/data
9281 elimination feature, which can reduce the size of program executables.
9283 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9284 driver (see @ref{The GNAT Driver and Project Files}).
9288 * Performance Considerations::
9289 * Reducing Size of Ada Executables with gnatelim::
9290 * Reducing Size of Executables with unused subprogram/data elimination::
9294 @c *****************************
9295 @node Performance Considerations
9296 @section Performance Considerations
9299 The GNAT system provides a number of options that allow a trade-off
9304 performance of the generated code
9307 speed of compilation
9310 minimization of dependences and recompilation
9313 the degree of run-time checking.
9317 The defaults (if no options are selected) aim at improving the speed
9318 of compilation and minimizing dependences, at the expense of performance
9319 of the generated code:
9326 no inlining of subprogram calls
9329 all run-time checks enabled except overflow and elaboration checks
9333 These options are suitable for most program development purposes. This
9334 chapter describes how you can modify these choices, and also provides
9335 some guidelines on debugging optimized code.
9338 * Controlling Run-Time Checks::
9339 * Use of Restrictions::
9340 * Optimization Levels::
9341 * Debugging Optimized Code::
9342 * Inlining of Subprograms::
9343 * Other Optimization Switches::
9344 * Optimization and Strict Aliasing::
9347 * Coverage Analysis::
9351 @node Controlling Run-Time Checks
9352 @subsection Controlling Run-Time Checks
9355 By default, GNAT generates all run-time checks, except arithmetic overflow
9356 checking for integer operations and checks for access before elaboration on
9357 subprogram calls. The latter are not required in default mode, because all
9358 necessary checking is done at compile time.
9359 @cindex @option{-gnatp} (@command{gcc})
9360 @cindex @option{-gnato} (@command{gcc})
9361 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9362 be modified. @xref{Run-Time Checks}.
9364 Our experience is that the default is suitable for most development
9367 We treat integer overflow specially because these
9368 are quite expensive and in our experience are not as important as other
9369 run-time checks in the development process. Note that division by zero
9370 is not considered an overflow check, and divide by zero checks are
9371 generated where required by default.
9373 Elaboration checks are off by default, and also not needed by default, since
9374 GNAT uses a static elaboration analysis approach that avoids the need for
9375 run-time checking. This manual contains a full chapter discussing the issue
9376 of elaboration checks, and if the default is not satisfactory for your use,
9377 you should read this chapter.
9379 For validity checks, the minimal checks required by the Ada Reference
9380 Manual (for case statements and assignments to array elements) are on
9381 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9382 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9383 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9384 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9385 are also suppressed entirely if @option{-gnatp} is used.
9387 @cindex Overflow checks
9388 @cindex Checks, overflow
9391 @cindex pragma Suppress
9392 @cindex pragma Unsuppress
9393 Note that the setting of the switches controls the default setting of
9394 the checks. They may be modified using either @code{pragma Suppress} (to
9395 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9396 checks) in the program source.
9398 @node Use of Restrictions
9399 @subsection Use of Restrictions
9402 The use of pragma Restrictions allows you to control which features are
9403 permitted in your program. Apart from the obvious point that if you avoid
9404 relatively expensive features like finalization (enforceable by the use
9405 of pragma Restrictions (No_Finalization), the use of this pragma does not
9406 affect the generated code in most cases.
9408 One notable exception to this rule is that the possibility of task abort
9409 results in some distributed overhead, particularly if finalization or
9410 exception handlers are used. The reason is that certain sections of code
9411 have to be marked as non-abortable.
9413 If you use neither the @code{abort} statement, nor asynchronous transfer
9414 of control (@code{select .. then abort}), then this distributed overhead
9415 is removed, which may have a general positive effect in improving
9416 overall performance. Especially code involving frequent use of tasking
9417 constructs and controlled types will show much improved performance.
9418 The relevant restrictions pragmas are
9420 @smallexample @c ada
9421 pragma Restrictions (No_Abort_Statements);
9422 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
9426 It is recommended that these restriction pragmas be used if possible. Note
9427 that this also means that you can write code without worrying about the
9428 possibility of an immediate abort at any point.
9430 @node Optimization Levels
9431 @subsection Optimization Levels
9432 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
9435 The default is optimization off. This results in the fastest compile
9436 times, but GNAT makes absolutely no attempt to optimize, and the
9437 generated programs are considerably larger and slower than when
9438 optimization is enabled. You can use the
9440 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
9441 @option{-O2}, @option{-O3}, and @option{-Os})
9444 @code{OPTIMIZE} qualifier
9446 to @command{gcc} to control the optimization level:
9449 @item ^-O0^/OPTIMIZE=NONE^
9450 No optimization (the default);
9451 generates unoptimized code but has
9452 the fastest compilation time.
9454 Note that many other compilers do fairly extensive optimization
9455 even if "no optimization" is specified. When using gcc, it is
9456 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
9457 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
9458 really does mean no optimization at all. This difference between
9459 gcc and other compilers should be kept in mind when doing
9460 performance comparisons.
9462 @item ^-O1^/OPTIMIZE=SOME^
9463 Moderate optimization;
9464 optimizes reasonably well but does not
9465 degrade compilation time significantly.
9467 @item ^-O2^/OPTIMIZE=ALL^
9469 @itemx /OPTIMIZE=DEVELOPMENT
9472 generates highly optimized code and has
9473 the slowest compilation time.
9475 @item ^-O3^/OPTIMIZE=INLINING^
9476 Full optimization as in @option{-O2},
9477 and also attempts automatic inlining of small
9478 subprograms within a unit (@pxref{Inlining of Subprograms}).
9480 @item ^-Os^/OPTIMIZE=SPACE^
9481 Optimize space usage of resulting program.
9485 Higher optimization levels perform more global transformations on the
9486 program and apply more expensive analysis algorithms in order to generate
9487 faster and more compact code. The price in compilation time, and the
9488 resulting improvement in execution time,
9489 both depend on the particular application and the hardware environment.
9490 You should experiment to find the best level for your application.
9492 The @option{^-Os^/OPTIMIZE=SPACE^} switch is independent of the time
9493 optimizations, so you can specify both @option{^-Os^/OPTIMIZE=SPACE^}
9494 and a time optimization on the same compile command.
9496 Since the precise set of optimizations done at each level will vary from
9497 release to release (and sometime from target to target), it is best to think
9498 of the optimization settings in general terms.
9499 The @cite{Using GNU GCC} manual contains details about
9500 ^the @option{-O} settings and a number of @option{-f} options that^how to^
9501 individually enable or disable specific optimizations.
9503 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
9504 been tested extensively at all optimization levels. There are some bugs
9505 which appear only with optimization turned on, but there have also been
9506 bugs which show up only in @emph{unoptimized} code. Selecting a lower
9507 level of optimization does not improve the reliability of the code
9508 generator, which in practice is highly reliable at all optimization
9511 Note regarding the use of @option{-O3}: The use of this optimization level
9512 is generally discouraged with GNAT, since it often results in larger
9513 executables which run more slowly. See further discussion of this point
9514 in @ref{Inlining of Subprograms}.
9516 @node Debugging Optimized Code
9517 @subsection Debugging Optimized Code
9518 @cindex Debugging optimized code
9519 @cindex Optimization and debugging
9522 Although it is possible to do a reasonable amount of debugging at
9524 nonzero optimization levels,
9525 the higher the level the more likely that
9528 @option{/OPTIMIZE} settings other than @code{NONE},
9529 such settings will make it more likely that
9531 source-level constructs will have been eliminated by optimization.
9532 For example, if a loop is strength-reduced, the loop
9533 control variable may be completely eliminated and thus cannot be
9534 displayed in the debugger.
9535 This can only happen at @option{-O2} or @option{-O3}.
9536 Explicit temporary variables that you code might be eliminated at
9537 ^level^setting^ @option{-O1} or higher.
9539 The use of the @option{^-g^/DEBUG^} switch,
9540 @cindex @option{^-g^/DEBUG^} (@command{gcc})
9541 which is needed for source-level debugging,
9542 affects the size of the program executable on disk,
9543 and indeed the debugging information can be quite large.
9544 However, it has no effect on the generated code (and thus does not
9545 degrade performance)
9547 Since the compiler generates debugging tables for a compilation unit before
9548 it performs optimizations, the optimizing transformations may invalidate some
9549 of the debugging data. You therefore need to anticipate certain
9550 anomalous situations that may arise while debugging optimized code.
9551 These are the most common cases:
9555 @i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next}
9557 the PC bouncing back and forth in the code. This may result from any of
9558 the following optimizations:
9562 @i{Common subexpression elimination:} using a single instance of code for a
9563 quantity that the source computes several times. As a result you
9564 may not be able to stop on what looks like a statement.
9567 @i{Invariant code motion:} moving an expression that does not change within a
9568 loop, to the beginning of the loop.
9571 @i{Instruction scheduling:} moving instructions so as to
9572 overlap loads and stores (typically) with other code, or in
9573 general to move computations of values closer to their uses. Often
9574 this causes you to pass an assignment statement without the assignment
9575 happening and then later bounce back to the statement when the
9576 value is actually needed. Placing a breakpoint on a line of code
9577 and then stepping over it may, therefore, not always cause all the
9578 expected side-effects.
9582 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
9583 two identical pieces of code are merged and the program counter suddenly
9584 jumps to a statement that is not supposed to be executed, simply because
9585 it (and the code following) translates to the same thing as the code
9586 that @emph{was} supposed to be executed. This effect is typically seen in
9587 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
9588 a @code{break} in a C @code{^switch^switch^} statement.
9591 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
9592 There are various reasons for this effect:
9596 In a subprogram prologue, a parameter may not yet have been moved to its
9600 A variable may be dead, and its register re-used. This is
9601 probably the most common cause.
9604 As mentioned above, the assignment of a value to a variable may
9608 A variable may be eliminated entirely by value propagation or
9609 other means. In this case, GCC may incorrectly generate debugging
9610 information for the variable
9614 In general, when an unexpected value appears for a local variable or parameter
9615 you should first ascertain if that value was actually computed by
9616 your program, as opposed to being incorrectly reported by the debugger.
9618 array elements in an object designated by an access value
9619 are generally less of a problem, once you have ascertained that the access
9621 Typically, this means checking variables in the preceding code and in the
9622 calling subprogram to verify that the value observed is explainable from other
9623 values (one must apply the procedure recursively to those
9624 other values); or re-running the code and stopping a little earlier
9625 (perhaps before the call) and stepping to better see how the variable obtained
9626 the value in question; or continuing to step @emph{from} the point of the
9627 strange value to see if code motion had simply moved the variable's
9632 In light of such anomalies, a recommended technique is to use @option{-O0}
9633 early in the software development cycle, when extensive debugging capabilities
9634 are most needed, and then move to @option{-O1} and later @option{-O2} as
9635 the debugger becomes less critical.
9636 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
9637 a release management issue.
9639 Note that if you use @option{-g} you can then use the @command{strip} program
9640 on the resulting executable,
9641 which removes both debugging information and global symbols.
9644 @node Inlining of Subprograms
9645 @subsection Inlining of Subprograms
9648 A call to a subprogram in the current unit is inlined if all the
9649 following conditions are met:
9653 The optimization level is at least @option{-O1}.
9656 The called subprogram is suitable for inlining: It must be small enough
9657 and not contain nested subprograms or anything else that @command{gcc}
9658 cannot support in inlined subprograms.
9661 The call occurs after the definition of the body of the subprogram.
9664 @cindex pragma Inline
9666 Either @code{pragma Inline} applies to the subprogram or it is
9667 small and automatic inlining (optimization level @option{-O3}) is
9672 Calls to subprograms in @code{with}'ed units are normally not inlined.
9673 To achieve actual inlining (that is, replacement of the call by the code
9674 in the body of the subprogram), the following conditions must all be true.
9678 The optimization level is at least @option{-O1}.
9681 The called subprogram is suitable for inlining: It must be small enough
9682 and not contain nested subprograms or anything else @command{gcc} cannot
9683 support in inlined subprograms.
9686 The call appears in a body (not in a package spec).
9689 There is a @code{pragma Inline} for the subprogram.
9692 @cindex @option{-gnatn} (@command{gcc})
9693 The @option{^-gnatn^/INLINE^} switch
9694 is used in the @command{gcc} command line
9697 Even if all these conditions are met, it may not be possible for
9698 the compiler to inline the call, due to the length of the body,
9699 or features in the body that make it impossible for the compiler
9702 Note that specifying the @option{-gnatn} switch causes additional
9703 compilation dependencies. Consider the following:
9705 @smallexample @c ada
9725 With the default behavior (no @option{-gnatn} switch specified), the
9726 compilation of the @code{Main} procedure depends only on its own source,
9727 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
9728 means that editing the body of @code{R} does not require recompiling
9731 On the other hand, the call @code{R.Q} is not inlined under these
9732 circumstances. If the @option{-gnatn} switch is present when @code{Main}
9733 is compiled, the call will be inlined if the body of @code{Q} is small
9734 enough, but now @code{Main} depends on the body of @code{R} in
9735 @file{r.adb} as well as on the spec. This means that if this body is edited,
9736 the main program must be recompiled. Note that this extra dependency
9737 occurs whether or not the call is in fact inlined by @command{gcc}.
9739 The use of front end inlining with @option{-gnatN} generates similar
9740 additional dependencies.
9742 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
9743 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
9744 can be used to prevent
9745 all inlining. This switch overrides all other conditions and ensures
9746 that no inlining occurs. The extra dependences resulting from
9747 @option{-gnatn} will still be active, even if
9748 this switch is used to suppress the resulting inlining actions.
9750 Note regarding the use of @option{-O3}: There is no difference in inlining
9751 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
9752 pragma @code{Inline} assuming the use of @option{-gnatn}
9753 or @option{-gnatN} (the switches that activate inlining). If you have used
9754 pragma @code{Inline} in appropriate cases, then it is usually much better
9755 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
9756 in this case only has the effect of inlining subprograms you did not
9757 think should be inlined. We often find that the use of @option{-O3} slows
9758 down code by performing excessive inlining, leading to increased instruction
9759 cache pressure from the increased code size. So the bottom line here is
9760 that you should not automatically assume that @option{-O3} is better than
9761 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
9762 it actually improves performance.
9764 @node Other Optimization Switches
9765 @subsection Other Optimization Switches
9766 @cindex Optimization Switches
9768 Since @code{GNAT} uses the @code{gcc} back end, all the specialized
9769 @code{gcc} optimization switches are potentially usable. These switches
9770 have not been extensively tested with GNAT but can generally be expected
9771 to work. Examples of switches in this category are
9772 @option{-funroll-loops} and
9773 the various target-specific @option{-m} options (in particular, it has been
9774 observed that @option{-march=pentium4} can significantly improve performance
9775 on appropriate machines). For full details of these switches, see the
9778 @node Optimization and Strict Aliasing
9779 @subsection Optimization and Strict Aliasing
9781 @cindex Strict Aliasing
9782 @cindex No_Strict_Aliasing
9785 The strong typing capabilities of Ada allow an optimizer to generate
9786 efficient code in situations where other languages would be forced to
9787 make worst case assumptions preventing such optimizations. Consider
9788 the following example:
9790 @smallexample @c ada
9793 type Int1 is new Integer;
9794 type Int2 is new Integer;
9795 type Int1A is access Int1;
9796 type Int2A is access Int2;
9803 for J in Data'Range loop
9804 if Data (J) = Int1V.all then
9805 Int2V.all := Int2V.all + 1;
9814 In this example, since the variable @code{Int1V} can only access objects
9815 of type @code{Int1}, and @code{Int2V} can only access objects of type
9816 @code{Int2}, there is no possibility that the assignment to
9817 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
9818 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
9819 for all iterations of the loop and avoid the extra memory reference
9820 required to dereference it each time through the loop.
9822 This kind of optimization, called strict aliasing analysis, is
9823 triggered by specifying an optimization level of @option{-O2} or
9824 higher and allows @code{GNAT} to generate more efficient code
9825 when access values are involved.
9827 However, although this optimization is always correct in terms of
9828 the formal semantics of the Ada Reference Manual, difficulties can
9829 arise if features like @code{Unchecked_Conversion} are used to break
9830 the typing system. Consider the following complete program example:
9832 @smallexample @c ada
9835 type int1 is new integer;
9836 type int2 is new integer;
9837 type a1 is access int1;
9838 type a2 is access int2;
9843 function to_a2 (Input : a1) return a2;
9846 with Unchecked_Conversion;
9848 function to_a2 (Input : a1) return a2 is
9850 new Unchecked_Conversion (a1, a2);
9852 return to_a2u (Input);
9858 with Text_IO; use Text_IO;
9860 v1 : a1 := new int1;
9861 v2 : a2 := to_a2 (v1);
9865 put_line (int1'image (v1.all));
9871 This program prints out 0 in @code{-O0} or @code{-O1}
9872 mode, but it prints out 1 in @code{-O2} mode. That's
9873 because in strict aliasing mode, the compiler can and
9874 does assume that the assignment to @code{v2.all} could not
9875 affect the value of @code{v1.all}, since different types
9878 This behavior is not a case of non-conformance with the standard, since
9879 the Ada RM specifies that an unchecked conversion where the resulting
9880 bit pattern is not a correct value of the target type can result in an
9881 abnormal value and attempting to reference an abnormal value makes the
9882 execution of a program erroneous. That's the case here since the result
9883 does not point to an object of type @code{int2}. This means that the
9884 effect is entirely unpredictable.
9886 However, although that explanation may satisfy a language
9887 lawyer, in practice an applications programmer expects an
9888 unchecked conversion involving pointers to create true
9889 aliases and the behavior of printing 1 seems plain wrong.
9890 In this case, the strict aliasing optimization is unwelcome.
9892 Indeed the compiler recognizes this possibility, and the
9893 unchecked conversion generates a warning:
9896 p2.adb:5:07: warning: possible aliasing problem with type "a2"
9897 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
9898 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
9902 Unfortunately the problem is recognized when compiling the body of
9903 package @code{p2}, but the actual "bad" code is generated while
9904 compiling the body of @code{m} and this latter compilation does not see
9905 the suspicious @code{Unchecked_Conversion}.
9907 As implied by the warning message, there are approaches you can use to
9908 avoid the unwanted strict aliasing optimization in a case like this.
9910 One possibility is to simply avoid the use of @code{-O2}, but
9911 that is a bit drastic, since it throws away a number of useful
9912 optimizations that do not involve strict aliasing assumptions.
9914 A less drastic approach is to compile the program using the
9915 option @code{-fno-strict-aliasing}. Actually it is only the
9916 unit containing the dereferencing of the suspicious pointer
9917 that needs to be compiled. So in this case, if we compile
9918 unit @code{m} with this switch, then we get the expected
9919 value of zero printed. Analyzing which units might need
9920 the switch can be painful, so a more reasonable approach
9921 is to compile the entire program with options @code{-O2}
9922 and @code{-fno-strict-aliasing}. If the performance is
9923 satisfactory with this combination of options, then the
9924 advantage is that the entire issue of possible "wrong"
9925 optimization due to strict aliasing is avoided.
9927 To avoid the use of compiler switches, the configuration
9928 pragma @code{No_Strict_Aliasing} with no parameters may be
9929 used to specify that for all access types, the strict
9930 aliasing optimization should be suppressed.
9932 However, these approaches are still overkill, in that they causes
9933 all manipulations of all access values to be deoptimized. A more
9934 refined approach is to concentrate attention on the specific
9935 access type identified as problematic.
9937 First, if a careful analysis of uses of the pointer shows
9938 that there are no possible problematic references, then
9939 the warning can be suppressed by bracketing the
9940 instantiation of @code{Unchecked_Conversion} to turn
9943 @smallexample @c ada
9944 pragma Warnings (Off);
9946 new Unchecked_Conversion (a1, a2);
9947 pragma Warnings (On);
9951 Of course that approach is not appropriate for this particular
9952 example, since indeed there is a problematic reference. In this
9953 case we can take one of two other approaches.
9955 The first possibility is to move the instantiation of unchecked
9956 conversion to the unit in which the type is declared. In
9957 this example, we would move the instantiation of
9958 @code{Unchecked_Conversion} from the body of package
9959 @code{p2} to the spec of package @code{p1}. Now the
9960 warning disappears. That's because any use of the
9961 access type knows there is a suspicious unchecked
9962 conversion, and the strict aliasing optimization
9963 is automatically suppressed for the type.
9965 If it is not practical to move the unchecked conversion to the same unit
9966 in which the destination access type is declared (perhaps because the
9967 source type is not visible in that unit), you may use pragma
9968 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
9969 same declarative sequence as the declaration of the access type:
9971 @smallexample @c ada
9972 type a2 is access int2;
9973 pragma No_Strict_Aliasing (a2);
9977 Here again, the compiler now knows that the strict aliasing optimization
9978 should be suppressed for any reference to type @code{a2} and the
9979 expected behavior is obtained.
9981 Finally, note that although the compiler can generate warnings for
9982 simple cases of unchecked conversions, there are tricker and more
9983 indirect ways of creating type incorrect aliases which the compiler
9984 cannot detect. Examples are the use of address overlays and unchecked
9985 conversions involving composite types containing access types as
9986 components. In such cases, no warnings are generated, but there can
9987 still be aliasing problems. One safe coding practice is to forbid the
9988 use of address clauses for type overlaying, and to allow unchecked
9989 conversion only for primitive types. This is not really a significant
9990 restriction since any possible desired effect can be achieved by
9991 unchecked conversion of access values.
9994 @node Coverage Analysis
9995 @subsection Coverage Analysis
9998 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
9999 the user to determine the distribution of execution time across a program,
10000 @pxref{Profiling} for details of usage.
10003 @node Reducing Size of Ada Executables with gnatelim
10004 @section Reducing Size of Ada Executables with @code{gnatelim}
10008 This section describes @command{gnatelim}, a tool which detects unused
10009 subprograms and helps the compiler to create a smaller executable for your
10014 * Running gnatelim::
10015 * Correcting the List of Eliminate Pragmas::
10016 * Making Your Executables Smaller::
10017 * Summary of the gnatelim Usage Cycle::
10020 @node About gnatelim
10021 @subsection About @code{gnatelim}
10024 When a program shares a set of Ada
10025 packages with other programs, it may happen that this program uses
10026 only a fraction of the subprograms defined in these packages. The code
10027 created for these unused subprograms increases the size of the executable.
10029 @code{gnatelim} tracks unused subprograms in an Ada program and
10030 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10031 subprograms that are declared but never called. By placing the list of
10032 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10033 recompiling your program, you may decrease the size of its executable,
10034 because the compiler will not generate the code for 'eliminated' subprograms.
10035 See GNAT Reference Manual for more information about this pragma.
10037 @code{gnatelim} needs as its input data the name of the main subprogram
10038 and a bind file for a main subprogram.
10040 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
10041 the main subprogram. @code{gnatelim} can work with both Ada and C
10042 bind files; when both are present, it uses the Ada bind file.
10043 The following commands will build the program and create the bind file:
10046 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10047 $ gnatbind main_prog
10050 Note that @code{gnatelim} needs neither object nor ALI files.
10052 @node Running gnatelim
10053 @subsection Running @code{gnatelim}
10056 @code{gnatelim} has the following command-line interface:
10059 $ gnatelim [options] name
10063 @code{name} should be a name of a source file that contains the main subprogram
10064 of a program (partition).
10066 @code{gnatelim} has the following switches:
10071 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10072 Quiet mode: by default @code{gnatelim} outputs to the standard error
10073 stream the number of program units left to be processed. This option turns
10076 @item ^-v^/VERBOSE^
10077 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10078 Verbose mode: @code{gnatelim} version information is printed as Ada
10079 comments to the standard output stream. Also, in addition to the number of
10080 program units left @code{gnatelim} will output the name of the current unit
10084 @cindex @option{^-a^/ALL^} (@command{gnatelim})
10085 Also look for subprograms from the GNAT run time that can be eliminated. Note
10086 that when @file{gnat.adc} is produced using this switch, the entire program
10087 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
10089 @item ^-I^/INCLUDE_DIRS=^@var{dir}
10090 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
10091 When looking for source files also look in directory @var{dir}. Specifying
10092 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
10093 sources in the current directory.
10095 @item ^-b^/BIND_FILE=^@var{bind_file}
10096 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
10097 Specifies @var{bind_file} as the bind file to process. If not set, the name
10098 of the bind file is computed from the full expanded Ada name
10099 of a main subprogram.
10101 @item ^-C^/CONFIG_FILE=^@var{config_file}
10102 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
10103 Specifies a file @var{config_file} that contains configuration pragmas. The
10104 file must be specified with full path.
10106 @item ^--GCC^/COMPILER^=@var{compiler_name}
10107 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
10108 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
10109 available on the path.
10111 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
10112 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
10113 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
10114 available on the path.
10118 @code{gnatelim} sends its output to the standard output stream, and all the
10119 tracing and debug information is sent to the standard error stream.
10120 In order to produce a proper GNAT configuration file
10121 @file{gnat.adc}, redirection must be used:
10125 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
10128 $ gnatelim main_prog.adb > gnat.adc
10137 $ gnatelim main_prog.adb >> gnat.adc
10141 in order to append the @code{gnatelim} output to the existing contents of
10145 @node Correcting the List of Eliminate Pragmas
10146 @subsection Correcting the List of Eliminate Pragmas
10149 In some rare cases @code{gnatelim} may try to eliminate
10150 subprograms that are actually called in the program. In this case, the
10151 compiler will generate an error message of the form:
10154 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
10158 You will need to manually remove the wrong @code{Eliminate} pragmas from
10159 the @file{gnat.adc} file. You should recompile your program
10160 from scratch after that, because you need a consistent @file{gnat.adc} file
10161 during the entire compilation.
10163 @node Making Your Executables Smaller
10164 @subsection Making Your Executables Smaller
10167 In order to get a smaller executable for your program you now have to
10168 recompile the program completely with the new @file{gnat.adc} file
10169 created by @code{gnatelim} in your current directory:
10172 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10176 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10177 recompile everything
10178 with the set of pragmas @code{Eliminate} that you have obtained with
10179 @command{gnatelim}).
10181 Be aware that the set of @code{Eliminate} pragmas is specific to each
10182 program. It is not recommended to merge sets of @code{Eliminate}
10183 pragmas created for different programs in one @file{gnat.adc} file.
10185 @node Summary of the gnatelim Usage Cycle
10186 @subsection Summary of the gnatelim Usage Cycle
10189 Here is a quick summary of the steps to be taken in order to reduce
10190 the size of your executables with @code{gnatelim}. You may use
10191 other GNAT options to control the optimization level,
10192 to produce the debugging information, to set search path, etc.
10196 Produce a bind file
10199 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10200 $ gnatbind main_prog
10204 Generate a list of @code{Eliminate} pragmas
10207 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10210 $ gnatelim main_prog >[>] gnat.adc
10215 Recompile the application
10218 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10223 @node Reducing Size of Executables with unused subprogram/data elimination
10224 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10225 @findex unused subprogram/data elimination
10228 This section describes how you can eliminate unused subprograms and data from
10229 your executable just by setting options at compilation time.
10232 * About unused subprogram/data elimination::
10233 * Compilation options::
10234 * Example of unused subprogram/data elimination::
10237 @node About unused subprogram/data elimination
10238 @subsection About unused subprogram/data elimination
10241 By default, an executable contains all code and data of its composing objects
10242 (directly linked or coming from statically linked libraries), even data or code
10243 never used by this executable.
10245 This feature will allow you to eliminate such unused code from your
10246 executable, making it smaller (in disk and in memory).
10248 This functionality is available on all Linux platforms except for the IA-64
10249 architecture and on all cross platforms using the ELF binary file format.
10250 In both cases GNU binutils version 2.16 or later are required to enable it.
10252 @node Compilation options
10253 @subsection Compilation options
10256 The operation of eliminating the unused code and data from the final executable
10257 is directly performed by the linker.
10259 In order to do this, it has to work with objects compiled with the
10261 @option{-ffunction-sections} @option{-fdata-sections}.
10262 @cindex @option{-ffunction-sections} (@command{gcc})
10263 @cindex @option{-fdata-sections} (@command{gcc})
10264 These options are usable with C and Ada files.
10265 They will place respectively each
10266 function or data in a separate section in the resulting object file.
10268 Once the objects and static libraries are created with these options, the
10269 linker can perform the dead code elimination. You can do this by setting
10270 the @option{-Wl,--gc-sections} option to gcc command or in the
10271 @option{-largs} section of gnatmake. This will perform a garbage collection of
10272 code and data never referenced.
10274 If the linker performs a partial link (@option{-r} ld linker option), then you
10275 will need to provide one or several entry point using the
10276 @option{-e} / @option{--entry} ld option.
10278 Note that objects compiled without the @option{-ffunction-sections} and
10279 @option{-fdata-sections} options can still be linked with the executable.
10280 However, no dead code elimination will be performed on those objects (they will
10283 The GNAT static library is now compiled with -ffunction-sections and
10284 -fdata-sections on some platforms. This allows you to eliminate the unused code
10285 and data of the GNAT library from your executable.
10287 @node Example of unused subprogram/data elimination
10288 @subsection Example of unused subprogram/data elimination
10291 Here is a simple example:
10293 @smallexample @c ada
10302 Used_Data : Integer;
10303 Unused_Data : Integer;
10305 procedure Used (Data : Integer);
10306 procedure Unused (Data : Integer);
10309 package body Aux is
10310 procedure Used (Data : Integer) is
10315 procedure Unused (Data : Integer) is
10317 Unused_Data := Data;
10323 @code{Unused} and @code{Unused_Data} are never referenced in this code
10324 excerpt, and hence they may be safely removed from the final executable.
10329 $ nm test | grep used
10330 020015f0 T aux__unused
10331 02005d88 B aux__unused_data
10332 020015cc T aux__used
10333 02005d84 B aux__used_data
10335 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10336 -largs -Wl,--gc-sections
10338 $ nm test | grep used
10339 02005350 T aux__used
10340 0201ffe0 B aux__used_data
10344 It can be observed that the procedure @code{Unused} and the object
10345 @code{Unused_Data} are removed by the linker when using the
10346 appropriate options.
10348 @c ********************************
10349 @node Renaming Files Using gnatchop
10350 @chapter Renaming Files Using @code{gnatchop}
10354 This chapter discusses how to handle files with multiple units by using
10355 the @code{gnatchop} utility. This utility is also useful in renaming
10356 files to meet the standard GNAT default file naming conventions.
10359 * Handling Files with Multiple Units::
10360 * Operating gnatchop in Compilation Mode::
10361 * Command Line for gnatchop::
10362 * Switches for gnatchop::
10363 * Examples of gnatchop Usage::
10366 @node Handling Files with Multiple Units
10367 @section Handling Files with Multiple Units
10370 The basic compilation model of GNAT requires that a file submitted to the
10371 compiler have only one unit and there be a strict correspondence
10372 between the file name and the unit name.
10374 The @code{gnatchop} utility allows both of these rules to be relaxed,
10375 allowing GNAT to process files which contain multiple compilation units
10376 and files with arbitrary file names. @code{gnatchop}
10377 reads the specified file and generates one or more output files,
10378 containing one unit per file. The unit and the file name correspond,
10379 as required by GNAT.
10381 If you want to permanently restructure a set of ``foreign'' files so that
10382 they match the GNAT rules, and do the remaining development using the
10383 GNAT structure, you can simply use @command{gnatchop} once, generate the
10384 new set of files and work with them from that point on.
10386 Alternatively, if you want to keep your files in the ``foreign'' format,
10387 perhaps to maintain compatibility with some other Ada compilation
10388 system, you can set up a procedure where you use @command{gnatchop} each
10389 time you compile, regarding the source files that it writes as temporary
10390 files that you throw away.
10392 @node Operating gnatchop in Compilation Mode
10393 @section Operating gnatchop in Compilation Mode
10396 The basic function of @code{gnatchop} is to take a file with multiple units
10397 and split it into separate files. The boundary between files is reasonably
10398 clear, except for the issue of comments and pragmas. In default mode, the
10399 rule is that any pragmas between units belong to the previous unit, except
10400 that configuration pragmas always belong to the following unit. Any comments
10401 belong to the following unit. These rules
10402 almost always result in the right choice of
10403 the split point without needing to mark it explicitly and most users will
10404 find this default to be what they want. In this default mode it is incorrect to
10405 submit a file containing only configuration pragmas, or one that ends in
10406 configuration pragmas, to @code{gnatchop}.
10408 However, using a special option to activate ``compilation mode'',
10410 can perform another function, which is to provide exactly the semantics
10411 required by the RM for handling of configuration pragmas in a compilation.
10412 In the absence of configuration pragmas (at the main file level), this
10413 option has no effect, but it causes such configuration pragmas to be handled
10414 in a quite different manner.
10416 First, in compilation mode, if @code{gnatchop} is given a file that consists of
10417 only configuration pragmas, then this file is appended to the
10418 @file{gnat.adc} file in the current directory. This behavior provides
10419 the required behavior described in the RM for the actions to be taken
10420 on submitting such a file to the compiler, namely that these pragmas
10421 should apply to all subsequent compilations in the same compilation
10422 environment. Using GNAT, the current directory, possibly containing a
10423 @file{gnat.adc} file is the representation
10424 of a compilation environment. For more information on the
10425 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
10427 Second, in compilation mode, if @code{gnatchop}
10428 is given a file that starts with
10429 configuration pragmas, and contains one or more units, then these
10430 configuration pragmas are prepended to each of the chopped files. This
10431 behavior provides the required behavior described in the RM for the
10432 actions to be taken on compiling such a file, namely that the pragmas
10433 apply to all units in the compilation, but not to subsequently compiled
10436 Finally, if configuration pragmas appear between units, they are appended
10437 to the previous unit. This results in the previous unit being illegal,
10438 since the compiler does not accept configuration pragmas that follow
10439 a unit. This provides the required RM behavior that forbids configuration
10440 pragmas other than those preceding the first compilation unit of a
10443 For most purposes, @code{gnatchop} will be used in default mode. The
10444 compilation mode described above is used only if you need exactly
10445 accurate behavior with respect to compilations, and you have files
10446 that contain multiple units and configuration pragmas. In this
10447 circumstance the use of @code{gnatchop} with the compilation mode
10448 switch provides the required behavior, and is for example the mode
10449 in which GNAT processes the ACVC tests.
10451 @node Command Line for gnatchop
10452 @section Command Line for @code{gnatchop}
10455 The @code{gnatchop} command has the form:
10458 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
10463 The only required argument is the file name of the file to be chopped.
10464 There are no restrictions on the form of this file name. The file itself
10465 contains one or more Ada units, in normal GNAT format, concatenated
10466 together. As shown, more than one file may be presented to be chopped.
10468 When run in default mode, @code{gnatchop} generates one output file in
10469 the current directory for each unit in each of the files.
10471 @var{directory}, if specified, gives the name of the directory to which
10472 the output files will be written. If it is not specified, all files are
10473 written to the current directory.
10475 For example, given a
10476 file called @file{hellofiles} containing
10478 @smallexample @c ada
10483 with Text_IO; use Text_IO;
10486 Put_Line ("Hello");
10496 $ gnatchop ^hellofiles^HELLOFILES.^
10500 generates two files in the current directory, one called
10501 @file{hello.ads} containing the single line that is the procedure spec,
10502 and the other called @file{hello.adb} containing the remaining text. The
10503 original file is not affected. The generated files can be compiled in
10507 When gnatchop is invoked on a file that is empty or that contains only empty
10508 lines and/or comments, gnatchop will not fail, but will not produce any
10511 For example, given a
10512 file called @file{toto.txt} containing
10514 @smallexample @c ada
10526 $ gnatchop ^toto.txt^TOT.TXT^
10530 will not produce any new file and will result in the following warnings:
10533 toto.txt:1:01: warning: empty file, contains no compilation units
10534 no compilation units found
10535 no source files written
10538 @node Switches for gnatchop
10539 @section Switches for @code{gnatchop}
10542 @command{gnatchop} recognizes the following switches:
10548 @cindex @option{--version} @command{gnatchop}
10549 Display Copyright and version, then exit disregarding all other options.
10552 @cindex @option{--help} @command{gnatchop}
10553 If @option{--version} was not used, display usage, then exit disregarding
10556 @item ^-c^/COMPILATION^
10557 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
10558 Causes @code{gnatchop} to operate in compilation mode, in which
10559 configuration pragmas are handled according to strict RM rules. See
10560 previous section for a full description of this mode.
10564 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
10565 used to parse the given file. Not all @code{xxx} options make sense,
10566 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
10567 process a source file that uses Latin-2 coding for identifiers.
10571 Causes @code{gnatchop} to generate a brief help summary to the standard
10572 output file showing usage information.
10574 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
10575 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
10576 Limit generated file names to the specified number @code{mm}
10578 This is useful if the
10579 resulting set of files is required to be interoperable with systems
10580 which limit the length of file names.
10582 If no value is given, or
10583 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
10584 a default of 39, suitable for OpenVMS Alpha
10585 Systems, is assumed
10588 No space is allowed between the @option{-k} and the numeric value. The numeric
10589 value may be omitted in which case a default of @option{-k8},
10591 with DOS-like file systems, is used. If no @option{-k} switch
10593 there is no limit on the length of file names.
10596 @item ^-p^/PRESERVE^
10597 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
10598 Causes the file ^modification^creation^ time stamp of the input file to be
10599 preserved and used for the time stamp of the output file(s). This may be
10600 useful for preserving coherency of time stamps in an environment where
10601 @code{gnatchop} is used as part of a standard build process.
10604 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
10605 Causes output of informational messages indicating the set of generated
10606 files to be suppressed. Warnings and error messages are unaffected.
10608 @item ^-r^/REFERENCE^
10609 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
10610 @findex Source_Reference
10611 Generate @code{Source_Reference} pragmas. Use this switch if the output
10612 files are regarded as temporary and development is to be done in terms
10613 of the original unchopped file. This switch causes
10614 @code{Source_Reference} pragmas to be inserted into each of the
10615 generated files to refers back to the original file name and line number.
10616 The result is that all error messages refer back to the original
10618 In addition, the debugging information placed into the object file (when
10619 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
10621 also refers back to this original file so that tools like profilers and
10622 debuggers will give information in terms of the original unchopped file.
10624 If the original file to be chopped itself contains
10625 a @code{Source_Reference}
10626 pragma referencing a third file, then gnatchop respects
10627 this pragma, and the generated @code{Source_Reference} pragmas
10628 in the chopped file refer to the original file, with appropriate
10629 line numbers. This is particularly useful when @code{gnatchop}
10630 is used in conjunction with @code{gnatprep} to compile files that
10631 contain preprocessing statements and multiple units.
10633 @item ^-v^/VERBOSE^
10634 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
10635 Causes @code{gnatchop} to operate in verbose mode. The version
10636 number and copyright notice are output, as well as exact copies of
10637 the gnat1 commands spawned to obtain the chop control information.
10639 @item ^-w^/OVERWRITE^
10640 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
10641 Overwrite existing file names. Normally @code{gnatchop} regards it as a
10642 fatal error if there is already a file with the same name as a
10643 file it would otherwise output, in other words if the files to be
10644 chopped contain duplicated units. This switch bypasses this
10645 check, and causes all but the last instance of such duplicated
10646 units to be skipped.
10650 @cindex @option{--GCC=} (@code{gnatchop})
10651 Specify the path of the GNAT parser to be used. When this switch is used,
10652 no attempt is made to add the prefix to the GNAT parser executable.
10656 @node Examples of gnatchop Usage
10657 @section Examples of @code{gnatchop} Usage
10661 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
10664 @item gnatchop -w hello_s.ada prerelease/files
10667 Chops the source file @file{hello_s.ada}. The output files will be
10668 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
10670 files with matching names in that directory (no files in the current
10671 directory are modified).
10673 @item gnatchop ^archive^ARCHIVE.^
10674 Chops the source file @file{^archive^ARCHIVE.^}
10675 into the current directory. One
10676 useful application of @code{gnatchop} is in sending sets of sources
10677 around, for example in email messages. The required sources are simply
10678 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
10680 @command{gnatchop} is used at the other end to reconstitute the original
10683 @item gnatchop file1 file2 file3 direc
10684 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
10685 the resulting files in the directory @file{direc}. Note that if any units
10686 occur more than once anywhere within this set of files, an error message
10687 is generated, and no files are written. To override this check, use the
10688 @option{^-w^/OVERWRITE^} switch,
10689 in which case the last occurrence in the last file will
10690 be the one that is output, and earlier duplicate occurrences for a given
10691 unit will be skipped.
10694 @node Configuration Pragmas
10695 @chapter Configuration Pragmas
10696 @cindex Configuration pragmas
10697 @cindex Pragmas, configuration
10700 Configuration pragmas include those pragmas described as
10701 such in the Ada Reference Manual, as well as
10702 implementation-dependent pragmas that are configuration pragmas. See the
10703 individual descriptions of pragmas in the @cite{GNAT Reference Manual} for
10704 details on these additional GNAT-specific configuration pragmas. Most
10705 notably, the pragma @code{Source_File_Name}, which allows
10706 specifying non-default names for source files, is a configuration
10707 pragma. The following is a complete list of configuration pragmas
10708 recognized by GNAT:
10715 Component_Alignment
10721 External_Name_Casing
10722 Float_Representation
10733 Propagate_Exceptions
10736 Restricted_Run_Time
10738 Restrictions_Warnings
10743 Task_Dispatching_Policy
10752 * Handling of Configuration Pragmas::
10753 * The Configuration Pragmas Files::
10756 @node Handling of Configuration Pragmas
10757 @section Handling of Configuration Pragmas
10759 Configuration pragmas may either appear at the start of a compilation
10760 unit, in which case they apply only to that unit, or they may apply to
10761 all compilations performed in a given compilation environment.
10763 GNAT also provides the @code{gnatchop} utility to provide an automatic
10764 way to handle configuration pragmas following the semantics for
10765 compilations (that is, files with multiple units), described in the RM.
10766 See @ref{Operating gnatchop in Compilation Mode} for details.
10767 However, for most purposes, it will be more convenient to edit the
10768 @file{gnat.adc} file that contains configuration pragmas directly,
10769 as described in the following section.
10771 @node The Configuration Pragmas Files
10772 @section The Configuration Pragmas Files
10773 @cindex @file{gnat.adc}
10776 In GNAT a compilation environment is defined by the current
10777 directory at the time that a compile command is given. This current
10778 directory is searched for a file whose name is @file{gnat.adc}. If
10779 this file is present, it is expected to contain one or more
10780 configuration pragmas that will be applied to the current compilation.
10781 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
10784 Configuration pragmas may be entered into the @file{gnat.adc} file
10785 either by running @code{gnatchop} on a source file that consists only of
10786 configuration pragmas, or more conveniently by
10787 direct editing of the @file{gnat.adc} file, which is a standard format
10790 In addition to @file{gnat.adc}, additional files containing configuration
10791 pragmas may be applied to the current compilation using the switch
10792 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
10793 contains only configuration pragmas. These configuration pragmas are
10794 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
10795 is present and switch @option{-gnatA} is not used).
10797 It is allowed to specify several switches @option{-gnatec}, all of which
10798 will be taken into account.
10800 If you are using project file, a separate mechanism is provided using
10801 project attributes, see @ref{Specifying Configuration Pragmas} for more
10805 Of special interest to GNAT OpenVMS Alpha is the following
10806 configuration pragma:
10808 @smallexample @c ada
10810 pragma Extend_System (Aux_DEC);
10815 In the presence of this pragma, GNAT adds to the definition of the
10816 predefined package SYSTEM all the additional types and subprograms that are
10817 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
10820 @node Handling Arbitrary File Naming Conventions Using gnatname
10821 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
10822 @cindex Arbitrary File Naming Conventions
10825 * Arbitrary File Naming Conventions::
10826 * Running gnatname::
10827 * Switches for gnatname::
10828 * Examples of gnatname Usage::
10831 @node Arbitrary File Naming Conventions
10832 @section Arbitrary File Naming Conventions
10835 The GNAT compiler must be able to know the source file name of a compilation
10836 unit. When using the standard GNAT default file naming conventions
10837 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
10838 does not need additional information.
10841 When the source file names do not follow the standard GNAT default file naming
10842 conventions, the GNAT compiler must be given additional information through
10843 a configuration pragmas file (@pxref{Configuration Pragmas})
10845 When the non standard file naming conventions are well-defined,
10846 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
10847 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
10848 if the file naming conventions are irregular or arbitrary, a number
10849 of pragma @code{Source_File_Name} for individual compilation units
10851 To help maintain the correspondence between compilation unit names and
10852 source file names within the compiler,
10853 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
10856 @node Running gnatname
10857 @section Running @code{gnatname}
10860 The usual form of the @code{gnatname} command is
10863 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
10867 All of the arguments are optional. If invoked without any argument,
10868 @code{gnatname} will display its usage.
10871 When used with at least one naming pattern, @code{gnatname} will attempt to
10872 find all the compilation units in files that follow at least one of the
10873 naming patterns. To find these compilation units,
10874 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
10878 One or several Naming Patterns may be given as arguments to @code{gnatname}.
10879 Each Naming Pattern is enclosed between double quotes.
10880 A Naming Pattern is a regular expression similar to the wildcard patterns
10881 used in file names by the Unix shells or the DOS prompt.
10884 Examples of Naming Patterns are
10893 For a more complete description of the syntax of Naming Patterns,
10894 see the second kind of regular expressions described in @file{g-regexp.ads}
10895 (the ``Glob'' regular expressions).
10898 When invoked with no switches, @code{gnatname} will create a configuration
10899 pragmas file @file{gnat.adc} in the current working directory, with pragmas
10900 @code{Source_File_Name} for each file that contains a valid Ada unit.
10902 @node Switches for gnatname
10903 @section Switches for @code{gnatname}
10906 Switches for @code{gnatname} must precede any specified Naming Pattern.
10909 You may specify any of the following switches to @code{gnatname}:
10915 @cindex @option{--version} @command{gnatname}
10916 Display Copyright and version, then exit disregarding all other options.
10919 @cindex @option{--help} @command{gnatname}
10920 If @option{--version} was not used, display usage, then exit disregarding
10923 @item ^-c^/CONFIG_FILE=^@file{file}
10924 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
10925 Create a configuration pragmas file @file{file} (instead of the default
10928 There may be zero, one or more space between @option{-c} and
10931 @file{file} may include directory information. @file{file} must be
10932 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
10933 When a switch @option{^-c^/CONFIG_FILE^} is
10934 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
10936 @item ^-d^/SOURCE_DIRS=^@file{dir}
10937 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
10938 Look for source files in directory @file{dir}. There may be zero, one or more
10939 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
10940 When a switch @option{^-d^/SOURCE_DIRS^}
10941 is specified, the current working directory will not be searched for source
10942 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
10943 or @option{^-D^/DIR_FILES^} switch.
10944 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
10945 If @file{dir} is a relative path, it is relative to the directory of
10946 the configuration pragmas file specified with switch
10947 @option{^-c^/CONFIG_FILE^},
10948 or to the directory of the project file specified with switch
10949 @option{^-P^/PROJECT_FILE^} or,
10950 if neither switch @option{^-c^/CONFIG_FILE^}
10951 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
10952 current working directory. The directory
10953 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
10955 @item ^-D^/DIRS_FILE=^@file{file}
10956 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
10957 Look for source files in all directories listed in text file @file{file}.
10958 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
10960 @file{file} must be an existing, readable text file.
10961 Each non empty line in @file{file} must be a directory.
10962 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
10963 switches @option{^-d^/SOURCE_DIRS^} as there are non empty lines in
10966 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
10967 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
10968 Foreign patterns. Using this switch, it is possible to add sources of languages
10969 other than Ada to the list of sources of a project file.
10970 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
10973 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
10976 will look for Ada units in all files with the @file{.ada} extension,
10977 and will add to the list of file for project @file{prj.gpr} the C files
10978 with extension ".^c^C^".
10981 @cindex @option{^-h^/HELP^} (@code{gnatname})
10982 Output usage (help) information. The output is written to @file{stdout}.
10984 @item ^-P^/PROJECT_FILE=^@file{proj}
10985 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
10986 Create or update project file @file{proj}. There may be zero, one or more space
10987 between @option{-P} and @file{proj}. @file{proj} may include directory
10988 information. @file{proj} must be writable.
10989 There may be only one switch @option{^-P^/PROJECT_FILE^}.
10990 When a switch @option{^-P^/PROJECT_FILE^} is specified,
10991 no switch @option{^-c^/CONFIG_FILE^} may be specified.
10993 @item ^-v^/VERBOSE^
10994 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
10995 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
10996 This includes name of the file written, the name of the directories to search
10997 and, for each file in those directories whose name matches at least one of
10998 the Naming Patterns, an indication of whether the file contains a unit,
10999 and if so the name of the unit.
11001 @item ^-v -v^/VERBOSE /VERBOSE^
11002 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11003 Very Verbose mode. In addition to the output produced in verbose mode,
11004 for each file in the searched directories whose name matches none of
11005 the Naming Patterns, an indication is given that there is no match.
11007 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11008 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11009 Excluded patterns. Using this switch, it is possible to exclude some files
11010 that would match the name patterns. For example,
11012 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11015 will look for Ada units in all files with the @file{.ada} extension,
11016 except those whose names end with @file{_nt.ada}.
11020 @node Examples of gnatname Usage
11021 @section Examples of @code{gnatname} Usage
11025 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11031 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11036 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11037 and be writable. In addition, the directory
11038 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11039 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11042 Note the optional spaces after @option{-c} and @option{-d}.
11047 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11048 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11051 $ gnatname /PROJECT_FILE=[HOME.ME]PROJ
11052 /EXCLUDED_PATTERN=*_nt_body.ada
11053 /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11054 /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11058 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11059 even in conjunction with one or several switches
11060 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11061 are used in this example.
11063 @c *****************************************
11064 @c * G N A T P r o j e c t M a n a g e r *
11065 @c *****************************************
11066 @node GNAT Project Manager
11067 @chapter GNAT Project Manager
11071 * Examples of Project Files::
11072 * Project File Syntax::
11073 * Objects and Sources in Project Files::
11074 * Importing Projects::
11075 * Project Extension::
11076 * Project Hierarchy Extension::
11077 * External References in Project Files::
11078 * Packages in Project Files::
11079 * Variables from Imported Projects::
11081 * Library Projects::
11082 * Stand-alone Library Projects::
11083 * Switches Related to Project Files::
11084 * Tools Supporting Project Files::
11085 * An Extended Example::
11086 * Project File Complete Syntax::
11089 @c ****************
11090 @c * Introduction *
11091 @c ****************
11094 @section Introduction
11097 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
11098 you to manage complex builds involving a number of source files, directories,
11099 and compilation options for different system configurations. In particular,
11100 project files allow you to specify:
11103 The directory or set of directories containing the source files, and/or the
11104 names of the specific source files themselves
11106 The directory in which the compiler's output
11107 (@file{ALI} files, object files, tree files) is to be placed
11109 The directory in which the executable programs is to be placed
11111 ^Switch^Switch^ settings for any of the project-enabled tools
11112 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
11113 @code{gnatfind}); you can apply these settings either globally or to individual
11116 The source files containing the main subprogram(s) to be built
11118 The source programming language(s) (currently Ada and/or C)
11120 Source file naming conventions; you can specify these either globally or for
11121 individual compilation units
11128 @node Project Files
11129 @subsection Project Files
11132 Project files are written in a syntax close to that of Ada, using familiar
11133 notions such as packages, context clauses, declarations, default values,
11134 assignments, and inheritance. Finally, project files can be built
11135 hierarchically from other project files, simplifying complex system
11136 integration and project reuse.
11138 A @dfn{project} is a specific set of values for various compilation properties.
11139 The settings for a given project are described by means of
11140 a @dfn{project file}, which is a text file written in an Ada-like syntax.
11141 Property values in project files are either strings or lists of strings.
11142 Properties that are not explicitly set receive default values. A project
11143 file may interrogate the values of @dfn{external variables} (user-defined
11144 command-line switches or environment variables), and it may specify property
11145 settings conditionally, based on the value of such variables.
11147 In simple cases, a project's source files depend only on other source files
11148 in the same project, or on the predefined libraries. (@emph{Dependence} is
11150 the Ada technical sense; as in one Ada unit @code{with}ing another.) However,
11151 the Project Manager also allows more sophisticated arrangements,
11152 where the source files in one project depend on source files in other
11156 One project can @emph{import} other projects containing needed source files.
11158 You can organize GNAT projects in a hierarchy: a @emph{child} project
11159 can extend a @emph{parent} project, inheriting the parent's source files and
11160 optionally overriding any of them with alternative versions
11164 More generally, the Project Manager lets you structure large development
11165 efforts into hierarchical subsystems, where build decisions are delegated
11166 to the subsystem level, and thus different compilation environments
11167 (^switch^switch^ settings) used for different subsystems.
11169 The Project Manager is invoked through the
11170 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
11171 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
11173 There may be zero, one or more spaces between @option{-P} and
11174 @option{@emph{projectfile}}.
11176 If you want to define (on the command line) an external variable that is
11177 queried by the project file, you must use the
11178 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
11179 The Project Manager parses and interprets the project file, and drives the
11180 invoked tool based on the project settings.
11182 The Project Manager supports a wide range of development strategies,
11183 for systems of all sizes. Here are some typical practices that are
11187 Using a common set of source files, but generating object files in different
11188 directories via different ^switch^switch^ settings
11190 Using a mostly-shared set of source files, but with different versions of
11195 The destination of an executable can be controlled inside a project file
11196 using the @option{^-o^-o^}
11198 In the absence of such a ^switch^switch^ either inside
11199 the project file or on the command line, any executable files generated by
11200 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
11201 in the project file. If no @code{Exec_Dir} is specified, they will be placed
11202 in the object directory of the project.
11204 You can use project files to achieve some of the effects of a source
11205 versioning system (for example, defining separate projects for
11206 the different sets of sources that comprise different releases) but the
11207 Project Manager is independent of any source configuration management tools
11208 that might be used by the developers.
11210 The next section introduces the main features of GNAT's project facility
11211 through a sequence of examples; subsequent sections will present the syntax
11212 and semantics in more detail. A more formal description of the project
11213 facility appears in the GNAT Reference Manual.
11215 @c *****************************
11216 @c * Examples of Project Files *
11217 @c *****************************
11219 @node Examples of Project Files
11220 @section Examples of Project Files
11222 This section illustrates some of the typical uses of project files and
11223 explains their basic structure and behavior.
11226 * Common Sources with Different ^Switches^Switches^ and Directories::
11227 * Using External Variables::
11228 * Importing Other Projects::
11229 * Extending a Project::
11232 @node Common Sources with Different ^Switches^Switches^ and Directories
11233 @subsection Common Sources with Different ^Switches^Switches^ and Directories
11237 * Specifying the Object Directory::
11238 * Specifying the Exec Directory::
11239 * Project File Packages::
11240 * Specifying ^Switch^Switch^ Settings::
11241 * Main Subprograms::
11242 * Executable File Names::
11243 * Source File Naming Conventions::
11244 * Source Language(s)::
11248 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
11249 @file{proc.adb} are in the @file{/common} directory. The file
11250 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
11251 package @code{Pack}. We want to compile these source files under two sets
11252 of ^switches^switches^:
11255 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
11256 and the @option{^-gnata^-gnata^},
11257 @option{^-gnato^-gnato^},
11258 and @option{^-gnatE^-gnatE^} switches to the
11259 compiler; the compiler's output is to appear in @file{/common/debug}
11261 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
11262 to the compiler; the compiler's output is to appear in @file{/common/release}
11266 The GNAT project files shown below, respectively @file{debug.gpr} and
11267 @file{release.gpr} in the @file{/common} directory, achieve these effects.
11280 ^/common/debug^[COMMON.DEBUG]^
11285 ^/common/release^[COMMON.RELEASE]^
11290 Here are the corresponding project files:
11292 @smallexample @c projectfile
11295 for Object_Dir use "debug";
11296 for Main use ("proc");
11299 for ^Default_Switches^Default_Switches^ ("Ada")
11301 for Executable ("proc.adb") use "proc1";
11306 package Compiler is
11307 for ^Default_Switches^Default_Switches^ ("Ada")
11308 use ("-fstack-check",
11311 "^-gnatE^-gnatE^");
11317 @smallexample @c projectfile
11320 for Object_Dir use "release";
11321 for Exec_Dir use ".";
11322 for Main use ("proc");
11324 package Compiler is
11325 for ^Default_Switches^Default_Switches^ ("Ada")
11333 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
11334 insensitive), and analogously the project defined by @file{release.gpr} is
11335 @code{"Release"}. For consistency the file should have the same name as the
11336 project, and the project file's extension should be @code{"gpr"}. These
11337 conventions are not required, but a warning is issued if they are not followed.
11339 If the current directory is @file{^/temp^[TEMP]^}, then the command
11341 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
11345 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
11346 as well as the @code{^proc1^PROC1.EXE^} executable,
11347 using the ^switch^switch^ settings defined in the project file.
11349 Likewise, the command
11351 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
11355 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
11356 and the @code{^proc^PROC.EXE^}
11357 executable in @file{^/common^[COMMON]^},
11358 using the ^switch^switch^ settings from the project file.
11361 @unnumberedsubsubsec Source Files
11364 If a project file does not explicitly specify a set of source directories or
11365 a set of source files, then by default the project's source files are the
11366 Ada source files in the project file directory. Thus @file{pack.ads},
11367 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
11369 @node Specifying the Object Directory
11370 @unnumberedsubsubsec Specifying the Object Directory
11373 Several project properties are modeled by Ada-style @emph{attributes};
11374 a property is defined by supplying the equivalent of an Ada attribute
11375 definition clause in the project file.
11376 A project's object directory is another such a property; the corresponding
11377 attribute is @code{Object_Dir}, and its value is also a string expression,
11378 specified either as absolute or relative. In the later case,
11379 it is relative to the project file directory. Thus the compiler's
11380 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
11381 (for the @code{Debug} project)
11382 and to @file{^/common/release^[COMMON.RELEASE]^}
11383 (for the @code{Release} project).
11384 If @code{Object_Dir} is not specified, then the default is the project file
11387 @node Specifying the Exec Directory
11388 @unnumberedsubsubsec Specifying the Exec Directory
11391 A project's exec directory is another property; the corresponding
11392 attribute is @code{Exec_Dir}, and its value is also a string expression,
11393 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
11394 then the default is the object directory (which may also be the project file
11395 directory if attribute @code{Object_Dir} is not specified). Thus the executable
11396 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
11397 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
11398 and in @file{^/common^[COMMON]^} for the @code{Release} project.
11400 @node Project File Packages
11401 @unnumberedsubsubsec Project File Packages
11404 A GNAT tool that is integrated with the Project Manager is modeled by a
11405 corresponding package in the project file. In the example above,
11406 The @code{Debug} project defines the packages @code{Builder}
11407 (for @command{gnatmake}) and @code{Compiler};
11408 the @code{Release} project defines only the @code{Compiler} package.
11410 The Ada-like package syntax is not to be taken literally. Although packages in
11411 project files bear a surface resemblance to packages in Ada source code, the
11412 notation is simply a way to convey a grouping of properties for a named
11413 entity. Indeed, the package names permitted in project files are restricted
11414 to a predefined set, corresponding to the project-aware tools, and the contents
11415 of packages are limited to a small set of constructs.
11416 The packages in the example above contain attribute definitions.
11418 @node Specifying ^Switch^Switch^ Settings
11419 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
11422 ^Switch^Switch^ settings for a project-aware tool can be specified through
11423 attributes in the package that corresponds to the tool.
11424 The example above illustrates one of the relevant attributes,
11425 @code{^Default_Switches^Default_Switches^}, which is defined in packages
11426 in both project files.
11427 Unlike simple attributes like @code{Source_Dirs},
11428 @code{^Default_Switches^Default_Switches^} is
11429 known as an @emph{associative array}. When you define this attribute, you must
11430 supply an ``index'' (a literal string), and the effect of the attribute
11431 definition is to set the value of the array at the specified index.
11432 For the @code{^Default_Switches^Default_Switches^} attribute,
11433 the index is a programming language (in our case, Ada),
11434 and the value specified (after @code{use}) must be a list
11435 of string expressions.
11437 The attributes permitted in project files are restricted to a predefined set.
11438 Some may appear at project level, others in packages.
11439 For any attribute that is an associative array, the index must always be a
11440 literal string, but the restrictions on this string (e.g., a file name or a
11441 language name) depend on the individual attribute.
11442 Also depending on the attribute, its specified value will need to be either a
11443 string or a string list.
11445 In the @code{Debug} project, we set the switches for two tools,
11446 @command{gnatmake} and the compiler, and thus we include the two corresponding
11447 packages; each package defines the @code{^Default_Switches^Default_Switches^}
11448 attribute with index @code{"Ada"}.
11449 Note that the package corresponding to
11450 @command{gnatmake} is named @code{Builder}. The @code{Release} project is
11451 similar, but only includes the @code{Compiler} package.
11453 In project @code{Debug} above, the ^switches^switches^ starting with
11454 @option{-gnat} that are specified in package @code{Compiler}
11455 could have been placed in package @code{Builder}, since @command{gnatmake}
11456 transmits all such ^switches^switches^ to the compiler.
11458 @node Main Subprograms
11459 @unnumberedsubsubsec Main Subprograms
11462 One of the specifiable properties of a project is a list of files that contain
11463 main subprograms. This property is captured in the @code{Main} attribute,
11464 whose value is a list of strings. If a project defines the @code{Main}
11465 attribute, it is not necessary to identify the main subprogram(s) when
11466 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
11468 @node Executable File Names
11469 @unnumberedsubsubsec Executable File Names
11472 By default, the executable file name corresponding to a main source is
11473 deduced from the main source file name. Through the attributes
11474 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
11475 it is possible to change this default.
11476 In project @code{Debug} above, the executable file name
11477 for main source @file{^proc.adb^PROC.ADB^} is
11478 @file{^proc1^PROC1.EXE^}.
11479 Attribute @code{Executable_Suffix}, when specified, may change the suffix
11480 of the executable files, when no attribute @code{Executable} applies:
11481 its value replace the platform-specific executable suffix.
11482 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
11483 specify a non default executable file name when several mains are built at once
11484 in a single @command{gnatmake} command.
11486 @node Source File Naming Conventions
11487 @unnumberedsubsubsec Source File Naming Conventions
11490 Since the project files above do not specify any source file naming
11491 conventions, the GNAT defaults are used. The mechanism for defining source
11492 file naming conventions -- a package named @code{Naming} --
11493 is described below (@pxref{Naming Schemes}).
11495 @node Source Language(s)
11496 @unnumberedsubsubsec Source Language(s)
11499 Since the project files do not specify a @code{Languages} attribute, by
11500 default the GNAT tools assume that the language of the project file is Ada.
11501 More generally, a project can comprise source files
11502 in Ada, C, and/or other languages.
11504 @node Using External Variables
11505 @subsection Using External Variables
11508 Instead of supplying different project files for debug and release, we can
11509 define a single project file that queries an external variable (set either
11510 on the command line or via an ^environment variable^logical name^) in order to
11511 conditionally define the appropriate settings. Again, assume that the
11512 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
11513 located in directory @file{^/common^[COMMON]^}. The following project file,
11514 @file{build.gpr}, queries the external variable named @code{STYLE} and
11515 defines an object directory and ^switch^switch^ settings based on whether
11516 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
11517 the default is @code{"deb"}.
11519 @smallexample @c projectfile
11522 for Main use ("proc");
11524 type Style_Type is ("deb", "rel");
11525 Style : Style_Type := external ("STYLE", "deb");
11529 for Object_Dir use "debug";
11532 for Object_Dir use "release";
11533 for Exec_Dir use ".";
11542 for ^Default_Switches^Default_Switches^ ("Ada")
11544 for Executable ("proc") use "proc1";
11553 package Compiler is
11557 for ^Default_Switches^Default_Switches^ ("Ada")
11558 use ("^-gnata^-gnata^",
11560 "^-gnatE^-gnatE^");
11563 for ^Default_Switches^Default_Switches^ ("Ada")
11574 @code{Style_Type} is an example of a @emph{string type}, which is the project
11575 file analog of an Ada enumeration type but whose components are string literals
11576 rather than identifiers. @code{Style} is declared as a variable of this type.
11578 The form @code{external("STYLE", "deb")} is known as an
11579 @emph{external reference}; its first argument is the name of an
11580 @emph{external variable}, and the second argument is a default value to be
11581 used if the external variable doesn't exist. You can define an external
11582 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
11583 or you can use ^an environment variable^a logical name^
11584 as an external variable.
11586 Each @code{case} construct is expanded by the Project Manager based on the
11587 value of @code{Style}. Thus the command
11590 gnatmake -P/common/build.gpr -XSTYLE=deb
11596 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
11601 is equivalent to the @command{gnatmake} invocation using the project file
11602 @file{debug.gpr} in the earlier example. So is the command
11604 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
11608 since @code{"deb"} is the default for @code{STYLE}.
11614 gnatmake -P/common/build.gpr -XSTYLE=rel
11620 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
11625 is equivalent to the @command{gnatmake} invocation using the project file
11626 @file{release.gpr} in the earlier example.
11628 @node Importing Other Projects
11629 @subsection Importing Other Projects
11630 @cindex @code{ADA_PROJECT_PATH}
11633 A compilation unit in a source file in one project may depend on compilation
11634 units in source files in other projects. To compile this unit under
11635 control of a project file, the
11636 dependent project must @emph{import} the projects containing the needed source
11638 This effect is obtained using syntax similar to an Ada @code{with} clause,
11639 but where @code{with}ed entities are strings that denote project files.
11641 As an example, suppose that the two projects @code{GUI_Proj} and
11642 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
11643 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
11644 and @file{^/comm^[COMM]^}, respectively.
11645 Suppose that the source files for @code{GUI_Proj} are
11646 @file{gui.ads} and @file{gui.adb}, and that the source files for
11647 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
11648 files is located in its respective project file directory. Schematically:
11667 We want to develop an application in directory @file{^/app^[APP]^} that
11668 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
11669 the corresponding project files (e.g. the ^switch^switch^ settings
11670 and object directory).
11671 Skeletal code for a main procedure might be something like the following:
11673 @smallexample @c ada
11676 procedure App_Main is
11685 Here is a project file, @file{app_proj.gpr}, that achieves the desired
11688 @smallexample @c projectfile
11690 with "/gui/gui_proj", "/comm/comm_proj";
11691 project App_Proj is
11692 for Main use ("app_main");
11698 Building an executable is achieved through the command:
11700 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
11703 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
11704 in the directory where @file{app_proj.gpr} resides.
11706 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
11707 (as illustrated above) the @code{with} clause can omit the extension.
11709 Our example specified an absolute path for each imported project file.
11710 Alternatively, the directory name of an imported object can be omitted
11714 The imported project file is in the same directory as the importing project
11717 You have defined ^an environment variable^a logical name^
11718 that includes the directory containing
11719 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
11720 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
11721 directory names separated by colons (semicolons on Windows).
11725 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
11726 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
11729 @smallexample @c projectfile
11731 with "gui_proj", "comm_proj";
11732 project App_Proj is
11733 for Main use ("app_main");
11739 Importing other projects can create ambiguities.
11740 For example, the same unit might be present in different imported projects, or
11741 it might be present in both the importing project and in an imported project.
11742 Both of these conditions are errors. Note that in the current version of
11743 the Project Manager, it is illegal to have an ambiguous unit even if the
11744 unit is never referenced by the importing project. This restriction may be
11745 relaxed in a future release.
11747 @node Extending a Project
11748 @subsection Extending a Project
11751 In large software systems it is common to have multiple
11752 implementations of a common interface; in Ada terms, multiple versions of a
11753 package body for the same specification. For example, one implementation
11754 might be safe for use in tasking programs, while another might only be used
11755 in sequential applications. This can be modeled in GNAT using the concept
11756 of @emph{project extension}. If one project (the ``child'') @emph{extends}
11757 another project (the ``parent'') then by default all source files of the
11758 parent project are inherited by the child, but the child project can
11759 override any of the parent's source files with new versions, and can also
11760 add new files. This facility is the project analog of a type extension in
11761 Object-Oriented Programming. Project hierarchies are permitted (a child
11762 project may be the parent of yet another project), and a project that
11763 inherits one project can also import other projects.
11765 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
11766 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
11767 @file{pack.adb}, and @file{proc.adb}:
11780 Note that the project file can simply be empty (that is, no attribute or
11781 package is defined):
11783 @smallexample @c projectfile
11785 project Seq_Proj is
11791 implying that its source files are all the Ada source files in the project
11794 Suppose we want to supply an alternate version of @file{pack.adb}, in
11795 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
11796 @file{pack.ads} and @file{proc.adb}. We can define a project
11797 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
11801 ^/tasking^[TASKING]^
11807 project Tasking_Proj extends "/seq/seq_proj" is
11813 The version of @file{pack.adb} used in a build depends on which project file
11816 Note that we could have obtained the desired behavior using project import
11817 rather than project inheritance; a @code{base} project would contain the
11818 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
11819 import @code{base} and add @file{pack.adb}, and likewise a tasking project
11820 would import @code{base} and add a different version of @file{pack.adb}. The
11821 choice depends on whether other sources in the original project need to be
11822 overridden. If they do, then project extension is necessary, otherwise,
11823 importing is sufficient.
11826 In a project file that extends another project file, it is possible to
11827 indicate that an inherited source is not part of the sources of the extending
11828 project. This is necessary sometimes when a package spec has been overloaded
11829 and no longer requires a body: in this case, it is necessary to indicate that
11830 the inherited body is not part of the sources of the project, otherwise there
11831 will be a compilation error when compiling the spec.
11833 For that purpose, the attribute @code{Excluded_Source_Files} is used.
11834 Its value is a string list: a list of file names.
11836 @smallexample @c @projectfile
11837 project B extends "a" is
11838 for Source_Files use ("pkg.ads");
11839 -- New spec of Pkg does not need a completion
11840 for Excluded_Source_Files use ("pkg.adb");
11844 Attribute @code{Excluded_Source_Files} may also be used to check if a source
11845 is still needed: if it is possible to build using @command{gnatmake} when such
11846 a source is put in attribute @code{Excluded_Source_Files} of a project P, then
11847 it is possible to remove the source completely from a system that includes
11850 @c ***********************
11851 @c * Project File Syntax *
11852 @c ***********************
11854 @node Project File Syntax
11855 @section Project File Syntax
11864 * Associative Array Attributes::
11865 * case Constructions::
11869 This section describes the structure of project files.
11871 A project may be an @emph{independent project}, entirely defined by a single
11872 project file. Any Ada source file in an independent project depends only
11873 on the predefined library and other Ada source files in the same project.
11876 A project may also @dfn{depend on} other projects, in either or both of
11877 the following ways:
11879 @item It may import any number of projects
11880 @item It may extend at most one other project
11884 The dependence relation is a directed acyclic graph (the subgraph reflecting
11885 the ``extends'' relation is a tree).
11887 A project's @dfn{immediate sources} are the source files directly defined by
11888 that project, either implicitly by residing in the project file's directory,
11889 or explicitly through any of the source-related attributes described below.
11890 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
11891 of @var{proj} together with the immediate sources (unless overridden) of any
11892 project on which @var{proj} depends (either directly or indirectly).
11895 @subsection Basic Syntax
11898 As seen in the earlier examples, project files have an Ada-like syntax.
11899 The minimal project file is:
11900 @smallexample @c projectfile
11909 The identifier @code{Empty} is the name of the project.
11910 This project name must be present after the reserved
11911 word @code{end} at the end of the project file, followed by a semi-colon.
11913 Any name in a project file, such as the project name or a variable name,
11914 has the same syntax as an Ada identifier.
11916 The reserved words of project files are the Ada reserved words plus
11917 @code{extends}, @code{external}, and @code{project}. Note that the only Ada
11918 reserved words currently used in project file syntax are:
11946 Comments in project files have the same syntax as in Ada, two consecutive
11947 hyphens through the end of the line.
11950 @subsection Packages
11953 A project file may contain @emph{packages}. The name of a package must be one
11954 of the identifiers from the following list. A package
11955 with a given name may only appear once in a project file. Package names are
11956 case insensitive. The following package names are legal:
11972 @code{Cross_Reference}
11976 @code{Pretty_Printer}
11986 @code{Language_Processing}
11990 In its simplest form, a package may be empty:
11992 @smallexample @c projectfile
12002 A package may contain @emph{attribute declarations},
12003 @emph{variable declarations} and @emph{case constructions}, as will be
12006 When there is ambiguity between a project name and a package name,
12007 the name always designates the project. To avoid possible confusion, it is
12008 always a good idea to avoid naming a project with one of the
12009 names allowed for packages or any name that starts with @code{gnat}.
12012 @subsection Expressions
12015 An @emph{expression} is either a @emph{string expression} or a
12016 @emph{string list expression}.
12018 A @emph{string expression} is either a @emph{simple string expression} or a
12019 @emph{compound string expression}.
12021 A @emph{simple string expression} is one of the following:
12023 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
12024 @item A string-valued variable reference (@pxref{Variables})
12025 @item A string-valued attribute reference (@pxref{Attributes})
12026 @item An external reference (@pxref{External References in Project Files})
12030 A @emph{compound string expression} is a concatenation of string expressions,
12031 using the operator @code{"&"}
12033 Path & "/" & File_Name & ".ads"
12037 A @emph{string list expression} is either a
12038 @emph{simple string list expression} or a
12039 @emph{compound string list expression}.
12041 A @emph{simple string list expression} is one of the following:
12043 @item A parenthesized list of zero or more string expressions,
12044 separated by commas
12046 File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
12049 @item A string list-valued variable reference
12050 @item A string list-valued attribute reference
12054 A @emph{compound string list expression} is the concatenation (using
12055 @code{"&"}) of a simple string list expression and an expression. Note that
12056 each term in a compound string list expression, except the first, may be
12057 either a string expression or a string list expression.
12059 @smallexample @c projectfile
12061 File_Name_List := () & File_Name; -- One string in this list
12062 Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
12064 Big_List := File_Name_List & Extended_File_Name_List;
12065 -- Concatenation of two string lists: three strings
12066 Illegal_List := "gnat.adc" & Extended_File_Name_List;
12067 -- Illegal: must start with a string list
12072 @subsection String Types
12075 A @emph{string type declaration} introduces a discrete set of string literals.
12076 If a string variable is declared to have this type, its value
12077 is restricted to the given set of literals.
12079 Here is an example of a string type declaration:
12081 @smallexample @c projectfile
12082 type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
12086 Variables of a string type are called @emph{typed variables}; all other
12087 variables are called @emph{untyped variables}. Typed variables are
12088 particularly useful in @code{case} constructions, to support conditional
12089 attribute declarations.
12090 (@pxref{case Constructions}).
12092 The string literals in the list are case sensitive and must all be different.
12093 They may include any graphic characters allowed in Ada, including spaces.
12095 A string type may only be declared at the project level, not inside a package.
12097 A string type may be referenced by its name if it has been declared in the same
12098 project file, or by an expanded name whose prefix is the name of the project
12099 in which it is declared.
12102 @subsection Variables
12105 A variable may be declared at the project file level, or within a package.
12106 Here are some examples of variable declarations:
12108 @smallexample @c projectfile
12110 This_OS : OS := external ("OS"); -- a typed variable declaration
12111 That_OS := "GNU/Linux"; -- an untyped variable declaration
12116 The syntax of a @emph{typed variable declaration} is identical to the Ada
12117 syntax for an object declaration. By contrast, the syntax of an untyped
12118 variable declaration is identical to an Ada assignment statement. In fact,
12119 variable declarations in project files have some of the characteristics of
12120 an assignment, in that successive declarations for the same variable are
12121 allowed. Untyped variable declarations do establish the expected kind of the
12122 variable (string or string list), and successive declarations for it must
12123 respect the initial kind.
12126 A string variable declaration (typed or untyped) declares a variable
12127 whose value is a string. This variable may be used as a string expression.
12128 @smallexample @c projectfile
12129 File_Name := "readme.txt";
12130 Saved_File_Name := File_Name & ".saved";
12134 A string list variable declaration declares a variable whose value is a list
12135 of strings. The list may contain any number (zero or more) of strings.
12137 @smallexample @c projectfile
12139 List_With_One_Element := ("^-gnaty^-gnaty^");
12140 List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
12141 Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
12142 "pack2.ada", "util_.ada", "util.ada");
12146 The same typed variable may not be declared more than once at project level,
12147 and it may not be declared more than once in any package; it is in effect
12150 The same untyped variable may be declared several times. Declarations are
12151 elaborated in the order in which they appear, so the new value replaces
12152 the old one, and any subsequent reference to the variable uses the new value.
12153 However, as noted above, if a variable has been declared as a string, all
12155 declarations must give it a string value. Similarly, if a variable has
12156 been declared as a string list, all subsequent declarations
12157 must give it a string list value.
12159 A @emph{variable reference} may take several forms:
12162 @item The simple variable name, for a variable in the current package (if any)
12163 or in the current project
12164 @item An expanded name, whose prefix is a context name.
12168 A @emph{context} may be one of the following:
12171 @item The name of an existing package in the current project
12172 @item The name of an imported project of the current project
12173 @item The name of an ancestor project (i.e., a project extended by the current
12174 project, either directly or indirectly)
12175 @item An expanded name whose prefix is an imported/parent project name, and
12176 whose selector is a package name in that project.
12180 A variable reference may be used in an expression.
12183 @subsection Attributes
12186 A project (and its packages) may have @emph{attributes} that define
12187 the project's properties. Some attributes have values that are strings;
12188 others have values that are string lists.
12190 There are two categories of attributes: @emph{simple attributes}
12191 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
12193 Legal project attribute names, and attribute names for each legal package are
12194 listed below. Attributes names are case-insensitive.
12196 The following attributes are defined on projects (all are simple attributes):
12198 @multitable @columnfractions .4 .3
12199 @item @emph{Attribute Name}
12201 @item @code{Source_Files}
12203 @item @code{Source_Dirs}
12205 @item @code{Source_List_File}
12207 @item @code{Object_Dir}
12209 @item @code{Exec_Dir}
12211 @item @code{Excluded_Source_Dirs}
12213 @item @code{Excluded_Source_Files}
12215 @item @code{Languages}
12219 @item @code{Library_Dir}
12221 @item @code{Library_Name}
12223 @item @code{Library_Kind}
12225 @item @code{Library_Version}
12227 @item @code{Library_Interface}
12229 @item @code{Library_Auto_Init}
12231 @item @code{Library_Options}
12233 @item @code{Library_Src_Dir}
12235 @item @code{Library_ALI_Dir}
12237 @item @code{Library_GCC}
12239 @item @code{Library_Symbol_File}
12241 @item @code{Library_Symbol_Policy}
12243 @item @code{Library_Reference_Symbol_File}
12245 @item @code{Externally_Built}
12250 The following attributes are defined for package @code{Naming}
12251 (@pxref{Naming Schemes}):
12253 @multitable @columnfractions .4 .2 .2 .2
12254 @item Attribute Name @tab Category @tab Index @tab Value
12255 @item @code{Spec_Suffix}
12256 @tab associative array
12259 @item @code{Body_Suffix}
12260 @tab associative array
12263 @item @code{Separate_Suffix}
12264 @tab simple attribute
12267 @item @code{Casing}
12268 @tab simple attribute
12271 @item @code{Dot_Replacement}
12272 @tab simple attribute
12276 @tab associative array
12280 @tab associative array
12283 @item @code{Specification_Exceptions}
12284 @tab associative array
12287 @item @code{Implementation_Exceptions}
12288 @tab associative array
12294 The following attributes are defined for packages @code{Builder},
12295 @code{Compiler}, @code{Binder},
12296 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
12297 (@pxref{^Switches^Switches^ and Project Files}).
12299 @multitable @columnfractions .4 .2 .2 .2
12300 @item Attribute Name @tab Category @tab Index @tab Value
12301 @item @code{^Default_Switches^Default_Switches^}
12302 @tab associative array
12305 @item @code{^Switches^Switches^}
12306 @tab associative array
12312 In addition, package @code{Compiler} has a single string attribute
12313 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
12314 string attribute @code{Global_Configuration_Pragmas}.
12317 Each simple attribute has a default value: the empty string (for string-valued
12318 attributes) and the empty list (for string list-valued attributes).
12320 An attribute declaration defines a new value for an attribute.
12322 Examples of simple attribute declarations:
12324 @smallexample @c projectfile
12325 for Object_Dir use "objects";
12326 for Source_Dirs use ("units", "test/drivers");
12330 The syntax of a @dfn{simple attribute declaration} is similar to that of an
12331 attribute definition clause in Ada.
12333 Attributes references may be appear in expressions.
12334 The general form for such a reference is @code{<entity>'<attribute>}:
12335 Associative array attributes are functions. Associative
12336 array attribute references must have an argument that is a string literal.
12340 @smallexample @c projectfile
12342 Naming'Dot_Replacement
12343 Imported_Project'Source_Dirs
12344 Imported_Project.Naming'Casing
12345 Builder'^Default_Switches^Default_Switches^("Ada")
12349 The prefix of an attribute may be:
12351 @item @code{project} for an attribute of the current project
12352 @item The name of an existing package of the current project
12353 @item The name of an imported project
12354 @item The name of a parent project that is extended by the current project
12355 @item An expanded name whose prefix is imported/parent project name,
12356 and whose selector is a package name
12361 @smallexample @c projectfile
12364 for Source_Dirs use project'Source_Dirs & "units";
12365 for Source_Dirs use project'Source_Dirs & "test/drivers"
12371 In the first attribute declaration, initially the attribute @code{Source_Dirs}
12372 has the default value: an empty string list. After this declaration,
12373 @code{Source_Dirs} is a string list of one element: @code{"units"}.
12374 After the second attribute declaration @code{Source_Dirs} is a string list of
12375 two elements: @code{"units"} and @code{"test/drivers"}.
12377 Note: this example is for illustration only. In practice,
12378 the project file would contain only one attribute declaration:
12380 @smallexample @c projectfile
12381 for Source_Dirs use ("units", "test/drivers");
12384 @node Associative Array Attributes
12385 @subsection Associative Array Attributes
12388 Some attributes are defined as @emph{associative arrays}. An associative
12389 array may be regarded as a function that takes a string as a parameter
12390 and delivers a string or string list value as its result.
12392 Here are some examples of single associative array attribute associations:
12394 @smallexample @c projectfile
12395 for Body ("main") use "Main.ada";
12396 for ^Switches^Switches^ ("main.ada")
12398 "^-gnatv^-gnatv^");
12399 for ^Switches^Switches^ ("main.ada")
12400 use Builder'^Switches^Switches^ ("main.ada")
12405 Like untyped variables and simple attributes, associative array attributes
12406 may be declared several times. Each declaration supplies a new value for the
12407 attribute, and replaces the previous setting.
12410 An associative array attribute may be declared as a full associative array
12411 declaration, with the value of the same attribute in an imported or extended
12414 @smallexample @c projectfile
12416 for Default_Switches use Default.Builder'Default_Switches;
12421 In this example, @code{Default} must be either a project imported by the
12422 current project, or the project that the current project extends. If the
12423 attribute is in a package (in this case, in package @code{Builder}), the same
12424 package needs to be specified.
12427 A full associative array declaration replaces any other declaration for the
12428 attribute, including other full associative array declaration. Single
12429 associative array associations may be declare after a full associative
12430 declaration, modifying the value for a single association of the attribute.
12432 @node case Constructions
12433 @subsection @code{case} Constructions
12436 A @code{case} construction is used in a project file to effect conditional
12438 Here is a typical example:
12440 @smallexample @c projectfile
12443 type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
12445 OS : OS_Type := external ("OS", "GNU/Linux");
12449 package Compiler is
12451 when "GNU/Linux" | "Unix" =>
12452 for ^Default_Switches^Default_Switches^ ("Ada")
12453 use ("^-gnath^-gnath^");
12455 for ^Default_Switches^Default_Switches^ ("Ada")
12456 use ("^-gnatP^-gnatP^");
12465 The syntax of a @code{case} construction is based on the Ada case statement
12466 (although there is no @code{null} construction for empty alternatives).
12468 The case expression must be a typed string variable.
12469 Each alternative comprises the reserved word @code{when}, either a list of
12470 literal strings separated by the @code{"|"} character or the reserved word
12471 @code{others}, and the @code{"=>"} token.
12472 Each literal string must belong to the string type that is the type of the
12474 An @code{others} alternative, if present, must occur last.
12476 After each @code{=>}, there are zero or more constructions. The only
12477 constructions allowed in a case construction are other case constructions,
12478 attribute declarations and variable declarations. String type declarations and
12479 package declarations are not allowed. Variable declarations are restricted to
12480 variables that have already been declared before the case construction.
12482 The value of the case variable is often given by an external reference
12483 (@pxref{External References in Project Files}).
12485 @c ****************************************
12486 @c * Objects and Sources in Project Files *
12487 @c ****************************************
12489 @node Objects and Sources in Project Files
12490 @section Objects and Sources in Project Files
12493 * Object Directory::
12495 * Source Directories::
12496 * Source File Names::
12500 Each project has exactly one object directory and one or more source
12501 directories. The source directories must contain at least one source file,
12502 unless the project file explicitly specifies that no source files are present
12503 (@pxref{Source File Names}).
12505 @node Object Directory
12506 @subsection Object Directory
12509 The object directory for a project is the directory containing the compiler's
12510 output (such as @file{ALI} files and object files) for the project's immediate
12513 The object directory is given by the value of the attribute @code{Object_Dir}
12514 in the project file.
12516 @smallexample @c projectfile
12517 for Object_Dir use "objects";
12521 The attribute @var{Object_Dir} has a string value, the path name of the object
12522 directory. The path name may be absolute or relative to the directory of the
12523 project file. This directory must already exist, and be readable and writable.
12525 By default, when the attribute @code{Object_Dir} is not given an explicit value
12526 or when its value is the empty string, the object directory is the same as the
12527 directory containing the project file.
12529 @node Exec Directory
12530 @subsection Exec Directory
12533 The exec directory for a project is the directory containing the executables
12534 for the project's main subprograms.
12536 The exec directory is given by the value of the attribute @code{Exec_Dir}
12537 in the project file.
12539 @smallexample @c projectfile
12540 for Exec_Dir use "executables";
12544 The attribute @var{Exec_Dir} has a string value, the path name of the exec
12545 directory. The path name may be absolute or relative to the directory of the
12546 project file. This directory must already exist, and be writable.
12548 By default, when the attribute @code{Exec_Dir} is not given an explicit value
12549 or when its value is the empty string, the exec directory is the same as the
12550 object directory of the project file.
12552 @node Source Directories
12553 @subsection Source Directories
12556 The source directories of a project are specified by the project file
12557 attribute @code{Source_Dirs}.
12559 This attribute's value is a string list. If the attribute is not given an
12560 explicit value, then there is only one source directory, the one where the
12561 project file resides.
12563 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
12566 @smallexample @c projectfile
12567 for Source_Dirs use ();
12571 indicates that the project contains no source files.
12573 Otherwise, each string in the string list designates one or more
12574 source directories.
12576 @smallexample @c projectfile
12577 for Source_Dirs use ("sources", "test/drivers");
12581 If a string in the list ends with @code{"/**"}, then the directory whose path
12582 name precedes the two asterisks, as well as all its subdirectories
12583 (recursively), are source directories.
12585 @smallexample @c projectfile
12586 for Source_Dirs use ("/system/sources/**");
12590 Here the directory @code{/system/sources} and all of its subdirectories
12591 (recursively) are source directories.
12593 To specify that the source directories are the directory of the project file
12594 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
12595 @smallexample @c projectfile
12596 for Source_Dirs use ("./**");
12600 Each of the source directories must exist and be readable.
12602 @node Source File Names
12603 @subsection Source File Names
12606 In a project that contains source files, their names may be specified by the
12607 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
12608 (a string). Source file names never include any directory information.
12610 If the attribute @code{Source_Files} is given an explicit value, then each
12611 element of the list is a source file name.
12613 @smallexample @c projectfile
12614 for Source_Files use ("main.adb");
12615 for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
12619 If the attribute @code{Source_Files} is not given an explicit value,
12620 but the attribute @code{Source_List_File} is given a string value,
12621 then the source file names are contained in the text file whose path name
12622 (absolute or relative to the directory of the project file) is the
12623 value of the attribute @code{Source_List_File}.
12625 Each line in the file that is not empty or is not a comment
12626 contains a source file name.
12628 @smallexample @c projectfile
12629 for Source_List_File use "source_list.txt";
12633 By default, if neither the attribute @code{Source_Files} nor the attribute
12634 @code{Source_List_File} is given an explicit value, then each file in the
12635 source directories that conforms to the project's naming scheme
12636 (@pxref{Naming Schemes}) is an immediate source of the project.
12638 A warning is issued if both attributes @code{Source_Files} and
12639 @code{Source_List_File} are given explicit values. In this case, the attribute
12640 @code{Source_Files} prevails.
12642 Each source file name must be the name of one existing source file
12643 in one of the source directories.
12645 A @code{Source_Files} attribute whose value is an empty list
12646 indicates that there are no source files in the project.
12648 If the order of the source directories is known statically, that is if
12649 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
12650 be several files with the same source file name. In this case, only the file
12651 in the first directory is considered as an immediate source of the project
12652 file. If the order of the source directories is not known statically, it is
12653 an error to have several files with the same source file name.
12655 Projects can be specified to have no Ada source
12656 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
12657 list, or the @code{"Ada"} may be absent from @code{Languages}:
12659 @smallexample @c projectfile
12660 for Source_Dirs use ();
12661 for Source_Files use ();
12662 for Languages use ("C", "C++");
12666 Otherwise, a project must contain at least one immediate source.
12668 Projects with no source files are useful as template packages
12669 (@pxref{Packages in Project Files}) for other projects; in particular to
12670 define a package @code{Naming} (@pxref{Naming Schemes}).
12672 @c ****************************
12673 @c * Importing Projects *
12674 @c ****************************
12676 @node Importing Projects
12677 @section Importing Projects
12678 @cindex @code{ADA_PROJECT_PATH}
12681 An immediate source of a project P may depend on source files that
12682 are neither immediate sources of P nor in the predefined library.
12683 To get this effect, P must @emph{import} the projects that contain the needed
12686 @smallexample @c projectfile
12688 with "project1", "utilities.gpr";
12689 with "/namings/apex.gpr";
12696 As can be seen in this example, the syntax for importing projects is similar
12697 to the syntax for importing compilation units in Ada. However, project files
12698 use literal strings instead of names, and the @code{with} clause identifies
12699 project files rather than packages.
12701 Each literal string is the file name or path name (absolute or relative) of a
12702 project file. If a string corresponds to a file name, with no path or a
12703 relative path, then its location is determined by the @emph{project path}. The
12704 latter can be queried using @code{gnatls -v}. It contains:
12708 In first position, the directory containing the current project file.
12710 In last position, the default project directory. This default project directory
12711 is part of the GNAT installation and is the standard place to install project
12712 files giving access to standard support libraries.
12714 @ref{Installing a library}
12718 In between, all the directories referenced in the
12719 ^environment variable^logical name^ @env{ADA_PROJECT_PATH} if it exists.
12723 If a relative pathname is used, as in
12725 @smallexample @c projectfile
12730 then the full path for the project is constructed by concatenating this
12731 relative path to those in the project path, in order, until a matching file is
12732 found. Any symbolic link will be fully resolved in the directory of the
12733 importing project file before the imported project file is examined.
12735 If the @code{with}'ed project file name does not have an extension,
12736 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
12737 then the file name as specified in the @code{with} clause (no extension) will
12738 be used. In the above example, if a file @code{project1.gpr} is found, then it
12739 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
12740 then it will be used; if neither file exists, this is an error.
12742 A warning is issued if the name of the project file does not match the
12743 name of the project; this check is case insensitive.
12745 Any source file that is an immediate source of the imported project can be
12746 used by the immediate sources of the importing project, transitively. Thus
12747 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
12748 sources of @code{A} may depend on the immediate sources of @code{C}, even if
12749 @code{A} does not import @code{C} explicitly. However, this is not recommended,
12750 because if and when @code{B} ceases to import @code{C}, some sources in
12751 @code{A} will no longer compile.
12753 A side effect of this capability is that normally cyclic dependencies are not
12754 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
12755 is not allowed to import @code{A}. However, there are cases when cyclic
12756 dependencies would be beneficial. For these cases, another form of import
12757 between projects exists, the @code{limited with}: a project @code{A} that
12758 imports a project @code{B} with a straight @code{with} may also be imported,
12759 directly or indirectly, by @code{B} on the condition that imports from @code{B}
12760 to @code{A} include at least one @code{limited with}.
12762 @smallexample @c 0projectfile
12768 limited with "../a/a.gpr";
12776 limited with "../a/a.gpr";
12782 In the above legal example, there are two project cycles:
12785 @item A -> C -> D -> A
12789 In each of these cycle there is one @code{limited with}: import of @code{A}
12790 from @code{B} and import of @code{A} from @code{D}.
12792 The difference between straight @code{with} and @code{limited with} is that
12793 the name of a project imported with a @code{limited with} cannot be used in the
12794 project that imports it. In particular, its packages cannot be renamed and
12795 its variables cannot be referred to.
12797 An exception to the above rules for @code{limited with} is that for the main
12798 project specified to @command{gnatmake} or to the @command{GNAT} driver a
12799 @code{limited with} is equivalent to a straight @code{with}. For example,
12800 in the example above, projects @code{B} and @code{D} could not be main
12801 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
12802 each have a @code{limited with} that is the only one in a cycle of importing
12805 @c *********************
12806 @c * Project Extension *
12807 @c *********************
12809 @node Project Extension
12810 @section Project Extension
12813 During development of a large system, it is sometimes necessary to use
12814 modified versions of some of the source files, without changing the original
12815 sources. This can be achieved through the @emph{project extension} facility.
12817 @smallexample @c projectfile
12818 project Modified_Utilities extends "/baseline/utilities.gpr" is ...
12822 A project extension declaration introduces an extending project
12823 (the @emph{child}) and a project being extended (the @emph{parent}).
12825 By default, a child project inherits all the sources of its parent.
12826 However, inherited sources can be overridden: a unit in a parent is hidden
12827 by a unit of the same name in the child.
12829 Inherited sources are considered to be sources (but not immediate sources)
12830 of the child project; see @ref{Project File Syntax}.
12832 An inherited source file retains any switches specified in the parent project.
12834 For example if the project @code{Utilities} contains the specification and the
12835 body of an Ada package @code{Util_IO}, then the project
12836 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
12837 The original body of @code{Util_IO} will not be considered in program builds.
12838 However, the package specification will still be found in the project
12841 A child project can have only one parent but it may import any number of other
12844 A project is not allowed to import directly or indirectly at the same time a
12845 child project and any of its ancestors.
12847 @c *******************************
12848 @c * Project Hierarchy Extension *
12849 @c *******************************
12851 @node Project Hierarchy Extension
12852 @section Project Hierarchy Extension
12855 When extending a large system spanning multiple projects, it is often
12856 inconvenient to extend every project in the hierarchy that is impacted by a
12857 small change introduced. In such cases, it is possible to create a virtual
12858 extension of entire hierarchy using @code{extends all} relationship.
12860 When the project is extended using @code{extends all} inheritance, all projects
12861 that are imported by it, both directly and indirectly, are considered virtually
12862 extended. That is, the Project Manager creates "virtual projects"
12863 that extend every project in the hierarchy; all these virtual projects have
12864 no sources of their own and have as object directory the object directory of
12865 the root of "extending all" project.
12867 It is possible to explicitly extend one or more projects in the hierarchy
12868 in order to modify the sources. These extending projects must be imported by
12869 the "extending all" project, which will replace the corresponding virtual
12870 projects with the explicit ones.
12872 When building such a project hierarchy extension, the Project Manager will
12873 ensure that both modified sources and sources in virtual extending projects
12874 that depend on them, are recompiled.
12876 By means of example, consider the following hierarchy of projects.
12880 project A, containing package P1
12882 project B importing A and containing package P2 which depends on P1
12884 project C importing B and containing package P3 which depends on P2
12888 We want to modify packages P1 and P3.
12890 This project hierarchy will need to be extended as follows:
12894 Create project A1 that extends A, placing modified P1 there:
12896 @smallexample @c 0projectfile
12897 project A1 extends "(...)/A" is
12902 Create project C1 that "extends all" C and imports A1, placing modified
12905 @smallexample @c 0projectfile
12907 project C1 extends all "(...)/C" is
12912 When you build project C1, your entire modified project space will be
12913 recompiled, including the virtual project B1 that has been impacted by the
12914 "extending all" inheritance of project C.
12916 Note that if a Library Project in the hierarchy is virtually extended,
12917 the virtual project that extends the Library Project is not a Library Project.
12919 @c ****************************************
12920 @c * External References in Project Files *
12921 @c ****************************************
12923 @node External References in Project Files
12924 @section External References in Project Files
12927 A project file may contain references to external variables; such references
12928 are called @emph{external references}.
12930 An external variable is either defined as part of the environment (an
12931 environment variable in Unix, for example) or else specified on the command
12932 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
12933 If both, then the command line value is used.
12935 The value of an external reference is obtained by means of the built-in
12936 function @code{external}, which returns a string value.
12937 This function has two forms:
12939 @item @code{external (external_variable_name)}
12940 @item @code{external (external_variable_name, default_value)}
12944 Each parameter must be a string literal. For example:
12946 @smallexample @c projectfile
12948 external ("OS", "GNU/Linux")
12952 In the form with one parameter, the function returns the value of
12953 the external variable given as parameter. If this name is not present in the
12954 environment, the function returns an empty string.
12956 In the form with two string parameters, the second argument is
12957 the value returned when the variable given as the first argument is not
12958 present in the environment. In the example above, if @code{"OS"} is not
12959 the name of ^an environment variable^a logical name^ and is not passed on
12960 the command line, then the returned value is @code{"GNU/Linux"}.
12962 An external reference may be part of a string expression or of a string
12963 list expression, and can therefore appear in a variable declaration or
12964 an attribute declaration.
12966 @smallexample @c projectfile
12968 type Mode_Type is ("Debug", "Release");
12969 Mode : Mode_Type := external ("MODE");
12976 @c *****************************
12977 @c * Packages in Project Files *
12978 @c *****************************
12980 @node Packages in Project Files
12981 @section Packages in Project Files
12984 A @emph{package} defines the settings for project-aware tools within a
12986 For each such tool one can declare a package; the names for these
12987 packages are preset (@pxref{Packages}).
12988 A package may contain variable declarations, attribute declarations, and case
12991 @smallexample @c projectfile
12994 package Builder is -- used by gnatmake
12995 for ^Default_Switches^Default_Switches^ ("Ada")
13004 The syntax of package declarations mimics that of package in Ada.
13006 Most of the packages have an attribute
13007 @code{^Default_Switches^Default_Switches^}.
13008 This attribute is an associative array, and its value is a string list.
13009 The index of the associative array is the name of a programming language (case
13010 insensitive). This attribute indicates the ^switch^switch^
13011 or ^switches^switches^ to be used
13012 with the corresponding tool.
13014 Some packages also have another attribute, @code{^Switches^Switches^},
13015 an associative array whose value is a string list.
13016 The index is the name of a source file.
13017 This attribute indicates the ^switch^switch^
13018 or ^switches^switches^ to be used by the corresponding
13019 tool when dealing with this specific file.
13021 Further information on these ^switch^switch^-related attributes is found in
13022 @ref{^Switches^Switches^ and Project Files}.
13024 A package may be declared as a @emph{renaming} of another package; e.g., from
13025 the project file for an imported project.
13027 @smallexample @c projectfile
13029 with "/global/apex.gpr";
13031 package Naming renames Apex.Naming;
13038 Packages that are renamed in other project files often come from project files
13039 that have no sources: they are just used as templates. Any modification in the
13040 template will be reflected automatically in all the project files that rename
13041 a package from the template.
13043 In addition to the tool-oriented packages, you can also declare a package
13044 named @code{Naming} to establish specialized source file naming conventions
13045 (@pxref{Naming Schemes}).
13047 @c ************************************
13048 @c * Variables from Imported Projects *
13049 @c ************************************
13051 @node Variables from Imported Projects
13052 @section Variables from Imported Projects
13055 An attribute or variable defined in an imported or parent project can
13056 be used in expressions in the importing / extending project.
13057 Such an attribute or variable is denoted by an expanded name whose prefix
13058 is either the name of the project or the expanded name of a package within
13061 @smallexample @c projectfile
13064 project Main extends "base" is
13065 Var1 := Imported.Var;
13066 Var2 := Base.Var & ".new";
13071 for ^Default_Switches^Default_Switches^ ("Ada")
13072 use Imported.Builder'Ada_^Switches^Switches^ &
13073 "^-gnatg^-gnatg^" &
13079 package Compiler is
13080 for ^Default_Switches^Default_Switches^ ("Ada")
13081 use Base.Compiler'Ada_^Switches^Switches^;
13092 The value of @code{Var1} is a copy of the variable @code{Var} defined
13093 in the project file @file{"imported.gpr"}
13095 the value of @code{Var2} is a copy of the value of variable @code{Var}
13096 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
13098 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13099 @code{Builder} is a string list that includes in its value a copy of the value
13100 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
13101 in project file @file{imported.gpr} plus two new elements:
13102 @option{"^-gnatg^-gnatg^"}
13103 and @option{"^-v^-v^"};
13105 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13106 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
13107 defined in the @code{Compiler} package in project file @file{base.gpr},
13108 the project being extended.
13111 @c ******************
13112 @c * Naming Schemes *
13113 @c ******************
13115 @node Naming Schemes
13116 @section Naming Schemes
13119 Sometimes an Ada software system is ported from a foreign compilation
13120 environment to GNAT, and the file names do not use the default GNAT
13121 conventions. Instead of changing all the file names (which for a variety
13122 of reasons might not be possible), you can define the relevant file
13123 naming scheme in the @code{Naming} package in your project file.
13126 Note that the use of pragmas described in
13127 @ref{Alternative File Naming Schemes} by mean of a configuration
13128 pragmas file is not supported when using project files. You must use
13129 the features described in this paragraph. You can however use specify
13130 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
13133 For example, the following
13134 package models the Apex file naming rules:
13136 @smallexample @c projectfile
13139 for Casing use "lowercase";
13140 for Dot_Replacement use ".";
13141 for Spec_Suffix ("Ada") use ".1.ada";
13142 for Body_Suffix ("Ada") use ".2.ada";
13149 For example, the following package models the HP Ada file naming rules:
13151 @smallexample @c projectfile
13154 for Casing use "lowercase";
13155 for Dot_Replacement use "__";
13156 for Spec_Suffix ("Ada") use "_.^ada^ada^";
13157 for Body_Suffix ("Ada") use ".^ada^ada^";
13163 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
13164 names in lower case)
13168 You can define the following attributes in package @code{Naming}:
13173 This must be a string with one of the three values @code{"lowercase"},
13174 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
13177 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
13179 @item @var{Dot_Replacement}
13180 This must be a string whose value satisfies the following conditions:
13183 @item It must not be empty
13184 @item It cannot start or end with an alphanumeric character
13185 @item It cannot be a single underscore
13186 @item It cannot start with an underscore followed by an alphanumeric
13187 @item It cannot contain a dot @code{'.'} except if the entire string
13192 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
13194 @item @var{Spec_Suffix}
13195 This is an associative array (indexed by the programming language name, case
13196 insensitive) whose value is a string that must satisfy the following
13200 @item It must not be empty
13201 @item It must include at least one dot
13204 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
13205 @code{"^.ads^.ADS^"}.
13207 @item @var{Body_Suffix}
13208 This is an associative array (indexed by the programming language name, case
13209 insensitive) whose value is a string that must satisfy the following
13213 @item It must not be empty
13214 @item It must include at least one dot
13215 @item It cannot be the same as @code{Spec_Suffix ("Ada")}
13218 If @code{Body_Suffix ("Ada")} and @code{Spec_Suffix ("Ada")} end with the
13219 same string, then a file name that ends with the longest of these two suffixes
13220 will be a body if the longest suffix is @code{Body_Suffix ("Ada")} or a spec
13221 if the longest suffix is @code{Spec_Suffix ("Ada")}.
13223 If @code{Body_Suffix ("Ada")} is not specified, then the default is
13224 @code{"^.adb^.ADB^"}.
13226 @item @var{Separate_Suffix}
13227 This must be a string whose value satisfies the same conditions as
13228 @code{Body_Suffix}. The same "longest suffix" rules apply.
13231 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
13232 value as @code{Body_Suffix ("Ada")}.
13236 You can use the associative array attribute @code{Spec} to define
13237 the source file name for an individual Ada compilation unit's spec. The array
13238 index must be a string literal that identifies the Ada unit (case insensitive).
13239 The value of this attribute must be a string that identifies the file that
13240 contains this unit's spec (case sensitive or insensitive depending on the
13243 @smallexample @c projectfile
13244 for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
13249 You can use the associative array attribute @code{Body} to
13250 define the source file name for an individual Ada compilation unit's body
13251 (possibly a subunit). The array index must be a string literal that identifies
13252 the Ada unit (case insensitive). The value of this attribute must be a string
13253 that identifies the file that contains this unit's body or subunit (case
13254 sensitive or insensitive depending on the operating system).
13256 @smallexample @c projectfile
13257 for Body ("MyPack.MyChild") use "mypack.mychild.body";
13261 @c ********************
13262 @c * Library Projects *
13263 @c ********************
13265 @node Library Projects
13266 @section Library Projects
13269 @emph{Library projects} are projects whose object code is placed in a library.
13270 (Note that this facility is not yet supported on all platforms)
13272 To create a library project, you need to define in its project file
13273 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
13274 Additionally, you may define other library-related attributes such as
13275 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
13276 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
13278 The @code{Library_Name} attribute has a string value. There is no restriction
13279 on the name of a library. It is the responsibility of the developer to
13280 choose a name that will be accepted by the platform. It is recommended to
13281 choose names that could be Ada identifiers; such names are almost guaranteed
13282 to be acceptable on all platforms.
13284 The @code{Library_Dir} attribute has a string value that designates the path
13285 (absolute or relative) of the directory where the library will reside.
13286 It must designate an existing directory, and this directory must be writable,
13287 different from the project's object directory and from any source directory
13288 in the project tree.
13290 If both @code{Library_Name} and @code{Library_Dir} are specified and
13291 are legal, then the project file defines a library project. The optional
13292 library-related attributes are checked only for such project files.
13294 The @code{Library_Kind} attribute has a string value that must be one of the
13295 following (case insensitive): @code{"static"}, @code{"dynamic"} or
13296 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
13297 attribute is not specified, the library is a static library, that is
13298 an archive of object files that can be potentially linked into a
13299 static executable. Otherwise, the library may be dynamic or
13300 relocatable, that is a library that is loaded only at the start of execution.
13302 If you need to build both a static and a dynamic library, you should use two
13303 different object directories, since in some cases some extra code needs to
13304 be generated for the latter. For such cases, it is recommended to either use
13305 two different project files, or a single one which uses external variables
13306 to indicate what kind of library should be build.
13308 The @code{Library_ALI_Dir} attribute may be specified to indicate the
13309 directory where the ALI files of the library will be copied. When it is
13310 not specified, the ALI files are copied to the directory specified in
13311 attribute @code{Library_Dir}. The directory specified by @code{Library_ALI_Dir}
13312 must be writable and different from the project's object directory and from
13313 any source directory in the project tree.
13315 The @code{Library_Version} attribute has a string value whose interpretation
13316 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
13317 used only for dynamic/relocatable libraries as the internal name of the
13318 library (the @code{"soname"}). If the library file name (built from the
13319 @code{Library_Name}) is different from the @code{Library_Version}, then the
13320 library file will be a symbolic link to the actual file whose name will be
13321 @code{Library_Version}.
13325 @smallexample @c projectfile
13331 for Library_Dir use "lib_dir";
13332 for Library_Name use "dummy";
13333 for Library_Kind use "relocatable";
13334 for Library_Version use "libdummy.so." & Version;
13341 Directory @file{lib_dir} will contain the internal library file whose name
13342 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
13343 @file{libdummy.so.1}.
13345 When @command{gnatmake} detects that a project file
13346 is a library project file, it will check all immediate sources of the project
13347 and rebuild the library if any of the sources have been recompiled.
13349 Standard project files can import library project files. In such cases,
13350 the libraries will only be rebuilt if some of its sources are recompiled
13351 because they are in the closure of some other source in an importing project.
13352 Sources of the library project files that are not in such a closure will
13353 not be checked, unless the full library is checked, because one of its sources
13354 needs to be recompiled.
13356 For instance, assume the project file @code{A} imports the library project file
13357 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
13358 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
13359 @file{l2.ads}, @file{l2.adb}.
13361 If @file{l1.adb} has been modified, then the library associated with @code{L}
13362 will be rebuilt when compiling all the immediate sources of @code{A} only
13363 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
13366 To be sure that all the sources in the library associated with @code{L} are
13367 up to date, and that all the sources of project @code{A} are also up to date,
13368 the following two commands needs to be used:
13375 When a library is built or rebuilt, an attempt is made first to delete all
13376 files in the library directory.
13377 All @file{ALI} files will also be copied from the object directory to the
13378 library directory. To build executables, @command{gnatmake} will use the
13379 library rather than the individual object files.
13382 It is also possible to create library project files for third-party libraries
13383 that are precompiled and cannot be compiled locally thanks to the
13384 @code{externally_built} attribute. (See @ref{Installing a library}).
13387 @c *******************************
13388 @c * Stand-alone Library Projects *
13389 @c *******************************
13391 @node Stand-alone Library Projects
13392 @section Stand-alone Library Projects
13395 A Stand-alone Library is a library that contains the necessary code to
13396 elaborate the Ada units that are included in the library. A Stand-alone
13397 Library is suitable to be used in an executable when the main is not
13398 in Ada. However, Stand-alone Libraries may also be used with an Ada main
13401 A Stand-alone Library Project is a Library Project where the library is
13402 a Stand-alone Library.
13404 To be a Stand-alone Library Project, in addition to the two attributes
13405 that make a project a Library Project (@code{Library_Name} and
13406 @code{Library_Dir}, see @ref{Library Projects}), the attribute
13407 @code{Library_Interface} must be defined.
13409 @smallexample @c projectfile
13411 for Library_Dir use "lib_dir";
13412 for Library_Name use "dummy";
13413 for Library_Interface use ("int1", "int1.child");
13417 Attribute @code{Library_Interface} has a non empty string list value,
13418 each string in the list designating a unit contained in an immediate source
13419 of the project file.
13421 When a Stand-alone Library is built, first the binder is invoked to build
13422 a package whose name depends on the library name
13423 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
13424 This binder-generated package includes initialization and
13425 finalization procedures whose
13426 names depend on the library name (dummyinit and dummyfinal in the example
13427 above). The object corresponding to this package is included in the library.
13429 A dynamic or relocatable Stand-alone Library is automatically initialized
13430 if automatic initialization of Stand-alone Libraries is supported on the
13431 platform and if attribute @code{Library_Auto_Init} is not specified or
13432 is specified with the value "true". A static Stand-alone Library is never
13433 automatically initialized.
13435 Single string attribute @code{Library_Auto_Init} may be specified with only
13436 two possible values: "false" or "true" (case-insensitive). Specifying
13437 "false" for attribute @code{Library_Auto_Init} will prevent automatic
13438 initialization of dynamic or relocatable libraries.
13440 When a non automatically initialized Stand-alone Library is used
13441 in an executable, its initialization procedure must be called before
13442 any service of the library is used.
13443 When the main subprogram is in Ada, it may mean that the initialization
13444 procedure has to be called during elaboration of another package.
13446 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
13447 (those that are listed in attribute @code{Library_Interface}) are copied to
13448 the Library Directory. As a consequence, only the Interface Units may be
13449 imported from Ada units outside of the library. If other units are imported,
13450 the binding phase will fail.
13452 When a Stand-Alone Library is bound, the switches that are specified in
13453 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
13454 used in the call to @command{gnatbind}.
13456 The string list attribute @code{Library_Options} may be used to specified
13457 additional switches to the call to @command{gcc} to link the library.
13459 The attribute @code{Library_Src_Dir}, may be specified for a
13460 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
13461 single string value. Its value must be the path (absolute or relative to the
13462 project directory) of an existing directory. This directory cannot be the
13463 object directory or one of the source directories, but it can be the same as
13464 the library directory. The sources of the Interface
13465 Units of the library, necessary to an Ada client of the library, will be
13466 copied to the designated directory, called Interface Copy directory.
13467 These sources includes the specs of the Interface Units, but they may also
13468 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
13469 are used, or when there is a generic units in the spec. Before the sources
13470 are copied to the Interface Copy directory, an attempt is made to delete all
13471 files in the Interface Copy directory.
13473 @c *************************************
13474 @c * Switches Related to Project Files *
13475 @c *************************************
13476 @node Switches Related to Project Files
13477 @section Switches Related to Project Files
13480 The following switches are used by GNAT tools that support project files:
13484 @item ^-P^/PROJECT_FILE=^@var{project}
13485 @cindex @option{^-P^/PROJECT_FILE^} (any tool supporting project files)
13486 Indicates the name of a project file. This project file will be parsed with
13487 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
13488 if any, and using the external references indicated
13489 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
13491 There may zero, one or more spaces between @option{-P} and @var{project}.
13495 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
13498 Since the Project Manager parses the project file only after all the switches
13499 on the command line are checked, the order of the switches
13500 @option{^-P^/PROJECT_FILE^},
13501 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
13502 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
13504 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
13505 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any tool supporting project files)
13506 Indicates that external variable @var{name} has the value @var{value}.
13507 The Project Manager will use this value for occurrences of
13508 @code{external(name)} when parsing the project file.
13512 If @var{name} or @var{value} includes a space, then @var{name=value} should be
13513 put between quotes.
13521 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
13522 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
13523 @var{name}, only the last one is used.
13526 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
13527 takes precedence over the value of the same name in the environment.
13529 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
13530 @cindex @code{^-vP^/MESSAGES_PROJECT_FILE^} (any tool supporting project files)
13531 @c Previous line uses code vs option command, to stay less than 80 chars
13532 Indicates the verbosity of the parsing of GNAT project files.
13535 @option{-vP0} means Default;
13536 @option{-vP1} means Medium;
13537 @option{-vP2} means High.
13541 There are three possible options for this qualifier: DEFAULT, MEDIUM and
13546 The default is ^Default^DEFAULT^: no output for syntactically correct
13549 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
13550 only the last one is used.
13554 @c **********************************
13555 @c * Tools Supporting Project Files *
13556 @c **********************************
13558 @node Tools Supporting Project Files
13559 @section Tools Supporting Project Files
13562 * gnatmake and Project Files::
13563 * The GNAT Driver and Project Files::
13566 @node gnatmake and Project Files
13567 @subsection gnatmake and Project Files
13570 This section covers several topics related to @command{gnatmake} and
13571 project files: defining ^switches^switches^ for @command{gnatmake}
13572 and for the tools that it invokes; specifying configuration pragmas;
13573 the use of the @code{Main} attribute; building and rebuilding library project
13577 * ^Switches^Switches^ and Project Files::
13578 * Specifying Configuration Pragmas::
13579 * Project Files and Main Subprograms::
13580 * Library Project Files::
13583 @node ^Switches^Switches^ and Project Files
13584 @subsubsection ^Switches^Switches^ and Project Files
13587 It is not currently possible to specify VMS style qualifiers in the project
13588 files; only Unix style ^switches^switches^ may be specified.
13592 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
13593 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
13594 attribute, a @code{^Switches^Switches^} attribute, or both;
13595 as their names imply, these ^switch^switch^-related
13596 attributes affect the ^switches^switches^ that are used for each of these GNAT
13598 @command{gnatmake} is invoked. As will be explained below, these
13599 component-specific ^switches^switches^ precede
13600 the ^switches^switches^ provided on the @command{gnatmake} command line.
13602 The @code{^Default_Switches^Default_Switches^} attribute is an associative
13603 array indexed by language name (case insensitive) whose value is a string list.
13606 @smallexample @c projectfile
13608 package Compiler is
13609 for ^Default_Switches^Default_Switches^ ("Ada")
13610 use ("^-gnaty^-gnaty^",
13617 The @code{^Switches^Switches^} attribute is also an associative array,
13618 indexed by a file name (which may or may not be case sensitive, depending
13619 on the operating system) whose value is a string list. For example:
13621 @smallexample @c projectfile
13624 for ^Switches^Switches^ ("main1.adb")
13626 for ^Switches^Switches^ ("main2.adb")
13633 For the @code{Builder} package, the file names must designate source files
13634 for main subprograms. For the @code{Binder} and @code{Linker} packages, the
13635 file names must designate @file{ALI} or source files for main subprograms.
13636 In each case just the file name without an explicit extension is acceptable.
13638 For each tool used in a program build (@command{gnatmake}, the compiler, the
13639 binder, and the linker), the corresponding package @dfn{contributes} a set of
13640 ^switches^switches^ for each file on which the tool is invoked, based on the
13641 ^switch^switch^-related attributes defined in the package.
13642 In particular, the ^switches^switches^
13643 that each of these packages contributes for a given file @var{f} comprise:
13647 the value of attribute @code{^Switches^Switches^ (@var{f})},
13648 if it is specified in the package for the given file,
13650 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
13651 if it is specified in the package.
13655 If neither of these attributes is defined in the package, then the package does
13656 not contribute any ^switches^switches^ for the given file.
13658 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
13659 two sets, in the following order: those contributed for the file
13660 by the @code{Builder} package;
13661 and the switches passed on the command line.
13663 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
13664 the ^switches^switches^ passed to the tool comprise three sets,
13665 in the following order:
13669 the applicable ^switches^switches^ contributed for the file
13670 by the @code{Builder} package in the project file supplied on the command line;
13673 those contributed for the file by the package (in the relevant project file --
13674 see below) corresponding to the tool; and
13677 the applicable switches passed on the command line.
13681 The term @emph{applicable ^switches^switches^} reflects the fact that
13682 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
13683 tools, depending on the individual ^switch^switch^.
13685 @command{gnatmake} may invoke the compiler on source files from different
13686 projects. The Project Manager will use the appropriate project file to
13687 determine the @code{Compiler} package for each source file being compiled.
13688 Likewise for the @code{Binder} and @code{Linker} packages.
13690 As an example, consider the following package in a project file:
13692 @smallexample @c projectfile
13695 package Compiler is
13696 for ^Default_Switches^Default_Switches^ ("Ada")
13698 for ^Switches^Switches^ ("a.adb")
13700 for ^Switches^Switches^ ("b.adb")
13702 "^-gnaty^-gnaty^");
13709 If @command{gnatmake} is invoked with this project file, and it needs to
13710 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
13711 @file{a.adb} will be compiled with the ^switch^switch^
13712 @option{^-O1^-O1^},
13713 @file{b.adb} with ^switches^switches^
13715 and @option{^-gnaty^-gnaty^},
13716 and @file{c.adb} with @option{^-g^-g^}.
13718 The following example illustrates the ordering of the ^switches^switches^
13719 contributed by different packages:
13721 @smallexample @c projectfile
13725 for ^Switches^Switches^ ("main.adb")
13733 package Compiler is
13734 for ^Switches^Switches^ ("main.adb")
13742 If you issue the command:
13745 gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
13749 then the compiler will be invoked on @file{main.adb} with the following
13750 sequence of ^switches^switches^
13753 ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
13756 with the last @option{^-O^-O^}
13757 ^switch^switch^ having precedence over the earlier ones;
13758 several other ^switches^switches^
13759 (such as @option{^-c^-c^}) are added implicitly.
13761 The ^switches^switches^
13763 and @option{^-O1^-O1^} are contributed by package
13764 @code{Builder}, @option{^-O2^-O2^} is contributed
13765 by the package @code{Compiler}
13766 and @option{^-O0^-O0^} comes from the command line.
13768 The @option{^-g^-g^}
13769 ^switch^switch^ will also be passed in the invocation of
13770 @command{Gnatlink.}
13772 A final example illustrates switch contributions from packages in different
13775 @smallexample @c projectfile
13778 for Source_Files use ("pack.ads", "pack.adb");
13779 package Compiler is
13780 for ^Default_Switches^Default_Switches^ ("Ada")
13781 use ("^-gnata^-gnata^");
13789 for Source_Files use ("foo_main.adb", "bar_main.adb");
13791 for ^Switches^Switches^ ("foo_main.adb")
13799 -- Ada source file:
13801 procedure Foo_Main is
13809 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
13813 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
13814 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
13815 @option{^-gnato^-gnato^} (passed on the command line).
13816 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
13817 are @option{^-g^-g^} from @code{Proj4.Builder},
13818 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
13819 and @option{^-gnato^-gnato^} from the command line.
13822 When using @command{gnatmake} with project files, some ^switches^switches^ or
13823 arguments may be expressed as relative paths. As the working directory where
13824 compilation occurs may change, these relative paths are converted to absolute
13825 paths. For the ^switches^switches^ found in a project file, the relative paths
13826 are relative to the project file directory, for the switches on the command
13827 line, they are relative to the directory where @command{gnatmake} is invoked.
13828 The ^switches^switches^ for which this occurs are:
13834 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
13836 ^-o^-o^, object files specified in package @code{Linker} or after
13837 -largs on the command line). The exception to this rule is the ^switch^switch^
13838 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
13840 @node Specifying Configuration Pragmas
13841 @subsubsection Specifying Configuration Pragmas
13843 When using @command{gnatmake} with project files, if there exists a file
13844 @file{gnat.adc} that contains configuration pragmas, this file will be
13847 Configuration pragmas can be defined by means of the following attributes in
13848 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
13849 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
13851 Both these attributes are single string attributes. Their values is the path
13852 name of a file containing configuration pragmas. If a path name is relative,
13853 then it is relative to the project directory of the project file where the
13854 attribute is defined.
13856 When compiling a source, the configuration pragmas used are, in order,
13857 those listed in the file designated by attribute
13858 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
13859 project file, if it is specified, and those listed in the file designated by
13860 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
13861 the project file of the source, if it exists.
13863 @node Project Files and Main Subprograms
13864 @subsubsection Project Files and Main Subprograms
13867 When using a project file, you can invoke @command{gnatmake}
13868 with one or several main subprograms, by specifying their source files on the
13872 gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
13876 Each of these needs to be a source file of the same project, except
13877 when the switch ^-u^/UNIQUE^ is used.
13880 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
13881 same project, one of the project in the tree rooted at the project specified
13882 on the command line. The package @code{Builder} of this common project, the
13883 "main project" is the one that is considered by @command{gnatmake}.
13886 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
13887 imported directly or indirectly by the project specified on the command line.
13888 Note that if such a source file is not part of the project specified on the
13889 command line, the ^switches^switches^ found in package @code{Builder} of the
13890 project specified on the command line, if any, that are transmitted
13891 to the compiler will still be used, not those found in the project file of
13895 When using a project file, you can also invoke @command{gnatmake} without
13896 explicitly specifying any main, and the effect depends on whether you have
13897 defined the @code{Main} attribute. This attribute has a string list value,
13898 where each element in the list is the name of a source file (the file
13899 extension is optional) that contains a unit that can be a main subprogram.
13901 If the @code{Main} attribute is defined in a project file as a non-empty
13902 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
13903 line, then invoking @command{gnatmake} with this project file but without any
13904 main on the command line is equivalent to invoking @command{gnatmake} with all
13905 the file names in the @code{Main} attribute on the command line.
13908 @smallexample @c projectfile
13911 for Main use ("main1", "main2", "main3");
13917 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
13919 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
13921 When the project attribute @code{Main} is not specified, or is specified
13922 as an empty string list, or when the switch @option{-u} is used on the command
13923 line, then invoking @command{gnatmake} with no main on the command line will
13924 result in all immediate sources of the project file being checked, and
13925 potentially recompiled. Depending on the presence of the switch @option{-u},
13926 sources from other project files on which the immediate sources of the main
13927 project file depend are also checked and potentially recompiled. In other
13928 words, the @option{-u} switch is applied to all of the immediate sources of the
13931 When no main is specified on the command line and attribute @code{Main} exists
13932 and includes several mains, or when several mains are specified on the
13933 command line, the default ^switches^switches^ in package @code{Builder} will
13934 be used for all mains, even if there are specific ^switches^switches^
13935 specified for one or several mains.
13937 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
13938 the specific ^switches^switches^ for each main, if they are specified.
13940 @node Library Project Files
13941 @subsubsection Library Project Files
13944 When @command{gnatmake} is invoked with a main project file that is a library
13945 project file, it is not allowed to specify one or more mains on the command
13949 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
13950 ^-l^/ACTION=LINK^ have special meanings.
13953 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
13954 to @command{gnatmake} that @command{gnatbind} should be invoked for the
13957 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13958 to @command{gnatmake} that the binder generated file should be compiled
13959 (in the case of a stand-alone library) and that the library should be built.
13963 @node The GNAT Driver and Project Files
13964 @subsection The GNAT Driver and Project Files
13967 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13968 can benefit from project files:
13969 @command{^gnatbind^gnatbind^},
13970 @command{^gnatcheck^gnatcheck^}),
13971 @command{^gnatclean^gnatclean^}),
13972 @command{^gnatelim^gnatelim^},
13973 @command{^gnatfind^gnatfind^},
13974 @command{^gnatlink^gnatlink^},
13975 @command{^gnatls^gnatls^},
13976 @command{^gnatmetric^gnatmetric^},
13977 @command{^gnatpp^gnatpp^},
13978 @command{^gnatstub^gnatstub^},
13979 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
13980 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13981 They must be invoked through the @command{gnat} driver.
13983 The @command{gnat} driver is a wrapper that accepts a number of commands and
13984 calls the corresponding tool. It was designed initially for VMS platforms (to
13985 convert VMS qualifiers to Unix-style switches), but it is now available on all
13988 On non-VMS platforms, the @command{gnat} driver accepts the following commands
13989 (case insensitive):
13993 BIND to invoke @command{^gnatbind^gnatbind^}
13995 CHOP to invoke @command{^gnatchop^gnatchop^}
13997 CLEAN to invoke @command{^gnatclean^gnatclean^}
13999 COMP or COMPILE to invoke the compiler
14001 ELIM to invoke @command{^gnatelim^gnatelim^}
14003 FIND to invoke @command{^gnatfind^gnatfind^}
14005 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
14007 LINK to invoke @command{^gnatlink^gnatlink^}
14009 LS or LIST to invoke @command{^gnatls^gnatls^}
14011 MAKE to invoke @command{^gnatmake^gnatmake^}
14013 NAME to invoke @command{^gnatname^gnatname^}
14015 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
14017 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
14019 METRIC to invoke @command{^gnatmetric^gnatmetric^}
14021 STUB to invoke @command{^gnatstub^gnatstub^}
14023 XREF to invoke @command{^gnatxref^gnatxref^}
14027 (note that the compiler is invoked using the command
14028 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
14031 On non VMS platforms, between @command{gnat} and the command, two
14032 special switches may be used:
14036 @command{-v} to display the invocation of the tool.
14038 @command{-dn} to prevent the @command{gnat} driver from removing
14039 the temporary files it has created. These temporary files are
14040 configuration files and temporary file list files.
14044 The command may be followed by switches and arguments for the invoked
14048 gnat bind -C main.ali
14054 Switches may also be put in text files, one switch per line, and the text
14055 files may be specified with their path name preceded by '@@'.
14058 gnat bind @@args.txt main.ali
14062 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
14063 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
14064 (@option{^-P^/PROJECT_FILE^},
14065 @option{^-X^/EXTERNAL_REFERENCE^} and
14066 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
14067 the switches of the invoking tool.
14070 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
14071 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
14072 the immediate sources of the specified project file.
14075 When GNAT METRIC is used with a project file, but with no source
14076 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
14077 with all the immediate sources of the specified project file and with
14078 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
14082 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
14083 a project file, no source is specified on the command line and
14084 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
14085 the underlying tool (^gnatpp^gnatpp^ or
14086 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
14087 not only for the immediate sources of the main project.
14089 (-U stands for Universal or Union of the project files of the project tree)
14093 For each of the following commands, there is optionally a corresponding
14094 package in the main project.
14098 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
14101 package @code{Check} for command CHECK (invoking
14102 @code{^gnatcheck^gnatcheck^})
14105 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
14108 package @code{Cross_Reference} for command XREF (invoking
14109 @code{^gnatxref^gnatxref^})
14112 package @code{Eliminate} for command ELIM (invoking
14113 @code{^gnatelim^gnatelim^})
14116 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
14119 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
14122 package @code{Gnatstub} for command STUB
14123 (invoking @code{^gnatstub^gnatstub^})
14126 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
14129 package @code{Metrics} for command METRIC
14130 (invoking @code{^gnatmetric^gnatmetric^})
14133 package @code{Pretty_Printer} for command PP or PRETTY
14134 (invoking @code{^gnatpp^gnatpp^})
14139 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
14140 a simple variable with a string list value. It contains ^switches^switches^
14141 for the invocation of @code{^gnatls^gnatls^}.
14143 @smallexample @c projectfile
14147 for ^Switches^Switches^
14156 All other packages have two attribute @code{^Switches^Switches^} and
14157 @code{^Default_Switches^Default_Switches^}.
14160 @code{^Switches^Switches^} is an associative array attribute, indexed by the
14161 source file name, that has a string list value: the ^switches^switches^ to be
14162 used when the tool corresponding to the package is invoked for the specific
14166 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
14167 indexed by the programming language that has a string list value.
14168 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
14169 ^switches^switches^ for the invocation of the tool corresponding
14170 to the package, except if a specific @code{^Switches^Switches^} attribute
14171 is specified for the source file.
14173 @smallexample @c projectfile
14177 for Source_Dirs use ("./**");
14180 for ^Switches^Switches^ use
14187 package Compiler is
14188 for ^Default_Switches^Default_Switches^ ("Ada")
14189 use ("^-gnatv^-gnatv^",
14190 "^-gnatwa^-gnatwa^");
14196 for ^Default_Switches^Default_Switches^ ("Ada")
14204 for ^Default_Switches^Default_Switches^ ("Ada")
14206 for ^Switches^Switches^ ("main.adb")
14215 for ^Default_Switches^Default_Switches^ ("Ada")
14222 package Cross_Reference is
14223 for ^Default_Switches^Default_Switches^ ("Ada")
14228 end Cross_Reference;
14234 With the above project file, commands such as
14237 ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
14238 ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
14239 ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
14240 ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
14241 ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
14245 will set up the environment properly and invoke the tool with the switches
14246 found in the package corresponding to the tool:
14247 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
14248 except @code{^Switches^Switches^ ("main.adb")}
14249 for @code{^gnatlink^gnatlink^}.
14250 It is also possible to invoke some of the tools,
14251 @code{^gnatcheck^gnatcheck^}),
14252 @code{^gnatmetric^gnatmetric^}),
14253 and @code{^gnatpp^gnatpp^})
14254 on a set of project units thanks to the combination of the switches
14255 @code{-P}, @code{-U} and possibly the main unit when one is interested
14256 in its closure. For instance,
14260 will compute the metrics for all the immediate units of project
14263 gnat metric -Pproj -U
14265 will compute the metrics for all the units of the closure of projects
14266 rooted at @code{proj}.
14268 gnat metric -Pproj -U main_unit
14270 will compute the metrics for the closure of units rooted at
14271 @code{main_unit}. This last possibility relies implicitly
14272 on @command{gnatbind}'s option @option{-R}.
14274 @c **********************
14275 @node An Extended Example
14276 @section An Extended Example
14279 Suppose that we have two programs, @var{prog1} and @var{prog2},
14280 whose sources are in corresponding directories. We would like
14281 to build them with a single @command{gnatmake} command, and we want to place
14282 their object files into @file{build} subdirectories of the source directories.
14283 Furthermore, we want to have to have two separate subdirectories
14284 in @file{build} -- @file{release} and @file{debug} -- which will contain
14285 the object files compiled with different set of compilation flags.
14287 In other words, we have the following structure:
14304 Here are the project files that we must place in a directory @file{main}
14305 to maintain this structure:
14309 @item We create a @code{Common} project with a package @code{Compiler} that
14310 specifies the compilation ^switches^switches^:
14315 @b{project} Common @b{is}
14317 @b{for} Source_Dirs @b{use} (); -- No source files
14321 @b{type} Build_Type @b{is} ("release", "debug");
14322 Build : Build_Type := External ("BUILD", "debug");
14325 @b{package} Compiler @b{is}
14326 @b{case} Build @b{is}
14327 @b{when} "release" =>
14328 @b{for} ^Default_Switches^Default_Switches^ ("Ada")
14329 @b{use} ("^-O2^-O2^");
14330 @b{when} "debug" =>
14331 @b{for} ^Default_Switches^Default_Switches^ ("Ada")
14332 @b{use} ("^-g^-g^");
14340 @item We create separate projects for the two programs:
14347 @b{project} Prog1 @b{is}
14349 @b{for} Source_Dirs @b{use} ("prog1");
14350 @b{for} Object_Dir @b{use} "prog1/build/" & Common.Build;
14352 @b{package} Compiler @b{renames} Common.Compiler;
14363 @b{project} Prog2 @b{is}
14365 @b{for} Source_Dirs @b{use} ("prog2");
14366 @b{for} Object_Dir @b{use} "prog2/build/" & Common.Build;
14368 @b{package} Compiler @b{renames} Common.Compiler;
14374 @item We create a wrapping project @code{Main}:
14383 @b{project} Main @b{is}
14385 @b{package} Compiler @b{renames} Common.Compiler;
14391 @item Finally we need to create a dummy procedure that @code{with}s (either
14392 explicitly or implicitly) all the sources of our two programs.
14397 Now we can build the programs using the command
14400 gnatmake ^-P^/PROJECT_FILE=^main dummy
14404 for the Debug mode, or
14408 gnatmake -Pmain -XBUILD=release
14414 GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
14419 for the Release mode.
14421 @c ********************************
14422 @c * Project File Complete Syntax *
14423 @c ********************************
14425 @node Project File Complete Syntax
14426 @section Project File Complete Syntax
14430 context_clause project_declaration
14436 @b{with} path_name @{ , path_name @} ;
14441 project_declaration ::=
14442 simple_project_declaration | project_extension
14444 simple_project_declaration ::=
14445 @b{project} <project_>simple_name @b{is}
14446 @{declarative_item@}
14447 @b{end} <project_>simple_name;
14449 project_extension ::=
14450 @b{project} <project_>simple_name @b{extends} path_name @b{is}
14451 @{declarative_item@}
14452 @b{end} <project_>simple_name;
14454 declarative_item ::=
14455 package_declaration |
14456 typed_string_declaration |
14457 other_declarative_item
14459 package_declaration ::=
14460 package_specification | package_renaming
14462 package_specification ::=
14463 @b{package} package_identifier @b{is}
14464 @{simple_declarative_item@}
14465 @b{end} package_identifier ;
14467 package_identifier ::=
14468 @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
14469 @code{Linker} | @code{Finder} | @code{Cross_Reference} |
14470 @code{^gnatls^gnatls^} | @code{IDE} | @code{Pretty_Printer}
14472 package_renaming ::==
14473 @b{package} package_identifier @b{renames}
14474 <project_>simple_name.package_identifier ;
14476 typed_string_declaration ::=
14477 @b{type} <typed_string_>_simple_name @b{is}
14478 ( string_literal @{, string_literal@} );
14480 other_declarative_item ::=
14481 attribute_declaration |
14482 typed_variable_declaration |
14483 variable_declaration |
14486 attribute_declaration ::=
14487 full_associative_array_declaration |
14488 @b{for} attribute_designator @b{use} expression ;
14490 full_associative_array_declaration ::=
14491 @b{for} <associative_array_attribute_>simple_name @b{use}
14492 <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
14494 attribute_designator ::=
14495 <simple_attribute_>simple_name |
14496 <associative_array_attribute_>simple_name ( string_literal )
14498 typed_variable_declaration ::=
14499 <typed_variable_>simple_name : <typed_string_>name := string_expression ;
14501 variable_declaration ::=
14502 <variable_>simple_name := expression;
14512 attribute_reference
14518 ( <string_>expression @{ , <string_>expression @} )
14521 @b{external} ( string_literal [, string_literal] )
14523 attribute_reference ::=
14524 attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
14526 attribute_prefix ::=
14528 <project_>simple_name | package_identifier |
14529 <project_>simple_name . package_identifier
14531 case_construction ::=
14532 @b{case} <typed_variable_>name @b{is}
14537 @b{when} discrete_choice_list =>
14538 @{case_construction | attribute_declaration@}
14540 discrete_choice_list ::=
14541 string_literal @{| string_literal@} |
14545 simple_name @{. simple_name@}
14548 identifier (same as Ada)
14552 @node The Cross-Referencing Tools gnatxref and gnatfind
14553 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
14558 The compiler generates cross-referencing information (unless
14559 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
14560 This information indicates where in the source each entity is declared and
14561 referenced. Note that entities in package Standard are not included, but
14562 entities in all other predefined units are included in the output.
14564 Before using any of these two tools, you need to compile successfully your
14565 application, so that GNAT gets a chance to generate the cross-referencing
14568 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
14569 information to provide the user with the capability to easily locate the
14570 declaration and references to an entity. These tools are quite similar,
14571 the difference being that @code{gnatfind} is intended for locating
14572 definitions and/or references to a specified entity or entities, whereas
14573 @code{gnatxref} is oriented to generating a full report of all
14576 To use these tools, you must not compile your application using the
14577 @option{-gnatx} switch on the @command{gnatmake} command line
14578 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
14579 information will not be generated.
14581 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
14582 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
14585 * gnatxref Switches::
14586 * gnatfind Switches::
14587 * Project Files for gnatxref and gnatfind::
14588 * Regular Expressions in gnatfind and gnatxref::
14589 * Examples of gnatxref Usage::
14590 * Examples of gnatfind Usage::
14593 @node gnatxref Switches
14594 @section @code{gnatxref} Switches
14597 The command invocation for @code{gnatxref} is:
14599 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
14606 @item sourcefile1, sourcefile2
14607 identifies the source files for which a report is to be generated. The
14608 ``with''ed units will be processed too. You must provide at least one file.
14610 These file names are considered to be regular expressions, so for instance
14611 specifying @file{source*.adb} is the same as giving every file in the current
14612 directory whose name starts with @file{source} and whose extension is
14615 You shouldn't specify any directory name, just base names. @command{gnatxref}
14616 and @command{gnatfind} will be able to locate these files by themselves using
14617 the source path. If you specify directories, no result is produced.
14622 The switches can be:
14626 @cindex @option{--version} @command{gnatxref}
14627 Display Copyright and version, then exit disregarding all other options.
14630 @cindex @option{--help} @command{gnatxref}
14631 If @option{--version} was not used, display usage, then exit disregarding
14634 @item ^-a^/ALL_FILES^
14635 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
14636 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
14637 the read-only files found in the library search path. Otherwise, these files
14638 will be ignored. This option can be used to protect Gnat sources or your own
14639 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
14640 much faster, and their output much smaller. Read-only here refers to access
14641 or permissions status in the file system for the current user.
14644 @cindex @option{-aIDIR} (@command{gnatxref})
14645 When looking for source files also look in directory DIR. The order in which
14646 source file search is undertaken is the same as for @command{gnatmake}.
14649 @cindex @option{-aODIR} (@command{gnatxref})
14650 When searching for library and object files, look in directory
14651 DIR. The order in which library files are searched is the same as for
14652 @command{gnatmake}.
14655 @cindex @option{-nostdinc} (@command{gnatxref})
14656 Do not look for sources in the system default directory.
14659 @cindex @option{-nostdlib} (@command{gnatxref})
14660 Do not look for library files in the system default directory.
14662 @item --RTS=@var{rts-path}
14663 @cindex @option{--RTS} (@command{gnatxref})
14664 Specifies the default location of the runtime library. Same meaning as the
14665 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14667 @item ^-d^/DERIVED_TYPES^
14668 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
14669 If this switch is set @code{gnatxref} will output the parent type
14670 reference for each matching derived types.
14672 @item ^-f^/FULL_PATHNAME^
14673 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
14674 If this switch is set, the output file names will be preceded by their
14675 directory (if the file was found in the search path). If this switch is
14676 not set, the directory will not be printed.
14678 @item ^-g^/IGNORE_LOCALS^
14679 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
14680 If this switch is set, information is output only for library-level
14681 entities, ignoring local entities. The use of this switch may accelerate
14682 @code{gnatfind} and @code{gnatxref}.
14685 @cindex @option{-IDIR} (@command{gnatxref})
14686 Equivalent to @samp{-aODIR -aIDIR}.
14689 @cindex @option{-pFILE} (@command{gnatxref})
14690 Specify a project file to use @xref{Project Files}.
14691 If you need to use the @file{.gpr}
14692 project files, you should use gnatxref through the GNAT driver
14693 (@command{gnat xref -Pproject}).
14695 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14696 project file in the current directory.
14698 If a project file is either specified or found by the tools, then the content
14699 of the source directory and object directory lines are added as if they
14700 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
14701 and @samp{^-aO^OBJECT_SEARCH^}.
14703 Output only unused symbols. This may be really useful if you give your
14704 main compilation unit on the command line, as @code{gnatxref} will then
14705 display every unused entity and 'with'ed package.
14709 Instead of producing the default output, @code{gnatxref} will generate a
14710 @file{tags} file that can be used by vi. For examples how to use this
14711 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
14712 to the standard output, thus you will have to redirect it to a file.
14718 All these switches may be in any order on the command line, and may even
14719 appear after the file names. They need not be separated by spaces, thus
14720 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14721 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14723 @node gnatfind Switches
14724 @section @code{gnatfind} Switches
14727 The command line for @code{gnatfind} is:
14730 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
14739 An entity will be output only if it matches the regular expression found
14740 in @samp{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
14742 Omitting the pattern is equivalent to specifying @samp{*}, which
14743 will match any entity. Note that if you do not provide a pattern, you
14744 have to provide both a sourcefile and a line.
14746 Entity names are given in Latin-1, with uppercase/lowercase equivalence
14747 for matching purposes. At the current time there is no support for
14748 8-bit codes other than Latin-1, or for wide characters in identifiers.
14751 @code{gnatfind} will look for references, bodies or declarations
14752 of symbols referenced in @file{sourcefile}, at line @samp{line}
14753 and column @samp{column}. See @ref{Examples of gnatfind Usage}
14754 for syntax examples.
14757 is a decimal integer identifying the line number containing
14758 the reference to the entity (or entities) to be located.
14761 is a decimal integer identifying the exact location on the
14762 line of the first character of the identifier for the
14763 entity reference. Columns are numbered from 1.
14765 @item file1 file2 ...
14766 The search will be restricted to these source files. If none are given, then
14767 the search will be done for every library file in the search path.
14768 These file must appear only after the pattern or sourcefile.
14770 These file names are considered to be regular expressions, so for instance
14771 specifying 'source*.adb' is the same as giving every file in the current
14772 directory whose name starts with 'source' and whose extension is 'adb'.
14774 The location of the spec of the entity will always be displayed, even if it
14775 isn't in one of file1, file2,... The occurrences of the entity in the
14776 separate units of the ones given on the command line will also be displayed.
14778 Note that if you specify at least one file in this part, @code{gnatfind} may
14779 sometimes not be able to find the body of the subprograms...
14784 At least one of 'sourcefile' or 'pattern' has to be present on
14787 The following switches are available:
14791 @cindex @option{--version} @command{gnatfind}
14792 Display Copyright and version, then exit disregarding all other options.
14795 @cindex @option{--help} @command{gnatfind}
14796 If @option{--version} was not used, display usage, then exit disregarding
14799 @item ^-a^/ALL_FILES^
14800 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
14801 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
14802 the read-only files found in the library search path. Otherwise, these files
14803 will be ignored. This option can be used to protect Gnat sources or your own
14804 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
14805 much faster, and their output much smaller. Read-only here refers to access
14806 or permission status in the file system for the current user.
14809 @cindex @option{-aIDIR} (@command{gnatfind})
14810 When looking for source files also look in directory DIR. The order in which
14811 source file search is undertaken is the same as for @command{gnatmake}.
14814 @cindex @option{-aODIR} (@command{gnatfind})
14815 When searching for library and object files, look in directory
14816 DIR. The order in which library files are searched is the same as for
14817 @command{gnatmake}.
14820 @cindex @option{-nostdinc} (@command{gnatfind})
14821 Do not look for sources in the system default directory.
14824 @cindex @option{-nostdlib} (@command{gnatfind})
14825 Do not look for library files in the system default directory.
14827 @item --RTS=@var{rts-path}
14828 @cindex @option{--RTS} (@command{gnatfind})
14829 Specifies the default location of the runtime library. Same meaning as the
14830 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14832 @item ^-d^/DERIVED_TYPE_INFORMATION^
14833 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
14834 If this switch is set, then @code{gnatfind} will output the parent type
14835 reference for each matching derived types.
14837 @item ^-e^/EXPRESSIONS^
14838 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
14839 By default, @code{gnatfind} accept the simple regular expression set for
14840 @samp{pattern}. If this switch is set, then the pattern will be
14841 considered as full Unix-style regular expression.
14843 @item ^-f^/FULL_PATHNAME^
14844 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
14845 If this switch is set, the output file names will be preceded by their
14846 directory (if the file was found in the search path). If this switch is
14847 not set, the directory will not be printed.
14849 @item ^-g^/IGNORE_LOCALS^
14850 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
14851 If this switch is set, information is output only for library-level
14852 entities, ignoring local entities. The use of this switch may accelerate
14853 @code{gnatfind} and @code{gnatxref}.
14856 @cindex @option{-IDIR} (@command{gnatfind})
14857 Equivalent to @samp{-aODIR -aIDIR}.
14860 @cindex @option{-pFILE} (@command{gnatfind})
14861 Specify a project file (@pxref{Project Files}) to use.
14862 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14863 project file in the current directory.
14865 If a project file is either specified or found by the tools, then the content
14866 of the source directory and object directory lines are added as if they
14867 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
14868 @samp{^-aO^/OBJECT_SEARCH^}.
14870 @item ^-r^/REFERENCES^
14871 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
14872 By default, @code{gnatfind} will output only the information about the
14873 declaration, body or type completion of the entities. If this switch is
14874 set, the @code{gnatfind} will locate every reference to the entities in
14875 the files specified on the command line (or in every file in the search
14876 path if no file is given on the command line).
14878 @item ^-s^/PRINT_LINES^
14879 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
14880 If this switch is set, then @code{gnatfind} will output the content
14881 of the Ada source file lines were the entity was found.
14883 @item ^-t^/TYPE_HIERARCHY^
14884 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
14885 If this switch is set, then @code{gnatfind} will output the type hierarchy for
14886 the specified type. It act like -d option but recursively from parent
14887 type to parent type. When this switch is set it is not possible to
14888 specify more than one file.
14893 All these switches may be in any order on the command line, and may even
14894 appear after the file names. They need not be separated by spaces, thus
14895 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14896 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14898 As stated previously, gnatfind will search in every directory in the
14899 search path. You can force it to look only in the current directory if
14900 you specify @code{*} at the end of the command line.
14902 @node Project Files for gnatxref and gnatfind
14903 @section Project Files for @command{gnatxref} and @command{gnatfind}
14906 Project files allow a programmer to specify how to compile its
14907 application, where to find sources, etc. These files are used
14909 primarily by GPS, but they can also be used
14912 @code{gnatxref} and @code{gnatfind}.
14914 A project file name must end with @file{.gpr}. If a single one is
14915 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
14916 extract the information from it. If multiple project files are found, none of
14917 them is read, and you have to use the @samp{-p} switch to specify the one
14920 The following lines can be included, even though most of them have default
14921 values which can be used in most cases.
14922 The lines can be entered in any order in the file.
14923 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
14924 each line. If you have multiple instances, only the last one is taken into
14929 [default: @code{"^./^[]^"}]
14930 specifies a directory where to look for source files. Multiple @code{src_dir}
14931 lines can be specified and they will be searched in the order they
14935 [default: @code{"^./^[]^"}]
14936 specifies a directory where to look for object and library files. Multiple
14937 @code{obj_dir} lines can be specified, and they will be searched in the order
14940 @item comp_opt=SWITCHES
14941 [default: @code{""}]
14942 creates a variable which can be referred to subsequently by using
14943 the @code{$@{comp_opt@}} notation. This is intended to store the default
14944 switches given to @command{gnatmake} and @command{gcc}.
14946 @item bind_opt=SWITCHES
14947 [default: @code{""}]
14948 creates a variable which can be referred to subsequently by using
14949 the @samp{$@{bind_opt@}} notation. This is intended to store the default
14950 switches given to @command{gnatbind}.
14952 @item link_opt=SWITCHES
14953 [default: @code{""}]
14954 creates a variable which can be referred to subsequently by using
14955 the @samp{$@{link_opt@}} notation. This is intended to store the default
14956 switches given to @command{gnatlink}.
14958 @item main=EXECUTABLE
14959 [default: @code{""}]
14960 specifies the name of the executable for the application. This variable can
14961 be referred to in the following lines by using the @samp{$@{main@}} notation.
14964 @item comp_cmd=COMMAND
14965 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
14968 @item comp_cmd=COMMAND
14969 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
14971 specifies the command used to compile a single file in the application.
14974 @item make_cmd=COMMAND
14975 [default: @code{"GNAT MAKE $@{main@}
14976 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
14977 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
14978 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
14981 @item make_cmd=COMMAND
14982 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
14983 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
14984 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
14986 specifies the command used to recompile the whole application.
14988 @item run_cmd=COMMAND
14989 [default: @code{"$@{main@}"}]
14990 specifies the command used to run the application.
14992 @item debug_cmd=COMMAND
14993 [default: @code{"gdb $@{main@}"}]
14994 specifies the command used to debug the application
14999 @command{gnatxref} and @command{gnatfind} only take into account the
15000 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
15002 @node Regular Expressions in gnatfind and gnatxref
15003 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
15006 As specified in the section about @command{gnatfind}, the pattern can be a
15007 regular expression. Actually, there are to set of regular expressions
15008 which are recognized by the program:
15011 @item globbing patterns
15012 These are the most usual regular expression. They are the same that you
15013 generally used in a Unix shell command line, or in a DOS session.
15015 Here is a more formal grammar:
15022 term ::= elmt -- matches elmt
15023 term ::= elmt elmt -- concatenation (elmt then elmt)
15024 term ::= * -- any string of 0 or more characters
15025 term ::= ? -- matches any character
15026 term ::= [char @{char@}] -- matches any character listed
15027 term ::= [char - char] -- matches any character in range
15031 @item full regular expression
15032 The second set of regular expressions is much more powerful. This is the
15033 type of regular expressions recognized by utilities such a @file{grep}.
15035 The following is the form of a regular expression, expressed in Ada
15036 reference manual style BNF is as follows
15043 regexp ::= term @{| term@} -- alternation (term or term ...)
15045 term ::= item @{item@} -- concatenation (item then item)
15047 item ::= elmt -- match elmt
15048 item ::= elmt * -- zero or more elmt's
15049 item ::= elmt + -- one or more elmt's
15050 item ::= elmt ? -- matches elmt or nothing
15053 elmt ::= nschar -- matches given character
15054 elmt ::= [nschar @{nschar@}] -- matches any character listed
15055 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
15056 elmt ::= [char - char] -- matches chars in given range
15057 elmt ::= \ char -- matches given character
15058 elmt ::= . -- matches any single character
15059 elmt ::= ( regexp ) -- parens used for grouping
15061 char ::= any character, including special characters
15062 nschar ::= any character except ()[].*+?^^^
15066 Following are a few examples:
15070 will match any of the two strings 'abcde' and 'fghi'.
15073 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
15076 will match any string which has only lowercase characters in it (and at
15077 least one character.
15082 @node Examples of gnatxref Usage
15083 @section Examples of @code{gnatxref} Usage
15085 @subsection General Usage
15088 For the following examples, we will consider the following units:
15090 @smallexample @c ada
15096 3: procedure Foo (B : in Integer);
15103 1: package body Main is
15104 2: procedure Foo (B : in Integer) is
15115 2: procedure Print (B : Integer);
15124 The first thing to do is to recompile your application (for instance, in
15125 that case just by doing a @samp{gnatmake main}, so that GNAT generates
15126 the cross-referencing information.
15127 You can then issue any of the following commands:
15129 @item gnatxref main.adb
15130 @code{gnatxref} generates cross-reference information for main.adb
15131 and every unit 'with'ed by main.adb.
15133 The output would be:
15141 Decl: main.ads 3:20
15142 Body: main.adb 2:20
15143 Ref: main.adb 4:13 5:13 6:19
15146 Ref: main.adb 6:8 7:8
15156 Decl: main.ads 3:15
15157 Body: main.adb 2:15
15160 Body: main.adb 1:14
15163 Ref: main.adb 6:12 7:12
15167 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
15168 its body is in main.adb, line 1, column 14 and is not referenced any where.
15170 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
15171 it referenced in main.adb, line 6 column 12 and line 7 column 12.
15173 @item gnatxref package1.adb package2.ads
15174 @code{gnatxref} will generates cross-reference information for
15175 package1.adb, package2.ads and any other package 'with'ed by any
15181 @subsection Using gnatxref with vi
15183 @code{gnatxref} can generate a tags file output, which can be used
15184 directly from @command{vi}. Note that the standard version of @command{vi}
15185 will not work properly with overloaded symbols. Consider using another
15186 free implementation of @command{vi}, such as @command{vim}.
15189 $ gnatxref -v gnatfind.adb > tags
15193 will generate the tags file for @code{gnatfind} itself (if the sources
15194 are in the search path!).
15196 From @command{vi}, you can then use the command @samp{:tag @i{entity}}
15197 (replacing @i{entity} by whatever you are looking for), and vi will
15198 display a new file with the corresponding declaration of entity.
15201 @node Examples of gnatfind Usage
15202 @section Examples of @code{gnatfind} Usage
15206 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
15207 Find declarations for all entities xyz referenced at least once in
15208 main.adb. The references are search in every library file in the search
15211 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
15214 The output will look like:
15216 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15217 ^directory/^[directory]^main.adb:24:10: xyz <= body
15218 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15222 that is to say, one of the entities xyz found in main.adb is declared at
15223 line 12 of main.ads (and its body is in main.adb), and another one is
15224 declared at line 45 of foo.ads
15226 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
15227 This is the same command as the previous one, instead @code{gnatfind} will
15228 display the content of the Ada source file lines.
15230 The output will look like:
15233 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15235 ^directory/^[directory]^main.adb:24:10: xyz <= body
15237 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15242 This can make it easier to find exactly the location your are looking
15245 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
15246 Find references to all entities containing an x that are
15247 referenced on line 123 of main.ads.
15248 The references will be searched only in main.ads and foo.adb.
15250 @item gnatfind main.ads:123
15251 Find declarations and bodies for all entities that are referenced on
15252 line 123 of main.ads.
15254 This is the same as @code{gnatfind "*":main.adb:123}.
15256 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
15257 Find the declaration for the entity referenced at column 45 in
15258 line 123 of file main.adb in directory mydir. Note that it
15259 is usual to omit the identifier name when the column is given,
15260 since the column position identifies a unique reference.
15262 The column has to be the beginning of the identifier, and should not
15263 point to any character in the middle of the identifier.
15267 @c *********************************
15268 @node The GNAT Pretty-Printer gnatpp
15269 @chapter The GNAT Pretty-Printer @command{gnatpp}
15271 @cindex Pretty-Printer
15274 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
15275 for source reformatting / pretty-printing.
15276 It takes an Ada source file as input and generates a reformatted
15278 You can specify various style directives via switches; e.g.,
15279 identifier case conventions, rules of indentation, and comment layout.
15281 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
15282 tree for the input source and thus requires the input to be syntactically and
15283 semantically legal.
15284 If this condition is not met, @command{gnatpp} will terminate with an
15285 error message; no output file will be generated.
15287 If the source files presented to @command{gnatpp} contain
15288 preprocessing directives, then the output file will
15289 correspond to the generated source after all
15290 preprocessing is carried out. There is no way
15291 using @command{gnatpp} to obtain pretty printed files that
15292 include the preprocessing directives.
15294 If the compilation unit
15295 contained in the input source depends semantically upon units located
15296 outside the current directory, you have to provide the source search path
15297 when invoking @command{gnatpp}, if these units are contained in files with
15298 names that do not follow the GNAT file naming rules, you have to provide
15299 the configuration file describing the corresponding naming scheme;
15300 see the description of the @command{gnatpp}
15301 switches below. Another possibility is to use a project file and to
15302 call @command{gnatpp} through the @command{gnat} driver
15304 The @command{gnatpp} command has the form
15307 $ gnatpp [@var{switches}] @var{filename}
15314 @var{switches} is an optional sequence of switches defining such properties as
15315 the formatting rules, the source search path, and the destination for the
15319 @var{filename} is the name (including the extension) of the source file to
15320 reformat; ``wildcards'' or several file names on the same gnatpp command are
15321 allowed. The file name may contain path information; it does not have to
15322 follow the GNAT file naming rules
15326 * Switches for gnatpp::
15327 * Formatting Rules::
15330 @node Switches for gnatpp
15331 @section Switches for @command{gnatpp}
15334 The following subsections describe the various switches accepted by
15335 @command{gnatpp}, organized by category.
15338 You specify a switch by supplying a name and generally also a value.
15339 In many cases the values for a switch with a given name are incompatible with
15341 (for example the switch that controls the casing of a reserved word may have
15342 exactly one value: upper case, lower case, or
15343 mixed case) and thus exactly one such switch can be in effect for an
15344 invocation of @command{gnatpp}.
15345 If more than one is supplied, the last one is used.
15346 However, some values for the same switch are mutually compatible.
15347 You may supply several such switches to @command{gnatpp}, but then
15348 each must be specified in full, with both the name and the value.
15349 Abbreviated forms (the name appearing once, followed by each value) are
15351 For example, to set
15352 the alignment of the assignment delimiter both in declarations and in
15353 assignment statements, you must write @option{-A2A3}
15354 (or @option{-A2 -A3}), but not @option{-A23}.
15358 In many cases the set of options for a given qualifier are incompatible with
15359 each other (for example the qualifier that controls the casing of a reserved
15360 word may have exactly one option, which specifies either upper case, lower
15361 case, or mixed case), and thus exactly one such option can be in effect for
15362 an invocation of @command{gnatpp}.
15363 If more than one is supplied, the last one is used.
15364 However, some qualifiers have options that are mutually compatible,
15365 and then you may then supply several such options when invoking
15369 In most cases, it is obvious whether or not the
15370 ^values for a switch with a given name^options for a given qualifier^
15371 are compatible with each other.
15372 When the semantics might not be evident, the summaries below explicitly
15373 indicate the effect.
15376 * Alignment Control::
15378 * Construct Layout Control::
15379 * General Text Layout Control::
15380 * Other Formatting Options::
15381 * Setting the Source Search Path::
15382 * Output File Control::
15383 * Other gnatpp Switches::
15386 @node Alignment Control
15387 @subsection Alignment Control
15388 @cindex Alignment control in @command{gnatpp}
15391 Programs can be easier to read if certain constructs are vertically aligned.
15392 By default all alignments are set ON.
15393 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
15394 OFF, and then use one or more of the other
15395 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
15396 to activate alignment for specific constructs.
15399 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
15403 Set all alignments to ON
15406 @item ^-A0^/ALIGN=OFF^
15407 Set all alignments to OFF
15409 @item ^-A1^/ALIGN=COLONS^
15410 Align @code{:} in declarations
15412 @item ^-A2^/ALIGN=DECLARATIONS^
15413 Align @code{:=} in initializations in declarations
15415 @item ^-A3^/ALIGN=STATEMENTS^
15416 Align @code{:=} in assignment statements
15418 @item ^-A4^/ALIGN=ARROWS^
15419 Align @code{=>} in associations
15421 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
15422 Align @code{at} keywords in the component clauses in record
15423 representation clauses
15427 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
15430 @node Casing Control
15431 @subsection Casing Control
15432 @cindex Casing control in @command{gnatpp}
15435 @command{gnatpp} allows you to specify the casing for reserved words,
15436 pragma names, attribute designators and identifiers.
15437 For identifiers you may define a
15438 general rule for name casing but also override this rule
15439 via a set of dictionary files.
15441 Three types of casing are supported: lower case, upper case, and mixed case.
15442 Lower and upper case are self-explanatory (but since some letters in
15443 Latin1 and other GNAT-supported character sets
15444 exist only in lower-case form, an upper case conversion will have no
15446 ``Mixed case'' means that the first letter, and also each letter immediately
15447 following an underscore, are converted to their uppercase forms;
15448 all the other letters are converted to their lowercase forms.
15451 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
15452 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
15453 Attribute designators are lower case
15455 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
15456 Attribute designators are upper case
15458 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
15459 Attribute designators are mixed case (this is the default)
15461 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
15462 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
15463 Keywords (technically, these are known in Ada as @emph{reserved words}) are
15464 lower case (this is the default)
15466 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
15467 Keywords are upper case
15469 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
15470 @item ^-nD^/NAME_CASING=AS_DECLARED^
15471 Name casing for defining occurrences are as they appear in the source file
15472 (this is the default)
15474 @item ^-nU^/NAME_CASING=UPPER_CASE^
15475 Names are in upper case
15477 @item ^-nL^/NAME_CASING=LOWER_CASE^
15478 Names are in lower case
15480 @item ^-nM^/NAME_CASING=MIXED_CASE^
15481 Names are in mixed case
15483 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
15484 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
15485 Pragma names are lower case
15487 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
15488 Pragma names are upper case
15490 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
15491 Pragma names are mixed case (this is the default)
15493 @item ^-D@var{file}^/DICTIONARY=@var{file}^
15494 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
15495 Use @var{file} as a @emph{dictionary file} that defines
15496 the casing for a set of specified names,
15497 thereby overriding the effect on these names by
15498 any explicit or implicit
15499 ^-n^/NAME_CASING^ switch.
15500 To supply more than one dictionary file,
15501 use ^several @option{-D} switches^a list of files as options^.
15504 @option{gnatpp} implicitly uses a @emph{default dictionary file}
15505 to define the casing for the Ada predefined names and
15506 the names declared in the GNAT libraries.
15508 @item ^-D-^/SPECIFIC_CASING^
15509 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
15510 Do not use the default dictionary file;
15511 instead, use the casing
15512 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
15517 The structure of a dictionary file, and details on the conventions
15518 used in the default dictionary file, are defined in @ref{Name Casing}.
15520 The @option{^-D-^/SPECIFIC_CASING^} and
15521 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
15524 @node Construct Layout Control
15525 @subsection Construct Layout Control
15526 @cindex Layout control in @command{gnatpp}
15529 This group of @command{gnatpp} switches controls the layout of comments and
15530 complex syntactic constructs. See @ref{Formatting Comments} for details
15534 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
15535 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
15536 All the comments remain unchanged
15538 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
15539 GNAT-style comment line indentation (this is the default).
15541 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
15542 Reference-manual comment line indentation.
15544 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
15545 GNAT-style comment beginning
15547 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
15548 Reformat comment blocks
15550 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
15551 Keep unchanged special form comments
15553 Reformat comment blocks
15555 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
15556 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
15557 GNAT-style layout (this is the default)
15559 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
15562 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
15565 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
15567 All the VT characters are removed from the comment text. All the HT characters
15568 are expanded with the sequences of space characters to get to the next tab
15571 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
15572 @item ^--no-separate-is^/NO_SEPARATE_IS^
15573 Do not place the keyword @code{is} on a separate line in a subprogram body in
15574 case if the specification occupies more then one line.
15576 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
15577 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
15578 Place the keyword @code{loop} in FOR and WHILE loop statements and the
15579 keyword @code{then} in IF statements on a separate line.
15581 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
15582 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
15583 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
15584 keyword @code{then} in IF statements on a separate line. This option is
15585 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
15587 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
15588 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
15589 Start each USE clause in a context clause from a separate line.
15591 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
15592 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
15593 Use a separate line for a loop or block statement name, but do not use an extra
15594 indentation level for the statement itself.
15600 The @option{-c1} and @option{-c2} switches are incompatible.
15601 The @option{-c3} and @option{-c4} switches are compatible with each other and
15602 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
15603 the other comment formatting switches.
15605 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
15610 For the @option{/COMMENTS_LAYOUT} qualifier:
15613 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
15615 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
15616 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
15620 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
15621 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
15624 @node General Text Layout Control
15625 @subsection General Text Layout Control
15628 These switches allow control over line length and indentation.
15631 @item ^-M@i{nnn}^/LINE_LENGTH_MAX=@i{nnn}^
15632 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
15633 Maximum line length, @i{nnn} from 32 ..256, the default value is 79
15635 @item ^-i@i{nnn}^/INDENTATION_LEVEL=@i{nnn}^
15636 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
15637 Indentation level, @i{nnn} from 1 .. 9, the default value is 3
15639 @item ^-cl@i{nnn}^/CONTINUATION_INDENT=@i{nnn}^
15640 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
15641 Indentation level for continuation lines (relative to the line being
15642 continued), @i{nnn} from 1 .. 9.
15644 value is one less then the (normal) indentation level, unless the
15645 indentation is set to 1 (in which case the default value for continuation
15646 line indentation is also 1)
15649 @node Other Formatting Options
15650 @subsection Other Formatting Options
15653 These switches control the inclusion of missing end/exit labels, and
15654 the indentation level in @b{case} statements.
15657 @item ^-e^/NO_MISSED_LABELS^
15658 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
15659 Do not insert missing end/exit labels. An end label is the name of
15660 a construct that may optionally be repeated at the end of the
15661 construct's declaration;
15662 e.g., the names of packages, subprograms, and tasks.
15663 An exit label is the name of a loop that may appear as target
15664 of an exit statement within the loop.
15665 By default, @command{gnatpp} inserts these end/exit labels when
15666 they are absent from the original source. This option suppresses such
15667 insertion, so that the formatted source reflects the original.
15669 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
15670 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
15671 Insert a Form Feed character after a pragma Page.
15673 @item ^-T@i{nnn}^/MAX_INDENT=@i{nnn}^
15674 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
15675 Do not use an additional indentation level for @b{case} alternatives
15676 and variants if there are @i{nnn} or more (the default
15678 If @i{nnn} is 0, an additional indentation level is
15679 used for @b{case} alternatives and variants regardless of their number.
15682 @node Setting the Source Search Path
15683 @subsection Setting the Source Search Path
15686 To define the search path for the input source file, @command{gnatpp}
15687 uses the same switches as the GNAT compiler, with the same effects.
15690 @item ^-I^/SEARCH=^@var{dir}
15691 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
15692 The same as the corresponding gcc switch
15694 @item ^-I-^/NOCURRENT_DIRECTORY^
15695 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
15696 The same as the corresponding gcc switch
15698 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
15699 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
15700 The same as the corresponding gcc switch
15702 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
15703 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
15704 The same as the corresponding gcc switch
15708 @node Output File Control
15709 @subsection Output File Control
15712 By default the output is sent to the file whose name is obtained by appending
15713 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
15714 (if the file with this name already exists, it is unconditionally overwritten).
15715 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
15716 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
15718 The output may be redirected by the following switches:
15721 @item ^-pipe^/STANDARD_OUTPUT^
15722 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
15723 Send the output to @code{Standard_Output}
15725 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
15726 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
15727 Write the output into @var{output_file}.
15728 If @var{output_file} already exists, @command{gnatpp} terminates without
15729 reading or processing the input file.
15731 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
15732 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
15733 Write the output into @var{output_file}, overwriting the existing file
15734 (if one is present).
15736 @item ^-r^/REPLACE^
15737 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
15738 Replace the input source file with the reformatted output, and copy the
15739 original input source into the file whose name is obtained by appending the
15740 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
15741 If a file with this name already exists, @command{gnatpp} terminates without
15742 reading or processing the input file.
15744 @item ^-rf^/OVERRIDING_REPLACE^
15745 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
15746 Like @option{^-r^/REPLACE^} except that if the file with the specified name
15747 already exists, it is overwritten.
15749 @item ^-rnb^/NO_BACKUP^
15750 @cindex @option{^-rnb^/NO_BACKUP^} (@code{gnatpp})
15751 Replace the input source file with the reformatted output without
15752 creating any backup copy of the input source.
15754 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
15755 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
15756 Specifies the format of the reformatted output file. The @var{xxx}
15757 ^string specified with the switch^option^ may be either
15759 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
15760 @item ``@option{^crlf^CRLF^}''
15761 the same as @option{^crlf^CRLF^}
15762 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
15763 @item ``@option{^lf^LF^}''
15764 the same as @option{^unix^UNIX^}
15767 @item ^-W^/RESULT_ENCODING=^@var{e}
15768 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
15769 Specify the wide character encoding method used to write the code in the
15771 @var{e} is one of the following:
15779 Upper half encoding
15781 @item ^s^SHIFT_JIS^
15791 Brackets encoding (default value)
15797 Options @option{^-pipe^/STANDARD_OUTPUT^},
15798 @option{^-o^/OUTPUT^} and
15799 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
15800 contains only one file to reformat.
15802 @option{^--eol^/END_OF_LINE^}
15804 @option{^-W^/RESULT_ENCODING^}
15805 cannot be used together
15806 with @option{^-pipe^/STANDARD_OUTPUT^} option.
15808 @node Other gnatpp Switches
15809 @subsection Other @code{gnatpp} Switches
15812 The additional @command{gnatpp} switches are defined in this subsection.
15815 @item ^-files @var{filename}^/FILES=@var{output_file}^
15816 @cindex @option{^-files^/FILES^} (@code{gnatpp})
15817 Take the argument source files from the specified file. This file should be an
15818 ordinary textual file containing file names separated by spaces or
15819 line breaks. You can use this switch more then once in the same call to
15820 @command{gnatpp}. You also can combine this switch with explicit list of
15823 @item ^-v^/VERBOSE^
15824 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
15826 @command{gnatpp} generates version information and then
15827 a trace of the actions it takes to produce or obtain the ASIS tree.
15829 @item ^-w^/WARNINGS^
15830 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
15832 @command{gnatpp} generates a warning whenever it cannot provide
15833 a required layout in the result source.
15836 @node Formatting Rules
15837 @section Formatting Rules
15840 The following subsections show how @command{gnatpp} treats ``white space'',
15841 comments, program layout, and name casing.
15842 They provide the detailed descriptions of the switches shown above.
15845 * White Space and Empty Lines::
15846 * Formatting Comments::
15847 * Construct Layout::
15851 @node White Space and Empty Lines
15852 @subsection White Space and Empty Lines
15855 @command{gnatpp} does not have an option to control space characters.
15856 It will add or remove spaces according to the style illustrated by the
15857 examples in the @cite{Ada Reference Manual}.
15859 The only format effectors
15860 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
15861 that will appear in the output file are platform-specific line breaks,
15862 and also format effectors within (but not at the end of) comments.
15863 In particular, each horizontal tab character that is not inside
15864 a comment will be treated as a space and thus will appear in the
15865 output file as zero or more spaces depending on
15866 the reformatting of the line in which it appears.
15867 The only exception is a Form Feed character, which is inserted after a
15868 pragma @code{Page} when @option{-ff} is set.
15870 The output file will contain no lines with trailing ``white space'' (spaces,
15873 Empty lines in the original source are preserved
15874 only if they separate declarations or statements.
15875 In such contexts, a
15876 sequence of two or more empty lines is replaced by exactly one empty line.
15877 Note that a blank line will be removed if it separates two ``comment blocks''
15878 (a comment block is a sequence of whole-line comments).
15879 In order to preserve a visual separation between comment blocks, use an
15880 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
15881 Likewise, if for some reason you wish to have a sequence of empty lines,
15882 use a sequence of empty comments instead.
15884 @node Formatting Comments
15885 @subsection Formatting Comments
15888 Comments in Ada code are of two kinds:
15891 a @emph{whole-line comment}, which appears by itself (possibly preceded by
15892 ``white space'') on a line
15895 an @emph{end-of-line comment}, which follows some other Ada lexical element
15900 The indentation of a whole-line comment is that of either
15901 the preceding or following line in
15902 the formatted source, depending on switch settings as will be described below.
15904 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
15905 between the end of the preceding Ada lexical element and the beginning
15906 of the comment as appear in the original source,
15907 unless either the comment has to be split to
15908 satisfy the line length limitation, or else the next line contains a
15909 whole line comment that is considered a continuation of this end-of-line
15910 comment (because it starts at the same position).
15912 cases, the start of the end-of-line comment is moved right to the nearest
15913 multiple of the indentation level.
15914 This may result in a ``line overflow'' (the right-shifted comment extending
15915 beyond the maximum line length), in which case the comment is split as
15918 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
15919 (GNAT-style comment line indentation)
15920 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
15921 (reference-manual comment line indentation).
15922 With reference-manual style, a whole-line comment is indented as if it
15923 were a declaration or statement at the same place
15924 (i.e., according to the indentation of the preceding line(s)).
15925 With GNAT style, a whole-line comment that is immediately followed by an
15926 @b{if} or @b{case} statement alternative, a record variant, or the reserved
15927 word @b{begin}, is indented based on the construct that follows it.
15930 @smallexample @c ada
15942 Reference-manual indentation produces:
15944 @smallexample @c ada
15956 while GNAT-style indentation produces:
15958 @smallexample @c ada
15970 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
15971 (GNAT style comment beginning) has the following
15976 For each whole-line comment that does not end with two hyphens,
15977 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
15978 to ensure that there are at least two spaces between these hyphens and the
15979 first non-blank character of the comment.
15983 For an end-of-line comment, if in the original source the next line is a
15984 whole-line comment that starts at the same position
15985 as the end-of-line comment,
15986 then the whole-line comment (and all whole-line comments
15987 that follow it and that start at the same position)
15988 will start at this position in the output file.
15991 That is, if in the original source we have:
15993 @smallexample @c ada
15996 A := B + C; -- B must be in the range Low1..High1
15997 -- C must be in the range Low2..High2
15998 --B+C will be in the range Low1+Low2..High1+High2
16004 Then in the formatted source we get
16006 @smallexample @c ada
16009 A := B + C; -- B must be in the range Low1..High1
16010 -- C must be in the range Low2..High2
16011 -- B+C will be in the range Low1+Low2..High1+High2
16017 A comment that exceeds the line length limit will be split.
16019 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
16020 the line belongs to a reformattable block, splitting the line generates a
16021 @command{gnatpp} warning.
16022 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
16023 comments may be reformatted in typical
16024 word processor style (that is, moving words between lines and putting as
16025 many words in a line as possible).
16028 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
16029 that has a special format (that is, a character that is neither a letter nor digit
16030 not white space nor line break immediately following the leading @code{--} of
16031 the comment) should be without any change moved from the argument source
16032 into reformatted source. This switch allows to preserve comments that are used
16033 as a special marks in the code (e.g. SPARK annotation).
16035 @node Construct Layout
16036 @subsection Construct Layout
16039 In several cases the suggested layout in the Ada Reference Manual includes
16040 an extra level of indentation that many programmers prefer to avoid. The
16041 affected cases include:
16045 @item Record type declaration (RM 3.8)
16047 @item Record representation clause (RM 13.5.1)
16049 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
16051 @item Block statement in case if a block has a statement identifier (RM 5.6)
16055 In compact mode (when GNAT style layout or compact layout is set),
16056 the pretty printer uses one level of indentation instead
16057 of two. This is achieved in the record definition and record representation
16058 clause cases by putting the @code{record} keyword on the same line as the
16059 start of the declaration or representation clause, and in the block and loop
16060 case by putting the block or loop header on the same line as the statement
16064 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
16065 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
16066 layout on the one hand, and uncompact layout
16067 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
16068 can be illustrated by the following examples:
16072 @multitable @columnfractions .5 .5
16073 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
16076 @smallexample @c ada
16083 @smallexample @c ada
16092 @smallexample @c ada
16094 a at 0 range 0 .. 31;
16095 b at 4 range 0 .. 31;
16099 @smallexample @c ada
16102 a at 0 range 0 .. 31;
16103 b at 4 range 0 .. 31;
16108 @smallexample @c ada
16116 @smallexample @c ada
16126 @smallexample @c ada
16127 Clear : for J in 1 .. 10 loop
16132 @smallexample @c ada
16134 for J in 1 .. 10 loop
16145 GNAT style, compact layout Uncompact layout
16147 type q is record type q is
16148 a : integer; record
16149 b : integer; a : integer;
16150 end record; b : integer;
16153 for q use record for q use
16154 a at 0 range 0 .. 31; record
16155 b at 4 range 0 .. 31; a at 0 range 0 .. 31;
16156 end record; b at 4 range 0 .. 31;
16159 Block : declare Block :
16160 A : Integer := 3; declare
16161 begin A : Integer := 3;
16163 end Block; Proc (A, A);
16166 Clear : for J in 1 .. 10 loop Clear :
16167 A (J) := 0; for J in 1 .. 10 loop
16168 end loop Clear; A (J) := 0;
16175 A further difference between GNAT style layout and compact layout is that
16176 GNAT style layout inserts empty lines as separation for
16177 compound statements, return statements and bodies.
16179 Note that the layout specified by
16180 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
16181 for named block and loop statements overrides the layout defined by these
16182 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
16183 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
16184 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
16187 @subsection Name Casing
16190 @command{gnatpp} always converts the usage occurrence of a (simple) name to
16191 the same casing as the corresponding defining identifier.
16193 You control the casing for defining occurrences via the
16194 @option{^-n^/NAME_CASING^} switch.
16196 With @option{-nD} (``as declared'', which is the default),
16199 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
16201 defining occurrences appear exactly as in the source file
16202 where they are declared.
16203 The other ^values for this switch^options for this qualifier^ ---
16204 @option{^-nU^UPPER_CASE^},
16205 @option{^-nL^LOWER_CASE^},
16206 @option{^-nM^MIXED_CASE^} ---
16208 ^upper, lower, or mixed case, respectively^the corresponding casing^.
16209 If @command{gnatpp} changes the casing of a defining
16210 occurrence, it analogously changes the casing of all the
16211 usage occurrences of this name.
16213 If the defining occurrence of a name is not in the source compilation unit
16214 currently being processed by @command{gnatpp}, the casing of each reference to
16215 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
16216 switch (subject to the dictionary file mechanism described below).
16217 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
16219 casing for the defining occurrence of the name.
16221 Some names may need to be spelled with casing conventions that are not
16222 covered by the upper-, lower-, and mixed-case transformations.
16223 You can arrange correct casing by placing such names in a
16224 @emph{dictionary file},
16225 and then supplying a @option{^-D^/DICTIONARY^} switch.
16226 The casing of names from dictionary files overrides
16227 any @option{^-n^/NAME_CASING^} switch.
16229 To handle the casing of Ada predefined names and the names from GNAT libraries,
16230 @command{gnatpp} assumes a default dictionary file.
16231 The name of each predefined entity is spelled with the same casing as is used
16232 for the entity in the @cite{Ada Reference Manual}.
16233 The name of each entity in the GNAT libraries is spelled with the same casing
16234 as is used in the declaration of that entity.
16236 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
16237 default dictionary file.
16238 Instead, the casing for predefined and GNAT-defined names will be established
16239 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
16240 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
16241 will appear as just shown,
16242 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
16243 To ensure that even such names are rendered in uppercase,
16244 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
16245 (or else, less conveniently, place these names in upper case in a dictionary
16248 A dictionary file is
16249 a plain text file; each line in this file can be either a blank line
16250 (containing only space characters and ASCII.HT characters), an Ada comment
16251 line, or the specification of exactly one @emph{casing schema}.
16253 A casing schema is a string that has the following syntax:
16257 @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
16259 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
16264 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
16265 @var{identifier} lexical element and the @var{letter_or_digit} category.)
16267 The casing schema string can be followed by white space and/or an Ada-style
16268 comment; any amount of white space is allowed before the string.
16270 If a dictionary file is passed as
16272 the value of a @option{-D@var{file}} switch
16275 an option to the @option{/DICTIONARY} qualifier
16278 simple name and every identifier, @command{gnatpp} checks if the dictionary
16279 defines the casing for the name or for some of its parts (the term ``subword''
16280 is used below to denote the part of a name which is delimited by ``_'' or by
16281 the beginning or end of the word and which does not contain any ``_'' inside):
16285 if the whole name is in the dictionary, @command{gnatpp} uses for this name
16286 the casing defined by the dictionary; no subwords are checked for this word
16289 for every subword @command{gnatpp} checks if the dictionary contains the
16290 corresponding string of the form @code{*@var{simple_identifier}*},
16291 and if it does, the casing of this @var{simple_identifier} is used
16295 if the whole name does not contain any ``_'' inside, and if for this name
16296 the dictionary contains two entries - one of the form @var{identifier},
16297 and another - of the form *@var{simple_identifier}*, then the first one
16298 is applied to define the casing of this name
16301 if more than one dictionary file is passed as @command{gnatpp} switches, each
16302 dictionary adds new casing exceptions and overrides all the existing casing
16303 exceptions set by the previous dictionaries
16306 when @command{gnatpp} checks if the word or subword is in the dictionary,
16307 this check is not case sensitive
16311 For example, suppose we have the following source to reformat:
16313 @smallexample @c ada
16316 name1 : integer := 1;
16317 name4_name3_name2 : integer := 2;
16318 name2_name3_name4 : Boolean;
16321 name2_name3_name4 := name4_name3_name2 > name1;
16327 And suppose we have two dictionaries:
16344 If @command{gnatpp} is called with the following switches:
16348 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
16351 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
16356 then we will get the following name casing in the @command{gnatpp} output:
16358 @smallexample @c ada
16361 NAME1 : Integer := 1;
16362 Name4_NAME3_Name2 : Integer := 2;
16363 Name2_NAME3_Name4 : Boolean;
16366 Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
16371 @c *********************************
16372 @node The GNAT Metric Tool gnatmetric
16373 @chapter The GNAT Metric Tool @command{gnatmetric}
16375 @cindex Metric tool
16378 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
16379 for computing various program metrics.
16380 It takes an Ada source file as input and generates a file containing the
16381 metrics data as output. Various switches control which
16382 metrics are computed and output.
16384 @command{gnatmetric} generates and uses the ASIS
16385 tree for the input source and thus requires the input to be syntactically and
16386 semantically legal.
16387 If this condition is not met, @command{gnatmetric} will generate
16388 an error message; no metric information for this file will be
16389 computed and reported.
16391 If the compilation unit contained in the input source depends semantically
16392 upon units in files located outside the current directory, you have to provide
16393 the source search path when invoking @command{gnatmetric}.
16394 If it depends semantically upon units that are contained
16395 in files with names that do not follow the GNAT file naming rules, you have to
16396 provide the configuration file describing the corresponding naming scheme (see
16397 the description of the @command{gnatmetric} switches below.)
16398 Alternatively, you may use a project file and invoke @command{gnatmetric}
16399 through the @command{gnat} driver.
16401 The @command{gnatmetric} command has the form
16404 $ gnatmetric [@i{switches}] @{@i{filename}@} [@i{-cargs gcc_switches}]
16411 @i{switches} specify the metrics to compute and define the destination for
16415 Each @i{filename} is the name (including the extension) of a source
16416 file to process. ``Wildcards'' are allowed, and
16417 the file name may contain path information.
16418 If no @i{filename} is supplied, then the @i{switches} list must contain
16420 @option{-files} switch (@pxref{Other gnatmetric Switches}).
16421 Including both a @option{-files} switch and one or more
16422 @i{filename} arguments is permitted.
16425 @i{-cargs gcc_switches} is a list of switches for
16426 @command{gcc}. They will be passed on to all compiler invocations made by
16427 @command{gnatmetric} to generate the ASIS trees. Here you can provide
16428 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
16429 and use the @option{-gnatec} switch to set the configuration file.
16433 * Switches for gnatmetric::
16436 @node Switches for gnatmetric
16437 @section Switches for @command{gnatmetric}
16440 The following subsections describe the various switches accepted by
16441 @command{gnatmetric}, organized by category.
16444 * Output Files Control::
16445 * Disable Metrics For Local Units::
16446 * Specifying a set of metrics to compute::
16447 * Other gnatmetric Switches::
16448 * Generate project-wide metrics::
16451 @node Output Files Control
16452 @subsection Output File Control
16453 @cindex Output file control in @command{gnatmetric}
16456 @command{gnatmetric} has two output formats. It can generate a
16457 textual (human-readable) form, and also XML. By default only textual
16458 output is generated.
16460 When generating the output in textual form, @command{gnatmetric} creates
16461 for each Ada source file a corresponding text file
16462 containing the computed metrics, except for the case when the set of metrics
16463 specified by gnatmetric parameters consists only of metrics that are computed
16464 for the whole set of analyzed sources, but not for each Ada source.
16465 By default, this file is placed in the same directory as where the source
16466 file is located, and its name is obtained
16467 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
16470 All the output information generated in XML format is placed in a single
16471 file. By default this file is placed in the current directory and has the
16472 name ^@file{metrix.xml}^@file{METRIX$XML}^.
16474 Some of the computed metrics are summed over the units passed to
16475 @command{gnatmetric}; for example, the total number of lines of code.
16476 By default this information is sent to @file{stdout}, but a file
16477 can be specified with the @option{-og} switch.
16479 The following switches control the @command{gnatmetric} output:
16482 @cindex @option{^-x^/XML^} (@command{gnatmetric})
16484 Generate the XML output
16486 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
16487 @item ^-nt^/NO_TEXT^
16488 Do not generate the output in text form (implies @option{^-x^/XML^})
16490 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
16491 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
16492 Put textual files with detailed metrics into @var{output_dir}
16494 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
16495 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
16496 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
16497 in the name of the output file.
16499 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
16500 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
16501 Put global metrics into @var{file_name}
16503 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
16504 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
16505 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
16507 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
16508 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
16509 Use ``short'' source file names in the output. (The @command{gnatmetric}
16510 output includes the name(s) of the Ada source file(s) from which the metrics
16511 are computed. By default each name includes the absolute path. The
16512 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
16513 to exclude all directory information from the file names that are output.)
16517 @node Disable Metrics For Local Units
16518 @subsection Disable Metrics For Local Units
16519 @cindex Disable Metrics For Local Units in @command{gnatmetric}
16522 @command{gnatmetric} relies on the GNAT compilation model @minus{}
16524 unit per one source file. It computes line metrics for the whole source
16525 file, and it also computes syntax
16526 and complexity metrics for the file's outermost unit.
16528 By default, @command{gnatmetric} will also compute all metrics for certain
16529 kinds of locally declared program units:
16533 subprogram (and generic subprogram) bodies;
16536 package (and generic package) specifications and bodies;
16539 task object and type specifications and bodies;
16542 protected object and type specifications and bodies.
16546 These kinds of entities will be referred to as
16547 @emph{eligible local program units}, or simply @emph{eligible local units},
16548 @cindex Eligible local unit (for @command{gnatmetric})
16549 in the discussion below.
16551 Note that a subprogram declaration, generic instantiation,
16552 or renaming declaration only receives metrics
16553 computation when it appear as the outermost entity
16556 Suppression of metrics computation for eligible local units can be
16557 obtained via the following switch:
16560 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
16561 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
16562 Do not compute detailed metrics for eligible local program units
16566 @node Specifying a set of metrics to compute
16567 @subsection Specifying a set of metrics to compute
16570 By default all the metrics are computed and reported. The switches
16571 described in this subsection allow you to control, on an individual
16572 basis, whether metrics are computed and
16573 reported. If at least one positive metric
16574 switch is specified (that is, a switch that defines that a given
16575 metric or set of metrics is to be computed), then only
16576 explicitly specified metrics are reported.
16579 * Line Metrics Control::
16580 * Syntax Metrics Control::
16581 * Complexity Metrics Control::
16584 @node Line Metrics Control
16585 @subsubsection Line Metrics Control
16586 @cindex Line metrics control in @command{gnatmetric}
16589 For any (legal) source file, and for each of its
16590 eligible local program units, @command{gnatmetric} computes the following
16595 the total number of lines;
16598 the total number of code lines (i.e., non-blank lines that are not comments)
16601 the number of comment lines
16604 the number of code lines containing end-of-line comments;
16607 the comment percentage: the ratio between the number of lines that contain
16608 comments and the number of all non-blank lines, expressed as a percentage;
16611 the number of empty lines and lines containing only space characters and/or
16612 format effectors (blank lines)
16615 the average number of code lines in subprogram bodies, task bodies, entry
16616 bodies and statement sequences in package bodies (this metric is only computed
16617 across the whole set of the analyzed units)
16622 @command{gnatmetric} sums the values of the line metrics for all the
16623 files being processed and then generates the cumulative results. The tool
16624 also computes for all the files being processed the average number of code
16627 You can use the following switches to select the specific line metrics
16628 to be computed and reported.
16631 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
16634 @cindex @option{--no-lines@var{x}}
16637 @item ^--lines-all^/LINE_COUNT_METRICS=ALL_ON^
16638 Report all the line metrics
16640 @item ^--no-lines-all^/LINE_COUNT_METRICS=ALL_OFF^
16641 Do not report any of line metrics
16643 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES_ON^
16644 Report the number of all lines
16646 @item ^--no-lines^/LINE_COUNT_METRICS=ALL_LINES_OFF^
16647 Do not report the number of all lines
16649 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES_ON^
16650 Report the number of code lines
16652 @item ^--no-lines-code^/LINE_COUNT_METRICS=CODE_LINES_OFF^
16653 Do not report the number of code lines
16655 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES_ON^
16656 Report the number of comment lines
16658 @item ^--no-lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES_OFF^
16659 Do not report the number of comment lines
16661 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES_ON^
16662 Report the number of code lines containing
16663 end-of-line comments
16665 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES_OFF^
16666 Do not report the number of code lines containing
16667 end-of-line comments
16669 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE_ON^
16670 Report the comment percentage in the program text
16672 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE_OFF^
16673 Do not report the comment percentage in the program text
16675 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES_ON^
16676 Report the number of blank lines
16678 @item ^--no-lines-blank^/LINE_COUNT_METRICS=BLANK_LINES_OFF^
16679 Do not report the number of blank lines
16681 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES_ON^
16682 Report the average number of code lines in subprogram bodies, task bodies,
16683 entry bodies and statement sequences in package bodies. The metric is computed
16684 and reported for the whole set of processed Ada sources only.
16686 @item ^--no-lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES_OFF^
16687 Do not report the average number of code lines in subprogram bodies,
16688 task bodies, entry bodies and statement sequences in package bodies.
16692 @node Syntax Metrics Control
16693 @subsubsection Syntax Metrics Control
16694 @cindex Syntax metrics control in @command{gnatmetric}
16697 @command{gnatmetric} computes various syntactic metrics for the
16698 outermost unit and for each eligible local unit:
16701 @item LSLOC (``Logical Source Lines Of Code'')
16702 The total number of declarations and the total number of statements
16704 @item Maximal static nesting level of inner program units
16706 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
16707 package, a task unit, a protected unit, a
16708 protected entry, a generic unit, or an explicitly declared subprogram other
16709 than an enumeration literal.''
16711 @item Maximal nesting level of composite syntactic constructs
16712 This corresponds to the notion of the
16713 maximum nesting level in the GNAT built-in style checks
16714 (@pxref{Style Checking})
16718 For the outermost unit in the file, @command{gnatmetric} additionally computes
16719 the following metrics:
16722 @item Public subprograms
16723 This metric is computed for package specifications. It is the
16724 number of subprograms and generic subprograms declared in the visible
16725 part (including the visible part of nested packages, protected objects, and
16728 @item All subprograms
16729 This metric is computed for bodies and subunits. The
16730 metric is equal to a total number of subprogram bodies in the compilation
16732 Neither generic instantiations nor renamings-as-a-body nor body stubs
16733 are counted. Any subprogram body is counted, independently of its nesting
16734 level and enclosing constructs. Generic bodies and bodies of protected
16735 subprograms are counted in the same way as ``usual'' subprogram bodies.
16738 This metric is computed for package specifications and
16739 generic package declarations. It is the total number of types
16740 that can be referenced from outside this compilation unit, plus the
16741 number of types from all the visible parts of all the visible generic
16742 packages. Generic formal types are not counted. Only types, not subtypes,
16746 Along with the total number of public types, the following
16747 types are counted and reported separately:
16754 Root tagged types (abstract, non-abstract, private, non-private). Type
16755 extensions are @emph{not} counted
16758 Private types (including private extensions)
16769 This metric is computed for any compilation unit. It is equal to the total
16770 number of the declarations of different types given in the compilation unit.
16771 The private and the corresponding full type declaration are counted as one
16772 type declaration. Incomplete type declarations and generic formal types
16774 No distinction is made among different kinds of types (abstract,
16775 private etc.); the total number of types is computed and reported.
16780 By default, all the syntax metrics are computed and reported. You can use the
16781 following switches to select specific syntax metrics.
16785 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
16788 @cindex @option{--no-syntax@var{x}}
16791 @item ^--syntax-all^/SYNTAX_METRICS=ALL_ON^
16792 Report all the syntax metrics
16794 @item ^--no-syntax-all^/ALL_OFF^
16795 Do not report any of syntax metrics
16797 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS_ON^
16798 Report the total number of declarations
16800 @item ^--no-declarations^/SYNTAX_METRICS=DECLARATIONS_OFF^
16801 Do not report the total number of declarations
16803 @item ^--statements^/SYNTAX_METRICS=STATEMENTS_ON^
16804 Report the total number of statements
16806 @item ^--no-statements^/SYNTAX_METRICS=STATEMENTS_OFF^
16807 Do not report the total number of statements
16809 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS_ON^
16810 Report the number of public subprograms in a compilation unit
16812 @item ^--no-public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS_OFF^
16813 Do not report the number of public subprograms in a compilation unit
16815 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS_ON^
16816 Report the number of all the subprograms in a compilation unit
16818 @item ^--no-all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS_OFF^
16819 Do not report the number of all the subprograms in a compilation unit
16821 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES_ON^
16822 Report the number of public types in a compilation unit
16824 @item ^--no-public-types^/SYNTAX_METRICS=PUBLIC_TYPES_OFF^
16825 Do not report the number of public types in a compilation unit
16827 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES_ON^
16828 Report the number of all the types in a compilation unit
16830 @item ^--no-all-types^/SYNTAX_METRICS=ALL_TYPES_OFF^
16831 Do not report the number of all the types in a compilation unit
16833 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_ON^
16834 Report the maximal program unit nesting level
16836 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
16837 Do not report the maximal program unit nesting level
16839 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING_ON^
16840 Report the maximal construct nesting level
16842 @item ^--no-construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING_OFF^
16843 Do not report the maximal construct nesting level
16847 @node Complexity Metrics Control
16848 @subsubsection Complexity Metrics Control
16849 @cindex Complexity metrics control in @command{gnatmetric}
16852 For a program unit that is an executable body (a subprogram body (including
16853 generic bodies), task body, entry body or a package body containing
16854 its own statement sequence) @command{gnatmetric} computes the following
16855 complexity metrics:
16859 McCabe cyclomatic complexity;
16862 McCabe essential complexity;
16865 maximal loop nesting level
16870 The McCabe complexity metrics are defined
16871 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
16873 According to McCabe, both control statements and short-circuit control forms
16874 should be taken into account when computing cyclomatic complexity. For each
16875 body, we compute three metric values:
16879 the complexity introduced by control
16880 statements only, without taking into account short-circuit forms,
16883 the complexity introduced by short-circuit control forms only, and
16887 cyclomatic complexity, which is the sum of these two values.
16891 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
16892 the code in the exception handlers and in all the nested program units.
16894 By default, all the complexity metrics are computed and reported.
16895 For more fine-grained control you can use
16896 the following switches:
16899 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
16902 @cindex @option{--no-complexity@var{x}}
16905 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL_ON^
16906 Report all the complexity metrics
16908 @item ^--no-complexity-all^/COMPLEXITY_METRICS=ALL_OFF^
16909 Do not report any of complexity metrics
16911 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC_ON^
16912 Report the McCabe Cyclomatic Complexity
16914 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC_OFF^
16915 Do not report the McCabe Cyclomatic Complexity
16917 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL_ON^
16918 Report the Essential Complexity
16920 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL_OFF^
16921 Do not report the Essential Complexity
16923 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
16924 Report maximal loop nesting level
16926 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_OFF^
16927 Do not report maximal loop nesting level
16929 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY_ON^
16930 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
16931 task bodies, entry bodies and statement sequences in package bodies.
16932 The metric is computed and reported for whole set of processed Ada sources
16935 @item ^--no-complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY_OFF^
16936 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
16937 bodies, task bodies, entry bodies and statement sequences in package bodies
16939 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
16940 @item ^-ne^/NO_EXITS_AS_GOTOS^
16941 Do not consider @code{exit} statements as @code{goto}s when
16942 computing Essential Complexity
16946 @node Other gnatmetric Switches
16947 @subsection Other @code{gnatmetric} Switches
16950 Additional @command{gnatmetric} switches are as follows:
16953 @item ^-files @var{filename}^/FILES=@var{filename}^
16954 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
16955 Take the argument source files from the specified file. This file should be an
16956 ordinary text file containing file names separated by spaces or
16957 line breaks. You can use this switch more then once in the same call to
16958 @command{gnatmetric}. You also can combine this switch with
16959 an explicit list of files.
16961 @item ^-v^/VERBOSE^
16962 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
16964 @command{gnatmetric} generates version information and then
16965 a trace of sources being processed.
16967 @item ^-dv^/DEBUG_OUTPUT^
16968 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
16970 @command{gnatmetric} generates various messages useful to understand what
16971 happens during the metrics computation
16974 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
16978 @node Generate project-wide metrics
16979 @subsection Generate project-wide metrics
16981 In order to compute metrics on all units of a given project, you can use
16982 the @command{gnat} driver along with the @option{-P} option:
16988 If the project @code{proj} depends upon other projects, you can compute
16989 the metrics on the project closure using the @option{-U} option:
16991 gnat metric -Pproj -U
16995 Finally, if not all the units are relevant to a particular main
16996 program in the project closure, you can generate metrics for the set
16997 of units needed to create a given main program (unit closure) using
16998 the @option{-U} option followed by the name of the main unit:
17000 gnat metric -Pproj -U main
17004 @c ***********************************
17005 @node File Name Krunching Using gnatkr
17006 @chapter File Name Krunching Using @code{gnatkr}
17010 This chapter discusses the method used by the compiler to shorten
17011 the default file names chosen for Ada units so that they do not
17012 exceed the maximum length permitted. It also describes the
17013 @code{gnatkr} utility that can be used to determine the result of
17014 applying this shortening.
17018 * Krunching Method::
17019 * Examples of gnatkr Usage::
17023 @section About @code{gnatkr}
17026 The default file naming rule in GNAT
17027 is that the file name must be derived from
17028 the unit name. The exact default rule is as follows:
17031 Take the unit name and replace all dots by hyphens.
17033 If such a replacement occurs in the
17034 second character position of a name, and the first character is
17035 ^a, g, s, or i^A, G, S, or I^ then replace the dot by the character
17036 ^~ (tilde)^$ (dollar sign)^
17037 instead of a minus.
17039 The reason for this exception is to avoid clashes
17040 with the standard names for children of System, Ada, Interfaces,
17041 and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^
17044 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
17045 switch of the compiler activates a ``krunching''
17046 circuit that limits file names to nn characters (where nn is a decimal
17047 integer). For example, using OpenVMS,
17048 where the maximum file name length is
17049 39, the value of nn is usually set to 39, but if you want to generate
17050 a set of files that would be usable if ported to a system with some
17051 different maximum file length, then a different value can be specified.
17052 The default value of 39 for OpenVMS need not be specified.
17054 The @code{gnatkr} utility can be used to determine the krunched name for
17055 a given file, when krunched to a specified maximum length.
17058 @section Using @code{gnatkr}
17061 The @code{gnatkr} command has the form
17065 $ gnatkr @var{name} [@var{length}]
17071 $ gnatkr @var{name} /COUNT=nn
17076 @var{name} is the uncrunched file name, derived from the name of the unit
17077 in the standard manner described in the previous section (i.e. in particular
17078 all dots are replaced by hyphens). The file name may or may not have an
17079 extension (defined as a suffix of the form period followed by arbitrary
17080 characters other than period). If an extension is present then it will
17081 be preserved in the output. For example, when krunching @file{hellofile.ads}
17082 to eight characters, the result will be hellofil.ads.
17084 Note: for compatibility with previous versions of @code{gnatkr} dots may
17085 appear in the name instead of hyphens, but the last dot will always be
17086 taken as the start of an extension. So if @code{gnatkr} is given an argument
17087 such as @file{Hello.World.adb} it will be treated exactly as if the first
17088 period had been a hyphen, and for example krunching to eight characters
17089 gives the result @file{hellworl.adb}.
17091 Note that the result is always all lower case (except on OpenVMS where it is
17092 all upper case). Characters of the other case are folded as required.
17094 @var{length} represents the length of the krunched name. The default
17095 when no argument is given is ^8^39^ characters. A length of zero stands for
17096 unlimited, in other words do not chop except for system files where the
17097 implied crunching length is always eight characters.
17100 The output is the krunched name. The output has an extension only if the
17101 original argument was a file name with an extension.
17103 @node Krunching Method
17104 @section Krunching Method
17107 The initial file name is determined by the name of the unit that the file
17108 contains. The name is formed by taking the full expanded name of the
17109 unit and replacing the separating dots with hyphens and
17110 using ^lowercase^uppercase^
17111 for all letters, except that a hyphen in the second character position is
17112 replaced by a ^tilde^dollar sign^ if the first character is
17113 ^a, i, g, or s^A, I, G, or S^.
17114 The extension is @code{.ads} for a
17115 specification and @code{.adb} for a body.
17116 Krunching does not affect the extension, but the file name is shortened to
17117 the specified length by following these rules:
17121 The name is divided into segments separated by hyphens, tildes or
17122 underscores and all hyphens, tildes, and underscores are
17123 eliminated. If this leaves the name short enough, we are done.
17126 If the name is too long, the longest segment is located (left-most
17127 if there are two of equal length), and shortened by dropping
17128 its last character. This is repeated until the name is short enough.
17130 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
17131 to fit the name into 8 characters as required by some operating systems.
17134 our-strings-wide_fixed 22
17135 our strings wide fixed 19
17136 our string wide fixed 18
17137 our strin wide fixed 17
17138 our stri wide fixed 16
17139 our stri wide fixe 15
17140 our str wide fixe 14
17141 our str wid fixe 13
17147 Final file name: oustwifi.adb
17151 The file names for all predefined units are always krunched to eight
17152 characters. The krunching of these predefined units uses the following
17153 special prefix replacements:
17157 replaced by @file{^a^A^-}
17160 replaced by @file{^g^G^-}
17163 replaced by @file{^i^I^-}
17166 replaced by @file{^s^S^-}
17169 These system files have a hyphen in the second character position. That
17170 is why normal user files replace such a character with a
17171 ^tilde^dollar sign^, to
17172 avoid confusion with system file names.
17174 As an example of this special rule, consider
17175 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
17178 ada-strings-wide_fixed 22
17179 a- strings wide fixed 18
17180 a- string wide fixed 17
17181 a- strin wide fixed 16
17182 a- stri wide fixed 15
17183 a- stri wide fixe 14
17184 a- str wide fixe 13
17190 Final file name: a-stwifi.adb
17194 Of course no file shortening algorithm can guarantee uniqueness over all
17195 possible unit names, and if file name krunching is used then it is your
17196 responsibility to ensure that no name clashes occur. The utility
17197 program @code{gnatkr} is supplied for conveniently determining the
17198 krunched name of a file.
17200 @node Examples of gnatkr Usage
17201 @section Examples of @code{gnatkr} Usage
17208 $ gnatkr very_long_unit_name.ads --> velounna.ads
17209 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
17210 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
17211 $ gnatkr grandparent-parent-child --> grparchi
17213 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
17214 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
17217 @node Preprocessing Using gnatprep
17218 @chapter Preprocessing Using @code{gnatprep}
17222 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
17224 Although designed for use with GNAT, @code{gnatprep} does not depend on any
17225 special GNAT features.
17226 For further discussion of conditional compilation in general, see
17227 @ref{Conditional Compilation}.
17231 * Switches for gnatprep::
17232 * Form of Definitions File::
17233 * Form of Input Text for gnatprep::
17237 @node Using gnatprep
17238 @section Using @code{gnatprep}
17241 To call @code{gnatprep} use
17244 $ gnatprep [switches] infile outfile [deffile]
17251 is an optional sequence of switches as described in the next section.
17254 is the full name of the input file, which is an Ada source
17255 file containing preprocessor directives.
17258 is the full name of the output file, which is an Ada source
17259 in standard Ada form. When used with GNAT, this file name will
17260 normally have an ads or adb suffix.
17263 is the full name of a text file containing definitions of
17264 symbols to be referenced by the preprocessor. This argument is
17265 optional, and can be replaced by the use of the @option{-D} switch.
17269 @node Switches for gnatprep
17270 @section Switches for @code{gnatprep}
17275 @item ^-b^/BLANK_LINES^
17276 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
17277 Causes both preprocessor lines and the lines deleted by
17278 preprocessing to be replaced by blank lines in the output source file,
17279 preserving line numbers in the output file.
17281 @item ^-c^/COMMENTS^
17282 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
17283 Causes both preprocessor lines and the lines deleted
17284 by preprocessing to be retained in the output source as comments marked
17285 with the special string @code{"--! "}. This option will result in line numbers
17286 being preserved in the output file.
17288 @item ^-C^/REPLACE_IN_COMMENTS^
17289 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
17290 Causes comments to be scanned. Normally comments are ignored by gnatprep.
17291 If this option is specified, then comments are scanned and any $symbol
17292 substitutions performed as in program text. This is particularly useful
17293 when structured comments are used (e.g. when writing programs in the
17294 SPARK dialect of Ada). Note that this switch is not available when
17295 doing integrated preprocessing (it would be useless in this context
17296 since comments are ignored by the compiler in any case).
17298 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
17299 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
17300 Defines a new symbol, associated with value. If no value is given on the
17301 command line, then symbol is considered to be @code{True}. This switch
17302 can be used in place of a definition file.
17306 @cindex @option{/REMOVE} (@command{gnatprep})
17307 This is the default setting which causes lines deleted by preprocessing
17308 to be entirely removed from the output file.
17311 @item ^-r^/REFERENCE^
17312 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
17313 Causes a @code{Source_Reference} pragma to be generated that
17314 references the original input file, so that error messages will use
17315 the file name of this original file. The use of this switch implies
17316 that preprocessor lines are not to be removed from the file, so its
17317 use will force @option{^-b^/BLANK_LINES^} mode if
17318 @option{^-c^/COMMENTS^}
17319 has not been specified explicitly.
17321 Note that if the file to be preprocessed contains multiple units, then
17322 it will be necessary to @code{gnatchop} the output file from
17323 @code{gnatprep}. If a @code{Source_Reference} pragma is present
17324 in the preprocessed file, it will be respected by
17325 @code{gnatchop ^-r^/REFERENCE^}
17326 so that the final chopped files will correctly refer to the original
17327 input source file for @code{gnatprep}.
17329 @item ^-s^/SYMBOLS^
17330 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
17331 Causes a sorted list of symbol names and values to be
17332 listed on the standard output file.
17334 @item ^-u^/UNDEFINED^
17335 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
17336 Causes undefined symbols to be treated as having the value FALSE in the context
17337 of a preprocessor test. In the absence of this option, an undefined symbol in
17338 a @code{#if} or @code{#elsif} test will be treated as an error.
17344 Note: if neither @option{-b} nor @option{-c} is present,
17345 then preprocessor lines and
17346 deleted lines are completely removed from the output, unless -r is
17347 specified, in which case -b is assumed.
17350 @node Form of Definitions File
17351 @section Form of Definitions File
17354 The definitions file contains lines of the form
17361 where symbol is an identifier, following normal Ada (case-insensitive)
17362 rules for its syntax, and value is one of the following:
17366 Empty, corresponding to a null substitution
17368 A string literal using normal Ada syntax
17370 Any sequence of characters from the set
17371 (letters, digits, period, underline).
17375 Comment lines may also appear in the definitions file, starting with
17376 the usual @code{--},
17377 and comments may be added to the definitions lines.
17379 @node Form of Input Text for gnatprep
17380 @section Form of Input Text for @code{gnatprep}
17383 The input text may contain preprocessor conditional inclusion lines,
17384 as well as general symbol substitution sequences.
17386 The preprocessor conditional inclusion commands have the form
17391 #if @i{expression} [then]
17393 #elsif @i{expression} [then]
17395 #elsif @i{expression} [then]
17406 In this example, @i{expression} is defined by the following grammar:
17408 @i{expression} ::= <symbol>
17409 @i{expression} ::= <symbol> = "<value>"
17410 @i{expression} ::= <symbol> = <symbol>
17411 @i{expression} ::= <symbol> 'Defined
17412 @i{expression} ::= not @i{expression}
17413 @i{expression} ::= @i{expression} and @i{expression}
17414 @i{expression} ::= @i{expression} or @i{expression}
17415 @i{expression} ::= @i{expression} and then @i{expression}
17416 @i{expression} ::= @i{expression} or else @i{expression}
17417 @i{expression} ::= ( @i{expression} )
17421 For the first test (@i{expression} ::= <symbol>) the symbol must have
17422 either the value true or false, that is to say the right-hand of the
17423 symbol definition must be one of the (case-insensitive) literals
17424 @code{True} or @code{False}. If the value is true, then the
17425 corresponding lines are included, and if the value is false, they are
17428 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
17429 the symbol has been defined in the definition file or by a @option{-D}
17430 switch on the command line. Otherwise, the test is false.
17432 The equality tests are case insensitive, as are all the preprocessor lines.
17434 If the symbol referenced is not defined in the symbol definitions file,
17435 then the effect depends on whether or not switch @option{-u}
17436 is specified. If so, then the symbol is treated as if it had the value
17437 false and the test fails. If this switch is not specified, then
17438 it is an error to reference an undefined symbol. It is also an error to
17439 reference a symbol that is defined with a value other than @code{True}
17442 The use of the @code{not} operator inverts the sense of this logical test.
17443 The @code{not} operator cannot be combined with the @code{or} or @code{and}
17444 operators, without parentheses. For example, "if not X or Y then" is not
17445 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
17447 The @code{then} keyword is optional as shown
17449 The @code{#} must be the first non-blank character on a line, but
17450 otherwise the format is free form. Spaces or tabs may appear between
17451 the @code{#} and the keyword. The keywords and the symbols are case
17452 insensitive as in normal Ada code. Comments may be used on a
17453 preprocessor line, but other than that, no other tokens may appear on a
17454 preprocessor line. Any number of @code{elsif} clauses can be present,
17455 including none at all. The @code{else} is optional, as in Ada.
17457 The @code{#} marking the start of a preprocessor line must be the first
17458 non-blank character on the line, i.e. it must be preceded only by
17459 spaces or horizontal tabs.
17461 Symbol substitution outside of preprocessor lines is obtained by using
17469 anywhere within a source line, except in a comment or within a
17470 string literal. The identifier
17471 following the @code{$} must match one of the symbols defined in the symbol
17472 definition file, and the result is to substitute the value of the
17473 symbol in place of @code{$symbol} in the output file.
17475 Note that although the substitution of strings within a string literal
17476 is not possible, it is possible to have a symbol whose defined value is
17477 a string literal. So instead of setting XYZ to @code{hello} and writing:
17480 Header : String := "$XYZ";
17484 you should set XYZ to @code{"hello"} and write:
17487 Header : String := $XYZ;
17491 and then the substitution will occur as desired.
17494 @node The GNAT Run-Time Library Builder gnatlbr
17495 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
17497 @cindex Library builder
17500 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
17501 supplied configuration pragmas.
17504 * Running gnatlbr::
17505 * Switches for gnatlbr::
17506 * Examples of gnatlbr Usage::
17509 @node Running gnatlbr
17510 @section Running @code{gnatlbr}
17513 The @code{gnatlbr} command has the form
17516 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
17519 @node Switches for gnatlbr
17520 @section Switches for @code{gnatlbr}
17523 @code{gnatlbr} recognizes the following switches:
17527 @item /CREATE=directory
17528 @cindex @code{/CREATE} (@code{gnatlbr})
17529 Create the new run-time library in the specified directory.
17531 @item /SET=directory
17532 @cindex @code{/SET} (@code{gnatlbr})
17533 Make the library in the specified directory the current run-time
17536 @item /DELETE=directory
17537 @cindex @code{/DELETE} (@code{gnatlbr})
17538 Delete the run-time library in the specified directory.
17541 @cindex @code{/CONFIG} (@code{gnatlbr})
17543 Use the configuration pragmas in the specified file when building
17547 Use the configuration pragmas in the specified file when compiling.
17551 @node Examples of gnatlbr Usage
17552 @section Example of @code{gnatlbr} Usage
17555 Contents of VAXFLOAT.ADC:
17556 pragma Float_Representation (VAX_Float);
17558 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
17560 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
17565 @node The GNAT Library Browser gnatls
17566 @chapter The GNAT Library Browser @code{gnatls}
17568 @cindex Library browser
17571 @code{gnatls} is a tool that outputs information about compiled
17572 units. It gives the relationship between objects, unit names and source
17573 files. It can also be used to check the source dependencies of a unit
17574 as well as various characteristics.
17576 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
17577 driver (see @ref{The GNAT Driver and Project Files}).
17581 * Switches for gnatls::
17582 * Examples of gnatls Usage::
17585 @node Running gnatls
17586 @section Running @code{gnatls}
17589 The @code{gnatls} command has the form
17592 $ gnatls switches @var{object_or_ali_file}
17596 The main argument is the list of object or @file{ali} files
17597 (@pxref{The Ada Library Information Files})
17598 for which information is requested.
17600 In normal mode, without additional option, @code{gnatls} produces a
17601 four-column listing. Each line represents information for a specific
17602 object. The first column gives the full path of the object, the second
17603 column gives the name of the principal unit in this object, the third
17604 column gives the status of the source and the fourth column gives the
17605 full path of the source representing this unit.
17606 Here is a simple example of use:
17610 ^./^[]^demo1.o demo1 DIF demo1.adb
17611 ^./^[]^demo2.o demo2 OK demo2.adb
17612 ^./^[]^hello.o h1 OK hello.adb
17613 ^./^[]^instr-child.o instr.child MOK instr-child.adb
17614 ^./^[]^instr.o instr OK instr.adb
17615 ^./^[]^tef.o tef DIF tef.adb
17616 ^./^[]^text_io_example.o text_io_example OK text_io_example.adb
17617 ^./^[]^tgef.o tgef DIF tgef.adb
17621 The first line can be interpreted as follows: the main unit which is
17623 object file @file{demo1.o} is demo1, whose main source is in
17624 @file{demo1.adb}. Furthermore, the version of the source used for the
17625 compilation of demo1 has been modified (DIF). Each source file has a status
17626 qualifier which can be:
17629 @item OK (unchanged)
17630 The version of the source file used for the compilation of the
17631 specified unit corresponds exactly to the actual source file.
17633 @item MOK (slightly modified)
17634 The version of the source file used for the compilation of the
17635 specified unit differs from the actual source file but not enough to
17636 require recompilation. If you use gnatmake with the qualifier
17637 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
17638 MOK will not be recompiled.
17640 @item DIF (modified)
17641 No version of the source found on the path corresponds to the source
17642 used to build this object.
17644 @item ??? (file not found)
17645 No source file was found for this unit.
17647 @item HID (hidden, unchanged version not first on PATH)
17648 The version of the source that corresponds exactly to the source used
17649 for compilation has been found on the path but it is hidden by another
17650 version of the same source that has been modified.
17654 @node Switches for gnatls
17655 @section Switches for @code{gnatls}
17658 @code{gnatls} recognizes the following switches:
17662 @cindex @option{--version} @command{gnatls}
17663 Display Copyright and version, then exit disregarding all other options.
17666 @cindex @option{--help} @command{gnatls}
17667 If @option{--version} was not used, display usage, then exit disregarding
17670 @item ^-a^/ALL_UNITS^
17671 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
17672 Consider all units, including those of the predefined Ada library.
17673 Especially useful with @option{^-d^/DEPENDENCIES^}.
17675 @item ^-d^/DEPENDENCIES^
17676 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
17677 List sources from which specified units depend on.
17679 @item ^-h^/OUTPUT=OPTIONS^
17680 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
17681 Output the list of options.
17683 @item ^-o^/OUTPUT=OBJECTS^
17684 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
17685 Only output information about object files.
17687 @item ^-s^/OUTPUT=SOURCES^
17688 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
17689 Only output information about source files.
17691 @item ^-u^/OUTPUT=UNITS^
17692 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
17693 Only output information about compilation units.
17695 @item ^-files^/FILES^=@var{file}
17696 @cindex @option{^-files^/FILES^} (@code{gnatls})
17697 Take as arguments the files listed in text file @var{file}.
17698 Text file @var{file} may contain empty lines that are ignored.
17699 Each non empty line should contain the name of an existing file.
17700 Several such switches may be specified simultaneously.
17702 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17703 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
17704 @itemx ^-I^/SEARCH=^@var{dir}
17705 @itemx ^-I-^/NOCURRENT_DIRECTORY^
17707 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
17708 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
17709 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
17710 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
17711 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
17712 flags (@pxref{Switches for gnatmake}).
17714 @item --RTS=@var{rts-path}
17715 @cindex @option{--RTS} (@code{gnatls})
17716 Specifies the default location of the runtime library. Same meaning as the
17717 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
17719 @item ^-v^/OUTPUT=VERBOSE^
17720 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
17721 Verbose mode. Output the complete source, object and project paths. Do not use
17722 the default column layout but instead use long format giving as much as
17723 information possible on each requested units, including special
17724 characteristics such as:
17727 @item Preelaborable
17728 The unit is preelaborable in the Ada sense.
17731 No elaboration code has been produced by the compiler for this unit.
17734 The unit is pure in the Ada sense.
17736 @item Elaborate_Body
17737 The unit contains a pragma Elaborate_Body.
17740 The unit contains a pragma Remote_Types.
17742 @item Shared_Passive
17743 The unit contains a pragma Shared_Passive.
17746 This unit is part of the predefined environment and cannot be modified
17749 @item Remote_Call_Interface
17750 The unit contains a pragma Remote_Call_Interface.
17756 @node Examples of gnatls Usage
17757 @section Example of @code{gnatls} Usage
17761 Example of using the verbose switch. Note how the source and
17762 object paths are affected by the -I switch.
17765 $ gnatls -v -I.. demo1.o
17767 GNATLS 5.03w (20041123-34)
17768 Copyright 1997-2004 Free Software Foundation, Inc.
17770 Source Search Path:
17771 <Current_Directory>
17773 /home/comar/local/adainclude/
17775 Object Search Path:
17776 <Current_Directory>
17778 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
17780 Project Search Path:
17781 <Current_Directory>
17782 /home/comar/local/lib/gnat/
17787 Kind => subprogram body
17788 Flags => No_Elab_Code
17789 Source => demo1.adb modified
17793 The following is an example of use of the dependency list.
17794 Note the use of the -s switch
17795 which gives a straight list of source files. This can be useful for
17796 building specialized scripts.
17799 $ gnatls -d demo2.o
17800 ./demo2.o demo2 OK demo2.adb
17806 $ gnatls -d -s -a demo1.o
17808 /home/comar/local/adainclude/ada.ads
17809 /home/comar/local/adainclude/a-finali.ads
17810 /home/comar/local/adainclude/a-filico.ads
17811 /home/comar/local/adainclude/a-stream.ads
17812 /home/comar/local/adainclude/a-tags.ads
17815 /home/comar/local/adainclude/gnat.ads
17816 /home/comar/local/adainclude/g-io.ads
17818 /home/comar/local/adainclude/system.ads
17819 /home/comar/local/adainclude/s-exctab.ads
17820 /home/comar/local/adainclude/s-finimp.ads
17821 /home/comar/local/adainclude/s-finroo.ads
17822 /home/comar/local/adainclude/s-secsta.ads
17823 /home/comar/local/adainclude/s-stalib.ads
17824 /home/comar/local/adainclude/s-stoele.ads
17825 /home/comar/local/adainclude/s-stratt.ads
17826 /home/comar/local/adainclude/s-tasoli.ads
17827 /home/comar/local/adainclude/s-unstyp.ads
17828 /home/comar/local/adainclude/unchconv.ads
17834 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
17836 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
17837 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
17838 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
17839 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
17840 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
17844 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
17845 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
17847 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
17848 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
17849 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
17850 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
17851 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
17852 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
17853 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
17854 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
17855 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
17856 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
17857 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
17861 @node Cleaning Up Using gnatclean
17862 @chapter Cleaning Up Using @code{gnatclean}
17864 @cindex Cleaning tool
17867 @code{gnatclean} is a tool that allows the deletion of files produced by the
17868 compiler, binder and linker, including ALI files, object files, tree files,
17869 expanded source files, library files, interface copy source files, binder
17870 generated files and executable files.
17873 * Running gnatclean::
17874 * Switches for gnatclean::
17875 @c * Examples of gnatclean Usage::
17878 @node Running gnatclean
17879 @section Running @code{gnatclean}
17882 The @code{gnatclean} command has the form:
17885 $ gnatclean switches @var{names}
17889 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
17890 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
17891 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
17894 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17895 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
17896 the linker. In informative-only mode, specified by switch
17897 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
17898 normal mode is listed, but no file is actually deleted.
17900 @node Switches for gnatclean
17901 @section Switches for @code{gnatclean}
17904 @code{gnatclean} recognizes the following switches:
17908 @cindex @option{--version} @command{gnatclean}
17909 Display Copyright and version, then exit disregarding all other options.
17912 @cindex @option{--help} @command{gnatclean}
17913 If @option{--version} was not used, display usage, then exit disregarding
17916 @item ^-c^/COMPILER_FILES_ONLY^
17917 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
17918 Only attempt to delete the files produced by the compiler, not those produced
17919 by the binder or the linker. The files that are not to be deleted are library
17920 files, interface copy files, binder generated files and executable files.
17922 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
17923 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
17924 Indicate that ALI and object files should normally be found in directory
17927 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
17928 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
17929 When using project files, if some errors or warnings are detected during
17930 parsing and verbose mode is not in effect (no use of switch
17931 ^-v^/VERBOSE^), then error lines start with the full path name of the project
17932 file, rather than its simple file name.
17935 @cindex @option{^-h^/HELP^} (@code{gnatclean})
17936 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
17938 @item ^-n^/NODELETE^
17939 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
17940 Informative-only mode. Do not delete any files. Output the list of the files
17941 that would have been deleted if this switch was not specified.
17943 @item ^-P^/PROJECT_FILE=^@var{project}
17944 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
17945 Use project file @var{project}. Only one such switch can be used.
17946 When cleaning a project file, the files produced by the compilation of the
17947 immediate sources or inherited sources of the project files are to be
17948 deleted. This is not depending on the presence or not of executable names
17949 on the command line.
17952 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
17953 Quiet output. If there are no errors, do not output anything, except in
17954 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
17955 (switch ^-n^/NODELETE^).
17957 @item ^-r^/RECURSIVE^
17958 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
17959 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
17960 clean all imported and extended project files, recursively. If this switch
17961 is not specified, only the files related to the main project file are to be
17962 deleted. This switch has no effect if no project file is specified.
17964 @item ^-v^/VERBOSE^
17965 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
17968 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
17969 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
17970 Indicates the verbosity of the parsing of GNAT project files.
17971 @xref{Switches Related to Project Files}.
17973 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
17974 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
17975 Indicates that external variable @var{name} has the value @var{value}.
17976 The Project Manager will use this value for occurrences of
17977 @code{external(name)} when parsing the project file.
17978 @xref{Switches Related to Project Files}.
17980 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17981 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
17982 When searching for ALI and object files, look in directory
17985 @item ^-I^/SEARCH=^@var{dir}
17986 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
17987 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
17989 @item ^-I-^/NOCURRENT_DIRECTORY^
17990 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
17991 @cindex Source files, suppressing search
17992 Do not look for ALI or object files in the directory
17993 where @code{gnatclean} was invoked.
17997 @c @node Examples of gnatclean Usage
17998 @c @section Examples of @code{gnatclean} Usage
18001 @node GNAT and Libraries
18002 @chapter GNAT and Libraries
18003 @cindex Library, building, installing, using
18006 This chapter describes how to build and use libraries with GNAT, and also shows
18007 how to recompile the GNAT run-time library. You should be familiar with the
18008 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
18012 * Introduction to Libraries in GNAT::
18013 * General Ada Libraries::
18014 * Stand-alone Ada Libraries::
18015 * Rebuilding the GNAT Run-Time Library::
18018 @node Introduction to Libraries in GNAT
18019 @section Introduction to Libraries in GNAT
18022 A library is, conceptually, a collection of objects which does not have its
18023 own main thread of execution, but rather provides certain services to the
18024 applications that use it. A library can be either statically linked with the
18025 application, in which case its code is directly included in the application,
18026 or, on platforms that support it, be dynamically linked, in which case
18027 its code is shared by all applications making use of this library.
18029 GNAT supports both types of libraries.
18030 In the static case, the compiled code can be provided in different ways. The
18031 simplest approach is to provide directly the set of objects resulting from
18032 compilation of the library source files. Alternatively, you can group the
18033 objects into an archive using whatever commands are provided by the operating
18034 system. For the latter case, the objects are grouped into a shared library.
18036 In the GNAT environment, a library has three types of components:
18042 @xref{The Ada Library Information Files}.
18044 Object files, an archive or a shared library.
18048 A GNAT library may expose all its source files, which is useful for
18049 documentation purposes. Alternatively, it may expose only the units needed by
18050 an external user to make use of the library. That is to say, the specs
18051 reflecting the library services along with all the units needed to compile
18052 those specs, which can include generic bodies or any body implementing an
18053 inlined routine. In the case of @emph{stand-alone libraries} those exposed
18054 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
18056 All compilation units comprising an application, including those in a library,
18057 need to be elaborated in an order partially defined by Ada's semantics. GNAT
18058 computes the elaboration order from the @file{ALI} files and this is why they
18059 constitute a mandatory part of GNAT libraries. Except in the case of
18060 @emph{stand-alone libraries}, where a specific library elaboration routine is
18061 produced independently of the application(s) using the library.
18063 @node General Ada Libraries
18064 @section General Ada Libraries
18067 * Building a library::
18068 * Installing a library::
18069 * Using a library::
18072 @node Building a library
18073 @subsection Building a library
18076 The easiest way to build a library is to use the Project Manager,
18077 which supports a special type of project called a @emph{Library Project}
18078 (@pxref{Library Projects}).
18080 A project is considered a library project, when two project-level attributes
18081 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
18082 control different aspects of library configuration, additional optional
18083 project-level attributes can be specified:
18086 This attribute controls whether the library is to be static or dynamic
18088 @item Library_Version
18089 This attribute specifies the library version; this value is used
18090 during dynamic linking of shared libraries to determine if the currently
18091 installed versions of the binaries are compatible.
18093 @item Library_Options
18095 These attributes specify additional low-level options to be used during
18096 library generation, and redefine the actual application used to generate
18101 The GNAT Project Manager takes full care of the library maintenance task,
18102 including recompilation of the source files for which objects do not exist
18103 or are not up to date, assembly of the library archive, and installation of
18104 the library (i.e., copying associated source, object and @file{ALI} files
18105 to the specified location).
18107 Here is a simple library project file:
18108 @smallexample @c ada
18110 for Source_Dirs use ("src1", "src2");
18111 for Object_Dir use "obj";
18112 for Library_Name use "mylib";
18113 for Library_Dir use "lib";
18114 for Library_Kind use "dynamic";
18119 and the compilation command to build and install the library:
18121 @smallexample @c ada
18122 $ gnatmake -Pmy_lib
18126 It is not entirely trivial to perform manually all the steps required to
18127 produce a library. We recommend that you use the GNAT Project Manager
18128 for this task. In special cases where this is not desired, the necessary
18129 steps are discussed below.
18131 There are various possibilities for compiling the units that make up the
18132 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
18133 with a conventional script. For simple libraries, it is also possible to create
18134 a dummy main program which depends upon all the packages that comprise the
18135 interface of the library. This dummy main program can then be given to
18136 @command{gnatmake}, which will ensure that all necessary objects are built.
18138 After this task is accomplished, you should follow the standard procedure
18139 of the underlying operating system to produce the static or shared library.
18141 Here is an example of such a dummy program:
18142 @smallexample @c ada
18144 with My_Lib.Service1;
18145 with My_Lib.Service2;
18146 with My_Lib.Service3;
18147 procedure My_Lib_Dummy is
18155 Here are the generic commands that will build an archive or a shared library.
18158 # compiling the library
18159 $ gnatmake -c my_lib_dummy.adb
18161 # we don't need the dummy object itself
18162 $ rm my_lib_dummy.o my_lib_dummy.ali
18164 # create an archive with the remaining objects
18165 $ ar rc libmy_lib.a *.o
18166 # some systems may require "ranlib" to be run as well
18168 # or create a shared library
18169 $ gcc -shared -o libmy_lib.so *.o
18170 # some systems may require the code to have been compiled with -fPIC
18172 # remove the object files that are now in the library
18175 # Make the ALI files read-only so that gnatmake will not try to
18176 # regenerate the objects that are in the library
18181 Please note that the library must have a name of the form @file{libxxx.a} or
18182 @file{libxxx.so} (or @file{libxxx.dll} on Windows) in order to be accessed by
18183 the directive @option{-lxxx} at link time.
18185 @node Installing a library
18186 @subsection Installing a library
18187 @cindex @code{ADA_PROJECT_PATH}
18190 If you use project files, library installation is part of the library build
18191 process. Thus no further action is needed in order to make use of the
18192 libraries that are built as part of the general application build. A usable
18193 version of the library is installed in the directory specified by the
18194 @code{Library_Dir} attribute of the library project file.
18196 You may want to install a library in a context different from where the library
18197 is built. This situation arises with third party suppliers, who may want
18198 to distribute a library in binary form where the user is not expected to be
18199 able to recompile the library. The simplest option in this case is to provide
18200 a project file slightly different from the one used to build the library, by
18201 using the @code{externally_built} attribute. For instance, the project
18202 file used to build the library in the previous section can be changed into the
18203 following one when the library is installed:
18205 @smallexample @c projectfile
18207 for Source_Dirs use ("src1", "src2");
18208 for Library_Name use "mylib";
18209 for Library_Dir use "lib";
18210 for Library_Kind use "dynamic";
18211 for Externally_Built use "true";
18216 This project file assumes that the directories @file{src1},
18217 @file{src2}, and @file{lib} exist in
18218 the directory containing the project file. The @code{externally_built}
18219 attribute makes it clear to the GNAT builder that it should not attempt to
18220 recompile any of the units from this library. It allows the library provider to
18221 restrict the source set to the minimum necessary for clients to make use of the
18222 library as described in the first section of this chapter. It is the
18223 responsibility of the library provider to install the necessary sources, ALI
18224 files and libraries in the directories mentioned in the project file. For
18225 convenience, the user's library project file should be installed in a location
18226 that will be searched automatically by the GNAT
18227 builder. These are the directories referenced in the @code{ADA_PROJECT_PATH}
18228 environment variable (@pxref{Importing Projects}), and also the default GNAT
18229 library location that can be queried with @command{gnatls -v} and is usually of
18230 the form $gnat_install_root/lib/gnat.
18232 When project files are not an option, it is also possible, but not recommended,
18233 to install the library so that the sources needed to use the library are on the
18234 Ada source path and the ALI files & libraries be on the Ada Object path (see
18235 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
18236 administrator can place general-purpose libraries in the default compiler
18237 paths, by specifying the libraries' location in the configuration files
18238 @file{ada_source_path} and @file{ada_object_path}. These configuration files
18239 must be located in the GNAT installation tree at the same place as the gcc spec
18240 file. The location of the gcc spec file can be determined as follows:
18246 The configuration files mentioned above have a simple format: each line
18247 must contain one unique directory name.
18248 Those names are added to the corresponding path
18249 in their order of appearance in the file. The names can be either absolute
18250 or relative; in the latter case, they are relative to where theses files
18253 The files @file{ada_source_path} and @file{ada_object_path} might not be
18255 GNAT installation, in which case, GNAT will look for its run-time library in
18256 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
18257 objects and @file{ALI} files). When the files exist, the compiler does not
18258 look in @file{adainclude} and @file{adalib}, and thus the
18259 @file{ada_source_path} file
18260 must contain the location for the GNAT run-time sources (which can simply
18261 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
18262 contain the location for the GNAT run-time objects (which can simply
18265 You can also specify a new default path to the run-time library at compilation
18266 time with the switch @option{--RTS=rts-path}. You can thus choose / change
18267 the run-time library you want your program to be compiled with. This switch is
18268 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
18269 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
18271 It is possible to install a library before or after the standard GNAT
18272 library, by reordering the lines in the configuration files. In general, a
18273 library must be installed before the GNAT library if it redefines
18276 @node Using a library
18277 @subsection Using a library
18279 @noindent Once again, the project facility greatly simplifies the use of
18280 libraries. In this context, using a library is just a matter of adding a
18281 @code{with} clause in the user project. For instance, to make use of the
18282 library @code{My_Lib} shown in examples in earlier sections, you can
18285 @smallexample @c projectfile
18292 Even if you have a third-party, non-Ada library, you can still use GNAT's
18293 Project Manager facility to provide a wrapper for it. For example, the
18294 following project, when @code{with}ed by your main project, will link with the
18295 third-party library @file{liba.a}:
18297 @smallexample @c projectfile
18300 for Externally_Built use "true";
18301 for Source_Files use ();
18302 for Library_Dir use "lib";
18303 for Library_Name use "a";
18304 for Library_Kind use "static";
18308 This is an alternative to the use of @code{pragma Linker_Options}. It is
18309 especially interesting in the context of systems with several interdependent
18310 static libraries where finding a proper linker order is not easy and best be
18311 left to the tools having visibility over project dependence information.
18314 In order to use an Ada library manually, you need to make sure that this
18315 library is on both your source and object path
18316 (see @ref{Search Paths and the Run-Time Library (RTL)}
18317 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
18318 in an archive or a shared library, you need to specify the desired
18319 library at link time.
18321 For example, you can use the library @file{mylib} installed in
18322 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
18325 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
18330 This can be expressed more simply:
18335 when the following conditions are met:
18338 @file{/dir/my_lib_src} has been added by the user to the environment
18339 variable @code{ADA_INCLUDE_PATH}, or by the administrator to the file
18340 @file{ada_source_path}
18342 @file{/dir/my_lib_obj} has been added by the user to the environment
18343 variable @code{ADA_OBJECTS_PATH}, or by the administrator to the file
18344 @file{ada_object_path}
18346 a pragma @code{Linker_Options} has been added to one of the sources.
18349 @smallexample @c ada
18350 pragma Linker_Options ("-lmy_lib");
18354 @node Stand-alone Ada Libraries
18355 @section Stand-alone Ada Libraries
18356 @cindex Stand-alone library, building, using
18359 * Introduction to Stand-alone Libraries::
18360 * Building a Stand-alone Library::
18361 * Creating a Stand-alone Library to be used in a non-Ada context::
18362 * Restrictions in Stand-alone Libraries::
18365 @node Introduction to Stand-alone Libraries
18366 @subsection Introduction to Stand-alone Libraries
18369 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
18371 elaborate the Ada units that are included in the library. In contrast with
18372 an ordinary library, which consists of all sources, objects and @file{ALI}
18374 library, a SAL may specify a restricted subset of compilation units
18375 to serve as a library interface. In this case, the fully
18376 self-sufficient set of files will normally consist of an objects
18377 archive, the sources of interface units' specs, and the @file{ALI}
18378 files of interface units.
18379 If an interface spec contains a generic unit or an inlined subprogram,
18381 source must also be provided; if the units that must be provided in the source
18382 form depend on other units, the source and @file{ALI} files of those must
18385 The main purpose of a SAL is to minimize the recompilation overhead of client
18386 applications when a new version of the library is installed. Specifically,
18387 if the interface sources have not changed, client applications do not need to
18388 be recompiled. If, furthermore, a SAL is provided in the shared form and its
18389 version, controlled by @code{Library_Version} attribute, is not changed,
18390 then the clients do not need to be relinked.
18392 SALs also allow the library providers to minimize the amount of library source
18393 text exposed to the clients. Such ``information hiding'' might be useful or
18394 necessary for various reasons.
18396 Stand-alone libraries are also well suited to be used in an executable whose
18397 main routine is not written in Ada.
18399 @node Building a Stand-alone Library
18400 @subsection Building a Stand-alone Library
18403 GNAT's Project facility provides a simple way of building and installing
18404 stand-alone libraries; see @ref{Stand-alone Library Projects}.
18405 To be a Stand-alone Library Project, in addition to the two attributes
18406 that make a project a Library Project (@code{Library_Name} and
18407 @code{Library_Dir}; see @ref{Library Projects}), the attribute
18408 @code{Library_Interface} must be defined. For example:
18410 @smallexample @c projectfile
18412 for Library_Dir use "lib_dir";
18413 for Library_Name use "dummy";
18414 for Library_Interface use ("int1", "int1.child");
18419 Attribute @code{Library_Interface} has a non-empty string list value,
18420 each string in the list designating a unit contained in an immediate source
18421 of the project file.
18423 When a Stand-alone Library is built, first the binder is invoked to build
18424 a package whose name depends on the library name
18425 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
18426 This binder-generated package includes initialization and
18427 finalization procedures whose
18428 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
18430 above). The object corresponding to this package is included in the library.
18432 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
18433 calling of these procedures if a static SAL is built, or if a shared SAL
18435 with the project-level attribute @code{Library_Auto_Init} set to
18438 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
18439 (those that are listed in attribute @code{Library_Interface}) are copied to
18440 the Library Directory. As a consequence, only the Interface Units may be
18441 imported from Ada units outside of the library. If other units are imported,
18442 the binding phase will fail.
18444 The attribute @code{Library_Src_Dir} may be specified for a
18445 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
18446 single string value. Its value must be the path (absolute or relative to the
18447 project directory) of an existing directory. This directory cannot be the
18448 object directory or one of the source directories, but it can be the same as
18449 the library directory. The sources of the Interface
18450 Units of the library that are needed by an Ada client of the library will be
18451 copied to the designated directory, called the Interface Copy directory.
18452 These sources include the specs of the Interface Units, but they may also
18453 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
18454 are used, or when there is a generic unit in the spec. Before the sources
18455 are copied to the Interface Copy directory, an attempt is made to delete all
18456 files in the Interface Copy directory.
18458 Building stand-alone libraries by hand is somewhat tedious, but for those
18459 occasions when it is necessary here are the steps that you need to perform:
18462 Compile all library sources.
18465 Invoke the binder with the switch @option{-n} (No Ada main program),
18466 with all the @file{ALI} files of the interfaces, and
18467 with the switch @option{-L} to give specific names to the @code{init}
18468 and @code{final} procedures. For example:
18470 gnatbind -n int1.ali int2.ali -Lsal1
18474 Compile the binder generated file:
18480 Link the dynamic library with all the necessary object files,
18481 indicating to the linker the names of the @code{init} (and possibly
18482 @code{final}) procedures for automatic initialization (and finalization).
18483 The built library should be placed in a directory different from
18484 the object directory.
18487 Copy the @code{ALI} files of the interface to the library directory,
18488 add in this copy an indication that it is an interface to a SAL
18489 (i.e. add a word @option{SL} on the line in the @file{ALI} file that starts
18490 with letter ``P'') and make the modified copy of the @file{ALI} file
18495 Using SALs is not different from using other libraries
18496 (see @ref{Using a library}).
18498 @node Creating a Stand-alone Library to be used in a non-Ada context
18499 @subsection Creating a Stand-alone Library to be used in a non-Ada context
18502 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
18505 The only extra step required is to ensure that library interface subprograms
18506 are compatible with the main program, by means of @code{pragma Export}
18507 or @code{pragma Convention}.
18509 Here is an example of simple library interface for use with C main program:
18511 @smallexample @c ada
18512 package Interface is
18514 procedure Do_Something;
18515 pragma Export (C, Do_Something, "do_something");
18517 procedure Do_Something_Else;
18518 pragma Export (C, Do_Something_Else, "do_something_else");
18524 On the foreign language side, you must provide a ``foreign'' view of the
18525 library interface; remember that it should contain elaboration routines in
18526 addition to interface subprograms.
18528 The example below shows the content of @code{mylib_interface.h} (note
18529 that there is no rule for the naming of this file, any name can be used)
18531 /* the library elaboration procedure */
18532 extern void mylibinit (void);
18534 /* the library finalization procedure */
18535 extern void mylibfinal (void);
18537 /* the interface exported by the library */
18538 extern void do_something (void);
18539 extern void do_something_else (void);
18543 Libraries built as explained above can be used from any program, provided
18544 that the elaboration procedures (named @code{mylibinit} in the previous
18545 example) are called before the library services are used. Any number of
18546 libraries can be used simultaneously, as long as the elaboration
18547 procedure of each library is called.
18549 Below is an example of a C program that uses the @code{mylib} library.
18552 #include "mylib_interface.h"
18557 /* First, elaborate the library before using it */
18560 /* Main program, using the library exported entities */
18562 do_something_else ();
18564 /* Library finalization at the end of the program */
18571 Note that invoking any library finalization procedure generated by
18572 @code{gnatbind} shuts down the Ada run-time environment.
18574 finalization of all Ada libraries must be performed at the end of the program.
18575 No call to these libraries or to the Ada run-time library should be made
18576 after the finalization phase.
18578 @node Restrictions in Stand-alone Libraries
18579 @subsection Restrictions in Stand-alone Libraries
18582 The pragmas listed below should be used with caution inside libraries,
18583 as they can create incompatibilities with other Ada libraries:
18585 @item pragma @code{Locking_Policy}
18586 @item pragma @code{Queuing_Policy}
18587 @item pragma @code{Task_Dispatching_Policy}
18588 @item pragma @code{Unreserve_All_Interrupts}
18592 When using a library that contains such pragmas, the user must make sure
18593 that all libraries use the same pragmas with the same values. Otherwise,
18594 @code{Program_Error} will
18595 be raised during the elaboration of the conflicting
18596 libraries. The usage of these pragmas and its consequences for the user
18597 should therefore be well documented.
18599 Similarly, the traceback in the exception occurrence mechanism should be
18600 enabled or disabled in a consistent manner across all libraries.
18601 Otherwise, Program_Error will be raised during the elaboration of the
18602 conflicting libraries.
18604 If the @code{Version} or @code{Body_Version}
18605 attributes are used inside a library, then you need to
18606 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
18607 libraries, so that version identifiers can be properly computed.
18608 In practice these attributes are rarely used, so this is unlikely
18609 to be a consideration.
18611 @node Rebuilding the GNAT Run-Time Library
18612 @section Rebuilding the GNAT Run-Time Library
18613 @cindex GNAT Run-Time Library, rebuilding
18614 @cindex Building the GNAT Run-Time Library
18615 @cindex Rebuilding the GNAT Run-Time Library
18616 @cindex Run-Time Library, rebuilding
18619 It may be useful to recompile the GNAT library in various contexts, the
18620 most important one being the use of partition-wide configuration pragmas
18621 such as @code{Normalize_Scalars}. A special Makefile called
18622 @code{Makefile.adalib} is provided to that effect and can be found in
18623 the directory containing the GNAT library. The location of this
18624 directory depends on the way the GNAT environment has been installed and can
18625 be determined by means of the command:
18632 The last entry in the object search path usually contains the
18633 gnat library. This Makefile contains its own documentation and in
18634 particular the set of instructions needed to rebuild a new library and
18637 @node Using the GNU make Utility
18638 @chapter Using the GNU @code{make} Utility
18642 This chapter offers some examples of makefiles that solve specific
18643 problems. It does not explain how to write a makefile (see the GNU make
18644 documentation), nor does it try to replace the @command{gnatmake} utility
18645 (@pxref{The GNAT Make Program gnatmake}).
18647 All the examples in this section are specific to the GNU version of
18648 make. Although @code{make} is a standard utility, and the basic language
18649 is the same, these examples use some advanced features found only in
18653 * Using gnatmake in a Makefile::
18654 * Automatically Creating a List of Directories::
18655 * Generating the Command Line Switches::
18656 * Overcoming Command Line Length Limits::
18659 @node Using gnatmake in a Makefile
18660 @section Using gnatmake in a Makefile
18665 Complex project organizations can be handled in a very powerful way by
18666 using GNU make combined with gnatmake. For instance, here is a Makefile
18667 which allows you to build each subsystem of a big project into a separate
18668 shared library. Such a makefile allows you to significantly reduce the link
18669 time of very big applications while maintaining full coherence at
18670 each step of the build process.
18672 The list of dependencies are handled automatically by
18673 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
18674 the appropriate directories.
18676 Note that you should also read the example on how to automatically
18677 create the list of directories
18678 (@pxref{Automatically Creating a List of Directories})
18679 which might help you in case your project has a lot of subdirectories.
18684 @font@heightrm=cmr8
18687 ## This Makefile is intended to be used with the following directory
18689 ## - The sources are split into a series of csc (computer software components)
18690 ## Each of these csc is put in its own directory.
18691 ## Their name are referenced by the directory names.
18692 ## They will be compiled into shared library (although this would also work
18693 ## with static libraries
18694 ## - The main program (and possibly other packages that do not belong to any
18695 ## csc is put in the top level directory (where the Makefile is).
18696 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
18697 ## \_ second_csc (sources) __ lib (will contain the library)
18699 ## Although this Makefile is build for shared library, it is easy to modify
18700 ## to build partial link objects instead (modify the lines with -shared and
18703 ## With this makefile, you can change any file in the system or add any new
18704 ## file, and everything will be recompiled correctly (only the relevant shared
18705 ## objects will be recompiled, and the main program will be re-linked).
18707 # The list of computer software component for your project. This might be
18708 # generated automatically.
18711 # Name of the main program (no extension)
18714 # If we need to build objects with -fPIC, uncomment the following line
18717 # The following variable should give the directory containing libgnat.so
18718 # You can get this directory through 'gnatls -v'. This is usually the last
18719 # directory in the Object_Path.
18722 # The directories for the libraries
18723 # (This macro expands the list of CSC to the list of shared libraries, you
18724 # could simply use the expanded form:
18725 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
18726 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
18728 $@{MAIN@}: objects $@{LIB_DIR@}
18729 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
18730 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
18733 # recompile the sources
18734 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
18736 # Note: In a future version of GNAT, the following commands will be simplified
18737 # by a new tool, gnatmlib
18739 mkdir -p $@{dir $@@ @}
18740 cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
18741 cd $@{dir $@@ @}; cp -f ../*.ali .
18743 # The dependencies for the modules
18744 # Note that we have to force the expansion of *.o, since in some cases
18745 # make won't be able to do it itself.
18746 aa/lib/libaa.so: $@{wildcard aa/*.o@}
18747 bb/lib/libbb.so: $@{wildcard bb/*.o@}
18748 cc/lib/libcc.so: $@{wildcard cc/*.o@}
18750 # Make sure all of the shared libraries are in the path before starting the
18753 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
18756 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
18757 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
18758 $@{RM@} $@{CSC_LIST:%=%/*.o@}
18759 $@{RM@} *.o *.ali $@{MAIN@}
18762 @node Automatically Creating a List of Directories
18763 @section Automatically Creating a List of Directories
18766 In most makefiles, you will have to specify a list of directories, and
18767 store it in a variable. For small projects, it is often easier to
18768 specify each of them by hand, since you then have full control over what
18769 is the proper order for these directories, which ones should be
18772 However, in larger projects, which might involve hundreds of
18773 subdirectories, it might be more convenient to generate this list
18776 The example below presents two methods. The first one, although less
18777 general, gives you more control over the list. It involves wildcard
18778 characters, that are automatically expanded by @code{make}. Its
18779 shortcoming is that you need to explicitly specify some of the
18780 organization of your project, such as for instance the directory tree
18781 depth, whether some directories are found in a separate tree,...
18783 The second method is the most general one. It requires an external
18784 program, called @code{find}, which is standard on all Unix systems. All
18785 the directories found under a given root directory will be added to the
18791 @font@heightrm=cmr8
18794 # The examples below are based on the following directory hierarchy:
18795 # All the directories can contain any number of files
18796 # ROOT_DIRECTORY -> a -> aa -> aaa
18799 # -> b -> ba -> baa
18802 # This Makefile creates a variable called DIRS, that can be reused any time
18803 # you need this list (see the other examples in this section)
18805 # The root of your project's directory hierarchy
18809 # First method: specify explicitly the list of directories
18810 # This allows you to specify any subset of all the directories you need.
18813 DIRS := a/aa/ a/ab/ b/ba/
18816 # Second method: use wildcards
18817 # Note that the argument(s) to wildcard below should end with a '/'.
18818 # Since wildcards also return file names, we have to filter them out
18819 # to avoid duplicate directory names.
18820 # We thus use make's @code{dir} and @code{sort} functions.
18821 # It sets DIRs to the following value (note that the directories aaa and baa
18822 # are not given, unless you change the arguments to wildcard).
18823 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
18826 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
18827 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
18830 # Third method: use an external program
18831 # This command is much faster if run on local disks, avoiding NFS slowdowns.
18832 # This is the most complete command: it sets DIRs to the following value:
18833 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
18836 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
18840 @node Generating the Command Line Switches
18841 @section Generating the Command Line Switches
18844 Once you have created the list of directories as explained in the
18845 previous section (@pxref{Automatically Creating a List of Directories}),
18846 you can easily generate the command line arguments to pass to gnatmake.
18848 For the sake of completeness, this example assumes that the source path
18849 is not the same as the object path, and that you have two separate lists
18853 # see "Automatically creating a list of directories" to create
18858 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
18859 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
18862 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
18865 @node Overcoming Command Line Length Limits
18866 @section Overcoming Command Line Length Limits
18869 One problem that might be encountered on big projects is that many
18870 operating systems limit the length of the command line. It is thus hard to give
18871 gnatmake the list of source and object directories.
18873 This example shows how you can set up environment variables, which will
18874 make @command{gnatmake} behave exactly as if the directories had been
18875 specified on the command line, but have a much higher length limit (or
18876 even none on most systems).
18878 It assumes that you have created a list of directories in your Makefile,
18879 using one of the methods presented in
18880 @ref{Automatically Creating a List of Directories}.
18881 For the sake of completeness, we assume that the object
18882 path (where the ALI files are found) is different from the sources patch.
18884 Note a small trick in the Makefile below: for efficiency reasons, we
18885 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
18886 expanded immediately by @code{make}. This way we overcome the standard
18887 make behavior which is to expand the variables only when they are
18890 On Windows, if you are using the standard Windows command shell, you must
18891 replace colons with semicolons in the assignments to these variables.
18896 @font@heightrm=cmr8
18899 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
18900 # This is the same thing as putting the -I arguments on the command line.
18901 # (the equivalent of using -aI on the command line would be to define
18902 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
18903 # You can of course have different values for these variables.
18905 # Note also that we need to keep the previous values of these variables, since
18906 # they might have been set before running 'make' to specify where the GNAT
18907 # library is installed.
18909 # see "Automatically creating a list of directories" to create these
18915 space:=$@{empty@} $@{empty@}
18916 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
18917 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
18918 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
18919 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
18920 export ADA_INCLUDE_PATH
18921 export ADA_OBJECT_PATH
18928 @node Memory Management Issues
18929 @chapter Memory Management Issues
18932 This chapter describes some useful memory pools provided in the GNAT library
18933 and in particular the GNAT Debug Pool facility, which can be used to detect
18934 incorrect uses of access values (including ``dangling references'').
18936 It also describes the @command{gnatmem} tool, which can be used to track down
18941 * Some Useful Memory Pools::
18942 * The GNAT Debug Pool Facility::
18944 * The gnatmem Tool::
18948 @node Some Useful Memory Pools
18949 @section Some Useful Memory Pools
18950 @findex Memory Pool
18951 @cindex storage, pool
18954 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
18955 storage pool. Allocations use the standard system call @code{malloc} while
18956 deallocations use the standard system call @code{free}. No reclamation is
18957 performed when the pool goes out of scope. For performance reasons, the
18958 standard default Ada allocators/deallocators do not use any explicit storage
18959 pools but if they did, they could use this storage pool without any change in
18960 behavior. That is why this storage pool is used when the user
18961 manages to make the default implicit allocator explicit as in this example:
18962 @smallexample @c ada
18963 type T1 is access Something;
18964 -- no Storage pool is defined for T2
18965 type T2 is access Something_Else;
18966 for T2'Storage_Pool use T1'Storage_Pool;
18967 -- the above is equivalent to
18968 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
18972 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
18973 pool. The allocation strategy is similar to @code{Pool_Local}'s
18974 except that the all
18975 storage allocated with this pool is reclaimed when the pool object goes out of
18976 scope. This pool provides a explicit mechanism similar to the implicit one
18977 provided by several Ada 83 compilers for allocations performed through a local
18978 access type and whose purpose was to reclaim memory when exiting the
18979 scope of a given local access. As an example, the following program does not
18980 leak memory even though it does not perform explicit deallocation:
18982 @smallexample @c ada
18983 with System.Pool_Local;
18984 procedure Pooloc1 is
18985 procedure Internal is
18986 type A is access Integer;
18987 X : System.Pool_Local.Unbounded_Reclaim_Pool;
18988 for A'Storage_Pool use X;
18991 for I in 1 .. 50 loop
18996 for I in 1 .. 100 loop
19003 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
19004 @code{Storage_Size} is specified for an access type.
19005 The whole storage for the pool is
19006 allocated at once, usually on the stack at the point where the access type is
19007 elaborated. It is automatically reclaimed when exiting the scope where the
19008 access type is defined. This package is not intended to be used directly by the
19009 user and it is implicitly used for each such declaration:
19011 @smallexample @c ada
19012 type T1 is access Something;
19013 for T1'Storage_Size use 10_000;
19016 @node The GNAT Debug Pool Facility
19017 @section The GNAT Debug Pool Facility
19019 @cindex storage, pool, memory corruption
19022 The use of unchecked deallocation and unchecked conversion can easily
19023 lead to incorrect memory references. The problems generated by such
19024 references are usually difficult to tackle because the symptoms can be
19025 very remote from the origin of the problem. In such cases, it is
19026 very helpful to detect the problem as early as possible. This is the
19027 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
19029 In order to use the GNAT specific debugging pool, the user must
19030 associate a debug pool object with each of the access types that may be
19031 related to suspected memory problems. See Ada Reference Manual 13.11.
19032 @smallexample @c ada
19033 type Ptr is access Some_Type;
19034 Pool : GNAT.Debug_Pools.Debug_Pool;
19035 for Ptr'Storage_Pool use Pool;
19039 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
19040 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
19041 allow the user to redefine allocation and deallocation strategies. They
19042 also provide a checkpoint for each dereference, through the use of
19043 the primitive operation @code{Dereference} which is implicitly called at
19044 each dereference of an access value.
19046 Once an access type has been associated with a debug pool, operations on
19047 values of the type may raise four distinct exceptions,
19048 which correspond to four potential kinds of memory corruption:
19051 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
19053 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
19055 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
19057 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
19061 For types associated with a Debug_Pool, dynamic allocation is performed using
19062 the standard GNAT allocation routine. References to all allocated chunks of
19063 memory are kept in an internal dictionary. Several deallocation strategies are
19064 provided, whereupon the user can choose to release the memory to the system,
19065 keep it allocated for further invalid access checks, or fill it with an easily
19066 recognizable pattern for debug sessions. The memory pattern is the old IBM
19067 hexadecimal convention: @code{16#DEADBEEF#}.
19069 See the documentation in the file g-debpoo.ads for more information on the
19070 various strategies.
19072 Upon each dereference, a check is made that the access value denotes a
19073 properly allocated memory location. Here is a complete example of use of
19074 @code{Debug_Pools}, that includes typical instances of memory corruption:
19075 @smallexample @c ada
19079 with Gnat.Io; use Gnat.Io;
19080 with Unchecked_Deallocation;
19081 with Unchecked_Conversion;
19082 with GNAT.Debug_Pools;
19083 with System.Storage_Elements;
19084 with Ada.Exceptions; use Ada.Exceptions;
19085 procedure Debug_Pool_Test is
19087 type T is access Integer;
19088 type U is access all T;
19090 P : GNAT.Debug_Pools.Debug_Pool;
19091 for T'Storage_Pool use P;
19093 procedure Free is new Unchecked_Deallocation (Integer, T);
19094 function UC is new Unchecked_Conversion (U, T);
19097 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
19107 Put_Line (Integer'Image(B.all));
19109 when E : others => Put_Line ("raised: " & Exception_Name (E));
19114 when E : others => Put_Line ("raised: " & Exception_Name (E));
19118 Put_Line (Integer'Image(B.all));
19120 when E : others => Put_Line ("raised: " & Exception_Name (E));
19125 when E : others => Put_Line ("raised: " & Exception_Name (E));
19128 end Debug_Pool_Test;
19132 The debug pool mechanism provides the following precise diagnostics on the
19133 execution of this erroneous program:
19136 Total allocated bytes : 0
19137 Total deallocated bytes : 0
19138 Current Water Mark: 0
19142 Total allocated bytes : 8
19143 Total deallocated bytes : 0
19144 Current Water Mark: 8
19147 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
19148 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
19149 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
19150 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
19152 Total allocated bytes : 8
19153 Total deallocated bytes : 4
19154 Current Water Mark: 4
19159 @node The gnatmem Tool
19160 @section The @command{gnatmem} Tool
19164 The @code{gnatmem} utility monitors dynamic allocation and
19165 deallocation activity in a program, and displays information about
19166 incorrect deallocations and possible sources of memory leaks.
19167 It provides three type of information:
19170 General information concerning memory management, such as the total
19171 number of allocations and deallocations, the amount of allocated
19172 memory and the high water mark, i.e. the largest amount of allocated
19173 memory in the course of program execution.
19176 Backtraces for all incorrect deallocations, that is to say deallocations
19177 which do not correspond to a valid allocation.
19180 Information on each allocation that is potentially the origin of a memory
19185 * Running gnatmem::
19186 * Switches for gnatmem::
19187 * Example of gnatmem Usage::
19190 @node Running gnatmem
19191 @subsection Running @code{gnatmem}
19194 @code{gnatmem} makes use of the output created by the special version of
19195 allocation and deallocation routines that record call information. This
19196 allows to obtain accurate dynamic memory usage history at a minimal cost to
19197 the execution speed. Note however, that @code{gnatmem} is not supported on
19198 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
19199 Solaris and Windows NT/2000/XP (x86).
19202 The @code{gnatmem} command has the form
19205 $ gnatmem [switches] user_program
19209 The program must have been linked with the instrumented version of the
19210 allocation and deallocation routines. This is done by linking with the
19211 @file{libgmem.a} library. For correct symbolic backtrace information,
19212 the user program should be compiled with debugging options
19213 (see @ref{Switches for gcc}). For example to build @file{my_program}:
19216 $ gnatmake -g my_program -largs -lgmem
19220 As library @file{libgmem.a} contains an alternate body for package
19221 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
19222 when an executable is linked with library @file{libgmem.a}. It is then not
19223 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
19226 When @file{my_program} is executed, the file @file{gmem.out} is produced.
19227 This file contains information about all allocations and deallocations
19228 performed by the program. It is produced by the instrumented allocations and
19229 deallocations routines and will be used by @code{gnatmem}.
19231 In order to produce symbolic backtrace information for allocations and
19232 deallocations performed by the GNAT run-time library, you need to use a
19233 version of that library that has been compiled with the @option{-g} switch
19234 (see @ref{Rebuilding the GNAT Run-Time Library}).
19236 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
19237 examine. If the location of @file{gmem.out} file was not explicitly supplied by
19238 @code{-i} switch, gnatmem will assume that this file can be found in the
19239 current directory. For example, after you have executed @file{my_program},
19240 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
19243 $ gnatmem my_program
19247 This will produce the output with the following format:
19249 *************** debut cc
19251 $ gnatmem my_program
19255 Total number of allocations : 45
19256 Total number of deallocations : 6
19257 Final Water Mark (non freed mem) : 11.29 Kilobytes
19258 High Water Mark : 11.40 Kilobytes
19263 Allocation Root # 2
19264 -------------------
19265 Number of non freed allocations : 11
19266 Final Water Mark (non freed mem) : 1.16 Kilobytes
19267 High Water Mark : 1.27 Kilobytes
19269 my_program.adb:23 my_program.alloc
19275 The first block of output gives general information. In this case, the
19276 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
19277 Unchecked_Deallocation routine occurred.
19280 Subsequent paragraphs display information on all allocation roots.
19281 An allocation root is a specific point in the execution of the program
19282 that generates some dynamic allocation, such as a ``@code{@b{new}}''
19283 construct. This root is represented by an execution backtrace (or subprogram
19284 call stack). By default the backtrace depth for allocations roots is 1, so
19285 that a root corresponds exactly to a source location. The backtrace can
19286 be made deeper, to make the root more specific.
19288 @node Switches for gnatmem
19289 @subsection Switches for @code{gnatmem}
19292 @code{gnatmem} recognizes the following switches:
19297 @cindex @option{-q} (@code{gnatmem})
19298 Quiet. Gives the minimum output needed to identify the origin of the
19299 memory leaks. Omits statistical information.
19302 @cindex @var{N} (@code{gnatmem})
19303 N is an integer literal (usually between 1 and 10) which controls the
19304 depth of the backtraces defining allocation root. The default value for
19305 N is 1. The deeper the backtrace, the more precise the localization of
19306 the root. Note that the total number of roots can depend on this
19307 parameter. This parameter must be specified @emph{before} the name of the
19308 executable to be analyzed, to avoid ambiguity.
19311 @cindex @option{-b} (@code{gnatmem})
19312 This switch has the same effect as just depth parameter.
19314 @item -i @var{file}
19315 @cindex @option{-i} (@code{gnatmem})
19316 Do the @code{gnatmem} processing starting from @file{file}, rather than
19317 @file{gmem.out} in the current directory.
19320 @cindex @option{-m} (@code{gnatmem})
19321 This switch causes @code{gnatmem} to mask the allocation roots that have less
19322 than n leaks. The default value is 1. Specifying the value of 0 will allow to
19323 examine even the roots that didn't result in leaks.
19326 @cindex @option{-s} (@code{gnatmem})
19327 This switch causes @code{gnatmem} to sort the allocation roots according to the
19328 specified order of sort criteria, each identified by a single letter. The
19329 currently supported criteria are @code{n, h, w} standing respectively for
19330 number of unfreed allocations, high watermark, and final watermark
19331 corresponding to a specific root. The default order is @code{nwh}.
19335 @node Example of gnatmem Usage
19336 @subsection Example of @code{gnatmem} Usage
19339 The following example shows the use of @code{gnatmem}
19340 on a simple memory-leaking program.
19341 Suppose that we have the following Ada program:
19343 @smallexample @c ada
19346 with Unchecked_Deallocation;
19347 procedure Test_Gm is
19349 type T is array (1..1000) of Integer;
19350 type Ptr is access T;
19351 procedure Free is new Unchecked_Deallocation (T, Ptr);
19354 procedure My_Alloc is
19359 procedure My_DeAlloc is
19367 for I in 1 .. 5 loop
19368 for J in I .. 5 loop
19379 The program needs to be compiled with debugging option and linked with
19380 @code{gmem} library:
19383 $ gnatmake -g test_gm -largs -lgmem
19387 Then we execute the program as usual:
19394 Then @code{gnatmem} is invoked simply with
19400 which produces the following output (result may vary on different platforms):
19405 Total number of allocations : 18
19406 Total number of deallocations : 5
19407 Final Water Mark (non freed mem) : 53.00 Kilobytes
19408 High Water Mark : 56.90 Kilobytes
19410 Allocation Root # 1
19411 -------------------
19412 Number of non freed allocations : 11
19413 Final Water Mark (non freed mem) : 42.97 Kilobytes
19414 High Water Mark : 46.88 Kilobytes
19416 test_gm.adb:11 test_gm.my_alloc
19418 Allocation Root # 2
19419 -------------------
19420 Number of non freed allocations : 1
19421 Final Water Mark (non freed mem) : 10.02 Kilobytes
19422 High Water Mark : 10.02 Kilobytes
19424 s-secsta.adb:81 system.secondary_stack.ss_init
19426 Allocation Root # 3
19427 -------------------
19428 Number of non freed allocations : 1
19429 Final Water Mark (non freed mem) : 12 Bytes
19430 High Water Mark : 12 Bytes
19432 s-secsta.adb:181 system.secondary_stack.ss_init
19436 Note that the GNAT run time contains itself a certain number of
19437 allocations that have no corresponding deallocation,
19438 as shown here for root #2 and root
19439 #3. This is a normal behavior when the number of non freed allocations
19440 is one, it allocates dynamic data structures that the run time needs for
19441 the complete lifetime of the program. Note also that there is only one
19442 allocation root in the user program with a single line back trace:
19443 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
19444 program shows that 'My_Alloc' is called at 2 different points in the
19445 source (line 21 and line 24). If those two allocation roots need to be
19446 distinguished, the backtrace depth parameter can be used:
19449 $ gnatmem 3 test_gm
19453 which will give the following output:
19458 Total number of allocations : 18
19459 Total number of deallocations : 5
19460 Final Water Mark (non freed mem) : 53.00 Kilobytes
19461 High Water Mark : 56.90 Kilobytes
19463 Allocation Root # 1
19464 -------------------
19465 Number of non freed allocations : 10
19466 Final Water Mark (non freed mem) : 39.06 Kilobytes
19467 High Water Mark : 42.97 Kilobytes
19469 test_gm.adb:11 test_gm.my_alloc
19470 test_gm.adb:24 test_gm
19471 b_test_gm.c:52 main
19473 Allocation Root # 2
19474 -------------------
19475 Number of non freed allocations : 1
19476 Final Water Mark (non freed mem) : 10.02 Kilobytes
19477 High Water Mark : 10.02 Kilobytes
19479 s-secsta.adb:81 system.secondary_stack.ss_init
19480 s-secsta.adb:283 <system__secondary_stack___elabb>
19481 b_test_gm.c:33 adainit
19483 Allocation Root # 3
19484 -------------------
19485 Number of non freed allocations : 1
19486 Final Water Mark (non freed mem) : 3.91 Kilobytes
19487 High Water Mark : 3.91 Kilobytes
19489 test_gm.adb:11 test_gm.my_alloc
19490 test_gm.adb:21 test_gm
19491 b_test_gm.c:52 main
19493 Allocation Root # 4
19494 -------------------
19495 Number of non freed allocations : 1
19496 Final Water Mark (non freed mem) : 12 Bytes
19497 High Water Mark : 12 Bytes
19499 s-secsta.adb:181 system.secondary_stack.ss_init
19500 s-secsta.adb:283 <system__secondary_stack___elabb>
19501 b_test_gm.c:33 adainit
19505 The allocation root #1 of the first example has been split in 2 roots #1
19506 and #3 thanks to the more precise associated backtrace.
19510 @node Stack Related Facilities
19511 @chapter Stack Related Facilities
19514 This chapter describes some useful tools associated with stack
19515 checking and analysis. In
19516 particular, it deals with dynamic and static stack usage measurements.
19519 * Stack Overflow Checking::
19520 * Static Stack Usage Analysis::
19521 * Dynamic Stack Usage Analysis::
19524 @node Stack Overflow Checking
19525 @section Stack Overflow Checking
19526 @cindex Stack Overflow Checking
19527 @cindex -fstack-check
19530 For most operating systems, @command{gcc} does not perform stack overflow
19531 checking by default. This means that if the main environment task or
19532 some other task exceeds the available stack space, then unpredictable
19533 behavior will occur. Most native systems offer some level of protection by
19534 adding a guard page at the end of each task stack. This mechanism is usually
19535 not enough for dealing properly with stack overflow situations because
19536 a large local variable could ``jump'' above the guard page.
19537 Furthermore, when the
19538 guard page is hit, there may not be any space left on the stack for executing
19539 the exception propagation code. Enabling stack checking avoids
19542 To activate stack checking, compile all units with the gcc option
19543 @option{-fstack-check}. For example:
19546 gcc -c -fstack-check package1.adb
19550 Units compiled with this option will generate extra instructions to check
19551 that any use of the stack (for procedure calls or for declaring local
19552 variables in declare blocks) does not exceed the available stack space.
19553 If the space is exceeded, then a @code{Storage_Error} exception is raised.
19555 For declared tasks, the stack size is controlled by the size
19556 given in an applicable @code{Storage_Size} pragma or by the value specified
19557 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
19558 the default size as defined in the GNAT runtime otherwise.
19560 For the environment task, the stack size depends on
19561 system defaults and is unknown to the compiler. Stack checking
19562 may still work correctly if a fixed
19563 size stack is allocated, but this cannot be guaranteed.
19565 To ensure that a clean exception is signalled for stack
19566 overflow, set the environment variable
19567 @code{GNAT_STACK_LIMIT} to indicate the maximum
19568 stack area that can be used, as in:
19569 @cindex GNAT_STACK_LIMIT
19572 SET GNAT_STACK_LIMIT 1600
19576 The limit is given in kilobytes, so the above declaration would
19577 set the stack limit of the environment task to 1.6 megabytes.
19578 Note that the only purpose of this usage is to limit the amount
19579 of stack used by the environment task. If it is necessary to
19580 increase the amount of stack for the environment task, then this
19581 is an operating systems issue, and must be addressed with the
19582 appropriate operating systems commands.
19585 To have a fixed size stack in the environment task, the stack must be put
19586 in the P0 address space and its size specified. Use these switches to
19590 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
19594 The quotes are required to keep case. The number after @samp{STACK=} is the
19595 size of the environmental task stack in pagelets (512 bytes). In this example
19596 the stack size is about 2 megabytes.
19599 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
19600 be placed in P0 space. Refer to @cite{HP OpenVMS Linker Utility Manual} for
19601 more details about the @option{/p0image} qualifier and the @option{stack}
19605 @node Static Stack Usage Analysis
19606 @section Static Stack Usage Analysis
19607 @cindex Static Stack Usage Analysis
19608 @cindex -fstack-usage
19611 A unit compiled with @option{-fstack-usage} will generate an extra file
19613 the maximum amount of stack used, on a per-function basis.
19614 The file has the same
19615 basename as the target object file with a @file{.su} extension.
19616 Each line of this file is made up of three fields:
19620 The name of the function.
19624 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
19627 The second field corresponds to the size of the known part of the function
19630 The qualifier @code{static} means that the function frame size
19632 It usually means that all local variables have a static size.
19633 In this case, the second field is a reliable measure of the function stack
19636 The qualifier @code{dynamic} means that the function frame size is not static.
19637 It happens mainly when some local variables have a dynamic size. When this
19638 qualifier appears alone, the second field is not a reliable measure
19639 of the function stack analysis. When it is qualified with @code{bounded}, it
19640 means that the second field is a reliable maximum of the function stack
19643 @node Dynamic Stack Usage Analysis
19644 @section Dynamic Stack Usage Analysis
19647 It is possible to measure the maximum amount of stack used by a task, by
19648 adding a switch to @command{gnatbind}, as:
19651 $ gnatbind -u0 file
19655 With this option, at each task termination, its stack usage is output on
19657 It is not always convenient to output the stack usage when the program
19658 is still running. Hence, it is possible to delay this output until program
19659 termination. for a given number of tasks specified as the argument of the
19660 @code{-u} option. For instance:
19663 $ gnatbind -u100 file
19667 will buffer the stack usage information of the first 100 tasks to terminate and
19668 output this info at program termination. Results are displayed in four
19672 Index | Task Name | Stack Size | Actual Use [min - max]
19679 is a number associated with each task.
19682 is the name of the task analyzed.
19685 is the maximum size for the stack.
19688 is the measure done by the stack analyzer. In order to prevent overflow,
19689 the stack is not entirely analyzed, and it's not possible to know exactly how
19690 much has actually been used. The real amount of stack used is between the min
19696 The environment task stack, e.g. the stack that contains the main unit, is
19697 only processed when the environment variable GNAT_STACK_LIMIT is set.
19700 @c *********************************
19702 @c *********************************
19703 @node Verifying Properties Using gnatcheck
19704 @chapter Verifying Properties Using @command{gnatcheck}
19706 @cindex @command{gnatcheck}
19709 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
19710 of Ada source files according to a given set of semantic rules.
19713 In order to check compliance with a given rule, @command{gnatcheck} has to
19714 semantically analyze the Ada sources.
19715 Therefore, checks can only be performed on
19716 legal Ada units. Moreover, when a unit depends semantically upon units located
19717 outside the current directory, the source search path has to be provided when
19718 calling @command{gnatcheck}, either through a specified project file or
19719 through @command{gnatcheck} switches as described below.
19721 A number of rules are predefined in @command{gnatcheck} and are described
19722 later in this chapter.
19723 You can also add new rules, by modifying the @command{gnatcheck} code and
19724 rebuilding the tool. In order to add a simple rule making some local checks,
19725 a small amount of straightforward ASIS-based programming is usually needed.
19727 Project support for @command{gnatcheck} is provided by the GNAT
19728 driver (see @ref{The GNAT Driver and Project Files}).
19730 Invoking @command{gnatcheck} on the command line has the form:
19733 $ gnatcheck [@i{switches}] @{@i{filename}@}
19734 [^-files^/FILES^=@{@i{arg_list_filename}@}]
19735 [-cargs @i{gcc_switches}] [-rules @i{rule_options}]
19742 @i{switches} specify the general tool options
19745 Each @i{filename} is the name (including the extension) of a source
19746 file to process. ``Wildcards'' are allowed, and
19747 the file name may contain path information.
19750 Each @i{arg_list_filename} is the name (including the extension) of a text
19751 file containing the names of the source files to process, separated by spaces
19755 @i{gcc_switches} is a list of switches for
19756 @command{gcc}. They will be passed on to all compiler invocations made by
19757 @command{gnatcheck} to generate the ASIS trees. Here you can provide
19758 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19759 and use the @option{-gnatec} switch to set the configuration file.
19762 @i{rule_options} is a list of options for controlling a set of
19763 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
19767 Either a @i{filename} or an @i{arg_list_filename} must be supplied.
19770 * Format of the Report File::
19771 * General gnatcheck Switches::
19772 * gnatcheck Rule Options::
19773 * Adding the Results of Compiler Checks to gnatcheck Output::
19774 * Project-Wide Checks::
19775 * Predefined Rules::
19778 @node Format of the Report File
19779 @section Format of the Report File
19780 @cindex Report file (for @code{gnatcheck})
19783 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
19785 It also creates, in the current
19786 directory, a text file named @file{^gnatcheck.out^GNATCHECK.OUT^} that
19787 contains the complete report of the last gnatcheck run. This report contains:
19789 @item a list of the Ada source files being checked,
19790 @item a list of enabled and disabled rules,
19791 @item a list of the diagnostic messages, ordered in three different ways
19792 and collected in three separate
19793 sections. Section 1 contains the raw list of diagnostic messages. It
19794 corresponds to the output going to @file{stdout}. Section 2 contains
19795 messages ordered by rules.
19796 Section 3 contains messages ordered by source files.
19799 @node General gnatcheck Switches
19800 @section General @command{gnatcheck} Switches
19803 The following switches control the general @command{gnatcheck} behavior
19807 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
19809 Process all units including those with read-only ALI files such as
19810 those from GNAT Run-Time library.
19814 @cindex @option{-d} (@command{gnatcheck})
19819 @cindex @option{-dd} (@command{gnatcheck})
19821 Progress indicator mode (for use in GPS)
19824 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
19826 List the predefined and user-defined rules. For more details see
19827 @ref{Predefined Rules}.
19829 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
19831 Use full source locations references in the report file. For a construct from
19832 a generic instantiation a full source location is a chain from the location
19833 of this construct in the generic unit to the place where this unit is
19836 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
19838 Quiet mode. All the diagnoses about rule violations are placed in the
19839 @command{gnatcheck} report file only, without duplicating in @file{stdout}.
19841 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
19843 Short format of the report file (no version information, no list of applied
19844 rules, no list of checked sources is included)
19846 @cindex @option{^-s1^/COMPILER_STYLE^} (@command{gnatcheck})
19847 @item ^-s1^/COMPILER_STYLE^
19848 Include the compiler-style section in the report file
19850 @cindex @option{^-s2^/BY_RULES^} (@command{gnatcheck})
19851 @item ^-s2^/BY_RULES^
19852 Include the section containing diagnoses ordered by rules in the report file
19854 @cindex @option{^-s3^/BY_FILES_BY_RULES^} (@command{gnatcheck})
19855 @item ^-s3^/BY_FILES_BY_RULES^
19856 Include the section containing diagnoses ordered by files and then by rules
19859 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
19860 @item ^-v^/VERBOSE^
19861 Verbose mode; @command{gnatcheck} generates version information and then
19862 a trace of sources being processed.
19867 Note that if any of the options @option{^-s1^/COMPILER_STYLE^},
19868 @option{^-s2^/BY_RULES^} or
19869 @option{^-s3^/BY_FILES_BY_RULES^} is specified,
19870 then the @command{gnatcheck} report file will only contain sections
19871 explicitly denoted by these options.
19873 @node gnatcheck Rule Options
19874 @section @command{gnatcheck} Rule Options
19877 The following options control the processing performed by
19878 @command{gnatcheck}.
19881 @cindex @option{+ALL} (@command{gnatcheck})
19883 Turn all the rule checks ON.
19885 @cindex @option{-ALL} (@command{gnatcheck})
19887 Turn all the rule checks OFF.
19889 @cindex @option{+R} (@command{gnatcheck})
19890 @item +R@i{rule_id[:param]}
19891 Turn on the check for a specified rule with the specified parameter, if any.
19892 @i{rule_id} must be the identifier of one of the currently implemented rules
19893 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
19894 are not case-sensitive. The @i{param} item must
19895 be a string representing a valid parameter(s) for the specified rule.
19896 If it contains any space characters then this string must be enclosed in
19899 @cindex @option{-R} (@command{gnatcheck})
19900 @item -R@i{rule_id[:param]}
19901 Turn off the check for a specified rule with the specified parameter, if any.
19903 @cindex @option{-from} (@command{gnatcheck})
19904 @item -from=@i{rule_option_filename}
19905 Read the rule options from the text file @i{rule_option_filename}, referred as
19906 ``rule file'' below.
19911 The default behavior is that all the rule checks are enabled, except for
19912 the checks performed by the compiler.
19914 and the checks associated with the
19918 A rule file is a text file containing a set of rule options.
19919 @cindex Rule file (for @code{gnatcheck})
19920 The file may contain empty lines and Ada-style comments (comment
19921 lines and end-of-line comments). The rule file has free format; that is,
19922 you do not have to start a new rule option on a new line.
19924 A rule file may contain other @option{-from=@i{rule_option_filename}}
19925 options, each such option being replaced with the content of the
19926 corresponding rule file during the rule files processing. In case a
19927 cycle is detected (that is, @i{rule_file_1} reads rule options from
19928 @i{rule_file_2}, and @i{rule_file_2} reads (directly or indirectly)
19929 rule options from @i{rule_file_1}), the processing
19930 of rule files is interrupted and a part of their content is ignored.
19933 @node Adding the Results of Compiler Checks to gnatcheck Output
19934 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
19937 The @command{gnatcheck} tool can include in the generated diagnostic messages
19939 the report file the results of the checks performed by the compiler. Though
19940 disabled by default, this effect may be obtained by using @option{+R} with
19941 the following rule identifiers and parameters:
19945 To record restrictions violations (that are performed by the compiler if the
19946 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
19948 @code{Restrictions} with the same parameters as pragma
19949 @code{Restrictions} or @code{Restriction_Warnings}.
19952 To record compiler style checks, use the rule named
19953 @code{Style_Checks}. A parameter of this rule can be either @code{All_Checks},
19954 which enables all the style checks, or a string that has exactly the same
19955 structure and semantics as the @code{string_LITERAL} parameter of GNAT pragma
19956 @code{Style_Checks} (for further information about this pragma, please
19957 refer to the @cite{@value{EDITION} Reference Manual}).
19960 To record compiler warnings (@pxref{Warning Message Control}), use the rule
19961 named @code{Warnings} with a parameter that is a valid
19962 @i{static_string_expression} argument of GNAT pragma @code{Warnings}
19963 (for further information about this pragma, please
19964 refer to the @cite{@value{EDITION} Reference Manual}).
19968 @node Project-Wide Checks
19969 @section Project-Wide Checks
19970 @cindex Project-wide checks (for @command{gnatcheck})
19973 In order to perform checks on all units of a given project, you can use
19974 the GNAT driver along with the @option{-P} option:
19976 gnat check -Pproj -rules -from=my_rules
19980 If the project @code{proj} depends upon other projects, you can perform
19981 checks on the project closure using the @option{-U} option:
19983 gnat check -Pproj -U -rules -from=my_rules
19987 Finally, if not all the units are relevant to a particular main
19988 program in the project closure, you can perform checks for the set
19989 of units needed to create a given main program (unit closure) using
19990 the @option{-U} option followed by the name of the main unit:
19992 gnat check -Pproj -U main -rules -from=my_rules
19996 @node Predefined Rules
19997 @section Predefined Rules
19998 @cindex Predefined rules (for @command{gnatcheck})
20001 @c (Jan 2007) Since the global rules are still under development and are not
20002 @c documented, there is no point in explaining the difference between
20003 @c global and local rules
20005 A rule in @command{gnatcheck} is either local or global.
20006 A @emph{local rule} is a rule that applies to a well-defined section
20007 of a program and that can be checked by analyzing only this section.
20008 A @emph{global rule} requires analysis of some global properties of the
20009 whole program (mostly related to the program call graph).
20010 As of @value{NOW}, the implementation of global rules should be
20011 considered to be at a preliminary stage. You can use the
20012 @option{+GLOBAL} option to enable all the global rules, and the
20013 @option{-GLOBAL} rule option to disable all the global rules.
20015 All the global rules in the list below are
20016 so indicated by marking them ``GLOBAL''.
20017 This +GLOBAL and -GLOBAL options are not
20018 included in the list of gnatcheck options above, because at the moment they
20019 are considered as a temporary debug options.
20021 @command{gnatcheck} performs rule checks for generic
20022 instances only for global rules. This limitation may be relaxed in a later
20027 The following subsections document the rules implemented in
20028 @command{gnatcheck}.
20029 The subsection title is the same as the rule identifier, which may be
20030 used as a parameter of the @option{+R} or @option{-R} options.
20034 * Abstract_Type_Declarations::
20035 * Anonymous_Arrays::
20036 * Anonymous_Subtypes::
20038 * Boolean_Relational_Operators::
20040 * Ceiling_Violations::
20042 * Controlled_Type_Declarations::
20043 * Declarations_In_Blocks::
20044 * Default_Parameters::
20045 * Discriminated_Records::
20046 * Enumeration_Ranges_In_CASE_Statements::
20047 * Exceptions_As_Control_Flow::
20048 * EXIT_Statements_With_No_Loop_Name::
20049 * Expanded_Loop_Exit_Names::
20050 * Explicit_Full_Discrete_Ranges::
20051 * Float_Equality_Checks::
20052 * Forbidden_Pragmas::
20053 * Function_Style_Procedures::
20054 * Generics_In_Subprograms::
20055 * GOTO_Statements::
20056 * Implicit_IN_Mode_Parameters::
20057 * Implicit_SMALL_For_Fixed_Point_Types::
20058 * Improperly_Located_Instantiations::
20059 * Improper_Returns::
20060 * Library_Level_Subprograms::
20063 * Improperly_Called_Protected_Entries::
20065 * Misnamed_Identifiers::
20066 * Multiple_Entries_In_Protected_Definitions::
20068 * Non_Qualified_Aggregates::
20069 * Non_Short_Circuit_Operators::
20070 * Non_SPARK_Attributes::
20071 * Non_Tagged_Derived_Types::
20072 * Non_Visible_Exceptions::
20073 * Numeric_Literals::
20074 * OTHERS_In_Aggregates::
20075 * OTHERS_In_CASE_Statements::
20076 * OTHERS_In_Exception_Handlers::
20077 * Outer_Loop_Exits::
20078 * Overloaded_Operators::
20079 * Overly_Nested_Control_Structures::
20080 * Parameters_Out_Of_Order::
20081 * Positional_Actuals_For_Defaulted_Generic_Parameters::
20082 * Positional_Actuals_For_Defaulted_Parameters::
20083 * Positional_Components::
20084 * Positional_Generic_Parameters::
20085 * Positional_Parameters::
20086 * Predefined_Numeric_Types::
20087 * Raising_External_Exceptions::
20088 * Raising_Predefined_Exceptions::
20091 * Side_Effect_Functions::
20094 * Unassigned_OUT_Parameters::
20095 * Uncommented_BEGIN_In_Package_Bodies::
20096 * Unconstrained_Array_Returns::
20097 * Universal_Ranges::
20098 * Unnamed_Blocks_And_Loops::
20100 * Unused_Subprograms::
20102 * USE_PACKAGE_Clauses::
20103 * Volatile_Objects_Without_Address_Clauses::
20107 @node Abstract_Type_Declarations
20108 @subsection @code{Abstract_Type_Declarations}
20109 @cindex @code{Abstract_Type_Declarations} rule (for @command{gnatcheck})
20112 Flag all declarations of abstract types. For an abstract private
20113 type, both the private and full type declarations are flagged.
20115 This rule has no parameters.
20118 @node Anonymous_Arrays
20119 @subsection @code{Anonymous_Arrays}
20120 @cindex @code{Anonymous_Arrays} rule (for @command{gnatcheck})
20123 Flag all anonymous array type definitions (by Ada semantics these can only
20124 occur in object declarations).
20126 This rule has no parameters.
20128 @node Anonymous_Subtypes
20129 @subsection @code{Anonymous_Subtypes}
20130 @cindex @code{Anonymous_Subtypes} rule (for @command{gnatcheck})
20133 Flag all uses of anonymous subtypes. A use of an anonymous subtype is
20134 any instance of a subtype indication with a constraint, other than one
20135 that occurs immediately within a subtype declaration. Any use of a range
20136 other than as a constraint used immediately within a subtype declaration
20137 is considered as an anonymous subtype.
20139 An effect of this rule is that @code{for} loops such as the following are
20140 flagged (since @code{1..N} is formally a ``range''):
20142 @smallexample @c ada
20143 for I in 1 .. N loop
20149 Declaring an explicit subtype solves the problem:
20151 @smallexample @c ada
20152 subtype S is Integer range 1..N;
20160 This rule has no parameters.
20163 @subsection @code{Blocks}
20164 @cindex @code{Blocks} rule (for @command{gnatcheck})
20167 Flag each block statement.
20169 This rule has no parameters.
20171 @node Boolean_Relational_Operators
20172 @subsection @code{Boolean_Relational_Operators}
20173 @cindex @code{Boolean_Relational_Operators} rule (for @command{gnatcheck})
20176 Flag each call to a predefined relational operator (``<'', ``>'', ``<='',
20177 ``>='', ``='' and ``/='') for the predefined Boolean type.
20178 (This rule is useful in enforcing the SPARK language restrictions.)
20180 Calls to predefined relational operators of any type derived from
20181 @code{Standard.Boolean} are not detected. Calls to user-defined functions
20182 with these designators, and uses of operators that are renamings
20183 of the predefined relational operators for @code{Standard.Boolean},
20184 are likewise not detected.
20186 This rule has no parameters.
20189 @node Ceiling_Violations
20190 @subsection @code{Ceiling_Violations} (under construction, GLOBAL)
20191 @cindex @code{Ceiling_Violations} rule (for @command{gnatcheck})
20194 Flag invocations of a protected operation by a task whose priority exceeds
20195 the protected object's ceiling.
20197 As of @value{NOW}, this rule has the following limitations:
20202 We consider only pragmas Priority and Interrupt_Priority as means to define
20203 a task/protected operation priority. We do not consider the effect of using
20204 Ada.Dynamic_Priorities.Set_Priority procedure;
20207 We consider only base task priorities, and no priority inheritance. That is,
20208 we do not make a difference between calls issued during task activation and
20209 execution of the sequence of statements from task body;
20212 Any situation when the priority of protected operation caller is set by a
20213 dynamic expression (that is, the corresponding Priority or
20214 Interrupt_Priority pragma has a non-static expression as an argument) we
20215 treat as a priority inconsistency (and, therefore, detect this situation).
20219 At the moment the notion of the main subprogram is not implemented in
20220 gnatcheck, so any pragma Priority in a library level subprogram body (in case
20221 if this subprogram can be a main subprogram of a partition) changes the
20222 priority of an environment task. So if we have more then one such pragma in
20223 the set of processed sources, the pragma that is processed last, defines the
20224 priority of an environment task.
20226 This rule has no parameters.
20229 @node Controlled_Type_Declarations
20230 @subsection @code{Controlled_Type_Declarations}
20231 @cindex @code{Controlled_Type_Declarations} rule (for @command{gnatcheck})
20234 Flag all declarations of controlled types. A declaration of a private type
20235 is flagged if its full declaration declares a controlled type. A declaration
20236 of a derived type is flagged if its ancestor type is controlled. Subtype
20237 declarations are not checked. A declaration of a type that itself is not a
20238 descendant of a type declared in @code{Ada.Finalization} but has a controlled
20239 component is not checked.
20241 This rule has no parameters.
20245 @node Declarations_In_Blocks
20246 @subsection @code{Declarations_In_Blocks}
20247 @cindex @code{Declarations_In_Blocks} rule (for @command{gnatcheck})
20250 Flag all block statements containing local declarations. A @code{declare}
20251 block with an empty @i{declarative_part} or with a @i{declarative part}
20252 containing only pragmas and/or @code{use} clauses is not flagged.
20254 This rule has no parameters.
20257 @node Default_Parameters
20258 @subsection @code{Default_Parameters}
20259 @cindex @code{Default_Parameters} rule (for @command{gnatcheck})
20262 Flag all default expressions for subprogram parameters. Parameter
20263 declarations of formal and generic subprograms are also checked.
20265 This rule has no parameters.
20268 @node Discriminated_Records
20269 @subsection @code{Discriminated_Records}
20270 @cindex @code{Discriminated_Records} rule (for @command{gnatcheck})
20273 Flag all declarations of record types with discriminants. Only the
20274 declarations of record and record extension types are checked. Incomplete,
20275 formal, private, derived and private extension type declarations are not
20276 checked. Task and protected type declarations also are not checked.
20278 This rule has no parameters.
20281 @node Enumeration_Ranges_In_CASE_Statements
20282 @subsection @code{Enumeration_Ranges_In_CASE_Statements}
20283 @cindex @code{Enumeration_Ranges_In_CASE_Statements} (for @command{gnatcheck})
20286 Flag each use of a range of enumeration literals as a choice in a
20287 @code{case} statement.
20288 All forms for specifying a range (explicit ranges
20289 such as @code{A .. B}, subtype marks and @code{'Range} attributes) are flagged.
20290 An enumeration range is
20291 flagged even if contains exactly one enumeration value or no values at all. A
20292 type derived from an enumeration type is considered as an enumeration type.
20294 This rule helps prevent maintenance problems arising from adding an
20295 enumeration value to a type and having it implicitly handled by an existing
20296 @code{case} statement with an enumeration range that includes the new literal.
20298 This rule has no parameters.
20301 @node Exceptions_As_Control_Flow
20302 @subsection @code{Exceptions_As_Control_Flow}
20303 @cindex @code{Exceptions_As_Control_Flow} (for @command{gnatcheck})
20306 Flag each place where an exception is explicitly raised and handled in the
20307 same subprogram body. A @code{raise} statement in an exception handler,
20308 package body, task body or entry body is not flagged.
20310 The rule has no parameters.
20312 @node EXIT_Statements_With_No_Loop_Name
20313 @subsection @code{EXIT_Statements_With_No_Loop_Name}
20314 @cindex @code{EXIT_Statements_With_No_Loop_Name} (for @command{gnatcheck})
20317 Flag each @code{exit} statement that does not specify the name of the loop
20320 The rule has no parameters.
20323 @node Expanded_Loop_Exit_Names
20324 @subsection @code{Expanded_Loop_Exit_Names}
20325 @cindex @code{Expanded_Loop_Exit_Names} rule (for @command{gnatcheck})
20328 Flag all expanded loop names in @code{exit} statements.
20330 This rule has no parameters.
20332 @node Explicit_Full_Discrete_Ranges
20333 @subsection @code{Explicit_Full_Discrete_Ranges}
20334 @cindex @code{Explicit_Full_Discrete_Ranges} rule (for @command{gnatcheck})
20337 Flag each discrete range that has the form @code{A'First .. A'Last}.
20339 This rule has no parameters.
20341 @node Float_Equality_Checks
20342 @subsection @code{Float_Equality_Checks}
20343 @cindex @code{Float_Equality_Checks} rule (for @command{gnatcheck})
20346 Flag all calls to the predefined equality operations for floating-point types.
20347 Both ``@code{=}'' and ``@code{/=}'' operations are checked.
20348 User-defined equality operations are not flagged, nor are ``@code{=}''
20349 and ``@code{/=}'' operations for fixed-point types.
20351 This rule has no parameters.
20354 @node Forbidden_Pragmas
20355 @subsection @code{Forbidden_Pragmas}
20356 @cindex @code{Forbidden_Pragmas} rule (for @command{gnatcheck})
20359 Flag each use of the specified pragmas. The pragmas to be detected
20360 are named in the rule's parameters.
20362 This rule has the following parameters:
20365 @item For the @option{+R} option
20368 @item @emph{Pragma_Name}
20369 Adds the specified pragma to the set of pragmas to be
20370 checked and sets the checks for all the specified pragmas
20371 ON. @emph{Pragma_Name} is treated as a name of a pragma. If it
20372 does not correspond to any pragma name defined in the Ada
20373 standard or to the name of a GNAT-specific pragma defined
20374 in the GNAT Reference Manual, it is treated as the name of
20378 All the GNAT-specific pragmas are detected; this sets
20379 the checks for all the specified pragmas ON.
20382 All pragmas are detected; this sets the rule ON.
20385 @item For the @option{-R} option
20387 @item @emph{Pragma_Name}
20388 Removes the specified pragma from the set of pragmas to be
20389 checked without affecting checks for
20390 other pragmas. @emph{Pragma_Name} is treated as a name
20391 of a pragma. If it does not correspond to any pragma
20392 defined in the Ada standard or to any name defined in the
20393 GNAT Reference Manual,
20394 this option is treated as turning OFF detection of all
20398 Turn OFF detection of all GNAT-specific pragmas
20401 Clear the list of the pragmas to be detected and
20407 Parameters are not case sensitive. If @emph{Pragma_Name} does not have
20408 the syntax of an Ada identifier and therefore can not be considered
20409 as a pragma name, a diagnostic message is generated and the corresponding
20410 parameter is ignored.
20412 When more then one parameter is given in the same rule option, the parameters
20413 must be separated by a comma.
20415 If more then one option for this rule is specified for the @command{gnatcheck}
20416 call, a new option overrides the previous one(s).
20418 The @option{+R} option with no parameters turns the rule ON with the set of
20419 pragmas to be detected defined by the previous rule options.
20420 (By default this set is empty, so if the only option specified for the rule is
20421 @option{+RForbidden_Pragmas} (with
20422 no parameter), then the rule is enabled, but it does not detect anything).
20423 The @option{-R} option with no parameter turns the rule OFF, but it does not
20424 affect the set of pragmas to be detected.
20429 @node Function_Style_Procedures
20430 @subsection @code{Function_Style_Procedures}
20431 @cindex @code{Function_Style_Procedures} rule (for @command{gnatcheck})
20434 Flag each procedure that can be rewritten as a function. A procedure can be
20435 converted into a function if it has exactly one parameter of mode @code{out}
20436 and no parameters of mode @code{in out}. Procedure declarations,
20437 formal procedure declarations, and generic procedure declarations are always
20439 bodies and body stubs are flagged only if they do not have corresponding
20440 separate declarations. Procedure renamings and procedure instantiations are
20443 If a procedure can be rewritten as a function, but its @code{out} parameter is
20444 of a limited type, it is not flagged.
20446 Protected procedures are not flagged. Null procedures also are not flagged.
20448 This rule has no parameters.
20451 @node Generics_In_Subprograms
20452 @subsection @code{Generics_In_Subprograms}
20453 @cindex @code{Generics_In_Subprograms} rule (for @command{gnatcheck})
20456 Flag each declaration of a generic unit in a subprogram. Generic
20457 declarations in the bodies of generic subprograms are also flagged.
20458 A generic unit nested in another generic unit is not flagged.
20459 If a generic unit is
20460 declared in a local package that is declared in a subprogram body, the
20461 generic unit is flagged.
20463 This rule has no parameters.
20466 @node GOTO_Statements
20467 @subsection @code{GOTO_Statements}
20468 @cindex @code{GOTO_Statements} rule (for @command{gnatcheck})
20471 Flag each occurrence of a @code{goto} statement.
20473 This rule has no parameters.
20476 @node Implicit_IN_Mode_Parameters
20477 @subsection @code{Implicit_IN_Mode_Parameters}
20478 @cindex @code{Implicit_IN_Mode_Parameters} rule (for @command{gnatcheck})
20481 Flag each occurrence of a formal parameter with an implicit @code{in} mode.
20482 Note that @code{access} parameters, although they technically behave
20483 like @code{in} parameters, are not flagged.
20485 This rule has no parameters.
20488 @node Implicit_SMALL_For_Fixed_Point_Types
20489 @subsection @code{Implicit_SMALL_For_Fixed_Point_Types}
20490 @cindex @code{Implicit_SMALL_For_Fixed_Point_Types} rule (for @command{gnatcheck})
20493 Flag each fixed point type declaration that lacks an explicit
20494 representation clause to define its @code{'Small} value.
20495 Since @code{'Small} can be defined only for ordinary fixed point types,
20496 decimal fixed point type declarations are not checked.
20498 This rule has no parameters.
20501 @node Improperly_Located_Instantiations
20502 @subsection @code{Improperly_Located_Instantiations}
20503 @cindex @code{Improperly_Located_Instantiations} rule (for @command{gnatcheck})
20506 Flag all generic instantiations in library-level package specifications
20507 (including library generic packages) and in all subprogram bodies.
20509 Instantiations in task and entry bodies are not flagged. Instantiations in the
20510 bodies of protected subprograms are flagged.
20512 This rule has no parameters.
20516 @node Improper_Returns
20517 @subsection @code{Improper_Returns}
20518 @cindex @code{Improper_Returns} rule (for @command{gnatcheck})
20521 Flag each explicit @code{return} statement in procedures, and
20522 multiple @code{return} statements in functions.
20523 Diagnostic messages are generated for all @code{return} statements
20524 in a procedure (thus each procedure must be written so that it
20525 returns implicitly at the end of its statement part),
20526 and for all @code{return} statements in a function after the first one.
20527 This rule supports the stylistic convention that each subprogram
20528 should have no more than one point of normal return.
20530 This rule has no parameters.
20533 @node Library_Level_Subprograms
20534 @subsection @code{Library_Level_Subprograms}
20535 @cindex @code{Library_Level_Subprograms} rule (for @command{gnatcheck})
20538 Flag all library-level subprograms (including generic subprogram instantiations).
20540 This rule has no parameters.
20543 @node Local_Packages
20544 @subsection @code{Local_Packages}
20545 @cindex @code{Local_Packages} rule (for @command{gnatcheck})
20548 Flag all local packages declared in package and generic package
20550 Local packages in bodies are not flagged.
20552 This rule has no parameters.
20555 @node Improperly_Called_Protected_Entries
20556 @subsection @code{Improperly_Called_Protected_Entries} (under construction, GLOBAL)
20557 @cindex @code{Improperly_Called_Protected_Entries} rule (for @command{gnatcheck})
20560 Flag each protected entry that can be called from more than one task.
20562 This rule has no parameters.
20566 @node Misnamed_Identifiers
20567 @subsection @code{Misnamed_Identifiers}
20568 @cindex @code{Misnamed_Identifiers} rule (for @command{gnatcheck})
20571 Flag the declaration of each identifier that does not have a suffix
20572 corresponding to the kind of entity being declared.
20573 The following declarations are checked:
20580 constant declarations (but not number declarations)
20583 package renaming declarations (but not generic package renaming
20588 This rule may have parameters. When used without parameters, the rule enforces
20589 the following checks:
20593 type-defining names end with @code{_T}, unless the type is an access type,
20594 in which case the suffix must be @code{_A}
20596 constant names end with @code{_C}
20598 names defining package renamings end with @code{_R}
20602 For a private or incomplete type declaration the following checks are
20603 made for the defining name suffix:
20607 For an incomplete type declaration: if the corresponding full type
20608 declaration is available, the defining identifier from the full type
20609 declaration is checked, but the defining identifier from the incomplete type
20610 declaration is not; otherwise the defining identifier from the incomplete
20611 type declaration is checked against the suffix specified for type
20615 For a private type declaration (including private extensions), the defining
20616 identifier from the private type declaration is checked against the type
20617 suffix (even if the corresponding full declaration is an access type
20618 declaration), and the defining identifier from the corresponding full type
20619 declaration is not checked.
20623 For a deferred constant, the defining name in the corresponding full constant
20624 declaration is not checked.
20626 Defining names of formal types are not checked.
20628 The rule may have the following parameters:
20632 For the @option{+R} option:
20635 Sets the default listed above for all the names to be checked.
20637 @item Type_Suffix=@emph{string}
20638 Specifies the suffix for a type name.
20640 @item Access_Suffix=@emph{string}
20641 Specifies the suffix for an access type name. If
20642 this parameter is set, it overrides for access
20643 types the suffix set by the @code{Type_Suffix} parameter.
20645 @item Constant_Suffix=@emph{string}
20646 Specifies the suffix for a constant name.
20648 @item Renaming_Suffix=@emph{string}
20649 Specifies the suffix for a package renaming name.
20653 For the @option{-R} option:
20656 Remove all the suffixes specified for the
20657 identifier suffix checks, whether by default or
20658 as specified by other rule parameters. All the
20659 checks for this rule are disabled as a result.
20662 Removes the suffix specified for types. This
20663 disables checks for types but does not disable
20664 any other checks for this rule (including the
20665 check for access type names if @code{Access_Suffix} is
20668 @item Access_Suffix
20669 Removes the suffix specified for access types.
20670 This disables checks for access type names but
20671 does not disable any other checks for this rule.
20672 If @code{Type_Suffix} is set, access type names are
20673 checked as ordinary type names.
20675 @item Constant_Suffix
20676 Removes the suffix specified for constants. This
20677 disables checks for constant names but does not
20678 disable any other checks for this rule.
20680 @item Renaming_Suffix
20681 Removes the suffix specified for package
20682 renamings. This disables checks for package
20683 renamings but does not disable any other checks
20689 If more than one parameter is used, parameters must be separated by commas.
20691 If more than one option is specified for the @command{gnatcheck} invocation,
20692 a new option overrides the previous one(s).
20694 The @option{+RMisnamed_Identifiers} option (with no parameter) enables
20696 name suffixes specified by previous options used for this rule.
20698 The @option{-RMisnamed_Identifiers} option (with no parameter) disables
20699 all the checks but keeps
20700 all the suffixes specified by previous options used for this rule.
20702 The @emph{string} value must be a valid suffix for an Ada identifier (after
20703 trimming all the leading and trailing space characters, if any).
20704 Parameters are not case sensitive, except the @emph{string} part.
20706 If any error is detected in a rule parameter, the parameter is ignored.
20707 In such a case the options that are set for the rule are not
20712 @node Multiple_Entries_In_Protected_Definitions
20713 @subsection @code{Multiple_Entries_In_Protected_Definitions}
20714 @cindex @code{Multiple_Entries_In_Protected_Definitions} rule (for @command{gnatcheck})
20717 Flag each protected definition (i.e., each protected object/type declaration)
20718 that defines more than one entry.
20719 Diagnostic messages are generated for all the entry declarations
20720 except the first one. An entry family is counted as one entry. Entries from
20721 the private part of the protected definition are also checked.
20723 This rule has no parameters.
20726 @subsection @code{Name_Clashes}
20727 @cindex @code{Name_Clashes} rule (for @command{gnatcheck})
20730 Check that certain names are not used as defining identifiers. To activate
20731 this rule, you need to supply a reference to the dictionary file(s) as a rule
20732 parameter(s) (more then one dictionary file can be specified). If no
20733 dictionary file is set, this rule will not cause anything to be flagged.
20734 Only defining occurrences, not references, are checked.
20735 The check is not case-sensitive.
20737 This rule is enabled by default, but without setting any corresponding
20738 dictionary file(s); thus the default effect is to do no checks.
20740 A dictionary file is a plain text file. The maximum line length for this file
20741 is 1024 characters. If the line is longer then this limit, extra characters
20744 Each line can be either an empty line, a comment line, or a line containing
20745 a list of identifiers separated by space or HT characters.
20746 A comment is an Ada-style comment (from @code{--} to end-of-line).
20747 Identifiers must follow the Ada syntax for identifiers.
20748 A line containing one or more identifiers may end with a comment.
20750 @node Non_Qualified_Aggregates
20751 @subsection @code{Non_Qualified_Aggregates}
20752 @cindex @code{Non_Qualified_Aggregates} rule (for @command{gnatcheck})
20755 Flag each non-qualified aggregate.
20756 A non-qualified aggregate is an
20757 aggregate that is not the expression of a qualified expression. A
20758 string literal is not considered an aggregate, but an array
20759 aggregate of a string type is considered as a normal aggregate.
20760 Aggregates of anonymous array types are not flagged.
20762 This rule has no parameters.
20765 @node Non_Short_Circuit_Operators
20766 @subsection @code{Non_Short_Circuit_Operators}
20767 @cindex @code{Non_Short_Circuit_Operators} rule (for @command{gnatcheck})
20770 Flag all calls to predefined @code{and} and @code{or} operators for
20771 any boolean type. Calls to
20772 user-defined @code{and} and @code{or} and to operators defined by renaming
20773 declarations are not flagged. Calls to predefined @code{and} and @code{or}
20774 operators for modular types or boolean array types are not flagged.
20776 This rule has no parameters.
20780 @node Non_SPARK_Attributes
20781 @subsection @code{Non_SPARK_Attributes}
20782 @cindex @code{Non_SPARK_Attributes} rule (for @command{gnatcheck})
20785 The SPARK language defines the following subset of Ada 95 attribute
20786 designators as those that can be used in SPARK programs. The use of
20787 any other attribute is flagged.
20790 @item @code{'Adjacent}
20793 @item @code{'Ceiling}
20794 @item @code{'Component_Size}
20795 @item @code{'Compose}
20796 @item @code{'Copy_Sign}
20797 @item @code{'Delta}
20798 @item @code{'Denorm}
20799 @item @code{'Digits}
20800 @item @code{'Exponent}
20801 @item @code{'First}
20802 @item @code{'Floor}
20804 @item @code{'Fraction}
20806 @item @code{'Leading_Part}
20807 @item @code{'Length}
20808 @item @code{'Machine}
20809 @item @code{'Machine_Emax}
20810 @item @code{'Machine_Emin}
20811 @item @code{'Machine_Mantissa}
20812 @item @code{'Machine_Overflows}
20813 @item @code{'Machine_Radix}
20814 @item @code{'Machine_Rounds}
20817 @item @code{'Model}
20818 @item @code{'Model_Emin}
20819 @item @code{'Model_Epsilon}
20820 @item @code{'Model_Mantissa}
20821 @item @code{'Model_Small}
20822 @item @code{'Modulus}
20825 @item @code{'Range}
20826 @item @code{'Remainder}
20827 @item @code{'Rounding}
20828 @item @code{'Safe_First}
20829 @item @code{'Safe_Last}
20830 @item @code{'Scaling}
20831 @item @code{'Signed_Zeros}
20833 @item @code{'Small}
20835 @item @code{'Truncation}
20836 @item @code{'Unbiased_Rounding}
20838 @item @code{'Valid}
20842 This rule has no parameters.
20845 @node Non_Tagged_Derived_Types
20846 @subsection @code{Non_Tagged_Derived_Types}
20847 @cindex @code{Non_Tagged_Derived_Types} rule (for @command{gnatcheck})
20850 Flag all derived type declarations that do not have a record extension part.
20852 This rule has no parameters.
20856 @node Non_Visible_Exceptions
20857 @subsection @code{Non_Visible_Exceptions}
20858 @cindex @code{Non_Visible_Exceptions} rule (for @command{gnatcheck})
20861 Flag constructs leading to the possibility of propagating an exception
20862 out of the scope in which the exception is declared.
20863 Two cases are detected:
20867 An exception declaration in a subprogram body, task body or block
20868 statement is flagged if the body or statement does not contain a handler for
20869 that exception or a handler with an @code{others} choice.
20872 A @code{raise} statement in an exception handler of a subprogram body,
20873 task body or block statement is flagged if it (re)raises a locally
20874 declared exception. This may occur under the following circumstances:
20877 it explicitly raises a locally declared exception, or
20879 it does not specify an exception name (i.e., it is simply @code{raise;})
20880 and the enclosing handler contains a locally declared exception in its
20886 Renamings of local exceptions are not flagged.
20888 This rule has no parameters.
20891 @node Numeric_Literals
20892 @subsection @code{Numeric_Literals}
20893 @cindex @code{Numeric_Literals} rule (for @command{gnatcheck})
20896 Flag each use of a numeric literal in an index expression, and in any
20897 circumstance except for the following:
20901 a literal occurring in the initialization expression for a constant
20902 declaration or a named number declaration, or
20905 an integer literal that is less than or equal to a value
20906 specified by the @option{N} rule parameter.
20910 This rule may have the following parameters for the @option{+R} option:
20914 @emph{N} is an integer literal used as the maximal value that is not flagged
20915 (i.e., integer literals not exceeding this value are allowed)
20918 All integer literals are flagged
20922 If no parameters are set, the maximum unflagged value is 1.
20924 The last specified check limit (or the fact that there is no limit at
20925 all) is used when multiple @option{+R} options appear.
20927 The @option{-R} option for this rule has no parameters.
20928 It disables the rule but retains the last specified maximum unflagged value.
20929 If the @option{+R} option subsequently appears, this value is used as the
20930 threshold for the check.
20933 @node OTHERS_In_Aggregates
20934 @subsection @code{OTHERS_In_Aggregates}
20935 @cindex @code{OTHERS_In_Aggregates} rule (for @command{gnatcheck})
20938 Flag each use of an @code{others} choice in extension aggregates.
20939 In record and array aggregates, an @code{others} choice is flagged unless
20940 it is used to refer to all components, or to all but one component.
20942 If, in case of a named array aggregate, there are two associations, one
20943 with an @code{others} choice and another with a discrete range, the
20944 @code{others} choice is flagged even if the discrete range specifies
20945 exactly one component; for example, @code{(1..1 => 0, others => 1)}.
20947 This rule has no parameters.
20949 @node OTHERS_In_CASE_Statements
20950 @subsection @code{OTHERS_In_CASE_Statements}
20951 @cindex @code{OTHERS_In_CASE_Statements} rule (for @command{gnatcheck})
20954 Flag any use of an @code{others} choice in a @code{case} statement.
20956 This rule has no parameters.
20958 @node OTHERS_In_Exception_Handlers
20959 @subsection @code{OTHERS_In_Exception_Handlers}
20960 @cindex @code{OTHERS_In_Exception_Handlers} rule (for @command{gnatcheck})
20963 Flag any use of an @code{others} choice in an exception handler.
20965 This rule has no parameters.
20968 @node Outer_Loop_Exits
20969 @subsection @code{Outer_Loop_Exits}
20970 @cindex @code{Outer_Loop_Exits} rule (for @command{gnatcheck})
20973 Flag each @code{exit} statement containing a loop name that is not the name
20974 of the immediately enclosing @code{loop} statement.
20976 This rule has no parameters.
20979 @node Overloaded_Operators
20980 @subsection @code{Overloaded_Operators}
20981 @cindex @code{Overloaded_Operators} rule (for @command{gnatcheck})
20984 Flag each function declaration that overloads an operator symbol.
20985 A function body is checked only if the body does not have a
20986 separate spec. Formal functions are also checked. For a
20987 renaming declaration, only renaming-as-declaration is checked
20989 This rule has no parameters.
20992 @node Overly_Nested_Control_Structures
20993 @subsection @code{Overly_Nested_Control_Structures}
20994 @cindex @code{Overly_Nested_Control_Structures} rule (for @command{gnatcheck})
20997 Flag each control structure whose nesting level exceeds the value provided
20998 in the rule parameter.
21000 The control structures checked are the following:
21003 @item @code{if} statement
21004 @item @code{case} statement
21005 @item @code{loop} statement
21006 @item Selective accept statement
21007 @item Timed entry call statement
21008 @item Conditional entry call
21009 @item Asynchronous select statement
21013 The rule may have the following parameter for the @option{+R} option:
21017 Positive integer specifying the maximal control structure nesting
21018 level that is not flagged
21022 If the parameter for the @option{+R} option is not a positive integer,
21023 the parameter is ignored and the rule is turned ON with the most recently
21024 specified maximal non-flagged nesting level.
21026 If more then one option is specified for the gnatcheck call, the later option and
21027 new parameter override the previous one(s).
21029 A @option{+R} option with no parameter turns the rule ON using the maximal
21030 non-flagged nesting level specified by the most recent @option{+R} option with
21031 a parameter, or the value 4 if there is no such previous @option{+R} option.
21035 @node Parameters_Out_Of_Order
21036 @subsection @code{Parameters_Out_Of_Order}
21037 @cindex @code{Parameters_Out_Of_Order} rule (for @command{gnatcheck})
21040 Flag each subprogram and entry declaration whose formal parameters are not
21041 ordered according to the following scheme:
21045 @item @code{in} and @code{access} parameters first,
21046 then @code{in out} parameters,
21047 and then @code{out} parameters;
21049 @item for @code{in} mode, parameters with default initialization expressions
21054 Only the first violation of the described order is flagged.
21056 The following constructs are checked:
21059 @item subprogram declarations (including null procedures);
21060 @item generic subprogram declarations;
21061 @item formal subprogram declarations;
21062 @item entry declarations;
21063 @item subprogram bodies and subprogram body stubs that do not
21064 have separate specifications
21068 Subprogram renamings are not checked.
21070 This rule has no parameters.
21073 @node Positional_Actuals_For_Defaulted_Generic_Parameters
21074 @subsection @code{Positional_Actuals_For_Defaulted_Generic_Parameters}
21075 @cindex @code{Positional_Actuals_For_Defaulted_Generic_Parameters} rule (for @command{gnatcheck})
21078 Flag each generic actual parameter corresponding to a generic formal
21079 parameter with a default initialization, if positional notation is used.
21081 This rule has no parameters.
21083 @node Positional_Actuals_For_Defaulted_Parameters
21084 @subsection @code{Positional_Actuals_For_Defaulted_Parameters}
21085 @cindex @code{Positional_Actuals_For_Defaulted_Parameters} rule (for @command{gnatcheck})
21088 Flag each actual parameter to a subprogram or entry call where the
21089 corresponding formal parameter has a default expression, if positional
21092 This rule has no parameters.
21094 @node Positional_Components
21095 @subsection @code{Positional_Components}
21096 @cindex @code{Positional_Components} rule (for @command{gnatcheck})
21099 Flag each array, record and extension aggregate that includes positional
21102 This rule has no parameters.
21105 @node Positional_Generic_Parameters
21106 @subsection @code{Positional_Generic_Parameters}
21107 @cindex @code{Positional_Generic_Parameters} rule (for @command{gnatcheck})
21110 Flag each instantiation using positional parameter notation.
21112 This rule has no parameters.
21115 @node Positional_Parameters
21116 @subsection @code{Positional_Parameters}
21117 @cindex @code{Positional_Parameters} rule (for @command{gnatcheck})
21120 Flag each subprogram or entry call using positional parameter notation,
21121 except for the following:
21125 Invocations of prefix or infix operators are not flagged
21127 If the called subprogram or entry has only one formal parameter,
21128 the call is not flagged;
21130 If a subprogram call uses the @emph{Object.Operation} notation, then
21133 the first parameter (that is, @emph{Object}) is not flagged;
21135 if the called subprogram has only two parameters, the second parameter
21136 of the call is not flagged;
21141 This rule has no parameters.
21146 @node Predefined_Numeric_Types
21147 @subsection @code{Predefined_Numeric_Types}
21148 @cindex @code{Predefined_Numeric_Types} rule (for @command{gnatcheck})
21151 Flag each explicit use of the name of any numeric type or subtype defined
21152 in package @code{Standard}.
21154 The rationale for this rule is to detect when the
21155 program may depend on platform-specific characteristics of the implementation
21156 of the predefined numeric types. Note that this rule is over-pessimistic;
21157 for example, a program that uses @code{String} indexing
21158 likely needs a variable of type @code{Integer}.
21159 Another example is the flagging of predefined numeric types with explicit
21162 @smallexample @c ada
21163 subtype My_Integer is Integer range Left .. Right;
21164 Vy_Var : My_Integer;
21168 This rule detects only numeric types and subtypes defined in
21169 @code{Standard}. The use of numeric types and subtypes defined in other
21170 predefined packages (such as @code{System.Any_Priority} or
21171 @code{Ada.Text_IO.Count}) is not flagged
21173 This rule has no parameters.
21177 @node Raising_External_Exceptions
21178 @subsection @code{Raising_External_Exceptions}
21179 @cindex @code{Raising_External_Exceptions} rule (for @command{gnatcheck})
21182 Flag any @code{raise} statement, in a program unit declared in a library
21183 package or in a generic library package, for an exception that is
21184 neither a predefined exception nor an exception that is also declared (or
21185 renamed) in the visible part of the package.
21187 This rule has no parameters.
21191 @node Raising_Predefined_Exceptions
21192 @subsection @code{Raising_Predefined_Exceptions}
21193 @cindex @code{Raising_Predefined_Exceptions} rule (for @command{gnatcheck})
21196 Flag each @code{raise} statement that raises a predefined exception
21197 (i.e., one of the exceptions @code{Constraint_Error}, @code{Numeric_Error},
21198 @code{Program_Error}, @code{Storage_Error}, or @code{Tasking_Error}).
21200 This rule has no parameters.
21205 @subsection @code{Recursion} (under construction, GLOBAL)
21206 @cindex @code{Recursion} rule (for @command{gnatcheck})
21209 Flag recursive subprograms (cycles in the call graph). Declarations, and not
21210 calls, of recursive subprograms are detected.
21212 This rule has no parameters.
21216 @node Side_Effect_Functions
21217 @subsection @code{Side_Effect_Functions} (under construction, GLOBAL)
21218 @cindex @code{Side_Effect_Functions} rule (for @command{gnatcheck})
21221 Flag functions with side effects.
21223 We define a side effect as changing any data object that is not local for the
21224 body of this function.
21226 At the moment, we do NOT consider a side effect any input-output operations
21227 (changing a state or a content of any file).
21229 We do not consider protected functions for this rule (???)
21231 There are the following sources of side effect:
21234 @item Explicit (or direct) side-effect:
21238 direct assignment to a non-local variable;
21241 direct call to an entity that is known to change some data object that is
21242 not local for the body of this function (Note, that if F1 calls F2 and F2
21243 does have a side effect, this does not automatically mean that F1 also
21244 have a side effect, because it may be the case that F2 is declared in
21245 F1's body and it changes some data object that is global for F2, but
21249 @item Indirect side-effect:
21252 Subprogram calls implicitly issued by:
21255 computing initialization expressions from type declarations as a part
21256 of object elaboration or allocator evaluation;
21258 computing implicit parameters of subprogram or entry calls or generic
21263 activation of a task that change some non-local data object (directly or
21267 elaboration code of a package that is a result of a package instantiation;
21270 controlled objects;
21273 @item Situations when we can suspect a side-effect, but the full static check
21274 is either impossible or too hard:
21277 assignment to access variables or to the objects pointed by access
21281 call to a subprogram pointed by access-to-subprogram value
21289 This rule has no parameters.
21293 @subsection @code{Slices}
21294 @cindex @code{Slices} rule (for @command{gnatcheck})
21297 Flag all uses of array slicing
21299 This rule has no parameters.
21302 @node Unassigned_OUT_Parameters
21303 @subsection @code{Unassigned_OUT_Parameters}
21304 @cindex @code{Unassigned_OUT_Parameters} rule (for @command{gnatcheck})
21307 Flags procedures' @code{out} parameters that are not assigned, and
21308 identifies the contexts in which the assignments are missing.
21310 An @code{out} parameter is flagged in the statements in the procedure
21311 body's handled sequence of statements (before the procedure body's
21312 @code{exception} part, if any) if this sequence of statements contains
21313 no assignments to the parameter.
21315 An @code{out} parameter is flagged in an exception handler in the exception
21316 part of the procedure body's handled sequence of statements if the handler
21317 contains no assignment to the parameter.
21319 Bodies of generic procedures are also considered.
21321 The following are treated as assignments to an @code{out} parameter:
21325 an assignment statement, with the parameter or some component as the target;
21328 passing the parameter (or one of its components) as an @code{out} or
21329 @code{in out} parameter.
21333 This rule does not have any parameters.
21337 @node Uncommented_BEGIN_In_Package_Bodies
21338 @subsection @code{Uncommented_BEGIN_In_Package_Bodies}
21339 @cindex @code{Uncommented_BEGIN_In_Package_Bodies} rule (for @command{gnatcheck})
21342 Flags each package body with declarations and a statement part that does not
21343 include a trailing comment on the line containing the @code{begin} keyword;
21344 this trailing comment needs to specify the package name and nothing else.
21345 The @code{begin} is not flagged if the package body does not
21346 contain any declarations.
21348 If the @code{begin} keyword is placed on the
21349 same line as the last declaration or the first statement, it is flagged
21350 independently of whether the line contains a trailing comment. The
21351 diagnostic message is attached to the line containing the first statement.
21353 This rule has no parameters.
21356 @node Unconstrained_Array_Returns
21357 @subsection @code{Unconstrained_Array_Returns}
21358 @cindex @code{Unconstrained_Array_Returns} rule (for @command{gnatcheck})
21361 Flag each function returning an unconstrained array. Function declarations,
21362 function bodies (and body stubs) having no separate specifications,
21363 and generic function instantiations are checked.
21364 Generic function declarations, function calls and function renamings are
21367 This rule has no parameters.
21369 @node Universal_Ranges
21370 @subsection @code{Universal_Ranges}
21371 @cindex @code{Universal_Ranges} rule (for @command{gnatcheck})
21374 Flag discrete ranges that are a part of an index constraint, constrained
21375 array definition, or @code{for}-loop parameter specification, and whose bounds
21376 are both of type @i{universal_integer}. Ranges that have at least one
21377 bound of a specific type (such as @code{1 .. N}, where @code{N} is a variable
21378 or an expression of non-universal type) are not flagged.
21380 This rule has no parameters.
21383 @node Unnamed_Blocks_And_Loops
21384 @subsection @code{Unnamed_Blocks_And_Loops}
21385 @cindex @code{Unnamed_Blocks_And_Loops} rule (for @command{gnatcheck})
21388 Flag each unnamed block statement and loop statement.
21390 The rule has no parameters.
21395 @node Unused_Subprograms
21396 @subsection @code{Unused_Subprograms} (under construction, GLOBAL)
21397 @cindex @code{Unused_Subprograms} rule (for @command{gnatcheck})
21400 Flag all unused subprograms.
21402 This rule has no parameters.
21408 @node USE_PACKAGE_Clauses
21409 @subsection @code{USE_PACKAGE_Clauses}
21410 @cindex @code{USE_PACKAGE_Clauses} rule (for @command{gnatcheck})
21413 Flag all @code{use} clauses for packages; @code{use type} clauses are
21416 This rule has no parameters.
21420 @node Volatile_Objects_Without_Address_Clauses
21421 @subsection @code{Volatile_Objects_Without_Address_Clauses}
21422 @cindex @code{Volatile_Objects_Without_Address_Clauses} rule (for @command{gnatcheck})
21425 Flag each volatile object that does not have an address clause.
21427 The following check is made: if the pragma @code{Volatile} is applied to a
21428 data object or to its type, then an address clause must
21429 be supplied for this object.
21431 This rule does not check the components of data objects,
21432 array components that are volatile as a result of the pragma
21433 @code{Volatile_Components}, or objects that are volatile because
21434 they are atomic as a result of pragmas @code{Atomic} or
21435 @code{Atomic_Components}.
21437 Only variable declarations, and not constant declarations, are checked.
21439 This rule has no parameters.
21442 @c *********************************
21443 @node Creating Sample Bodies Using gnatstub
21444 @chapter Creating Sample Bodies Using @command{gnatstub}
21448 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
21449 for library unit declarations.
21451 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
21452 driver (see @ref{The GNAT Driver and Project Files}).
21454 To create a body stub, @command{gnatstub} has to compile the library
21455 unit declaration. Therefore, bodies can be created only for legal
21456 library units. Moreover, if a library unit depends semantically upon
21457 units located outside the current directory, you have to provide
21458 the source search path when calling @command{gnatstub}, see the description
21459 of @command{gnatstub} switches below.
21462 * Running gnatstub::
21463 * Switches for gnatstub::
21466 @node Running gnatstub
21467 @section Running @command{gnatstub}
21470 @command{gnatstub} has the command-line interface of the form
21473 $ gnatstub [switches] filename [directory]
21480 is the name of the source file that contains a library unit declaration
21481 for which a body must be created. The file name may contain the path
21483 The file name does not have to follow the GNAT file name conventions. If the
21485 does not follow GNAT file naming conventions, the name of the body file must
21487 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
21488 If the file name follows the GNAT file naming
21489 conventions and the name of the body file is not provided,
21492 of the body file from the argument file name by replacing the @file{.ads}
21494 with the @file{.adb} suffix.
21497 indicates the directory in which the body stub is to be placed (the default
21502 is an optional sequence of switches as described in the next section
21505 @node Switches for gnatstub
21506 @section Switches for @command{gnatstub}
21512 @cindex @option{^-f^/FULL^} (@command{gnatstub})
21513 If the destination directory already contains a file with the name of the
21515 for the argument spec file, replace it with the generated body stub.
21517 @item ^-hs^/HEADER=SPEC^
21518 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
21519 Put the comment header (i.e., all the comments preceding the
21520 compilation unit) from the source of the library unit declaration
21521 into the body stub.
21523 @item ^-hg^/HEADER=GENERAL^
21524 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
21525 Put a sample comment header into the body stub.
21529 @cindex @option{-IDIR} (@command{gnatstub})
21531 @cindex @option{-I-} (@command{gnatstub})
21534 @item /NOCURRENT_DIRECTORY
21535 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
21537 ^These switches have ^This switch has^ the same meaning as in calls to
21539 ^They define ^It defines ^ the source search path in the call to
21540 @command{gcc} issued
21541 by @command{gnatstub} to compile an argument source file.
21543 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
21544 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
21545 This switch has the same meaning as in calls to @command{gcc}.
21546 It defines the additional configuration file to be passed to the call to
21547 @command{gcc} issued
21548 by @command{gnatstub} to compile an argument source file.
21550 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
21551 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
21552 (@var{n} is a non-negative integer). Set the maximum line length in the
21553 body stub to @var{n}; the default is 79. The maximum value that can be
21554 specified is 32767. Note that in the special case of configuration
21555 pragma files, the maximum is always 32767 regardless of whether or
21556 not this switch appears.
21558 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
21559 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
21560 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
21561 the generated body sample to @var{n}.
21562 The default indentation is 3.
21564 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
21565 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
21566 Order local bodies alphabetically. (By default local bodies are ordered
21567 in the same way as the corresponding local specs in the argument spec file.)
21569 @item ^-i^/INDENTATION=^@var{n}
21570 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
21571 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
21573 @item ^-k^/TREE_FILE=SAVE^
21574 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
21575 Do not remove the tree file (i.e., the snapshot of the compiler internal
21576 structures used by @command{gnatstub}) after creating the body stub.
21578 @item ^-l^/LINE_LENGTH=^@var{n}
21579 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
21580 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
21582 @item ^-o^/BODY=^@var{body-name}
21583 @cindex @option{^-o^/BODY^} (@command{gnatstub})
21584 Body file name. This should be set if the argument file name does not
21586 the GNAT file naming
21587 conventions. If this switch is omitted the default name for the body will be
21589 from the argument file name according to the GNAT file naming conventions.
21592 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
21593 Quiet mode: do not generate a confirmation when a body is
21594 successfully created, and do not generate a message when a body is not
21598 @item ^-r^/TREE_FILE=REUSE^
21599 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
21600 Reuse the tree file (if it exists) instead of creating it. Instead of
21601 creating the tree file for the library unit declaration, @command{gnatstub}
21602 tries to find it in the current directory and use it for creating
21603 a body. If the tree file is not found, no body is created. This option
21604 also implies @option{^-k^/SAVE^}, whether or not
21605 the latter is set explicitly.
21607 @item ^-t^/TREE_FILE=OVERWRITE^
21608 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
21609 Overwrite the existing tree file. If the current directory already
21610 contains the file which, according to the GNAT file naming rules should
21611 be considered as a tree file for the argument source file,
21613 will refuse to create the tree file needed to create a sample body
21614 unless this option is set.
21616 @item ^-v^/VERBOSE^
21617 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
21618 Verbose mode: generate version information.
21622 @node Other Utility Programs
21623 @chapter Other Utility Programs
21626 This chapter discusses some other utility programs available in the Ada
21630 * Using Other Utility Programs with GNAT::
21631 * The External Symbol Naming Scheme of GNAT::
21632 * Converting Ada Files to html with gnathtml::
21633 * Installing gnathtml::
21640 @node Using Other Utility Programs with GNAT
21641 @section Using Other Utility Programs with GNAT
21644 The object files generated by GNAT are in standard system format and in
21645 particular the debugging information uses this format. This means
21646 programs generated by GNAT can be used with existing utilities that
21647 depend on these formats.
21650 In general, any utility program that works with C will also often work with
21651 Ada programs generated by GNAT. This includes software utilities such as
21652 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
21656 @node The External Symbol Naming Scheme of GNAT
21657 @section The External Symbol Naming Scheme of GNAT
21660 In order to interpret the output from GNAT, when using tools that are
21661 originally intended for use with other languages, it is useful to
21662 understand the conventions used to generate link names from the Ada
21665 All link names are in all lowercase letters. With the exception of library
21666 procedure names, the mechanism used is simply to use the full expanded
21667 Ada name with dots replaced by double underscores. For example, suppose
21668 we have the following package spec:
21670 @smallexample @c ada
21681 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
21682 the corresponding link name is @code{qrs__mn}.
21684 Of course if a @code{pragma Export} is used this may be overridden:
21686 @smallexample @c ada
21691 pragma Export (Var1, C, External_Name => "var1_name");
21693 pragma Export (Var2, C, Link_Name => "var2_link_name");
21700 In this case, the link name for @var{Var1} is whatever link name the
21701 C compiler would assign for the C function @var{var1_name}. This typically
21702 would be either @var{var1_name} or @var{_var1_name}, depending on operating
21703 system conventions, but other possibilities exist. The link name for
21704 @var{Var2} is @var{var2_link_name}, and this is not operating system
21708 One exception occurs for library level procedures. A potential ambiguity
21709 arises between the required name @code{_main} for the C main program,
21710 and the name we would otherwise assign to an Ada library level procedure
21711 called @code{Main} (which might well not be the main program).
21713 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
21714 names. So if we have a library level procedure such as
21716 @smallexample @c ada
21719 procedure Hello (S : String);
21725 the external name of this procedure will be @var{_ada_hello}.
21728 @node Converting Ada Files to html with gnathtml
21729 @section Converting Ada Files to HTML with @code{gnathtml}
21732 This @code{Perl} script allows Ada source files to be browsed using
21733 standard Web browsers. For installation procedure, see the section
21734 @xref{Installing gnathtml}.
21736 Ada reserved keywords are highlighted in a bold font and Ada comments in
21737 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
21738 switch to suppress the generation of cross-referencing information, user
21739 defined variables and types will appear in a different color; you will
21740 be able to click on any identifier and go to its declaration.
21742 The command line is as follow:
21744 $ perl gnathtml.pl [^switches^options^] ada-files
21748 You can pass it as many Ada files as you want. @code{gnathtml} will generate
21749 an html file for every ada file, and a global file called @file{index.htm}.
21750 This file is an index of every identifier defined in the files.
21752 The available ^switches^options^ are the following ones:
21756 @cindex @option{-83} (@code{gnathtml})
21757 Only the Ada 83 subset of keywords will be highlighted.
21759 @item -cc @var{color}
21760 @cindex @option{-cc} (@code{gnathtml})
21761 This option allows you to change the color used for comments. The default
21762 value is green. The color argument can be any name accepted by html.
21765 @cindex @option{-d} (@code{gnathtml})
21766 If the Ada files depend on some other files (for instance through
21767 @code{with} clauses, the latter files will also be converted to html.
21768 Only the files in the user project will be converted to html, not the files
21769 in the run-time library itself.
21772 @cindex @option{-D} (@code{gnathtml})
21773 This command is the same as @option{-d} above, but @command{gnathtml} will
21774 also look for files in the run-time library, and generate html files for them.
21776 @item -ext @var{extension}
21777 @cindex @option{-ext} (@code{gnathtml})
21778 This option allows you to change the extension of the generated HTML files.
21779 If you do not specify an extension, it will default to @file{htm}.
21782 @cindex @option{-f} (@code{gnathtml})
21783 By default, gnathtml will generate html links only for global entities
21784 ('with'ed units, global variables and types,...). If you specify
21785 @option{-f} on the command line, then links will be generated for local
21788 @item -l @var{number}
21789 @cindex @option{-l} (@code{gnathtml})
21790 If this ^switch^option^ is provided and @var{number} is not 0, then
21791 @code{gnathtml} will number the html files every @var{number} line.
21794 @cindex @option{-I} (@code{gnathtml})
21795 Specify a directory to search for library files (@file{.ALI} files) and
21796 source files. You can provide several -I switches on the command line,
21797 and the directories will be parsed in the order of the command line.
21800 @cindex @option{-o} (@code{gnathtml})
21801 Specify the output directory for html files. By default, gnathtml will
21802 saved the generated html files in a subdirectory named @file{html/}.
21804 @item -p @var{file}
21805 @cindex @option{-p} (@code{gnathtml})
21806 If you are using Emacs and the most recent Emacs Ada mode, which provides
21807 a full Integrated Development Environment for compiling, checking,
21808 running and debugging applications, you may use @file{.gpr} files
21809 to give the directories where Emacs can find sources and object files.
21811 Using this ^switch^option^, you can tell gnathtml to use these files.
21812 This allows you to get an html version of your application, even if it
21813 is spread over multiple directories.
21815 @item -sc @var{color}
21816 @cindex @option{-sc} (@code{gnathtml})
21817 This ^switch^option^ allows you to change the color used for symbol
21819 The default value is red. The color argument can be any name accepted by html.
21821 @item -t @var{file}
21822 @cindex @option{-t} (@code{gnathtml})
21823 This ^switch^option^ provides the name of a file. This file contains a list of
21824 file names to be converted, and the effect is exactly as though they had
21825 appeared explicitly on the command line. This
21826 is the recommended way to work around the command line length limit on some
21831 @node Installing gnathtml
21832 @section Installing @code{gnathtml}
21835 @code{Perl} needs to be installed on your machine to run this script.
21836 @code{Perl} is freely available for almost every architecture and
21837 Operating System via the Internet.
21839 On Unix systems, you may want to modify the first line of the script
21840 @code{gnathtml}, to explicitly tell the Operating system where Perl
21841 is. The syntax of this line is:
21843 #!full_path_name_to_perl
21847 Alternatively, you may run the script using the following command line:
21850 $ perl gnathtml.pl [switches] files
21859 The GNAT distribution provides an Ada 95 template for the HP Language
21860 Sensitive Editor (LSE), a component of DECset. In order to
21861 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
21868 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
21869 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
21870 the collection phase with the /DEBUG qualifier.
21873 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
21874 $ DEFINE LIB$DEBUG PCA$COLLECTOR
21875 $ RUN/DEBUG <PROGRAM_NAME>
21880 @node Running and Debugging Ada Programs
21881 @chapter Running and Debugging Ada Programs
21885 This chapter discusses how to debug Ada programs.
21887 It applies to GNAT on the Alpha OpenVMS platform;
21888 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
21889 since HP has implemented Ada support in the OpenVMS debugger on I64.
21892 An incorrect Ada program may be handled in three ways by the GNAT compiler:
21896 The illegality may be a violation of the static semantics of Ada. In
21897 that case GNAT diagnoses the constructs in the program that are illegal.
21898 It is then a straightforward matter for the user to modify those parts of
21902 The illegality may be a violation of the dynamic semantics of Ada. In
21903 that case the program compiles and executes, but may generate incorrect
21904 results, or may terminate abnormally with some exception.
21907 When presented with a program that contains convoluted errors, GNAT
21908 itself may terminate abnormally without providing full diagnostics on
21909 the incorrect user program.
21913 * The GNAT Debugger GDB::
21915 * Introduction to GDB Commands::
21916 * Using Ada Expressions::
21917 * Calling User-Defined Subprograms::
21918 * Using the Next Command in a Function::
21921 * Debugging Generic Units::
21922 * GNAT Abnormal Termination or Failure to Terminate::
21923 * Naming Conventions for GNAT Source Files::
21924 * Getting Internal Debugging Information::
21925 * Stack Traceback::
21931 @node The GNAT Debugger GDB
21932 @section The GNAT Debugger GDB
21935 @code{GDB} is a general purpose, platform-independent debugger that
21936 can be used to debug mixed-language programs compiled with @command{gcc},
21937 and in particular is capable of debugging Ada programs compiled with
21938 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
21939 complex Ada data structures.
21941 The manual @cite{Debugging with GDB}
21943 , located in the GNU:[DOCS] directory,
21945 contains full details on the usage of @code{GDB}, including a section on
21946 its usage on programs. This manual should be consulted for full
21947 details. The section that follows is a brief introduction to the
21948 philosophy and use of @code{GDB}.
21950 When GNAT programs are compiled, the compiler optionally writes debugging
21951 information into the generated object file, including information on
21952 line numbers, and on declared types and variables. This information is
21953 separate from the generated code. It makes the object files considerably
21954 larger, but it does not add to the size of the actual executable that
21955 will be loaded into memory, and has no impact on run-time performance. The
21956 generation of debug information is triggered by the use of the
21957 ^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out
21958 the compilations. It is important to emphasize that the use of these
21959 options does not change the generated code.
21961 The debugging information is written in standard system formats that
21962 are used by many tools, including debuggers and profilers. The format
21963 of the information is typically designed to describe C types and
21964 semantics, but GNAT implements a translation scheme which allows full
21965 details about Ada types and variables to be encoded into these
21966 standard C formats. Details of this encoding scheme may be found in
21967 the file exp_dbug.ads in the GNAT source distribution. However, the
21968 details of this encoding are, in general, of no interest to a user,
21969 since @code{GDB} automatically performs the necessary decoding.
21971 When a program is bound and linked, the debugging information is
21972 collected from the object files, and stored in the executable image of
21973 the program. Again, this process significantly increases the size of
21974 the generated executable file, but it does not increase the size of
21975 the executable program itself. Furthermore, if this program is run in
21976 the normal manner, it runs exactly as if the debug information were
21977 not present, and takes no more actual memory.
21979 However, if the program is run under control of @code{GDB}, the
21980 debugger is activated. The image of the program is loaded, at which
21981 point it is ready to run. If a run command is given, then the program
21982 will run exactly as it would have if @code{GDB} were not present. This
21983 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
21984 entirely non-intrusive until a breakpoint is encountered. If no
21985 breakpoint is ever hit, the program will run exactly as it would if no
21986 debugger were present. When a breakpoint is hit, @code{GDB} accesses
21987 the debugging information and can respond to user commands to inspect
21988 variables, and more generally to report on the state of execution.
21992 @section Running GDB
21995 This section describes how to initiate the debugger.
21996 @c The above sentence is really just filler, but it was otherwise
21997 @c clumsy to get the first paragraph nonindented given the conditional
21998 @c nature of the description
22001 The debugger can be launched from a @code{GPS} menu or
22002 directly from the command line. The description below covers the latter use.
22003 All the commands shown can be used in the @code{GPS} debug console window,
22004 but there are usually more GUI-based ways to achieve the same effect.
22007 The command to run @code{GDB} is
22010 $ ^gdb program^GDB PROGRAM^
22014 where @code{^program^PROGRAM^} is the name of the executable file. This
22015 activates the debugger and results in a prompt for debugger commands.
22016 The simplest command is simply @code{run}, which causes the program to run
22017 exactly as if the debugger were not present. The following section
22018 describes some of the additional commands that can be given to @code{GDB}.
22020 @c *******************************
22021 @node Introduction to GDB Commands
22022 @section Introduction to GDB Commands
22025 @code{GDB} contains a large repertoire of commands. The manual
22026 @cite{Debugging with GDB}
22028 (located in the GNU:[DOCS] directory)
22030 includes extensive documentation on the use
22031 of these commands, together with examples of their use. Furthermore,
22032 the command @var{help} invoked from within @code{GDB} activates a simple help
22033 facility which summarizes the available commands and their options.
22034 In this section we summarize a few of the most commonly
22035 used commands to give an idea of what @code{GDB} is about. You should create
22036 a simple program with debugging information and experiment with the use of
22037 these @code{GDB} commands on the program as you read through the
22041 @item set args @var{arguments}
22042 The @var{arguments} list above is a list of arguments to be passed to
22043 the program on a subsequent run command, just as though the arguments
22044 had been entered on a normal invocation of the program. The @code{set args}
22045 command is not needed if the program does not require arguments.
22048 The @code{run} command causes execution of the program to start from
22049 the beginning. If the program is already running, that is to say if
22050 you are currently positioned at a breakpoint, then a prompt will ask
22051 for confirmation that you want to abandon the current execution and
22054 @item breakpoint @var{location}
22055 The breakpoint command sets a breakpoint, that is to say a point at which
22056 execution will halt and @code{GDB} will await further
22057 commands. @var{location} is
22058 either a line number within a file, given in the format @code{file:linenumber},
22059 or it is the name of a subprogram. If you request that a breakpoint be set on
22060 a subprogram that is overloaded, a prompt will ask you to specify on which of
22061 those subprograms you want to breakpoint. You can also
22062 specify that all of them should be breakpointed. If the program is run
22063 and execution encounters the breakpoint, then the program
22064 stops and @code{GDB} signals that the breakpoint was encountered by
22065 printing the line of code before which the program is halted.
22067 @item breakpoint exception @var{name}
22068 A special form of the breakpoint command which breakpoints whenever
22069 exception @var{name} is raised.
22070 If @var{name} is omitted,
22071 then a breakpoint will occur when any exception is raised.
22073 @item print @var{expression}
22074 This will print the value of the given expression. Most simple
22075 Ada expression formats are properly handled by @code{GDB}, so the expression
22076 can contain function calls, variables, operators, and attribute references.
22079 Continues execution following a breakpoint, until the next breakpoint or the
22080 termination of the program.
22083 Executes a single line after a breakpoint. If the next statement
22084 is a subprogram call, execution continues into (the first statement of)
22085 the called subprogram.
22088 Executes a single line. If this line is a subprogram call, executes and
22089 returns from the call.
22092 Lists a few lines around the current source location. In practice, it
22093 is usually more convenient to have a separate edit window open with the
22094 relevant source file displayed. Successive applications of this command
22095 print subsequent lines. The command can be given an argument which is a
22096 line number, in which case it displays a few lines around the specified one.
22099 Displays a backtrace of the call chain. This command is typically
22100 used after a breakpoint has occurred, to examine the sequence of calls that
22101 leads to the current breakpoint. The display includes one line for each
22102 activation record (frame) corresponding to an active subprogram.
22105 At a breakpoint, @code{GDB} can display the values of variables local
22106 to the current frame. The command @code{up} can be used to
22107 examine the contents of other active frames, by moving the focus up
22108 the stack, that is to say from callee to caller, one frame at a time.
22111 Moves the focus of @code{GDB} down from the frame currently being
22112 examined to the frame of its callee (the reverse of the previous command),
22114 @item frame @var{n}
22115 Inspect the frame with the given number. The value 0 denotes the frame
22116 of the current breakpoint, that is to say the top of the call stack.
22121 The above list is a very short introduction to the commands that
22122 @code{GDB} provides. Important additional capabilities, including conditional
22123 breakpoints, the ability to execute command sequences on a breakpoint,
22124 the ability to debug at the machine instruction level and many other
22125 features are described in detail in @cite{Debugging with GDB}.
22126 Note that most commands can be abbreviated
22127 (for example, c for continue, bt for backtrace).
22129 @node Using Ada Expressions
22130 @section Using Ada Expressions
22131 @cindex Ada expressions
22134 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
22135 extensions. The philosophy behind the design of this subset is
22139 That @code{GDB} should provide basic literals and access to operations for
22140 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
22141 leaving more sophisticated computations to subprograms written into the
22142 program (which therefore may be called from @code{GDB}).
22145 That type safety and strict adherence to Ada language restrictions
22146 are not particularly important to the @code{GDB} user.
22149 That brevity is important to the @code{GDB} user.
22153 Thus, for brevity, the debugger acts as if there were
22154 implicit @code{with} and @code{use} clauses in effect for all user-written
22155 packages, thus making it unnecessary to fully qualify most names with
22156 their packages, regardless of context. Where this causes ambiguity,
22157 @code{GDB} asks the user's intent.
22159 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
22161 @node Calling User-Defined Subprograms
22162 @section Calling User-Defined Subprograms
22165 An important capability of @code{GDB} is the ability to call user-defined
22166 subprograms while debugging. This is achieved simply by entering
22167 a subprogram call statement in the form:
22170 call subprogram-name (parameters)
22174 The keyword @code{call} can be omitted in the normal case where the
22175 @code{subprogram-name} does not coincide with any of the predefined
22176 @code{GDB} commands.
22178 The effect is to invoke the given subprogram, passing it the
22179 list of parameters that is supplied. The parameters can be expressions and
22180 can include variables from the program being debugged. The
22181 subprogram must be defined
22182 at the library level within your program, and @code{GDB} will call the
22183 subprogram within the environment of your program execution (which
22184 means that the subprogram is free to access or even modify variables
22185 within your program).
22187 The most important use of this facility is in allowing the inclusion of
22188 debugging routines that are tailored to particular data structures
22189 in your program. Such debugging routines can be written to provide a suitably
22190 high-level description of an abstract type, rather than a low-level dump
22191 of its physical layout. After all, the standard
22192 @code{GDB print} command only knows the physical layout of your
22193 types, not their abstract meaning. Debugging routines can provide information
22194 at the desired semantic level and are thus enormously useful.
22196 For example, when debugging GNAT itself, it is crucial to have access to
22197 the contents of the tree nodes used to represent the program internally.
22198 But tree nodes are represented simply by an integer value (which in turn
22199 is an index into a table of nodes).
22200 Using the @code{print} command on a tree node would simply print this integer
22201 value, which is not very useful. But the PN routine (defined in file
22202 treepr.adb in the GNAT sources) takes a tree node as input, and displays
22203 a useful high level representation of the tree node, which includes the
22204 syntactic category of the node, its position in the source, the integers
22205 that denote descendant nodes and parent node, as well as varied
22206 semantic information. To study this example in more detail, you might want to
22207 look at the body of the PN procedure in the stated file.
22209 @node Using the Next Command in a Function
22210 @section Using the Next Command in a Function
22213 When you use the @code{next} command in a function, the current source
22214 location will advance to the next statement as usual. A special case
22215 arises in the case of a @code{return} statement.
22217 Part of the code for a return statement is the ``epilog'' of the function.
22218 This is the code that returns to the caller. There is only one copy of
22219 this epilog code, and it is typically associated with the last return
22220 statement in the function if there is more than one return. In some
22221 implementations, this epilog is associated with the first statement
22224 The result is that if you use the @code{next} command from a return
22225 statement that is not the last return statement of the function you
22226 may see a strange apparent jump to the last return statement or to
22227 the start of the function. You should simply ignore this odd jump.
22228 The value returned is always that from the first return statement
22229 that was stepped through.
22231 @node Ada Exceptions
22232 @section Breaking on Ada Exceptions
22236 You can set breakpoints that trip when your program raises
22237 selected exceptions.
22240 @item break exception
22241 Set a breakpoint that trips whenever (any task in the) program raises
22244 @item break exception @var{name}
22245 Set a breakpoint that trips whenever (any task in the) program raises
22246 the exception @var{name}.
22248 @item break exception unhandled
22249 Set a breakpoint that trips whenever (any task in the) program raises an
22250 exception for which there is no handler.
22252 @item info exceptions
22253 @itemx info exceptions @var{regexp}
22254 The @code{info exceptions} command permits the user to examine all defined
22255 exceptions within Ada programs. With a regular expression, @var{regexp}, as
22256 argument, prints out only those exceptions whose name matches @var{regexp}.
22264 @code{GDB} allows the following task-related commands:
22268 This command shows a list of current Ada tasks, as in the following example:
22275 ID TID P-ID Thread Pri State Name
22276 1 8088000 0 807e000 15 Child Activation Wait main_task
22277 2 80a4000 1 80ae000 15 Accept/Select Wait b
22278 3 809a800 1 80a4800 15 Child Activation Wait a
22279 * 4 80ae800 3 80b8000 15 Running c
22283 In this listing, the asterisk before the first task indicates it to be the
22284 currently running task. The first column lists the task ID that is used
22285 to refer to tasks in the following commands.
22287 @item break @var{linespec} task @var{taskid}
22288 @itemx break @var{linespec} task @var{taskid} if @dots{}
22289 @cindex Breakpoints and tasks
22290 These commands are like the @code{break @dots{} thread @dots{}}.
22291 @var{linespec} specifies source lines.
22293 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
22294 to specify that you only want @code{GDB} to stop the program when a
22295 particular Ada task reaches this breakpoint. @var{taskid} is one of the
22296 numeric task identifiers assigned by @code{GDB}, shown in the first
22297 column of the @samp{info tasks} display.
22299 If you do not specify @samp{task @var{taskid}} when you set a
22300 breakpoint, the breakpoint applies to @emph{all} tasks of your
22303 You can use the @code{task} qualifier on conditional breakpoints as
22304 well; in this case, place @samp{task @var{taskid}} before the
22305 breakpoint condition (before the @code{if}).
22307 @item task @var{taskno}
22308 @cindex Task switching
22310 This command allows to switch to the task referred by @var{taskno}. In
22311 particular, This allows to browse the backtrace of the specified
22312 task. It is advised to switch back to the original task before
22313 continuing execution otherwise the scheduling of the program may be
22318 For more detailed information on the tasking support,
22319 see @cite{Debugging with GDB}.
22321 @node Debugging Generic Units
22322 @section Debugging Generic Units
22323 @cindex Debugging Generic Units
22327 GNAT always uses code expansion for generic instantiation. This means that
22328 each time an instantiation occurs, a complete copy of the original code is
22329 made, with appropriate substitutions of formals by actuals.
22331 It is not possible to refer to the original generic entities in
22332 @code{GDB}, but it is always possible to debug a particular instance of
22333 a generic, by using the appropriate expanded names. For example, if we have
22335 @smallexample @c ada
22340 generic package k is
22341 procedure kp (v1 : in out integer);
22345 procedure kp (v1 : in out integer) is
22351 package k1 is new k;
22352 package k2 is new k;
22354 var : integer := 1;
22367 Then to break on a call to procedure kp in the k2 instance, simply
22371 (gdb) break g.k2.kp
22375 When the breakpoint occurs, you can step through the code of the
22376 instance in the normal manner and examine the values of local variables, as for
22379 @node GNAT Abnormal Termination or Failure to Terminate
22380 @section GNAT Abnormal Termination or Failure to Terminate
22381 @cindex GNAT Abnormal Termination or Failure to Terminate
22384 When presented with programs that contain serious errors in syntax
22386 GNAT may on rare occasions experience problems in operation, such
22388 segmentation fault or illegal memory access, raising an internal
22389 exception, terminating abnormally, or failing to terminate at all.
22390 In such cases, you can activate
22391 various features of GNAT that can help you pinpoint the construct in your
22392 program that is the likely source of the problem.
22394 The following strategies are presented in increasing order of
22395 difficulty, corresponding to your experience in using GNAT and your
22396 familiarity with compiler internals.
22400 Run @command{gcc} with the @option{-gnatf}. This first
22401 switch causes all errors on a given line to be reported. In its absence,
22402 only the first error on a line is displayed.
22404 The @option{-gnatdO} switch causes errors to be displayed as soon as they
22405 are encountered, rather than after compilation is terminated. If GNAT
22406 terminates prematurely or goes into an infinite loop, the last error
22407 message displayed may help to pinpoint the culprit.
22410 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
22411 mode, @command{gcc} produces ongoing information about the progress of the
22412 compilation and provides the name of each procedure as code is
22413 generated. This switch allows you to find which Ada procedure was being
22414 compiled when it encountered a code generation problem.
22417 @cindex @option{-gnatdc} switch
22418 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
22419 switch that does for the front-end what @option{^-v^VERBOSE^} does
22420 for the back end. The system prints the name of each unit,
22421 either a compilation unit or nested unit, as it is being analyzed.
22423 Finally, you can start
22424 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
22425 front-end of GNAT, and can be run independently (normally it is just
22426 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
22427 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
22428 @code{where} command is the first line of attack; the variable
22429 @code{lineno} (seen by @code{print lineno}), used by the second phase of
22430 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
22431 which the execution stopped, and @code{input_file name} indicates the name of
22435 @node Naming Conventions for GNAT Source Files
22436 @section Naming Conventions for GNAT Source Files
22439 In order to examine the workings of the GNAT system, the following
22440 brief description of its organization may be helpful:
22444 Files with prefix @file{^sc^SC^} contain the lexical scanner.
22447 All files prefixed with @file{^par^PAR^} are components of the parser. The
22448 numbers correspond to chapters of the Ada Reference Manual. For example,
22449 parsing of select statements can be found in @file{par-ch9.adb}.
22452 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
22453 numbers correspond to chapters of the Ada standard. For example, all
22454 issues involving context clauses can be found in @file{sem_ch10.adb}. In
22455 addition, some features of the language require sufficient special processing
22456 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
22457 dynamic dispatching, etc.
22460 All files prefixed with @file{^exp^EXP^} perform normalization and
22461 expansion of the intermediate representation (abstract syntax tree, or AST).
22462 these files use the same numbering scheme as the parser and semantics files.
22463 For example, the construction of record initialization procedures is done in
22464 @file{exp_ch3.adb}.
22467 The files prefixed with @file{^bind^BIND^} implement the binder, which
22468 verifies the consistency of the compilation, determines an order of
22469 elaboration, and generates the bind file.
22472 The files @file{atree.ads} and @file{atree.adb} detail the low-level
22473 data structures used by the front-end.
22476 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
22477 the abstract syntax tree as produced by the parser.
22480 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
22481 all entities, computed during semantic analysis.
22484 Library management issues are dealt with in files with prefix
22490 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
22491 defined in Annex A.
22496 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
22497 defined in Annex B.
22501 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
22502 both language-defined children and GNAT run-time routines.
22506 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
22507 general-purpose packages, fully documented in their specifications. All
22508 the other @file{.c} files are modifications of common @command{gcc} files.
22511 @node Getting Internal Debugging Information
22512 @section Getting Internal Debugging Information
22515 Most compilers have internal debugging switches and modes. GNAT
22516 does also, except GNAT internal debugging switches and modes are not
22517 secret. A summary and full description of all the compiler and binder
22518 debug flags are in the file @file{debug.adb}. You must obtain the
22519 sources of the compiler to see the full detailed effects of these flags.
22521 The switches that print the source of the program (reconstructed from
22522 the internal tree) are of general interest for user programs, as are the
22524 the full internal tree, and the entity table (the symbol table
22525 information). The reconstructed source provides a readable version of the
22526 program after the front-end has completed analysis and expansion,
22527 and is useful when studying the performance of specific constructs.
22528 For example, constraint checks are indicated, complex aggregates
22529 are replaced with loops and assignments, and tasking primitives
22530 are replaced with run-time calls.
22532 @node Stack Traceback
22533 @section Stack Traceback
22535 @cindex stack traceback
22536 @cindex stack unwinding
22539 Traceback is a mechanism to display the sequence of subprogram calls that
22540 leads to a specified execution point in a program. Often (but not always)
22541 the execution point is an instruction at which an exception has been raised.
22542 This mechanism is also known as @i{stack unwinding} because it obtains
22543 its information by scanning the run-time stack and recovering the activation
22544 records of all active subprograms. Stack unwinding is one of the most
22545 important tools for program debugging.
22547 The first entry stored in traceback corresponds to the deepest calling level,
22548 that is to say the subprogram currently executing the instruction
22549 from which we want to obtain the traceback.
22551 Note that there is no runtime performance penalty when stack traceback
22552 is enabled, and no exception is raised during program execution.
22555 * Non-Symbolic Traceback::
22556 * Symbolic Traceback::
22559 @node Non-Symbolic Traceback
22560 @subsection Non-Symbolic Traceback
22561 @cindex traceback, non-symbolic
22564 Note: this feature is not supported on all platforms. See
22565 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
22569 * Tracebacks From an Unhandled Exception::
22570 * Tracebacks From Exception Occurrences (non-symbolic)::
22571 * Tracebacks From Anywhere in a Program (non-symbolic)::
22574 @node Tracebacks From an Unhandled Exception
22575 @subsubsection Tracebacks From an Unhandled Exception
22578 A runtime non-symbolic traceback is a list of addresses of call instructions.
22579 To enable this feature you must use the @option{-E}
22580 @code{gnatbind}'s option. With this option a stack traceback is stored as part
22581 of exception information. You can retrieve this information using the
22582 @code{addr2line} tool.
22584 Here is a simple example:
22586 @smallexample @c ada
22592 raise Constraint_Error;
22607 $ gnatmake stb -bargs -E
22610 Execution terminated by unhandled exception
22611 Exception name: CONSTRAINT_ERROR
22613 Call stack traceback locations:
22614 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
22618 As we see the traceback lists a sequence of addresses for the unhandled
22619 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
22620 guess that this exception come from procedure P1. To translate these
22621 addresses into the source lines where the calls appear, the
22622 @code{addr2line} tool, described below, is invaluable. The use of this tool
22623 requires the program to be compiled with debug information.
22626 $ gnatmake -g stb -bargs -E
22629 Execution terminated by unhandled exception
22630 Exception name: CONSTRAINT_ERROR
22632 Call stack traceback locations:
22633 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
22635 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
22636 0x4011f1 0x77e892a4
22638 00401373 at d:/stb/stb.adb:5
22639 0040138B at d:/stb/stb.adb:10
22640 0040139C at d:/stb/stb.adb:14
22641 00401335 at d:/stb/b~stb.adb:104
22642 004011C4 at /build/.../crt1.c:200
22643 004011F1 at /build/.../crt1.c:222
22644 77E892A4 in ?? at ??:0
22648 The @code{addr2line} tool has several other useful options:
22652 to get the function name corresponding to any location
22654 @item --demangle=gnat
22655 to use the gnat decoding mode for the function names. Note that
22656 for binutils version 2.9.x the option is simply @option{--demangle}.
22660 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
22661 0x40139c 0x401335 0x4011c4 0x4011f1
22663 00401373 in stb.p1 at d:/stb/stb.adb:5
22664 0040138B in stb.p2 at d:/stb/stb.adb:10
22665 0040139C in stb at d:/stb/stb.adb:14
22666 00401335 in main at d:/stb/b~stb.adb:104
22667 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
22668 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
22672 From this traceback we can see that the exception was raised in
22673 @file{stb.adb} at line 5, which was reached from a procedure call in
22674 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
22675 which contains the call to the main program.
22676 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
22677 and the output will vary from platform to platform.
22679 It is also possible to use @code{GDB} with these traceback addresses to debug
22680 the program. For example, we can break at a given code location, as reported
22681 in the stack traceback:
22687 Furthermore, this feature is not implemented inside Windows DLL. Only
22688 the non-symbolic traceback is reported in this case.
22691 (gdb) break *0x401373
22692 Breakpoint 1 at 0x401373: file stb.adb, line 5.
22696 It is important to note that the stack traceback addresses
22697 do not change when debug information is included. This is particularly useful
22698 because it makes it possible to release software without debug information (to
22699 minimize object size), get a field report that includes a stack traceback
22700 whenever an internal bug occurs, and then be able to retrieve the sequence
22701 of calls with the same program compiled with debug information.
22703 @node Tracebacks From Exception Occurrences (non-symbolic)
22704 @subsubsection Tracebacks From Exception Occurrences
22707 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
22708 The stack traceback is attached to the exception information string, and can
22709 be retrieved in an exception handler within the Ada program, by means of the
22710 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
22712 @smallexample @c ada
22714 with Ada.Exceptions;
22719 use Ada.Exceptions;
22727 Text_IO.Put_Line (Exception_Information (E));
22741 This program will output:
22746 Exception name: CONSTRAINT_ERROR
22747 Message: stb.adb:12
22748 Call stack traceback locations:
22749 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
22752 @node Tracebacks From Anywhere in a Program (non-symbolic)
22753 @subsubsection Tracebacks From Anywhere in a Program
22756 It is also possible to retrieve a stack traceback from anywhere in a
22757 program. For this you need to
22758 use the @code{GNAT.Traceback} API. This package includes a procedure called
22759 @code{Call_Chain} that computes a complete stack traceback, as well as useful
22760 display procedures described below. It is not necessary to use the
22761 @option{-E gnatbind} option in this case, because the stack traceback mechanism
22762 is invoked explicitly.
22765 In the following example we compute a traceback at a specific location in
22766 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
22767 convert addresses to strings:
22769 @smallexample @c ada
22771 with GNAT.Traceback;
22772 with GNAT.Debug_Utilities;
22778 use GNAT.Traceback;
22781 TB : Tracebacks_Array (1 .. 10);
22782 -- We are asking for a maximum of 10 stack frames.
22784 -- Len will receive the actual number of stack frames returned.
22786 Call_Chain (TB, Len);
22788 Text_IO.Put ("In STB.P1 : ");
22790 for K in 1 .. Len loop
22791 Text_IO.Put (Debug_Utilities.Image (TB (K)));
22812 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
22813 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
22817 You can then get further information by invoking the @code{addr2line}
22818 tool as described earlier (note that the hexadecimal addresses
22819 need to be specified in C format, with a leading ``0x'').
22821 @node Symbolic Traceback
22822 @subsection Symbolic Traceback
22823 @cindex traceback, symbolic
22826 A symbolic traceback is a stack traceback in which procedure names are
22827 associated with each code location.
22830 Note that this feature is not supported on all platforms. See
22831 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
22832 list of currently supported platforms.
22835 Note that the symbolic traceback requires that the program be compiled
22836 with debug information. If it is not compiled with debug information
22837 only the non-symbolic information will be valid.
22840 * Tracebacks From Exception Occurrences (symbolic)::
22841 * Tracebacks From Anywhere in a Program (symbolic)::
22844 @node Tracebacks From Exception Occurrences (symbolic)
22845 @subsubsection Tracebacks From Exception Occurrences
22847 @smallexample @c ada
22849 with GNAT.Traceback.Symbolic;
22855 raise Constraint_Error;
22872 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
22877 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
22880 0040149F in stb.p1 at stb.adb:8
22881 004014B7 in stb.p2 at stb.adb:13
22882 004014CF in stb.p3 at stb.adb:18
22883 004015DD in ada.stb at stb.adb:22
22884 00401461 in main at b~stb.adb:168
22885 004011C4 in __mingw_CRTStartup at crt1.c:200
22886 004011F1 in mainCRTStartup at crt1.c:222
22887 77E892A4 in ?? at ??:0
22891 In the above example the ``.\'' syntax in the @command{gnatmake} command
22892 is currently required by @command{addr2line} for files that are in
22893 the current working directory.
22894 Moreover, the exact sequence of linker options may vary from platform
22896 The above @option{-largs} section is for Windows platforms. By contrast,
22897 under Unix there is no need for the @option{-largs} section.
22898 Differences across platforms are due to details of linker implementation.
22900 @node Tracebacks From Anywhere in a Program (symbolic)
22901 @subsubsection Tracebacks From Anywhere in a Program
22904 It is possible to get a symbolic stack traceback
22905 from anywhere in a program, just as for non-symbolic tracebacks.
22906 The first step is to obtain a non-symbolic
22907 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
22908 information. Here is an example:
22910 @smallexample @c ada
22912 with GNAT.Traceback;
22913 with GNAT.Traceback.Symbolic;
22918 use GNAT.Traceback;
22919 use GNAT.Traceback.Symbolic;
22922 TB : Tracebacks_Array (1 .. 10);
22923 -- We are asking for a maximum of 10 stack frames.
22925 -- Len will receive the actual number of stack frames returned.
22927 Call_Chain (TB, Len);
22928 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
22941 @c ******************************
22943 @node Compatibility with HP Ada
22944 @chapter Compatibility with HP Ada
22945 @cindex Compatibility
22950 @cindex Compatibility between GNAT and HP Ada
22951 This chapter compares HP Ada (formerly known as ``DEC Ada'')
22952 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
22953 GNAT is highly compatible
22954 with HP Ada, and it should generally be straightforward to port code
22955 from the HP Ada environment to GNAT. However, there are a few language
22956 and implementation differences of which the user must be aware. These
22957 differences are discussed in this chapter. In
22958 addition, the operating environment and command structure for the
22959 compiler are different, and these differences are also discussed.
22961 For further details on these and other compatibility issues,
22962 see Appendix E of the HP publication
22963 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
22965 Except where otherwise indicated, the description of GNAT for OpenVMS
22966 applies to both the Alpha and I64 platforms.
22968 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
22969 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
22971 The discussion in this chapter addresses specifically the implementation
22972 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
22973 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
22974 GNAT always follows the Alpha implementation.
22976 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
22977 attributes are recognized, although only a subset of them can sensibly
22978 be implemented. The description of pragmas in the
22979 @cite{GNAT Reference Manual} indicates whether or not they are applicable
22980 to non-VMS systems.
22983 * Ada Language Compatibility::
22984 * Differences in the Definition of Package System::
22985 * Language-Related Features::
22986 * The Package STANDARD::
22987 * The Package SYSTEM::
22988 * Tasking and Task-Related Features::
22989 * Pragmas and Pragma-Related Features::
22990 * Library of Predefined Units::
22992 * Main Program Definition::
22993 * Implementation-Defined Attributes::
22994 * Compiler and Run-Time Interfacing::
22995 * Program Compilation and Library Management::
22997 * Implementation Limits::
22998 * Tools and Utilities::
23001 @node Ada Language Compatibility
23002 @section Ada Language Compatibility
23005 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
23006 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
23007 with Ada 83, and therefore Ada 83 programs will compile
23008 and run under GNAT with
23009 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
23010 provides details on specific incompatibilities.
23012 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
23013 as well as the pragma @code{ADA_83}, to force the compiler to
23014 operate in Ada 83 mode. This mode does not guarantee complete
23015 conformance to Ada 83, but in practice is sufficient to
23016 eliminate most sources of incompatibilities.
23017 In particular, it eliminates the recognition of the
23018 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
23019 in Ada 83 programs is legal, and handles the cases of packages
23020 with optional bodies, and generics that instantiate unconstrained
23021 types without the use of @code{(<>)}.
23023 @node Differences in the Definition of Package System
23024 @section Differences in the Definition of Package @code{System}
23027 An Ada compiler is allowed to add
23028 implementation-dependent declarations to package @code{System}.
23030 GNAT does not take advantage of this permission, and the version of
23031 @code{System} provided by GNAT exactly matches that defined in the Ada
23034 However, HP Ada adds an extensive set of declarations to package
23036 as fully documented in the HP Ada manuals. To minimize changes required
23037 for programs that make use of these extensions, GNAT provides the pragma
23038 @code{Extend_System} for extending the definition of package System. By using:
23039 @cindex pragma @code{Extend_System}
23040 @cindex @code{Extend_System} pragma
23042 @smallexample @c ada
23045 pragma Extend_System (Aux_DEC);
23051 the set of definitions in @code{System} is extended to include those in
23052 package @code{System.Aux_DEC}.
23053 @cindex @code{System.Aux_DEC} package
23054 @cindex @code{Aux_DEC} package (child of @code{System})
23055 These definitions are incorporated directly into package @code{System},
23056 as though they had been declared there. For a
23057 list of the declarations added, see the specification of this package,
23058 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
23059 @cindex @file{s-auxdec.ads} file
23060 The pragma @code{Extend_System} is a configuration pragma, which means that
23061 it can be placed in the file @file{gnat.adc}, so that it will automatically
23062 apply to all subsequent compilations. See @ref{Configuration Pragmas},
23063 for further details.
23065 An alternative approach that avoids the use of the non-standard
23066 @code{Extend_System} pragma is to add a context clause to the unit that
23067 references these facilities:
23069 @smallexample @c ada
23071 with System.Aux_DEC;
23072 use System.Aux_DEC;
23077 The effect is not quite semantically identical to incorporating
23078 the declarations directly into package @code{System},
23079 but most programs will not notice a difference
23080 unless they use prefix notation (e.g. @code{System.Integer_8})
23081 to reference the entities directly in package @code{System}.
23082 For units containing such references,
23083 the prefixes must either be removed, or the pragma @code{Extend_System}
23086 @node Language-Related Features
23087 @section Language-Related Features
23090 The following sections highlight differences in types,
23091 representations of types, operations, alignment, and
23095 * Integer Types and Representations::
23096 * Floating-Point Types and Representations::
23097 * Pragmas Float_Representation and Long_Float::
23098 * Fixed-Point Types and Representations::
23099 * Record and Array Component Alignment::
23100 * Address Clauses::
23101 * Other Representation Clauses::
23104 @node Integer Types and Representations
23105 @subsection Integer Types and Representations
23108 The set of predefined integer types is identical in HP Ada and GNAT.
23109 Furthermore the representation of these integer types is also identical,
23110 including the capability of size clauses forcing biased representation.
23113 HP Ada for OpenVMS Alpha systems has defined the
23114 following additional integer types in package @code{System}:
23131 @code{LARGEST_INTEGER}
23135 In GNAT, the first four of these types may be obtained from the
23136 standard Ada package @code{Interfaces}.
23137 Alternatively, by use of the pragma @code{Extend_System}, identical
23138 declarations can be referenced directly in package @code{System}.
23139 On both GNAT and HP Ada, the maximum integer size is 64 bits.
23141 @node Floating-Point Types and Representations
23142 @subsection Floating-Point Types and Representations
23143 @cindex Floating-Point types
23146 The set of predefined floating-point types is identical in HP Ada and GNAT.
23147 Furthermore the representation of these floating-point
23148 types is also identical. One important difference is that the default
23149 representation for HP Ada is @code{VAX_Float}, but the default representation
23152 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
23153 pragma @code{Float_Representation} as described in the HP Ada
23155 For example, the declarations:
23157 @smallexample @c ada
23159 type F_Float is digits 6;
23160 pragma Float_Representation (VAX_Float, F_Float);
23165 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
23167 This set of declarations actually appears in @code{System.Aux_DEC},
23169 the full set of additional floating-point declarations provided in
23170 the HP Ada version of package @code{System}.
23171 This and similar declarations may be accessed in a user program
23172 by using pragma @code{Extend_System}. The use of this
23173 pragma, and the related pragma @code{Long_Float} is described in further
23174 detail in the following section.
23176 @node Pragmas Float_Representation and Long_Float
23177 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
23180 HP Ada provides the pragma @code{Float_Representation}, which
23181 acts as a program library switch to allow control over
23182 the internal representation chosen for the predefined
23183 floating-point types declared in the package @code{Standard}.
23184 The format of this pragma is as follows:
23186 @smallexample @c ada
23188 pragma Float_Representation(VAX_Float | IEEE_Float);
23193 This pragma controls the representation of floating-point
23198 @code{VAX_Float} specifies that floating-point
23199 types are represented by default with the VAX system hardware types
23200 @code{F-floating}, @code{D-floating}, @code{G-floating}.
23201 Note that the @code{H-floating}
23202 type was available only on VAX systems, and is not available
23203 in either HP Ada or GNAT.
23206 @code{IEEE_Float} specifies that floating-point
23207 types are represented by default with the IEEE single and
23208 double floating-point types.
23212 GNAT provides an identical implementation of the pragma
23213 @code{Float_Representation}, except that it functions as a
23214 configuration pragma. Note that the
23215 notion of configuration pragma corresponds closely to the
23216 HP Ada notion of a program library switch.
23218 When no pragma is used in GNAT, the default is @code{IEEE_Float},
23220 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
23221 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
23222 advisable to change the format of numbers passed to standard library
23223 routines, and if necessary explicit type conversions may be needed.
23225 The use of @code{IEEE_Float} is recommended in GNAT since it is more
23226 efficient, and (given that it conforms to an international standard)
23227 potentially more portable.
23228 The situation in which @code{VAX_Float} may be useful is in interfacing
23229 to existing code and data that expect the use of @code{VAX_Float}.
23230 In such a situation use the predefined @code{VAX_Float}
23231 types in package @code{System}, as extended by
23232 @code{Extend_System}. For example, use @code{System.F_Float}
23233 to specify the 32-bit @code{F-Float} format.
23236 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
23237 to allow control over the internal representation chosen
23238 for the predefined type @code{Long_Float} and for floating-point
23239 type declarations with digits specified in the range 7 .. 15.
23240 The format of this pragma is as follows:
23242 @smallexample @c ada
23244 pragma Long_Float (D_FLOAT | G_FLOAT);
23248 @node Fixed-Point Types and Representations
23249 @subsection Fixed-Point Types and Representations
23252 On HP Ada for OpenVMS Alpha systems, rounding is
23253 away from zero for both positive and negative numbers.
23254 Therefore, @code{+0.5} rounds to @code{1},
23255 and @code{-0.5} rounds to @code{-1}.
23257 On GNAT the results of operations
23258 on fixed-point types are in accordance with the Ada
23259 rules. In particular, results of operations on decimal
23260 fixed-point types are truncated.
23262 @node Record and Array Component Alignment
23263 @subsection Record and Array Component Alignment
23266 On HP Ada for OpenVMS Alpha, all non composite components
23267 are aligned on natural boundaries. For example, 1-byte
23268 components are aligned on byte boundaries, 2-byte
23269 components on 2-byte boundaries, 4-byte components on 4-byte
23270 byte boundaries, and so on. The OpenVMS Alpha hardware
23271 runs more efficiently with naturally aligned data.
23273 On GNAT, alignment rules are compatible
23274 with HP Ada for OpenVMS Alpha.
23276 @node Address Clauses
23277 @subsection Address Clauses
23280 In HP Ada and GNAT, address clauses are supported for
23281 objects and imported subprograms.
23282 The predefined type @code{System.Address} is a private type
23283 in both compilers on Alpha OpenVMS, with the same representation
23284 (it is simply a machine pointer). Addition, subtraction, and comparison
23285 operations are available in the standard Ada package
23286 @code{System.Storage_Elements}, or in package @code{System}
23287 if it is extended to include @code{System.Aux_DEC} using a
23288 pragma @code{Extend_System} as previously described.
23290 Note that code that @code{with}'s both this extended package @code{System}
23291 and the package @code{System.Storage_Elements} should not @code{use}
23292 both packages, or ambiguities will result. In general it is better
23293 not to mix these two sets of facilities. The Ada package was
23294 designed specifically to provide the kind of features that HP Ada
23295 adds directly to package @code{System}.
23297 The type @code{System.Address} is a 64-bit integer type in GNAT for
23298 I64 OpenVMS. For more information,
23299 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
23301 GNAT is compatible with HP Ada in its handling of address
23302 clauses, except for some limitations in
23303 the form of address clauses for composite objects with
23304 initialization. Such address clauses are easily replaced
23305 by the use of an explicitly-defined constant as described
23306 in the Ada Reference Manual (13.1(22)). For example, the sequence
23309 @smallexample @c ada
23311 X, Y : Integer := Init_Func;
23312 Q : String (X .. Y) := "abc";
23314 for Q'Address use Compute_Address;
23319 will be rejected by GNAT, since the address cannot be computed at the time
23320 that @code{Q} is declared. To achieve the intended effect, write instead:
23322 @smallexample @c ada
23325 X, Y : Integer := Init_Func;
23326 Q_Address : constant Address := Compute_Address;
23327 Q : String (X .. Y) := "abc";
23329 for Q'Address use Q_Address;
23335 which will be accepted by GNAT (and other Ada compilers), and is also
23336 compatible with Ada 83. A fuller description of the restrictions
23337 on address specifications is found in the @cite{GNAT Reference Manual}.
23339 @node Other Representation Clauses
23340 @subsection Other Representation Clauses
23343 GNAT implements in a compatible manner all the representation
23344 clauses supported by HP Ada. In addition, GNAT
23345 implements the representation clause forms that were introduced in Ada 95,
23346 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
23348 @node The Package STANDARD
23349 @section The Package @code{STANDARD}
23352 The package @code{STANDARD}, as implemented by HP Ada, is fully
23353 described in the @cite{Ada Reference Manual} and in the
23354 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
23355 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
23357 In addition, HP Ada supports the Latin-1 character set in
23358 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
23359 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
23360 the type @code{WIDE_CHARACTER}.
23362 The floating-point types supported by GNAT are those
23363 supported by HP Ada, but the defaults are different, and are controlled by
23364 pragmas. See @ref{Floating-Point Types and Representations}, for details.
23366 @node The Package SYSTEM
23367 @section The Package @code{SYSTEM}
23370 HP Ada provides a specific version of the package
23371 @code{SYSTEM} for each platform on which the language is implemented.
23372 For the complete specification of the package @code{SYSTEM}, see
23373 Appendix F of the @cite{HP Ada Language Reference Manual}.
23375 On HP Ada, the package @code{SYSTEM} includes the following conversion
23378 @item @code{TO_ADDRESS(INTEGER)}
23380 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
23382 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
23384 @item @code{TO_INTEGER(ADDRESS)}
23386 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
23388 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
23389 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
23393 By default, GNAT supplies a version of @code{SYSTEM} that matches
23394 the definition given in the @cite{Ada Reference Manual}.
23396 is a subset of the HP system definitions, which is as
23397 close as possible to the original definitions. The only difference
23398 is that the definition of @code{SYSTEM_NAME} is different:
23400 @smallexample @c ada
23402 type Name is (SYSTEM_NAME_GNAT);
23403 System_Name : constant Name := SYSTEM_NAME_GNAT;
23408 Also, GNAT adds the Ada declarations for
23409 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
23411 However, the use of the following pragma causes GNAT
23412 to extend the definition of package @code{SYSTEM} so that it
23413 encompasses the full set of HP-specific extensions,
23414 including the functions listed above:
23416 @smallexample @c ada
23418 pragma Extend_System (Aux_DEC);
23423 The pragma @code{Extend_System} is a configuration pragma that
23424 is most conveniently placed in the @file{gnat.adc} file. See the
23425 @cite{GNAT Reference Manual} for further details.
23427 HP Ada does not allow the recompilation of the package
23428 @code{SYSTEM}. Instead HP Ada provides several pragmas
23429 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
23430 to modify values in the package @code{SYSTEM}.
23431 On OpenVMS Alpha systems, the pragma
23432 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
23433 its single argument.
23435 GNAT does permit the recompilation of package @code{SYSTEM} using
23436 the special switch @option{-gnatg}, and this switch can be used if
23437 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
23438 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
23439 or @code{MEMORY_SIZE} by any other means.
23441 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
23442 enumeration literal @code{SYSTEM_NAME_GNAT}.
23444 The definitions provided by the use of
23446 @smallexample @c ada
23447 pragma Extend_System (AUX_Dec);
23451 are virtually identical to those provided by the HP Ada 83 package
23452 @code{SYSTEM}. One important difference is that the name of the
23454 function for type @code{UNSIGNED_LONGWORD} is changed to
23455 @code{TO_ADDRESS_LONG}.
23456 See the @cite{GNAT Reference Manual} for a discussion of why this change was
23460 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
23462 an extension to Ada 83 not strictly compatible with the reference manual.
23463 GNAT, in order to be exactly compatible with the standard,
23464 does not provide this capability. In HP Ada 83, the
23465 point of this definition is to deal with a call like:
23467 @smallexample @c ada
23468 TO_ADDRESS (16#12777#);
23472 Normally, according to Ada 83 semantics, one would expect this to be
23473 ambiguous, since it matches both the @code{INTEGER} and
23474 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
23475 However, in HP Ada 83, there is no ambiguity, since the
23476 definition using @i{universal_integer} takes precedence.
23478 In GNAT, since the version with @i{universal_integer} cannot be supplied,
23480 not possible to be 100% compatible. Since there are many programs using
23481 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
23483 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
23484 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
23486 @smallexample @c ada
23487 function To_Address (X : Integer) return Address;
23488 pragma Pure_Function (To_Address);
23490 function To_Address_Long (X : Unsigned_Longword) return Address;
23491 pragma Pure_Function (To_Address_Long);
23495 This means that programs using @code{TO_ADDRESS} for
23496 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
23498 @node Tasking and Task-Related Features
23499 @section Tasking and Task-Related Features
23502 This section compares the treatment of tasking in GNAT
23503 and in HP Ada for OpenVMS Alpha.
23504 The GNAT description applies to both Alpha and I64 OpenVMS.
23505 For detailed information on tasking in
23506 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
23507 relevant run-time reference manual.
23510 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
23511 * Assigning Task IDs::
23512 * Task IDs and Delays::
23513 * Task-Related Pragmas::
23514 * Scheduling and Task Priority::
23516 * External Interrupts::
23519 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
23520 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
23523 On OpenVMS Alpha systems, each Ada task (except a passive
23524 task) is implemented as a single stream of execution
23525 that is created and managed by the kernel. On these
23526 systems, HP Ada tasking support is based on DECthreads,
23527 an implementation of the POSIX standard for threads.
23529 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
23530 code that calls DECthreads routines can be used together.
23531 The interaction between Ada tasks and DECthreads routines
23532 can have some benefits. For example when on OpenVMS Alpha,
23533 HP Ada can call C code that is already threaded.
23535 GNAT uses the facilities of DECthreads,
23536 and Ada tasks are mapped to threads.
23538 @node Assigning Task IDs
23539 @subsection Assigning Task IDs
23542 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
23543 the environment task that executes the main program. On
23544 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
23545 that have been created but are not yet activated.
23547 On OpenVMS Alpha systems, task IDs are assigned at
23548 activation. On GNAT systems, task IDs are also assigned at
23549 task creation but do not have the same form or values as
23550 task ID values in HP Ada. There is no null task, and the
23551 environment task does not have a specific task ID value.
23553 @node Task IDs and Delays
23554 @subsection Task IDs and Delays
23557 On OpenVMS Alpha systems, tasking delays are implemented
23558 using Timer System Services. The Task ID is used for the
23559 identification of the timer request (the @code{REQIDT} parameter).
23560 If Timers are used in the application take care not to use
23561 @code{0} for the identification, because cancelling such a timer
23562 will cancel all timers and may lead to unpredictable results.
23564 @node Task-Related Pragmas
23565 @subsection Task-Related Pragmas
23568 Ada supplies the pragma @code{TASK_STORAGE}, which allows
23569 specification of the size of the guard area for a task
23570 stack. (The guard area forms an area of memory that has no
23571 read or write access and thus helps in the detection of
23572 stack overflow.) On OpenVMS Alpha systems, if the pragma
23573 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
23574 area is created. In the absence of a pragma @code{TASK_STORAGE},
23575 a default guard area is created.
23577 GNAT supplies the following task-related pragmas:
23580 @item @code{TASK_INFO}
23582 This pragma appears within a task definition and
23583 applies to the task in which it appears. The argument
23584 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
23586 @item @code{TASK_STORAGE}
23588 GNAT implements pragma @code{TASK_STORAGE} in the same way as
23590 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
23591 @code{SUPPRESS}, and @code{VOLATILE}.
23593 @node Scheduling and Task Priority
23594 @subsection Scheduling and Task Priority
23597 HP Ada implements the Ada language requirement that
23598 when two tasks are eligible for execution and they have
23599 different priorities, the lower priority task does not
23600 execute while the higher priority task is waiting. The HP
23601 Ada Run-Time Library keeps a task running until either the
23602 task is suspended or a higher priority task becomes ready.
23604 On OpenVMS Alpha systems, the default strategy is round-
23605 robin with preemption. Tasks of equal priority take turns
23606 at the processor. A task is run for a certain period of
23607 time and then placed at the tail of the ready queue for
23608 its priority level.
23610 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
23611 which can be used to enable or disable round-robin
23612 scheduling of tasks with the same priority.
23613 See the relevant HP Ada run-time reference manual for
23614 information on using the pragmas to control HP Ada task
23617 GNAT follows the scheduling rules of Annex D (Real-Time
23618 Annex) of the @cite{Ada Reference Manual}. In general, this
23619 scheduling strategy is fully compatible with HP Ada
23620 although it provides some additional constraints (as
23621 fully documented in Annex D).
23622 GNAT implements time slicing control in a manner compatible with
23623 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
23624 are identical to the HP Ada 83 pragma of the same name.
23625 Note that it is not possible to mix GNAT tasking and
23626 HP Ada 83 tasking in the same program, since the two run-time
23627 libraries are not compatible.
23629 @node The Task Stack
23630 @subsection The Task Stack
23633 In HP Ada, a task stack is allocated each time a
23634 non-passive task is activated. As soon as the task is
23635 terminated, the storage for the task stack is deallocated.
23636 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
23637 a default stack size is used. Also, regardless of the size
23638 specified, some additional space is allocated for task
23639 management purposes. On OpenVMS Alpha systems, at least
23640 one page is allocated.
23642 GNAT handles task stacks in a similar manner. In accordance with
23643 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
23644 an alternative method for controlling the task stack size.
23645 The specification of the attribute @code{T'STORAGE_SIZE} is also
23646 supported in a manner compatible with HP Ada.
23648 @node External Interrupts
23649 @subsection External Interrupts
23652 On HP Ada, external interrupts can be associated with task entries.
23653 GNAT is compatible with HP Ada in its handling of external interrupts.
23655 @node Pragmas and Pragma-Related Features
23656 @section Pragmas and Pragma-Related Features
23659 Both HP Ada and GNAT supply all language-defined pragmas
23660 as specified by the Ada 83 standard. GNAT also supplies all
23661 language-defined pragmas introduced by Ada 95 and Ada 2005.
23662 In addition, GNAT implements the implementation-defined pragmas
23666 @item @code{AST_ENTRY}
23668 @item @code{COMMON_OBJECT}
23670 @item @code{COMPONENT_ALIGNMENT}
23672 @item @code{EXPORT_EXCEPTION}
23674 @item @code{EXPORT_FUNCTION}
23676 @item @code{EXPORT_OBJECT}
23678 @item @code{EXPORT_PROCEDURE}
23680 @item @code{EXPORT_VALUED_PROCEDURE}
23682 @item @code{FLOAT_REPRESENTATION}
23686 @item @code{IMPORT_EXCEPTION}
23688 @item @code{IMPORT_FUNCTION}
23690 @item @code{IMPORT_OBJECT}
23692 @item @code{IMPORT_PROCEDURE}
23694 @item @code{IMPORT_VALUED_PROCEDURE}
23696 @item @code{INLINE_GENERIC}
23698 @item @code{INTERFACE_NAME}
23700 @item @code{LONG_FLOAT}
23702 @item @code{MAIN_STORAGE}
23704 @item @code{PASSIVE}
23706 @item @code{PSECT_OBJECT}
23708 @item @code{SHARE_GENERIC}
23710 @item @code{SUPPRESS_ALL}
23712 @item @code{TASK_STORAGE}
23714 @item @code{TIME_SLICE}
23720 These pragmas are all fully implemented, with the exception of @code{TITLE},
23721 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
23722 recognized, but which have no
23723 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
23724 use of Ada protected objects. In GNAT, all generics are inlined.
23726 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
23727 a separate subprogram specification which must appear before the
23730 GNAT also supplies a number of implementation-defined pragmas as follows:
23732 @item @code{ABORT_DEFER}
23734 @item @code{ADA_83}
23736 @item @code{ADA_95}
23738 @item @code{ADA_05}
23740 @item @code{ANNOTATE}
23742 @item @code{ASSERT}
23744 @item @code{C_PASS_BY_COPY}
23746 @item @code{CPP_CLASS}
23748 @item @code{CPP_CONSTRUCTOR}
23750 @item @code{CPP_DESTRUCTOR}
23754 @item @code{EXTEND_SYSTEM}
23756 @item @code{LINKER_ALIAS}
23758 @item @code{LINKER_SECTION}
23760 @item @code{MACHINE_ATTRIBUTE}
23762 @item @code{NO_RETURN}
23764 @item @code{PURE_FUNCTION}
23766 @item @code{SOURCE_FILE_NAME}
23768 @item @code{SOURCE_REFERENCE}
23770 @item @code{TASK_INFO}
23772 @item @code{UNCHECKED_UNION}
23774 @item @code{UNIMPLEMENTED_UNIT}
23776 @item @code{UNIVERSAL_DATA}
23778 @item @code{UNSUPPRESS}
23780 @item @code{WARNINGS}
23782 @item @code{WEAK_EXTERNAL}
23786 For full details on these GNAT implementation-defined pragmas, see
23787 the GNAT Reference Manual.
23790 * Restrictions on the Pragma INLINE::
23791 * Restrictions on the Pragma INTERFACE::
23792 * Restrictions on the Pragma SYSTEM_NAME::
23795 @node Restrictions on the Pragma INLINE
23796 @subsection Restrictions on Pragma @code{INLINE}
23799 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
23801 @item Parameters cannot have a task type.
23803 @item Function results cannot be task types, unconstrained
23804 array types, or unconstrained types with discriminants.
23806 @item Bodies cannot declare the following:
23808 @item Subprogram body or stub (imported subprogram is allowed)
23812 @item Generic declarations
23814 @item Instantiations
23818 @item Access types (types derived from access types allowed)
23820 @item Array or record types
23822 @item Dependent tasks
23824 @item Direct recursive calls of subprogram or containing
23825 subprogram, directly or via a renaming
23831 In GNAT, the only restriction on pragma @code{INLINE} is that the
23832 body must occur before the call if both are in the same
23833 unit, and the size must be appropriately small. There are
23834 no other specific restrictions which cause subprograms to
23835 be incapable of being inlined.
23837 @node Restrictions on the Pragma INTERFACE
23838 @subsection Restrictions on Pragma @code{INTERFACE}
23841 The following restrictions on pragma @code{INTERFACE}
23842 are enforced by both HP Ada and GNAT:
23844 @item Languages accepted: Ada, Bliss, C, Fortran, Default.
23845 Default is the default on OpenVMS Alpha systems.
23847 @item Parameter passing: Language specifies default
23848 mechanisms but can be overridden with an @code{EXPORT} pragma.
23851 @item Ada: Use internal Ada rules.
23853 @item Bliss, C: Parameters must be mode @code{in}; cannot be
23854 record or task type. Result cannot be a string, an
23855 array, or a record.
23857 @item Fortran: Parameters cannot have a task type. Result cannot
23858 be a string, an array, or a record.
23863 GNAT is entirely upwards compatible with HP Ada, and in addition allows
23864 record parameters for all languages.
23866 @node Restrictions on the Pragma SYSTEM_NAME
23867 @subsection Restrictions on Pragma @code{SYSTEM_NAME}
23870 For HP Ada for OpenVMS Alpha, the enumeration literal
23871 for the type @code{NAME} is @code{OPENVMS_AXP}.
23872 In GNAT, the enumeration
23873 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
23875 @node Library of Predefined Units
23876 @section Library of Predefined Units
23879 A library of predefined units is provided as part of the
23880 HP Ada and GNAT implementations. HP Ada does not provide
23881 the package @code{MACHINE_CODE} but instead recommends importing
23884 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
23885 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
23887 The HP Ada Predefined Library units are modified to remove post-Ada 83
23888 incompatibilities and to make them interoperable with GNAT
23889 (@pxref{Changes to DECLIB}, for details).
23890 The units are located in the @file{DECLIB} directory.
23892 The GNAT RTL is contained in
23893 the @file{ADALIB} directory, and
23894 the default search path is set up to find @code{DECLIB} units in preference
23895 to @code{ADALIB} units with the same name (@code{TEXT_IO},
23896 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
23899 * Changes to DECLIB::
23902 @node Changes to DECLIB
23903 @subsection Changes to @code{DECLIB}
23906 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
23907 compatibility are minor and include the following:
23910 @item Adjusting the location of pragmas and record representation
23911 clauses to obey Ada 95 (and thus Ada 2005) rules
23913 @item Adding the proper notation to generic formal parameters
23914 that take unconstrained types in instantiation
23916 @item Adding pragma @code{ELABORATE_BODY} to package specifications
23917 that have package bodies not otherwise allowed
23919 @item Replacing occurrences of the identifier ``@code{PROTECTED}'' by
23920 ``@code{PROTECTD}''.
23921 Currently these are found only in the @code{STARLET} package spec.
23923 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
23924 where the address size is constrained to 32 bits.
23928 None of the above changes is visible to users.
23934 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
23937 @item Command Language Interpreter (CLI interface)
23939 @item DECtalk Run-Time Library (DTK interface)
23941 @item Librarian utility routines (LBR interface)
23943 @item General Purpose Run-Time Library (LIB interface)
23945 @item Math Run-Time Library (MTH interface)
23947 @item National Character Set Run-Time Library (NCS interface)
23949 @item Compiled Code Support Run-Time Library (OTS interface)
23951 @item Parallel Processing Run-Time Library (PPL interface)
23953 @item Screen Management Run-Time Library (SMG interface)
23955 @item Sort Run-Time Library (SOR interface)
23957 @item String Run-Time Library (STR interface)
23959 @item STARLET System Library
23962 @item X Window System Version 11R4 and 11R5 (X, XLIB interface)
23964 @item X Windows Toolkit (XT interface)
23966 @item X/Motif Version 1.1.3 and 1.2 (XM interface)
23970 GNAT provides implementations of these HP bindings in the @code{DECLIB}
23971 directory, on both the Alpha and I64 OpenVMS platforms.
23973 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
23975 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
23976 A pragma @code{Linker_Options} has been added to packages @code{Xm},
23977 @code{Xt}, and @code{X_Lib}
23978 causing the default X/Motif sharable image libraries to be linked in. This
23979 is done via options files named @file{xm.opt}, @file{xt.opt}, and
23980 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
23982 It may be necessary to edit these options files to update or correct the
23983 library names if, for example, the newer X/Motif bindings from
23984 @file{ADA$EXAMPLES}
23985 had been (previous to installing GNAT) copied and renamed to supersede the
23986 default @file{ADA$PREDEFINED} versions.
23989 * Shared Libraries and Options Files::
23990 * Interfaces to C::
23993 @node Shared Libraries and Options Files
23994 @subsection Shared Libraries and Options Files
23997 When using the HP Ada
23998 predefined X and Motif bindings, the linking with their sharable images is
23999 done automatically by @command{GNAT LINK}.
24000 When using other X and Motif bindings, you need
24001 to add the corresponding sharable images to the command line for
24002 @code{GNAT LINK}. When linking with shared libraries, or with
24003 @file{.OPT} files, you must
24004 also add them to the command line for @command{GNAT LINK}.
24006 A shared library to be used with GNAT is built in the same way as other
24007 libraries under VMS. The VMS Link command can be used in standard fashion.
24009 @node Interfaces to C
24010 @subsection Interfaces to C
24014 provides the following Ada types and operations:
24017 @item C types package (@code{C_TYPES})
24019 @item C strings (@code{C_TYPES.NULL_TERMINATED})
24021 @item Other_types (@code{SHORT_INT})
24025 Interfacing to C with GNAT, you can use the above approach
24026 described for HP Ada or the facilities of Annex B of
24027 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
24028 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
24029 information, see the section ``Interfacing to C'' in the
24030 @cite{GNAT Reference Manual}.
24032 The @option{-gnatF} qualifier forces default and explicit
24033 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
24034 to be uppercased for compatibility with the default behavior
24035 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
24037 @node Main Program Definition
24038 @section Main Program Definition
24041 The following section discusses differences in the
24042 definition of main programs on HP Ada and GNAT.
24043 On HP Ada, main programs are defined to meet the
24044 following conditions:
24046 @item Procedure with no formal parameters (returns @code{0} upon
24049 @item Procedure with no formal parameters (returns @code{42} when
24050 an unhandled exception is raised)
24052 @item Function with no formal parameters whose returned value
24053 is of a discrete type
24055 @item Procedure with one @code{out} formal of a discrete type for
24056 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE}
24062 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
24063 a main function or main procedure returns a discrete
24064 value whose size is less than 64 bits (32 on VAX systems),
24065 the value is zero- or sign-extended as appropriate.
24066 On GNAT, main programs are defined as follows:
24068 @item Must be a non-generic, parameterless subprogram that
24069 is either a procedure or function returning an Ada
24070 @code{STANDARD.INTEGER} (the predefined type)
24072 @item Cannot be a generic subprogram or an instantiation of a
24076 @node Implementation-Defined Attributes
24077 @section Implementation-Defined Attributes
24080 GNAT provides all HP Ada implementation-defined
24083 @node Compiler and Run-Time Interfacing
24084 @section Compiler and Run-Time Interfacing
24087 HP Ada provides the following qualifiers to pass options to the linker
24090 @item @option{/WAIT} and @option{/SUBMIT}
24092 @item @option{/COMMAND}
24094 @item @option{/[NO]MAP}
24096 @item @option{/OUTPUT=@i{file-spec}}
24098 @item @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK}
24102 To pass options to the linker, GNAT provides the following
24106 @item @option{/EXECUTABLE=@i{exec-name}}
24108 @item @option{/VERBOSE}
24110 @item @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK}
24114 For more information on these switches, see
24115 @ref{Switches for gnatlink}.
24116 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
24117 to control optimization. HP Ada also supplies the
24120 @item @code{OPTIMIZE}
24122 @item @code{INLINE}
24124 @item @code{INLINE_GENERIC}
24126 @item @code{SUPPRESS_ALL}
24128 @item @code{PASSIVE}
24132 In GNAT, optimization is controlled strictly by command
24133 line parameters, as described in the corresponding section of this guide.
24134 The HP pragmas for control of optimization are
24135 recognized but ignored.
24137 Note that in GNAT, the default is optimization off, whereas in HP Ada
24138 the default is that optimization is turned on.
24140 @node Program Compilation and Library Management
24141 @section Program Compilation and Library Management
24144 HP Ada and GNAT provide a comparable set of commands to
24145 build programs. HP Ada also provides a program library,
24146 which is a concept that does not exist on GNAT. Instead,
24147 GNAT provides directories of sources that are compiled as
24150 The following table summarizes
24151 the HP Ada commands and provides
24152 equivalent GNAT commands. In this table, some GNAT
24153 equivalents reflect the fact that GNAT does not use the
24154 concept of a program library. Instead, it uses a model
24155 in which collections of source and object files are used
24156 in a manner consistent with other languages like C and
24157 Fortran. Therefore, standard system file commands are used
24158 to manipulate these elements. Those GNAT commands are marked with
24160 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
24163 @multitable @columnfractions .35 .65
24165 @item @emph{HP Ada Command}
24166 @tab @emph{GNAT Equivalent / Description}
24168 @item @command{ADA}
24169 @tab @command{GNAT COMPILE}@*
24170 Invokes the compiler to compile one or more Ada source files.
24172 @item @command{ACS ATTACH}@*
24173 @tab [No equivalent]@*
24174 Switches control of terminal from current process running the program
24177 @item @command{ACS CHECK}
24178 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
24179 Forms the execution closure of one
24180 or more compiled units and checks completeness and currency.
24182 @item @command{ACS COMPILE}
24183 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
24184 Forms the execution closure of one or
24185 more specified units, checks completeness and currency,
24186 identifies units that have revised source files, compiles same,
24187 and recompiles units that are or will become obsolete.
24188 Also completes incomplete generic instantiations.
24190 @item @command{ACS COPY FOREIGN}
24192 Copies a foreign object file into the program library as a
24195 @item @command{ACS COPY UNIT}
24197 Copies a compiled unit from one program library to another.
24199 @item @command{ACS CREATE LIBRARY}
24200 @tab Create /directory (*)@*
24201 Creates a program library.
24203 @item @command{ACS CREATE SUBLIBRARY}
24204 @tab Create /directory (*)@*
24205 Creates a program sublibrary.
24207 @item @command{ACS DELETE LIBRARY}
24209 Deletes a program library and its contents.
24211 @item @command{ACS DELETE SUBLIBRARY}
24213 Deletes a program sublibrary and its contents.
24215 @item @command{ACS DELETE UNIT}
24216 @tab Delete file (*)@*
24217 On OpenVMS systems, deletes one or more compiled units from
24218 the current program library.
24220 @item @command{ACS DIRECTORY}
24221 @tab Directory (*)@*
24222 On OpenVMS systems, lists units contained in the current
24225 @item @command{ACS ENTER FOREIGN}
24227 Allows the import of a foreign body as an Ada library
24228 specification and enters a reference to a pointer.
24230 @item @command{ACS ENTER UNIT}
24232 Enters a reference (pointer) from the current program library to
24233 a unit compiled into another program library.
24235 @item @command{ACS EXIT}
24236 @tab [No equivalent]@*
24237 Exits from the program library manager.
24239 @item @command{ACS EXPORT}
24241 Creates an object file that contains system-specific object code
24242 for one or more units. With GNAT, object files can simply be copied
24243 into the desired directory.
24245 @item @command{ACS EXTRACT SOURCE}
24247 Allows access to the copied source file for each Ada compilation unit
24249 @item @command{ACS HELP}
24250 @tab @command{HELP GNAT}@*
24251 Provides online help.
24253 @item @command{ACS LINK}
24254 @tab @command{GNAT LINK}@*
24255 Links an object file containing Ada units into an executable file.
24257 @item @command{ACS LOAD}
24259 Loads (partially compiles) Ada units into the program library.
24260 Allows loading a program from a collection of files into a library
24261 without knowing the relationship among units.
24263 @item @command{ACS MERGE}
24265 Merges into the current program library, one or more units from
24266 another library where they were modified.
24268 @item @command{ACS RECOMPILE}
24269 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
24270 Recompiles from external or copied source files any obsolete
24271 unit in the closure. Also, completes any incomplete generic
24274 @item @command{ACS REENTER}
24275 @tab @command{GNAT MAKE}@*
24276 Reenters current references to units compiled after last entered
24277 with the @command{ACS ENTER UNIT} command.
24279 @item @command{ACS SET LIBRARY}
24280 @tab Set default (*)@*
24281 Defines a program library to be the compilation context as well
24282 as the target library for compiler output and commands in general.
24284 @item @command{ACS SET PRAGMA}
24285 @tab Edit @file{gnat.adc} (*)@*
24286 Redefines specified values of the library characteristics
24287 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
24288 and @code{Float_Representation}.
24290 @item @command{ACS SET SOURCE}
24291 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
24292 Defines the source file search list for the @command{ACS COMPILE} command.
24294 @item @command{ACS SHOW LIBRARY}
24295 @tab Directory (*)@*
24296 Lists information about one or more program libraries.
24298 @item @command{ACS SHOW PROGRAM}
24299 @tab [No equivalent]@*
24300 Lists information about the execution closure of one or
24301 more units in the program library.
24303 @item @command{ACS SHOW SOURCE}
24304 @tab Show logical @code{ADA_INCLUDE_PATH}@*
24305 Shows the source file search used when compiling units.
24307 @item @command{ACS SHOW VERSION}
24308 @tab Compile with @option{VERBOSE} option
24309 Displays the version number of the compiler and program library
24312 @item @command{ACS SPAWN}
24313 @tab [No equivalent]@*
24314 Creates a subprocess of the current process (same as @command{DCL SPAWN}
24317 @item @command{ACS VERIFY}
24318 @tab [No equivalent]@*
24319 Performs a series of consistency checks on a program library to
24320 determine whether the library structure and library files are in
24327 @section Input-Output
24330 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
24331 Management Services (RMS) to perform operations on
24335 HP Ada and GNAT predefine an identical set of input-
24336 output packages. To make the use of the
24337 generic @code{TEXT_IO} operations more convenient, HP Ada
24338 provides predefined library packages that instantiate the
24339 integer and floating-point operations for the predefined
24340 integer and floating-point types as shown in the following table.
24342 @multitable @columnfractions .45 .55
24343 @item @emph{Package Name} @tab Instantiation
24345 @item @code{INTEGER_TEXT_IO}
24346 @tab @code{INTEGER_IO(INTEGER)}
24348 @item @code{SHORT_INTEGER_TEXT_IO}
24349 @tab @code{INTEGER_IO(SHORT_INTEGER)}
24351 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
24352 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
24354 @item @code{FLOAT_TEXT_IO}
24355 @tab @code{FLOAT_IO(FLOAT)}
24357 @item @code{LONG_FLOAT_TEXT_IO}
24358 @tab @code{FLOAT_IO(LONG_FLOAT)}
24362 The HP Ada predefined packages and their operations
24363 are implemented using OpenVMS Alpha files and input-output
24364 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
24365 Familiarity with the following is recommended:
24367 @item RMS file organizations and access methods
24369 @item OpenVMS file specifications and directories
24371 @item OpenVMS File Definition Language (FDL)
24375 GNAT provides I/O facilities that are completely
24376 compatible with HP Ada. The distribution includes the
24377 standard HP Ada versions of all I/O packages, operating
24378 in a manner compatible with HP Ada. In particular, the
24379 following packages are by default the HP Ada (Ada 83)
24380 versions of these packages rather than the renamings
24381 suggested in Annex J of the Ada Reference Manual:
24383 @item @code{TEXT_IO}
24385 @item @code{SEQUENTIAL_IO}
24387 @item @code{DIRECT_IO}
24391 The use of the standard child package syntax (for
24392 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
24394 GNAT provides HP-compatible predefined instantiations
24395 of the @code{TEXT_IO} packages, and also
24396 provides the standard predefined instantiations required
24397 by the @cite{Ada Reference Manual}.
24399 For further information on how GNAT interfaces to the file
24400 system or how I/O is implemented in programs written in
24401 mixed languages, see the chapter ``Implementation of the
24402 Standard I/O'' in the @cite{GNAT Reference Manual}.
24403 This chapter covers the following:
24405 @item Standard I/O packages
24407 @item @code{FORM} strings
24409 @item @code{ADA.DIRECT_IO}
24411 @item @code{ADA.SEQUENTIAL_IO}
24413 @item @code{ADA.TEXT_IO}
24415 @item Stream pointer positioning
24417 @item Reading and writing non-regular files
24419 @item @code{GET_IMMEDIATE}
24421 @item Treating @code{TEXT_IO} files as streams
24428 @node Implementation Limits
24429 @section Implementation Limits
24432 The following table lists implementation limits for HP Ada
24434 @multitable @columnfractions .60 .20 .20
24436 @item @emph{Compilation Parameter}
24441 @item In a subprogram or entry declaration, maximum number of
24442 formal parameters that are of an unconstrained record type
24447 @item Maximum identifier length (number of characters)
24452 @item Maximum number of characters in a source line
24457 @item Maximum collection size (number of bytes)
24462 @item Maximum number of discriminants for a record type
24467 @item Maximum number of formal parameters in an entry or
24468 subprogram declaration
24473 @item Maximum number of dimensions in an array type
24478 @item Maximum number of library units and subunits in a compilation.
24483 @item Maximum number of library units and subunits in an execution.
24488 @item Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
24489 or @code{PSECT_OBJECT}
24494 @item Maximum number of enumeration literals in an enumeration type
24500 @item Maximum number of lines in a source file
24505 @item Maximum number of bits in any object
24510 @item Maximum size of the static portion of a stack frame (approximate)
24515 @node Tools and Utilities
24516 @section Tools and Utilities
24519 The following table lists some of the OpenVMS development tools
24520 available for HP Ada, and the corresponding tools for
24521 use with @value{EDITION} on Alpha and I64 platforms.
24522 Aside from the debugger, all the OpenVMS tools identified are part
24523 of the DECset package.
24526 @c Specify table in TeX since Texinfo does a poor job
24530 \settabs\+Language-Sensitive Editor\quad
24531 &Product with HP Ada\quad
24534 &\it Product with HP Ada
24535 & \it Product with GNAT Pro\cr
24537 \+Code Management System
24541 \+Language-Sensitive Editor
24543 & emacs or HP LSE (Alpha)\cr
24553 & OpenVMS Debug (I64)\cr
24555 \+Source Code Analyzer /
24572 \+Coverage Analyzer
24576 \+Module Management
24578 & Not applicable\cr
24588 @c This is the Texinfo version of the table. It renders poorly in pdf, hence
24589 @c the TeX version above for the printed version
24591 @c @multitable @columnfractions .3 .4 .4
24592 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
24594 @tab @i{Tool with HP Ada}
24595 @tab @i{Tool with @value{EDITION}}
24596 @item Code Management@*System
24599 @item Language-Sensitive@*Editor
24601 @tab emacs or HP LSE (Alpha)
24610 @tab OpenVMS Debug (I64)
24611 @item Source Code Analyzer /@*Cross Referencer
24615 @tab HP Digital Test@*Manager (DTM)
24617 @item Performance and@*Coverage Analyzer
24620 @item Module Management@*System
24622 @tab Not applicable
24629 @c **************************************
24630 @node Platform-Specific Information for the Run-Time Libraries
24631 @appendix Platform-Specific Information for the Run-Time Libraries
24632 @cindex Tasking and threads libraries
24633 @cindex Threads libraries and tasking
24634 @cindex Run-time libraries (platform-specific information)
24637 The GNAT run-time implementation may vary with respect to both the
24638 underlying threads library and the exception handling scheme.
24639 For threads support, one or more of the following are supplied:
24641 @item @b{native threads library}, a binding to the thread package from
24642 the underlying operating system
24644 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
24645 POSIX thread package
24649 For exception handling, either or both of two models are supplied:
24651 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
24652 Most programs should experience a substantial speed improvement by
24653 being compiled with a ZCX run-time.
24654 This is especially true for
24655 tasking applications or applications with many exception handlers.}
24656 @cindex Zero-Cost Exceptions
24657 @cindex ZCX (Zero-Cost Exceptions)
24658 which uses binder-generated tables that
24659 are interrogated at run time to locate a handler
24661 @item @b{setjmp / longjmp} (``SJLJ''),
24662 @cindex setjmp/longjmp Exception Model
24663 @cindex SJLJ (setjmp/longjmp Exception Model)
24664 which uses dynamically-set data to establish
24665 the set of handlers
24669 This appendix summarizes which combinations of threads and exception support
24670 are supplied on various GNAT platforms.
24671 It then shows how to select a particular library either
24672 permanently or temporarily,
24673 explains the properties of (and tradeoffs among) the various threads
24674 libraries, and provides some additional
24675 information about several specific platforms.
24678 * Summary of Run-Time Configurations::
24679 * Specifying a Run-Time Library::
24680 * Choosing the Scheduling Policy::
24681 * Solaris-Specific Considerations::
24682 * Linux-Specific Considerations::
24683 * AIX-Specific Considerations::
24686 @node Summary of Run-Time Configurations
24687 @section Summary of Run-Time Configurations
24689 @multitable @columnfractions .30 .70
24690 @item @b{alpha-openvms}
24691 @item @code{@ @ }@i{rts-native (default)}
24692 @item @code{@ @ @ @ }Tasking @tab native VMS threads
24693 @item @code{@ @ @ @ }Exceptions @tab ZCX
24695 @item @b{alpha-tru64}
24696 @item @code{@ @ }@i{rts-native (default)}
24697 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
24698 @item @code{@ @ @ @ }Exceptions @tab ZCX
24700 @item @code{@ @ }@i{rts-sjlj}
24701 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
24702 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24704 @item @b{ia64-hp_linux}
24705 @item @code{@ @ }@i{rts-native (default)}
24706 @item @code{@ @ @ @ }Tasking @tab pthread library
24707 @item @code{@ @ @ @ }Exceptions @tab ZCX
24709 @item @b{ia64-hpux}
24710 @item @code{@ @ }@i{rts-native (default)}
24711 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
24712 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24714 @item @b{ia64-openvms}
24715 @item @code{@ @ }@i{rts-native (default)}
24716 @item @code{@ @ @ @ }Tasking @tab native VMS threads
24717 @item @code{@ @ @ @ }Exceptions @tab ZCX
24719 @item @b{ia64-sgi_linux}
24720 @item @code{@ @ }@i{rts-native (default)}
24721 @item @code{@ @ @ @ }Tasking @tab pthread library
24722 @item @code{@ @ @ @ }Exceptions @tab ZCX
24724 @item @b{mips-irix}
24725 @item @code{@ @ }@i{rts-native (default)}
24726 @item @code{@ @ @ @ }Tasking @tab native IRIX threads
24727 @item @code{@ @ @ @ }Exceptions @tab ZCX
24730 @item @code{@ @ }@i{rts-native (default)}
24731 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
24732 @item @code{@ @ @ @ }Exceptions @tab ZCX
24734 @item @code{@ @ }@i{rts-sjlj}
24735 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
24736 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24739 @item @code{@ @ }@i{rts-native (default)}
24740 @item @code{@ @ @ @ }Tasking @tab native AIX threads
24741 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24743 @item @b{ppc-darwin}
24744 @item @code{@ @ }@i{rts-native (default)}
24745 @item @code{@ @ @ @ }Tasking @tab native MacOS threads
24746 @item @code{@ @ @ @ }Exceptions @tab ZCX
24748 @item @b{sparc-solaris} @tab
24749 @item @code{@ @ }@i{rts-native (default)}
24750 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
24751 @item @code{@ @ @ @ }Exceptions @tab ZCX
24753 @item @code{@ @ }@i{rts-pthread}
24754 @item @code{@ @ @ @ }Tasking @tab pthread library
24755 @item @code{@ @ @ @ }Exceptions @tab ZCX
24757 @item @code{@ @ }@i{rts-sjlj}
24758 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
24759 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24761 @item @b{sparc64-solaris} @tab
24762 @item @code{@ @ }@i{rts-native (default)}
24763 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
24764 @item @code{@ @ @ @ }Exceptions @tab ZCX
24766 @item @b{x86-linux}
24767 @item @code{@ @ }@i{rts-native (default)}
24768 @item @code{@ @ @ @ }Tasking @tab pthread library
24769 @item @code{@ @ @ @ }Exceptions @tab ZCX
24771 @item @code{@ @ }@i{rts-sjlj}
24772 @item @code{@ @ @ @ }Tasking @tab pthread library
24773 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24776 @item @code{@ @ }@i{rts-native (default)}
24777 @item @code{@ @ @ @ }Tasking @tab native LynxOS threads
24778 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24780 @item @b{x86-solaris}
24781 @item @code{@ @ }@i{rts-native (default)}
24782 @item @code{@ @ @ @ }Tasking @tab native Solaris threads
24783 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24785 @item @b{x86-windows}
24786 @item @code{@ @ }@i{rts-native (default)}
24787 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
24788 @item @code{@ @ @ @ }Exceptions @tab ZCX
24790 @item @code{@ @ }@i{rts-sjlj (default)}
24791 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
24792 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24794 @item @b{x86_64-linux}
24795 @item @code{@ @ }@i{rts-native (default)}
24796 @item @code{@ @ @ @ }Tasking @tab pthread library
24797 @item @code{@ @ @ @ }Exceptions @tab ZCX
24799 @item @code{@ @ }@i{rts-sjlj}
24800 @item @code{@ @ @ @ }Tasking @tab pthread library
24801 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24805 @node Specifying a Run-Time Library
24806 @section Specifying a Run-Time Library
24809 The @file{adainclude} subdirectory containing the sources of the GNAT
24810 run-time library, and the @file{adalib} subdirectory containing the
24811 @file{ALI} files and the static and/or shared GNAT library, are located
24812 in the gcc target-dependent area:
24815 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
24819 As indicated above, on some platforms several run-time libraries are supplied.
24820 These libraries are installed in the target dependent area and
24821 contain a complete source and binary subdirectory. The detailed description
24822 below explains the differences between the different libraries in terms of
24823 their thread support.
24825 The default run-time library (when GNAT is installed) is @emph{rts-native}.
24826 This default run time is selected by the means of soft links.
24827 For example on x86-linux:
24833 +--- adainclude----------+
24835 +--- adalib-----------+ |
24837 +--- rts-native | |
24839 | +--- adainclude <---+
24841 | +--- adalib <----+
24852 If the @i{rts-sjlj} library is to be selected on a permanent basis,
24853 these soft links can be modified with the following commands:
24857 $ rm -f adainclude adalib
24858 $ ln -s rts-sjlj/adainclude adainclude
24859 $ ln -s rts-sjlj/adalib adalib
24863 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
24864 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
24865 @file{$target/ada_object_path}.
24867 Selecting another run-time library temporarily can be
24868 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
24869 @cindex @option{--RTS} option
24871 @node Choosing the Scheduling Policy
24872 @section Choosing the Scheduling Policy
24875 When using a POSIX threads implementation, you have a choice of several
24876 scheduling policies: @code{SCHED_FIFO},
24877 @cindex @code{SCHED_FIFO} scheduling policy
24879 @cindex @code{SCHED_RR} scheduling policy
24880 and @code{SCHED_OTHER}.
24881 @cindex @code{SCHED_OTHER} scheduling policy
24882 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
24883 or @code{SCHED_RR} requires special (e.g., root) privileges.
24885 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
24887 @cindex @code{SCHED_FIFO} scheduling policy
24888 you can use one of the following:
24892 @code{pragma Time_Slice (0.0)}
24893 @cindex pragma Time_Slice
24895 the corresponding binder option @option{-T0}
24896 @cindex @option{-T0} option
24898 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
24899 @cindex pragma Task_Dispatching_Policy
24903 To specify @code{SCHED_RR},
24904 @cindex @code{SCHED_RR} scheduling policy
24905 you should use @code{pragma Time_Slice} with a
24906 value greater than @code{0.0}, or else use the corresponding @option{-T}
24909 @node Solaris-Specific Considerations
24910 @section Solaris-Specific Considerations
24911 @cindex Solaris Sparc threads libraries
24914 This section addresses some topics related to the various threads libraries
24918 * Solaris Threads Issues::
24921 @node Solaris Threads Issues
24922 @subsection Solaris Threads Issues
24925 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
24926 library based on POSIX threads --- @emph{rts-pthread}.
24927 @cindex rts-pthread threads library
24928 This run-time library has the advantage of being mostly shared across all
24929 POSIX-compliant thread implementations, and it also provides under
24930 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
24931 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
24932 and @code{PTHREAD_PRIO_PROTECT}
24933 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
24934 semantics that can be selected using the predefined pragma
24935 @code{Locking_Policy}
24936 @cindex pragma Locking_Policy (under rts-pthread)
24938 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
24939 @cindex @code{Inheritance_Locking} (under rts-pthread)
24940 @cindex @code{Ceiling_Locking} (under rts-pthread)
24942 As explained above, the native run-time library is based on the Solaris thread
24943 library (@code{libthread}) and is the default library.
24945 When the Solaris threads library is used (this is the default), programs
24946 compiled with GNAT can automatically take advantage of
24947 and can thus execute on multiple processors.
24948 The user can alternatively specify a processor on which the program should run
24949 to emulate a single-processor system. The multiprocessor / uniprocessor choice
24951 setting the environment variable @code{GNAT_PROCESSOR}
24952 @cindex @code{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
24953 to one of the following:
24957 Use the default configuration (run the program on all
24958 available processors) - this is the same as having
24959 @code{GNAT_PROCESSOR} unset
24962 Let the run-time implementation choose one processor and run the program on
24965 @item 0 .. Last_Proc
24966 Run the program on the specified processor.
24967 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
24968 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
24971 @node Linux-Specific Considerations
24972 @section Linux-Specific Considerations
24973 @cindex Linux threads libraries
24976 On GNU/Linux without NPTL support (usually system with GNU C Library
24977 older than 2.3), the signal model is not POSIX compliant, which means
24978 that to send a signal to the process, you need to send the signal to all
24979 threads, e.g. by using @code{killpg()}.
24981 @node AIX-Specific Considerations
24982 @section AIX-Specific Considerations
24983 @cindex AIX resolver library
24986 On AIX, the resolver library initializes some internal structure on
24987 the first call to @code{get*by*} functions, which are used to implement
24988 @code{GNAT.Sockets.Get_Host_By_Name} and
24989 @code{GNAT.Sockets.Get_Host_By_Address}.
24990 If such initialization occurs within an Ada task, and the stack size for
24991 the task is the default size, a stack overflow may occur.
24993 To avoid this overflow, the user should either ensure that the first call
24994 to @code{GNAT.Sockets.Get_Host_By_Name} or
24995 @code{GNAT.Sockets.Get_Host_By_Addrss}
24996 occurs in the environment task, or use @code{pragma Storage_Size} to
24997 specify a sufficiently large size for the stack of the task that contains
25000 @c *******************************
25001 @node Example of Binder Output File
25002 @appendix Example of Binder Output File
25005 This Appendix displays the source code for @command{gnatbind}'s output
25006 file generated for a simple ``Hello World'' program.
25007 Comments have been added for clarification purposes.
25009 @smallexample @c adanocomment
25013 -- The package is called Ada_Main unless this name is actually used
25014 -- as a unit name in the partition, in which case some other unique
25018 package ada_main is
25020 Elab_Final_Code : Integer;
25021 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
25023 -- The main program saves the parameters (argument count,
25024 -- argument values, environment pointer) in global variables
25025 -- for later access by other units including
25026 -- Ada.Command_Line.
25028 gnat_argc : Integer;
25029 gnat_argv : System.Address;
25030 gnat_envp : System.Address;
25032 -- The actual variables are stored in a library routine. This
25033 -- is useful for some shared library situations, where there
25034 -- are problems if variables are not in the library.
25036 pragma Import (C, gnat_argc);
25037 pragma Import (C, gnat_argv);
25038 pragma Import (C, gnat_envp);
25040 -- The exit status is similarly an external location
25042 gnat_exit_status : Integer;
25043 pragma Import (C, gnat_exit_status);
25045 GNAT_Version : constant String :=
25046 "GNAT Version: 6.0.0w (20061115)";
25047 pragma Export (C, GNAT_Version, "__gnat_version");
25049 -- This is the generated adafinal routine that performs
25050 -- finalization at the end of execution. In the case where
25051 -- Ada is the main program, this main program makes a call
25052 -- to adafinal at program termination.
25054 procedure adafinal;
25055 pragma Export (C, adafinal, "adafinal");
25057 -- This is the generated adainit routine that performs
25058 -- initialization at the start of execution. In the case
25059 -- where Ada is the main program, this main program makes
25060 -- a call to adainit at program startup.
25063 pragma Export (C, adainit, "adainit");
25065 -- This routine is called at the start of execution. It is
25066 -- a dummy routine that is used by the debugger to breakpoint
25067 -- at the start of execution.
25069 procedure Break_Start;
25070 pragma Import (C, Break_Start, "__gnat_break_start");
25072 -- This is the actual generated main program (it would be
25073 -- suppressed if the no main program switch were used). As
25074 -- required by standard system conventions, this program has
25075 -- the external name main.
25079 argv : System.Address;
25080 envp : System.Address)
25082 pragma Export (C, main, "main");
25084 -- The following set of constants give the version
25085 -- identification values for every unit in the bound
25086 -- partition. This identification is computed from all
25087 -- dependent semantic units, and corresponds to the
25088 -- string that would be returned by use of the
25089 -- Body_Version or Version attributes.
25091 type Version_32 is mod 2 ** 32;
25092 u00001 : constant Version_32 := 16#7880BEB3#;
25093 u00002 : constant Version_32 := 16#0D24CBD0#;
25094 u00003 : constant Version_32 := 16#3283DBEB#;
25095 u00004 : constant Version_32 := 16#2359F9ED#;
25096 u00005 : constant Version_32 := 16#664FB847#;
25097 u00006 : constant Version_32 := 16#68E803DF#;
25098 u00007 : constant Version_32 := 16#5572E604#;
25099 u00008 : constant Version_32 := 16#46B173D8#;
25100 u00009 : constant Version_32 := 16#156A40CF#;
25101 u00010 : constant Version_32 := 16#033DABE0#;
25102 u00011 : constant Version_32 := 16#6AB38FEA#;
25103 u00012 : constant Version_32 := 16#22B6217D#;
25104 u00013 : constant Version_32 := 16#68A22947#;
25105 u00014 : constant Version_32 := 16#18CC4A56#;
25106 u00015 : constant Version_32 := 16#08258E1B#;
25107 u00016 : constant Version_32 := 16#367D5222#;
25108 u00017 : constant Version_32 := 16#20C9ECA4#;
25109 u00018 : constant Version_32 := 16#50D32CB6#;
25110 u00019 : constant Version_32 := 16#39A8BB77#;
25111 u00020 : constant Version_32 := 16#5CF8FA2B#;
25112 u00021 : constant Version_32 := 16#2F1EB794#;
25113 u00022 : constant Version_32 := 16#31AB6444#;
25114 u00023 : constant Version_32 := 16#1574B6E9#;
25115 u00024 : constant Version_32 := 16#5109C189#;
25116 u00025 : constant Version_32 := 16#56D770CD#;
25117 u00026 : constant Version_32 := 16#02F9DE3D#;
25118 u00027 : constant Version_32 := 16#08AB6B2C#;
25119 u00028 : constant Version_32 := 16#3FA37670#;
25120 u00029 : constant Version_32 := 16#476457A0#;
25121 u00030 : constant Version_32 := 16#731E1B6E#;
25122 u00031 : constant Version_32 := 16#23C2E789#;
25123 u00032 : constant Version_32 := 16#0F1BD6A1#;
25124 u00033 : constant Version_32 := 16#7C25DE96#;
25125 u00034 : constant Version_32 := 16#39ADFFA2#;
25126 u00035 : constant Version_32 := 16#571DE3E7#;
25127 u00036 : constant Version_32 := 16#5EB646AB#;
25128 u00037 : constant Version_32 := 16#4249379B#;
25129 u00038 : constant Version_32 := 16#0357E00A#;
25130 u00039 : constant Version_32 := 16#3784FB72#;
25131 u00040 : constant Version_32 := 16#2E723019#;
25132 u00041 : constant Version_32 := 16#623358EA#;
25133 u00042 : constant Version_32 := 16#107F9465#;
25134 u00043 : constant Version_32 := 16#6843F68A#;
25135 u00044 : constant Version_32 := 16#63305874#;
25136 u00045 : constant Version_32 := 16#31E56CE1#;
25137 u00046 : constant Version_32 := 16#02917970#;
25138 u00047 : constant Version_32 := 16#6CCBA70E#;
25139 u00048 : constant Version_32 := 16#41CD4204#;
25140 u00049 : constant Version_32 := 16#572E3F58#;
25141 u00050 : constant Version_32 := 16#20729FF5#;
25142 u00051 : constant Version_32 := 16#1D4F93E8#;
25143 u00052 : constant Version_32 := 16#30B2EC3D#;
25144 u00053 : constant Version_32 := 16#34054F96#;
25145 u00054 : constant Version_32 := 16#5A199860#;
25146 u00055 : constant Version_32 := 16#0E7F912B#;
25147 u00056 : constant Version_32 := 16#5760634A#;
25148 u00057 : constant Version_32 := 16#5D851835#;
25150 -- The following Export pragmas export the version numbers
25151 -- with symbolic names ending in B (for body) or S
25152 -- (for spec) so that they can be located in a link. The
25153 -- information provided here is sufficient to track down
25154 -- the exact versions of units used in a given build.
25156 pragma Export (C, u00001, "helloB");
25157 pragma Export (C, u00002, "system__standard_libraryB");
25158 pragma Export (C, u00003, "system__standard_libraryS");
25159 pragma Export (C, u00004, "adaS");
25160 pragma Export (C, u00005, "ada__text_ioB");
25161 pragma Export (C, u00006, "ada__text_ioS");
25162 pragma Export (C, u00007, "ada__exceptionsB");
25163 pragma Export (C, u00008, "ada__exceptionsS");
25164 pragma Export (C, u00009, "gnatS");
25165 pragma Export (C, u00010, "gnat__heap_sort_aB");
25166 pragma Export (C, u00011, "gnat__heap_sort_aS");
25167 pragma Export (C, u00012, "systemS");
25168 pragma Export (C, u00013, "system__exception_tableB");
25169 pragma Export (C, u00014, "system__exception_tableS");
25170 pragma Export (C, u00015, "gnat__htableB");
25171 pragma Export (C, u00016, "gnat__htableS");
25172 pragma Export (C, u00017, "system__exceptionsS");
25173 pragma Export (C, u00018, "system__machine_state_operationsB");
25174 pragma Export (C, u00019, "system__machine_state_operationsS");
25175 pragma Export (C, u00020, "system__machine_codeS");
25176 pragma Export (C, u00021, "system__storage_elementsB");
25177 pragma Export (C, u00022, "system__storage_elementsS");
25178 pragma Export (C, u00023, "system__secondary_stackB");
25179 pragma Export (C, u00024, "system__secondary_stackS");
25180 pragma Export (C, u00025, "system__parametersB");
25181 pragma Export (C, u00026, "system__parametersS");
25182 pragma Export (C, u00027, "system__soft_linksB");
25183 pragma Export (C, u00028, "system__soft_linksS");
25184 pragma Export (C, u00029, "system__stack_checkingB");
25185 pragma Export (C, u00030, "system__stack_checkingS");
25186 pragma Export (C, u00031, "system__tracebackB");
25187 pragma Export (C, u00032, "system__tracebackS");
25188 pragma Export (C, u00033, "ada__streamsS");
25189 pragma Export (C, u00034, "ada__tagsB");
25190 pragma Export (C, u00035, "ada__tagsS");
25191 pragma Export (C, u00036, "system__string_opsB");
25192 pragma Export (C, u00037, "system__string_opsS");
25193 pragma Export (C, u00038, "interfacesS");
25194 pragma Export (C, u00039, "interfaces__c_streamsB");
25195 pragma Export (C, u00040, "interfaces__c_streamsS");
25196 pragma Export (C, u00041, "system__file_ioB");
25197 pragma Export (C, u00042, "system__file_ioS");
25198 pragma Export (C, u00043, "ada__finalizationB");
25199 pragma Export (C, u00044, "ada__finalizationS");
25200 pragma Export (C, u00045, "system__finalization_rootB");
25201 pragma Export (C, u00046, "system__finalization_rootS");
25202 pragma Export (C, u00047, "system__finalization_implementationB");
25203 pragma Export (C, u00048, "system__finalization_implementationS");
25204 pragma Export (C, u00049, "system__string_ops_concat_3B");
25205 pragma Export (C, u00050, "system__string_ops_concat_3S");
25206 pragma Export (C, u00051, "system__stream_attributesB");
25207 pragma Export (C, u00052, "system__stream_attributesS");
25208 pragma Export (C, u00053, "ada__io_exceptionsS");
25209 pragma Export (C, u00054, "system__unsigned_typesS");
25210 pragma Export (C, u00055, "system__file_control_blockS");
25211 pragma Export (C, u00056, "ada__finalization__list_controllerB");
25212 pragma Export (C, u00057, "ada__finalization__list_controllerS");
25214 -- BEGIN ELABORATION ORDER
25217 -- gnat.heap_sort_a (spec)
25218 -- gnat.heap_sort_a (body)
25219 -- gnat.htable (spec)
25220 -- gnat.htable (body)
25221 -- interfaces (spec)
25223 -- system.machine_code (spec)
25224 -- system.parameters (spec)
25225 -- system.parameters (body)
25226 -- interfaces.c_streams (spec)
25227 -- interfaces.c_streams (body)
25228 -- system.standard_library (spec)
25229 -- ada.exceptions (spec)
25230 -- system.exception_table (spec)
25231 -- system.exception_table (body)
25232 -- ada.io_exceptions (spec)
25233 -- system.exceptions (spec)
25234 -- system.storage_elements (spec)
25235 -- system.storage_elements (body)
25236 -- system.machine_state_operations (spec)
25237 -- system.machine_state_operations (body)
25238 -- system.secondary_stack (spec)
25239 -- system.stack_checking (spec)
25240 -- system.soft_links (spec)
25241 -- system.soft_links (body)
25242 -- system.stack_checking (body)
25243 -- system.secondary_stack (body)
25244 -- system.standard_library (body)
25245 -- system.string_ops (spec)
25246 -- system.string_ops (body)
25249 -- ada.streams (spec)
25250 -- system.finalization_root (spec)
25251 -- system.finalization_root (body)
25252 -- system.string_ops_concat_3 (spec)
25253 -- system.string_ops_concat_3 (body)
25254 -- system.traceback (spec)
25255 -- system.traceback (body)
25256 -- ada.exceptions (body)
25257 -- system.unsigned_types (spec)
25258 -- system.stream_attributes (spec)
25259 -- system.stream_attributes (body)
25260 -- system.finalization_implementation (spec)
25261 -- system.finalization_implementation (body)
25262 -- ada.finalization (spec)
25263 -- ada.finalization (body)
25264 -- ada.finalization.list_controller (spec)
25265 -- ada.finalization.list_controller (body)
25266 -- system.file_control_block (spec)
25267 -- system.file_io (spec)
25268 -- system.file_io (body)
25269 -- ada.text_io (spec)
25270 -- ada.text_io (body)
25272 -- END ELABORATION ORDER
25276 -- The following source file name pragmas allow the generated file
25277 -- names to be unique for different main programs. They are needed
25278 -- since the package name will always be Ada_Main.
25280 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
25281 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
25283 -- Generated package body for Ada_Main starts here
25285 package body ada_main is
25287 -- The actual finalization is performed by calling the
25288 -- library routine in System.Standard_Library.Adafinal
25290 procedure Do_Finalize;
25291 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
25298 procedure adainit is
25300 -- These booleans are set to True once the associated unit has
25301 -- been elaborated. It is also used to avoid elaborating the
25302 -- same unit twice.
25305 pragma Import (Ada, E040, "interfaces__c_streams_E");
25308 pragma Import (Ada, E008, "ada__exceptions_E");
25311 pragma Import (Ada, E014, "system__exception_table_E");
25314 pragma Import (Ada, E053, "ada__io_exceptions_E");
25317 pragma Import (Ada, E017, "system__exceptions_E");
25320 pragma Import (Ada, E024, "system__secondary_stack_E");
25323 pragma Import (Ada, E030, "system__stack_checking_E");
25326 pragma Import (Ada, E028, "system__soft_links_E");
25329 pragma Import (Ada, E035, "ada__tags_E");
25332 pragma Import (Ada, E033, "ada__streams_E");
25335 pragma Import (Ada, E046, "system__finalization_root_E");
25338 pragma Import (Ada, E048, "system__finalization_implementation_E");
25341 pragma Import (Ada, E044, "ada__finalization_E");
25344 pragma Import (Ada, E057, "ada__finalization__list_controller_E");
25347 pragma Import (Ada, E055, "system__file_control_block_E");
25350 pragma Import (Ada, E042, "system__file_io_E");
25353 pragma Import (Ada, E006, "ada__text_io_E");
25355 -- Set_Globals is a library routine that stores away the
25356 -- value of the indicated set of global values in global
25357 -- variables within the library.
25359 procedure Set_Globals
25360 (Main_Priority : Integer;
25361 Time_Slice_Value : Integer;
25362 WC_Encoding : Character;
25363 Locking_Policy : Character;
25364 Queuing_Policy : Character;
25365 Task_Dispatching_Policy : Character;
25366 Adafinal : System.Address;
25367 Unreserve_All_Interrupts : Integer;
25368 Exception_Tracebacks : Integer);
25369 @findex __gnat_set_globals
25370 pragma Import (C, Set_Globals, "__gnat_set_globals");
25372 -- SDP_Table_Build is a library routine used to build the
25373 -- exception tables. See unit Ada.Exceptions in files
25374 -- a-except.ads/adb for full details of how zero cost
25375 -- exception handling works. This procedure, the call to
25376 -- it, and the two following tables are all omitted if the
25377 -- build is in longjmp/setjump exception mode.
25379 @findex SDP_Table_Build
25380 @findex Zero Cost Exceptions
25381 procedure SDP_Table_Build
25382 (SDP_Addresses : System.Address;
25383 SDP_Count : Natural;
25384 Elab_Addresses : System.Address;
25385 Elab_Addr_Count : Natural);
25386 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
25388 -- Table of Unit_Exception_Table addresses. Used for zero
25389 -- cost exception handling to build the top level table.
25391 ST : aliased constant array (1 .. 23) of System.Address := (
25393 Ada.Text_Io'UET_Address,
25394 Ada.Exceptions'UET_Address,
25395 Gnat.Heap_Sort_A'UET_Address,
25396 System.Exception_Table'UET_Address,
25397 System.Machine_State_Operations'UET_Address,
25398 System.Secondary_Stack'UET_Address,
25399 System.Parameters'UET_Address,
25400 System.Soft_Links'UET_Address,
25401 System.Stack_Checking'UET_Address,
25402 System.Traceback'UET_Address,
25403 Ada.Streams'UET_Address,
25404 Ada.Tags'UET_Address,
25405 System.String_Ops'UET_Address,
25406 Interfaces.C_Streams'UET_Address,
25407 System.File_Io'UET_Address,
25408 Ada.Finalization'UET_Address,
25409 System.Finalization_Root'UET_Address,
25410 System.Finalization_Implementation'UET_Address,
25411 System.String_Ops_Concat_3'UET_Address,
25412 System.Stream_Attributes'UET_Address,
25413 System.File_Control_Block'UET_Address,
25414 Ada.Finalization.List_Controller'UET_Address);
25416 -- Table of addresses of elaboration routines. Used for
25417 -- zero cost exception handling to make sure these
25418 -- addresses are included in the top level procedure
25421 EA : aliased constant array (1 .. 23) of System.Address := (
25422 adainit'Code_Address,
25423 Do_Finalize'Code_Address,
25424 Ada.Exceptions'Elab_Spec'Address,
25425 System.Exceptions'Elab_Spec'Address,
25426 Interfaces.C_Streams'Elab_Spec'Address,
25427 System.Exception_Table'Elab_Body'Address,
25428 Ada.Io_Exceptions'Elab_Spec'Address,
25429 System.Stack_Checking'Elab_Spec'Address,
25430 System.Soft_Links'Elab_Body'Address,
25431 System.Secondary_Stack'Elab_Body'Address,
25432 Ada.Tags'Elab_Spec'Address,
25433 Ada.Tags'Elab_Body'Address,
25434 Ada.Streams'Elab_Spec'Address,
25435 System.Finalization_Root'Elab_Spec'Address,
25436 Ada.Exceptions'Elab_Body'Address,
25437 System.Finalization_Implementation'Elab_Spec'Address,
25438 System.Finalization_Implementation'Elab_Body'Address,
25439 Ada.Finalization'Elab_Spec'Address,
25440 Ada.Finalization.List_Controller'Elab_Spec'Address,
25441 System.File_Control_Block'Elab_Spec'Address,
25442 System.File_Io'Elab_Body'Address,
25443 Ada.Text_Io'Elab_Spec'Address,
25444 Ada.Text_Io'Elab_Body'Address);
25446 -- Start of processing for adainit
25450 -- Call SDP_Table_Build to build the top level procedure
25451 -- table for zero cost exception handling (omitted in
25452 -- longjmp/setjump mode).
25454 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
25456 -- Call Set_Globals to record various information for
25457 -- this partition. The values are derived by the binder
25458 -- from information stored in the ali files by the compiler.
25460 @findex __gnat_set_globals
25462 (Main_Priority => -1,
25463 -- Priority of main program, -1 if no pragma Priority used
25465 Time_Slice_Value => -1,
25466 -- Time slice from Time_Slice pragma, -1 if none used
25468 WC_Encoding => 'b',
25469 -- Wide_Character encoding used, default is brackets
25471 Locking_Policy => ' ',
25472 -- Locking_Policy used, default of space means not
25473 -- specified, otherwise it is the first character of
25474 -- the policy name.
25476 Queuing_Policy => ' ',
25477 -- Queuing_Policy used, default of space means not
25478 -- specified, otherwise it is the first character of
25479 -- the policy name.
25481 Task_Dispatching_Policy => ' ',
25482 -- Task_Dispatching_Policy used, default of space means
25483 -- not specified, otherwise first character of the
25486 Adafinal => System.Null_Address,
25487 -- Address of Adafinal routine, not used anymore
25489 Unreserve_All_Interrupts => 0,
25490 -- Set true if pragma Unreserve_All_Interrupts was used
25492 Exception_Tracebacks => 0);
25493 -- Indicates if exception tracebacks are enabled
25495 Elab_Final_Code := 1;
25497 -- Now we have the elaboration calls for all units in the partition.
25498 -- The Elab_Spec and Elab_Body attributes generate references to the
25499 -- implicit elaboration procedures generated by the compiler for
25500 -- each unit that requires elaboration.
25503 Interfaces.C_Streams'Elab_Spec;
25507 Ada.Exceptions'Elab_Spec;
25510 System.Exception_Table'Elab_Body;
25514 Ada.Io_Exceptions'Elab_Spec;
25518 System.Exceptions'Elab_Spec;
25522 System.Stack_Checking'Elab_Spec;
25525 System.Soft_Links'Elab_Body;
25530 System.Secondary_Stack'Elab_Body;
25534 Ada.Tags'Elab_Spec;
25537 Ada.Tags'Elab_Body;
25541 Ada.Streams'Elab_Spec;
25545 System.Finalization_Root'Elab_Spec;
25549 Ada.Exceptions'Elab_Body;
25553 System.Finalization_Implementation'Elab_Spec;
25556 System.Finalization_Implementation'Elab_Body;
25560 Ada.Finalization'Elab_Spec;
25564 Ada.Finalization.List_Controller'Elab_Spec;
25568 System.File_Control_Block'Elab_Spec;
25572 System.File_Io'Elab_Body;
25576 Ada.Text_Io'Elab_Spec;
25579 Ada.Text_Io'Elab_Body;
25583 Elab_Final_Code := 0;
25591 procedure adafinal is
25600 -- main is actually a function, as in the ANSI C standard,
25601 -- defined to return the exit status. The three parameters
25602 -- are the argument count, argument values and environment
25605 @findex Main Program
25608 argv : System.Address;
25609 envp : System.Address)
25612 -- The initialize routine performs low level system
25613 -- initialization using a standard library routine which
25614 -- sets up signal handling and performs any other
25615 -- required setup. The routine can be found in file
25618 @findex __gnat_initialize
25619 procedure initialize;
25620 pragma Import (C, initialize, "__gnat_initialize");
25622 -- The finalize routine performs low level system
25623 -- finalization using a standard library routine. The
25624 -- routine is found in file a-final.c and in the standard
25625 -- distribution is a dummy routine that does nothing, so
25626 -- really this is a hook for special user finalization.
25628 @findex __gnat_finalize
25629 procedure finalize;
25630 pragma Import (C, finalize, "__gnat_finalize");
25632 -- We get to the main program of the partition by using
25633 -- pragma Import because if we try to with the unit and
25634 -- call it Ada style, then not only do we waste time
25635 -- recompiling it, but also, we don't really know the right
25636 -- switches (e.g. identifier character set) to be used
25639 procedure Ada_Main_Program;
25640 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
25642 -- Start of processing for main
25645 -- Save global variables
25651 -- Call low level system initialization
25655 -- Call our generated Ada initialization routine
25659 -- This is the point at which we want the debugger to get
25664 -- Now we call the main program of the partition
25668 -- Perform Ada finalization
25672 -- Perform low level system finalization
25676 -- Return the proper exit status
25677 return (gnat_exit_status);
25680 -- This section is entirely comments, so it has no effect on the
25681 -- compilation of the Ada_Main package. It provides the list of
25682 -- object files and linker options, as well as some standard
25683 -- libraries needed for the link. The gnatlink utility parses
25684 -- this b~hello.adb file to read these comment lines to generate
25685 -- the appropriate command line arguments for the call to the
25686 -- system linker. The BEGIN/END lines are used for sentinels for
25687 -- this parsing operation.
25689 -- The exact file names will of course depend on the environment,
25690 -- host/target and location of files on the host system.
25692 @findex Object file list
25693 -- BEGIN Object file/option list
25696 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
25697 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
25698 -- END Object file/option list
25704 The Ada code in the above example is exactly what is generated by the
25705 binder. We have added comments to more clearly indicate the function
25706 of each part of the generated @code{Ada_Main} package.
25708 The code is standard Ada in all respects, and can be processed by any
25709 tools that handle Ada. In particular, it is possible to use the debugger
25710 in Ada mode to debug the generated @code{Ada_Main} package. For example,
25711 suppose that for reasons that you do not understand, your program is crashing
25712 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
25713 you can place a breakpoint on the call:
25715 @smallexample @c ada
25716 Ada.Text_Io'Elab_Body;
25720 and trace the elaboration routine for this package to find out where
25721 the problem might be (more usually of course you would be debugging
25722 elaboration code in your own application).
25724 @node Elaboration Order Handling in GNAT
25725 @appendix Elaboration Order Handling in GNAT
25726 @cindex Order of elaboration
25727 @cindex Elaboration control
25730 * Elaboration Code::
25731 * Checking the Elaboration Order::
25732 * Controlling the Elaboration Order::
25733 * Controlling Elaboration in GNAT - Internal Calls::
25734 * Controlling Elaboration in GNAT - External Calls::
25735 * Default Behavior in GNAT - Ensuring Safety::
25736 * Treatment of Pragma Elaborate::
25737 * Elaboration Issues for Library Tasks::
25738 * Mixing Elaboration Models::
25739 * What to Do If the Default Elaboration Behavior Fails::
25740 * Elaboration for Access-to-Subprogram Values::
25741 * Summary of Procedures for Elaboration Control::
25742 * Other Elaboration Order Considerations::
25746 This chapter describes the handling of elaboration code in Ada and
25747 in GNAT, and discusses how the order of elaboration of program units can
25748 be controlled in GNAT, either automatically or with explicit programming
25751 @node Elaboration Code
25752 @section Elaboration Code
25755 Ada provides rather general mechanisms for executing code at elaboration
25756 time, that is to say before the main program starts executing. Such code arises
25760 @item Initializers for variables.
25761 Variables declared at the library level, in package specs or bodies, can
25762 require initialization that is performed at elaboration time, as in:
25763 @smallexample @c ada
25765 Sqrt_Half : Float := Sqrt (0.5);
25769 @item Package initialization code
25770 Code in a @code{BEGIN-END} section at the outer level of a package body is
25771 executed as part of the package body elaboration code.
25773 @item Library level task allocators
25774 Tasks that are declared using task allocators at the library level
25775 start executing immediately and hence can execute at elaboration time.
25779 Subprogram calls are possible in any of these contexts, which means that
25780 any arbitrary part of the program may be executed as part of the elaboration
25781 code. It is even possible to write a program which does all its work at
25782 elaboration time, with a null main program, although stylistically this
25783 would usually be considered an inappropriate way to structure
25786 An important concern arises in the context of elaboration code:
25787 we have to be sure that it is executed in an appropriate order. What we
25788 have is a series of elaboration code sections, potentially one section
25789 for each unit in the program. It is important that these execute
25790 in the correct order. Correctness here means that, taking the above
25791 example of the declaration of @code{Sqrt_Half},
25792 if some other piece of
25793 elaboration code references @code{Sqrt_Half},
25794 then it must run after the
25795 section of elaboration code that contains the declaration of
25798 There would never be any order of elaboration problem if we made a rule
25799 that whenever you @code{with} a unit, you must elaborate both the spec and body
25800 of that unit before elaborating the unit doing the @code{with}'ing:
25802 @smallexample @c ada
25806 package Unit_2 is ...
25812 would require that both the body and spec of @code{Unit_1} be elaborated
25813 before the spec of @code{Unit_2}. However, a rule like that would be far too
25814 restrictive. In particular, it would make it impossible to have routines
25815 in separate packages that were mutually recursive.
25817 You might think that a clever enough compiler could look at the actual
25818 elaboration code and determine an appropriate correct order of elaboration,
25819 but in the general case, this is not possible. Consider the following
25822 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
25824 the variable @code{Sqrt_1}, which is declared in the elaboration code
25825 of the body of @code{Unit_1}:
25827 @smallexample @c ada
25829 Sqrt_1 : Float := Sqrt (0.1);
25834 The elaboration code of the body of @code{Unit_1} also contains:
25836 @smallexample @c ada
25839 if expression_1 = 1 then
25840 Q := Unit_2.Func_2;
25847 @code{Unit_2} is exactly parallel,
25848 it has a procedure @code{Func_2} that references
25849 the variable @code{Sqrt_2}, which is declared in the elaboration code of
25850 the body @code{Unit_2}:
25852 @smallexample @c ada
25854 Sqrt_2 : Float := Sqrt (0.1);
25859 The elaboration code of the body of @code{Unit_2} also contains:
25861 @smallexample @c ada
25864 if expression_2 = 2 then
25865 Q := Unit_1.Func_1;
25872 Now the question is, which of the following orders of elaboration is
25897 If you carefully analyze the flow here, you will see that you cannot tell
25898 at compile time the answer to this question.
25899 If @code{expression_1} is not equal to 1,
25900 and @code{expression_2} is not equal to 2,
25901 then either order is acceptable, because neither of the function calls is
25902 executed. If both tests evaluate to true, then neither order is acceptable
25903 and in fact there is no correct order.
25905 If one of the two expressions is true, and the other is false, then one
25906 of the above orders is correct, and the other is incorrect. For example,
25907 if @code{expression_1} /= 1 and @code{expression_2} = 2,
25908 then the call to @code{Func_1}
25909 will occur, but not the call to @code{Func_2.}
25910 This means that it is essential
25911 to elaborate the body of @code{Unit_1} before
25912 the body of @code{Unit_2}, so the first
25913 order of elaboration is correct and the second is wrong.
25915 By making @code{expression_1} and @code{expression_2}
25916 depend on input data, or perhaps
25917 the time of day, we can make it impossible for the compiler or binder
25918 to figure out which of these expressions will be true, and hence it
25919 is impossible to guarantee a safe order of elaboration at run time.
25921 @node Checking the Elaboration Order
25922 @section Checking the Elaboration Order
25925 In some languages that involve the same kind of elaboration problems,
25926 e.g. Java and C++, the programmer is expected to worry about these
25927 ordering problems himself, and it is common to
25928 write a program in which an incorrect elaboration order gives
25929 surprising results, because it references variables before they
25931 Ada is designed to be a safe language, and a programmer-beware approach is
25932 clearly not sufficient. Consequently, the language provides three lines
25936 @item Standard rules
25937 Some standard rules restrict the possible choice of elaboration
25938 order. In particular, if you @code{with} a unit, then its spec is always
25939 elaborated before the unit doing the @code{with}. Similarly, a parent
25940 spec is always elaborated before the child spec, and finally
25941 a spec is always elaborated before its corresponding body.
25943 @item Dynamic elaboration checks
25944 @cindex Elaboration checks
25945 @cindex Checks, elaboration
25946 Dynamic checks are made at run time, so that if some entity is accessed
25947 before it is elaborated (typically by means of a subprogram call)
25948 then the exception (@code{Program_Error}) is raised.
25950 @item Elaboration control
25951 Facilities are provided for the programmer to specify the desired order
25955 Let's look at these facilities in more detail. First, the rules for
25956 dynamic checking. One possible rule would be simply to say that the
25957 exception is raised if you access a variable which has not yet been
25958 elaborated. The trouble with this approach is that it could require
25959 expensive checks on every variable reference. Instead Ada has two
25960 rules which are a little more restrictive, but easier to check, and
25964 @item Restrictions on calls
25965 A subprogram can only be called at elaboration time if its body
25966 has been elaborated. The rules for elaboration given above guarantee
25967 that the spec of the subprogram has been elaborated before the
25968 call, but not the body. If this rule is violated, then the
25969 exception @code{Program_Error} is raised.
25971 @item Restrictions on instantiations
25972 A generic unit can only be instantiated if the body of the generic
25973 unit has been elaborated. Again, the rules for elaboration given above
25974 guarantee that the spec of the generic unit has been elaborated
25975 before the instantiation, but not the body. If this rule is
25976 violated, then the exception @code{Program_Error} is raised.
25980 The idea is that if the body has been elaborated, then any variables
25981 it references must have been elaborated; by checking for the body being
25982 elaborated we guarantee that none of its references causes any
25983 trouble. As we noted above, this is a little too restrictive, because a
25984 subprogram that has no non-local references in its body may in fact be safe
25985 to call. However, it really would be unsafe to rely on this, because
25986 it would mean that the caller was aware of details of the implementation
25987 in the body. This goes against the basic tenets of Ada.
25989 A plausible implementation can be described as follows.
25990 A Boolean variable is associated with each subprogram
25991 and each generic unit. This variable is initialized to False, and is set to
25992 True at the point body is elaborated. Every call or instantiation checks the
25993 variable, and raises @code{Program_Error} if the variable is False.
25995 Note that one might think that it would be good enough to have one Boolean
25996 variable for each package, but that would not deal with cases of trying
25997 to call a body in the same package as the call
25998 that has not been elaborated yet.
25999 Of course a compiler may be able to do enough analysis to optimize away
26000 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
26001 does such optimizations, but still the easiest conceptual model is to
26002 think of there being one variable per subprogram.
26004 @node Controlling the Elaboration Order
26005 @section Controlling the Elaboration Order
26008 In the previous section we discussed the rules in Ada which ensure
26009 that @code{Program_Error} is raised if an incorrect elaboration order is
26010 chosen. This prevents erroneous executions, but we need mechanisms to
26011 specify a correct execution and avoid the exception altogether.
26012 To achieve this, Ada provides a number of features for controlling
26013 the order of elaboration. We discuss these features in this section.
26015 First, there are several ways of indicating to the compiler that a given
26016 unit has no elaboration problems:
26019 @item packages that do not require a body
26020 A library package that does not require a body does not permit
26021 a body (this rule was introduced in Ada 95).
26022 Thus if we have a such a package, as in:
26024 @smallexample @c ada
26027 package Definitions is
26029 type m is new integer;
26031 type a is array (1 .. 10) of m;
26032 type b is array (1 .. 20) of m;
26040 A package that @code{with}'s @code{Definitions} may safely instantiate
26041 @code{Definitions.Subp} because the compiler can determine that there
26042 definitely is no package body to worry about in this case
26045 @cindex pragma Pure
26047 Places sufficient restrictions on a unit to guarantee that
26048 no call to any subprogram in the unit can result in an
26049 elaboration problem. This means that the compiler does not need
26050 to worry about the point of elaboration of such units, and in
26051 particular, does not need to check any calls to any subprograms
26054 @item pragma Preelaborate
26055 @findex Preelaborate
26056 @cindex pragma Preelaborate
26057 This pragma places slightly less stringent restrictions on a unit than
26059 but these restrictions are still sufficient to ensure that there
26060 are no elaboration problems with any calls to the unit.
26062 @item pragma Elaborate_Body
26063 @findex Elaborate_Body
26064 @cindex pragma Elaborate_Body
26065 This pragma requires that the body of a unit be elaborated immediately
26066 after its spec. Suppose a unit @code{A} has such a pragma,
26067 and unit @code{B} does
26068 a @code{with} of unit @code{A}. Recall that the standard rules require
26069 the spec of unit @code{A}
26070 to be elaborated before the @code{with}'ing unit; given the pragma in
26071 @code{A}, we also know that the body of @code{A}
26072 will be elaborated before @code{B}, so
26073 that calls to @code{A} are safe and do not need a check.
26078 unlike pragma @code{Pure} and pragma @code{Preelaborate},
26080 @code{Elaborate_Body} does not guarantee that the program is
26081 free of elaboration problems, because it may not be possible
26082 to satisfy the requested elaboration order.
26083 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
26085 marks @code{Unit_1} as @code{Elaborate_Body},
26086 and not @code{Unit_2,} then the order of
26087 elaboration will be:
26099 Now that means that the call to @code{Func_1} in @code{Unit_2}
26100 need not be checked,
26101 it must be safe. But the call to @code{Func_2} in
26102 @code{Unit_1} may still fail if
26103 @code{Expression_1} is equal to 1,
26104 and the programmer must still take
26105 responsibility for this not being the case.
26107 If all units carry a pragma @code{Elaborate_Body}, then all problems are
26108 eliminated, except for calls entirely within a body, which are
26109 in any case fully under programmer control. However, using the pragma
26110 everywhere is not always possible.
26111 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
26112 we marked both of them as having pragma @code{Elaborate_Body}, then
26113 clearly there would be no possible elaboration order.
26115 The above pragmas allow a server to guarantee safe use by clients, and
26116 clearly this is the preferable approach. Consequently a good rule
26117 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
26118 and if this is not possible,
26119 mark them as @code{Elaborate_Body} if possible.
26120 As we have seen, there are situations where neither of these
26121 three pragmas can be used.
26122 So we also provide methods for clients to control the
26123 order of elaboration of the servers on which they depend:
26126 @item pragma Elaborate (unit)
26128 @cindex pragma Elaborate
26129 This pragma is placed in the context clause, after a @code{with} clause,
26130 and it requires that the body of the named unit be elaborated before
26131 the unit in which the pragma occurs. The idea is to use this pragma
26132 if the current unit calls at elaboration time, directly or indirectly,
26133 some subprogram in the named unit.
26135 @item pragma Elaborate_All (unit)
26136 @findex Elaborate_All
26137 @cindex pragma Elaborate_All
26138 This is a stronger version of the Elaborate pragma. Consider the
26142 Unit A @code{with}'s unit B and calls B.Func in elab code
26143 Unit B @code{with}'s unit C, and B.Func calls C.Func
26147 Now if we put a pragma @code{Elaborate (B)}
26148 in unit @code{A}, this ensures that the
26149 body of @code{B} is elaborated before the call, but not the
26150 body of @code{C}, so
26151 the call to @code{C.Func} could still cause @code{Program_Error} to
26154 The effect of a pragma @code{Elaborate_All} is stronger, it requires
26155 not only that the body of the named unit be elaborated before the
26156 unit doing the @code{with}, but also the bodies of all units that the
26157 named unit uses, following @code{with} links transitively. For example,
26158 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
26160 not only that the body of @code{B} be elaborated before @code{A},
26162 body of @code{C}, because @code{B} @code{with}'s @code{C}.
26166 We are now in a position to give a usage rule in Ada for avoiding
26167 elaboration problems, at least if dynamic dispatching and access to
26168 subprogram values are not used. We will handle these cases separately
26171 The rule is simple. If a unit has elaboration code that can directly or
26172 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
26173 a generic package in a @code{with}'ed unit,
26174 then if the @code{with}'ed unit does not have
26175 pragma @code{Pure} or @code{Preelaborate}, then the client should have
26176 a pragma @code{Elaborate_All}
26177 for the @code{with}'ed unit. By following this rule a client is
26178 assured that calls can be made without risk of an exception.
26180 For generic subprogram instantiations, the rule can be relaxed to
26181 require only a pragma @code{Elaborate} since elaborating the body
26182 of a subprogram cannot cause any transitive elaboration (we are
26183 not calling the subprogram in this case, just elaborating its
26186 If this rule is not followed, then a program may be in one of four
26190 @item No order exists
26191 No order of elaboration exists which follows the rules, taking into
26192 account any @code{Elaborate}, @code{Elaborate_All},
26193 or @code{Elaborate_Body} pragmas. In
26194 this case, an Ada compiler must diagnose the situation at bind
26195 time, and refuse to build an executable program.
26197 @item One or more orders exist, all incorrect
26198 One or more acceptable elaboration orders exist, and all of them
26199 generate an elaboration order problem. In this case, the binder
26200 can build an executable program, but @code{Program_Error} will be raised
26201 when the program is run.
26203 @item Several orders exist, some right, some incorrect
26204 One or more acceptable elaboration orders exists, and some of them
26205 work, and some do not. The programmer has not controlled
26206 the order of elaboration, so the binder may or may not pick one of
26207 the correct orders, and the program may or may not raise an
26208 exception when it is run. This is the worst case, because it means
26209 that the program may fail when moved to another compiler, or even
26210 another version of the same compiler.
26212 @item One or more orders exists, all correct
26213 One ore more acceptable elaboration orders exist, and all of them
26214 work. In this case the program runs successfully. This state of
26215 affairs can be guaranteed by following the rule we gave above, but
26216 may be true even if the rule is not followed.
26220 Note that one additional advantage of following our rules on the use
26221 of @code{Elaborate} and @code{Elaborate_All}
26222 is that the program continues to stay in the ideal (all orders OK) state
26223 even if maintenance
26224 changes some bodies of some units. Conversely, if a program that does
26225 not follow this rule happens to be safe at some point, this state of affairs
26226 may deteriorate silently as a result of maintenance changes.
26228 You may have noticed that the above discussion did not mention
26229 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
26230 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
26231 code in the body makes calls to some other unit, so it is still necessary
26232 to use @code{Elaborate_All} on such units.
26234 @node Controlling Elaboration in GNAT - Internal Calls
26235 @section Controlling Elaboration in GNAT - Internal Calls
26238 In the case of internal calls, i.e. calls within a single package, the
26239 programmer has full control over the order of elaboration, and it is up
26240 to the programmer to elaborate declarations in an appropriate order. For
26243 @smallexample @c ada
26246 function One return Float;
26250 function One return Float is
26259 will obviously raise @code{Program_Error} at run time, because function
26260 One will be called before its body is elaborated. In this case GNAT will
26261 generate a warning that the call will raise @code{Program_Error}:
26267 2. function One return Float;
26269 4. Q : Float := One;
26271 >>> warning: cannot call "One" before body is elaborated
26272 >>> warning: Program_Error will be raised at run time
26275 6. function One return Float is
26288 Note that in this particular case, it is likely that the call is safe, because
26289 the function @code{One} does not access any global variables.
26290 Nevertheless in Ada, we do not want the validity of the check to depend on
26291 the contents of the body (think about the separate compilation case), so this
26292 is still wrong, as we discussed in the previous sections.
26294 The error is easily corrected by rearranging the declarations so that the
26295 body of @code{One} appears before the declaration containing the call
26296 (note that in Ada 95 and Ada 2005,
26297 declarations can appear in any order, so there is no restriction that
26298 would prevent this reordering, and if we write:
26300 @smallexample @c ada
26303 function One return Float;
26305 function One return Float is
26316 then all is well, no warning is generated, and no
26317 @code{Program_Error} exception
26319 Things are more complicated when a chain of subprograms is executed:
26321 @smallexample @c ada
26324 function A return Integer;
26325 function B return Integer;
26326 function C return Integer;
26328 function B return Integer is begin return A; end;
26329 function C return Integer is begin return B; end;
26333 function A return Integer is begin return 1; end;
26339 Now the call to @code{C}
26340 at elaboration time in the declaration of @code{X} is correct, because
26341 the body of @code{C} is already elaborated,
26342 and the call to @code{B} within the body of
26343 @code{C} is correct, but the call
26344 to @code{A} within the body of @code{B} is incorrect, because the body
26345 of @code{A} has not been elaborated, so @code{Program_Error}
26346 will be raised on the call to @code{A}.
26347 In this case GNAT will generate a
26348 warning that @code{Program_Error} may be
26349 raised at the point of the call. Let's look at the warning:
26355 2. function A return Integer;
26356 3. function B return Integer;
26357 4. function C return Integer;
26359 6. function B return Integer is begin return A; end;
26361 >>> warning: call to "A" before body is elaborated may
26362 raise Program_Error
26363 >>> warning: "B" called at line 7
26364 >>> warning: "C" called at line 9
26366 7. function C return Integer is begin return B; end;
26368 9. X : Integer := C;
26370 11. function A return Integer is begin return 1; end;
26380 Note that the message here says ``may raise'', instead of the direct case,
26381 where the message says ``will be raised''. That's because whether
26383 actually called depends in general on run-time flow of control.
26384 For example, if the body of @code{B} said
26386 @smallexample @c ada
26389 function B return Integer is
26391 if some-condition-depending-on-input-data then
26402 then we could not know until run time whether the incorrect call to A would
26403 actually occur, so @code{Program_Error} might
26404 or might not be raised. It is possible for a compiler to
26405 do a better job of analyzing bodies, to
26406 determine whether or not @code{Program_Error}
26407 might be raised, but it certainly
26408 couldn't do a perfect job (that would require solving the halting problem
26409 and is provably impossible), and because this is a warning anyway, it does
26410 not seem worth the effort to do the analysis. Cases in which it
26411 would be relevant are rare.
26413 In practice, warnings of either of the forms given
26414 above will usually correspond to
26415 real errors, and should be examined carefully and eliminated.
26416 In the rare case where a warning is bogus, it can be suppressed by any of
26417 the following methods:
26421 Compile with the @option{-gnatws} switch set
26424 Suppress @code{Elaboration_Check} for the called subprogram
26427 Use pragma @code{Warnings_Off} to turn warnings off for the call
26431 For the internal elaboration check case,
26432 GNAT by default generates the
26433 necessary run-time checks to ensure
26434 that @code{Program_Error} is raised if any
26435 call fails an elaboration check. Of course this can only happen if a
26436 warning has been issued as described above. The use of pragma
26437 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
26438 some of these checks, meaning that it may be possible (but is not
26439 guaranteed) for a program to be able to call a subprogram whose body
26440 is not yet elaborated, without raising a @code{Program_Error} exception.
26442 @node Controlling Elaboration in GNAT - External Calls
26443 @section Controlling Elaboration in GNAT - External Calls
26446 The previous section discussed the case in which the execution of a
26447 particular thread of elaboration code occurred entirely within a
26448 single unit. This is the easy case to handle, because a programmer
26449 has direct and total control over the order of elaboration, and
26450 furthermore, checks need only be generated in cases which are rare
26451 and which the compiler can easily detect.
26452 The situation is more complex when separate compilation is taken into account.
26453 Consider the following:
26455 @smallexample @c ada
26459 function Sqrt (Arg : Float) return Float;
26462 package body Math is
26463 function Sqrt (Arg : Float) return Float is
26472 X : Float := Math.Sqrt (0.5);
26485 where @code{Main} is the main program. When this program is executed, the
26486 elaboration code must first be executed, and one of the jobs of the
26487 binder is to determine the order in which the units of a program are
26488 to be elaborated. In this case we have four units: the spec and body
26490 the spec of @code{Stuff} and the body of @code{Main}).
26491 In what order should the four separate sections of elaboration code
26494 There are some restrictions in the order of elaboration that the binder
26495 can choose. In particular, if unit U has a @code{with}
26496 for a package @code{X}, then you
26497 are assured that the spec of @code{X}
26498 is elaborated before U , but you are
26499 not assured that the body of @code{X}
26500 is elaborated before U.
26501 This means that in the above case, the binder is allowed to choose the
26512 but that's not good, because now the call to @code{Math.Sqrt}
26513 that happens during
26514 the elaboration of the @code{Stuff}
26515 spec happens before the body of @code{Math.Sqrt} is
26516 elaborated, and hence causes @code{Program_Error} exception to be raised.
26517 At first glance, one might say that the binder is misbehaving, because
26518 obviously you want to elaborate the body of something you @code{with}
26520 that is not a general rule that can be followed in all cases. Consider
26522 @smallexample @c ada
26530 package body Y is ...
26533 package body X is ...
26539 This is a common arrangement, and, apart from the order of elaboration
26540 problems that might arise in connection with elaboration code, this works fine.
26541 A rule that says that you must first elaborate the body of anything you
26542 @code{with} cannot work in this case:
26543 the body of @code{X} @code{with}'s @code{Y},
26544 which means you would have to
26545 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
26547 you have to elaborate the body of @code{X} first, but ... and we have a
26548 loop that cannot be broken.
26550 It is true that the binder can in many cases guess an order of elaboration
26551 that is unlikely to cause a @code{Program_Error}
26552 exception to be raised, and it tries to do so (in the
26553 above example of @code{Math/Stuff/Spec}, the GNAT binder will
26555 elaborate the body of @code{Math} right after its spec, so all will be well).
26557 However, a program that blindly relies on the binder to be helpful can
26558 get into trouble, as we discussed in the previous sections, so
26560 provides a number of facilities for assisting the programmer in
26561 developing programs that are robust with respect to elaboration order.
26563 @node Default Behavior in GNAT - Ensuring Safety
26564 @section Default Behavior in GNAT - Ensuring Safety
26567 The default behavior in GNAT ensures elaboration safety. In its
26568 default mode GNAT implements the
26569 rule we previously described as the right approach. Let's restate it:
26573 @emph{If a unit has elaboration code that can directly or indirectly make a
26574 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
26575 package in a @code{with}'ed unit, then if the @code{with}'ed unit
26576 does not have pragma @code{Pure} or
26577 @code{Preelaborate}, then the client should have an
26578 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
26580 @emph{In the case of instantiating a generic subprogram, it is always
26581 sufficient to have only an @code{Elaborate} pragma for the
26582 @code{with}'ed unit.}
26586 By following this rule a client is assured that calls and instantiations
26587 can be made without risk of an exception.
26589 In this mode GNAT traces all calls that are potentially made from
26590 elaboration code, and puts in any missing implicit @code{Elaborate}
26591 and @code{Elaborate_All} pragmas.
26592 The advantage of this approach is that no elaboration problems
26593 are possible if the binder can find an elaboration order that is
26594 consistent with these implicit @code{Elaborate} and
26595 @code{Elaborate_All} pragmas. The
26596 disadvantage of this approach is that no such order may exist.
26598 If the binder does not generate any diagnostics, then it means that it has
26599 found an elaboration order that is guaranteed to be safe. However, the binder
26600 may still be relying on implicitly generated @code{Elaborate} and
26601 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
26604 If it is important to guarantee portability, then the compilations should
26607 (warn on elaboration problems) switch. This will cause warning messages
26608 to be generated indicating the missing @code{Elaborate} and
26609 @code{Elaborate_All} pragmas.
26610 Consider the following source program:
26612 @smallexample @c ada
26617 m : integer := k.r;
26624 where it is clear that there
26625 should be a pragma @code{Elaborate_All}
26626 for unit @code{k}. An implicit pragma will be generated, and it is
26627 likely that the binder will be able to honor it. However, if you want
26628 to port this program to some other Ada compiler than GNAT.
26629 it is safer to include the pragma explicitly in the source. If this
26630 unit is compiled with the
26632 switch, then the compiler outputs a warning:
26639 3. m : integer := k.r;
26641 >>> warning: call to "r" may raise Program_Error
26642 >>> warning: missing pragma Elaborate_All for "k"
26650 and these warnings can be used as a guide for supplying manually
26651 the missing pragmas. It is usually a bad idea to use this warning
26652 option during development. That's because it will warn you when
26653 you need to put in a pragma, but cannot warn you when it is time
26654 to take it out. So the use of pragma @code{Elaborate_All} may lead to
26655 unnecessary dependencies and even false circularities.
26657 This default mode is more restrictive than the Ada Reference
26658 Manual, and it is possible to construct programs which will compile
26659 using the dynamic model described there, but will run into a
26660 circularity using the safer static model we have described.
26662 Of course any Ada compiler must be able to operate in a mode
26663 consistent with the requirements of the Ada Reference Manual,
26664 and in particular must have the capability of implementing the
26665 standard dynamic model of elaboration with run-time checks.
26667 In GNAT, this standard mode can be achieved either by the use of
26668 the @option{-gnatE} switch on the compiler (@command{gcc} or
26669 @command{gnatmake}) command, or by the use of the configuration pragma:
26671 @smallexample @c ada
26672 pragma Elaboration_Checks (RM);
26676 Either approach will cause the unit affected to be compiled using the
26677 standard dynamic run-time elaboration checks described in the Ada
26678 Reference Manual. The static model is generally preferable, since it
26679 is clearly safer to rely on compile and link time checks rather than
26680 run-time checks. However, in the case of legacy code, it may be
26681 difficult to meet the requirements of the static model. This
26682 issue is further discussed in
26683 @ref{What to Do If the Default Elaboration Behavior Fails}.
26685 Note that the static model provides a strict subset of the allowed
26686 behavior and programs of the Ada Reference Manual, so if you do
26687 adhere to the static model and no circularities exist,
26688 then you are assured that your program will
26689 work using the dynamic model, providing that you remove any
26690 pragma Elaborate statements from the source.
26692 @node Treatment of Pragma Elaborate
26693 @section Treatment of Pragma Elaborate
26694 @cindex Pragma Elaborate
26697 The use of @code{pragma Elaborate}
26698 should generally be avoided in Ada 95 and Ada 2005 programs,
26699 since there is no guarantee that transitive calls
26700 will be properly handled. Indeed at one point, this pragma was placed
26701 in Annex J (Obsolescent Features), on the grounds that it is never useful.
26703 Now that's a bit restrictive. In practice, the case in which
26704 @code{pragma Elaborate} is useful is when the caller knows that there
26705 are no transitive calls, or that the called unit contains all necessary
26706 transitive @code{pragma Elaborate} statements, and legacy code often
26707 contains such uses.
26709 Strictly speaking the static mode in GNAT should ignore such pragmas,
26710 since there is no assurance at compile time that the necessary safety
26711 conditions are met. In practice, this would cause GNAT to be incompatible
26712 with correctly written Ada 83 code that had all necessary
26713 @code{pragma Elaborate} statements in place. Consequently, we made the
26714 decision that GNAT in its default mode will believe that if it encounters
26715 a @code{pragma Elaborate} then the programmer knows what they are doing,
26716 and it will trust that no elaboration errors can occur.
26718 The result of this decision is two-fold. First to be safe using the
26719 static mode, you should remove all @code{pragma Elaborate} statements.
26720 Second, when fixing circularities in existing code, you can selectively
26721 use @code{pragma Elaborate} statements to convince the static mode of
26722 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
26725 When using the static mode with @option{-gnatwl}, any use of
26726 @code{pragma Elaborate} will generate a warning about possible
26729 @node Elaboration Issues for Library Tasks
26730 @section Elaboration Issues for Library Tasks
26731 @cindex Library tasks, elaboration issues
26732 @cindex Elaboration of library tasks
26735 In this section we examine special elaboration issues that arise for
26736 programs that declare library level tasks.
26738 Generally the model of execution of an Ada program is that all units are
26739 elaborated, and then execution of the program starts. However, the
26740 declaration of library tasks definitely does not fit this model. The
26741 reason for this is that library tasks start as soon as they are declared
26742 (more precisely, as soon as the statement part of the enclosing package
26743 body is reached), that is to say before elaboration
26744 of the program is complete. This means that if such a task calls a
26745 subprogram, or an entry in another task, the callee may or may not be
26746 elaborated yet, and in the standard
26747 Reference Manual model of dynamic elaboration checks, you can even
26748 get timing dependent Program_Error exceptions, since there can be
26749 a race between the elaboration code and the task code.
26751 The static model of elaboration in GNAT seeks to avoid all such
26752 dynamic behavior, by being conservative, and the conservative
26753 approach in this particular case is to assume that all the code
26754 in a task body is potentially executed at elaboration time if
26755 a task is declared at the library level.
26757 This can definitely result in unexpected circularities. Consider
26758 the following example
26760 @smallexample @c ada
26766 type My_Int is new Integer;
26768 function Ident (M : My_Int) return My_Int;
26772 package body Decls is
26773 task body Lib_Task is
26779 function Ident (M : My_Int) return My_Int is
26787 procedure Put_Val (Arg : Decls.My_Int);
26791 package body Utils is
26792 procedure Put_Val (Arg : Decls.My_Int) is
26794 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
26801 Decls.Lib_Task.Start;
26806 If the above example is compiled in the default static elaboration
26807 mode, then a circularity occurs. The circularity comes from the call
26808 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
26809 this call occurs in elaboration code, we need an implicit pragma
26810 @code{Elaborate_All} for @code{Utils}. This means that not only must
26811 the spec and body of @code{Utils} be elaborated before the body
26812 of @code{Decls}, but also the spec and body of any unit that is
26813 @code{with'ed} by the body of @code{Utils} must also be elaborated before
26814 the body of @code{Decls}. This is the transitive implication of
26815 pragma @code{Elaborate_All} and it makes sense, because in general
26816 the body of @code{Put_Val} might have a call to something in a
26817 @code{with'ed} unit.
26819 In this case, the body of Utils (actually its spec) @code{with's}
26820 @code{Decls}. Unfortunately this means that the body of @code{Decls}
26821 must be elaborated before itself, in case there is a call from the
26822 body of @code{Utils}.
26824 Here is the exact chain of events we are worrying about:
26828 In the body of @code{Decls} a call is made from within the body of a library
26829 task to a subprogram in the package @code{Utils}. Since this call may
26830 occur at elaboration time (given that the task is activated at elaboration
26831 time), we have to assume the worst, i.e. that the
26832 call does happen at elaboration time.
26835 This means that the body and spec of @code{Util} must be elaborated before
26836 the body of @code{Decls} so that this call does not cause an access before
26840 Within the body of @code{Util}, specifically within the body of
26841 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
26845 One such @code{with}'ed package is package @code{Decls}, so there
26846 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
26847 In fact there is such a call in this example, but we would have to
26848 assume that there was such a call even if it were not there, since
26849 we are not supposed to write the body of @code{Decls} knowing what
26850 is in the body of @code{Utils}; certainly in the case of the
26851 static elaboration model, the compiler does not know what is in
26852 other bodies and must assume the worst.
26855 This means that the spec and body of @code{Decls} must also be
26856 elaborated before we elaborate the unit containing the call, but
26857 that unit is @code{Decls}! This means that the body of @code{Decls}
26858 must be elaborated before itself, and that's a circularity.
26862 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
26863 the body of @code{Decls} you will get a true Ada Reference Manual
26864 circularity that makes the program illegal.
26866 In practice, we have found that problems with the static model of
26867 elaboration in existing code often arise from library tasks, so
26868 we must address this particular situation.
26870 Note that if we compile and run the program above, using the dynamic model of
26871 elaboration (that is to say use the @option{-gnatE} switch),
26872 then it compiles, binds,
26873 links, and runs, printing the expected result of 2. Therefore in some sense
26874 the circularity here is only apparent, and we need to capture
26875 the properties of this program that distinguish it from other library-level
26876 tasks that have real elaboration problems.
26878 We have four possible answers to this question:
26883 Use the dynamic model of elaboration.
26885 If we use the @option{-gnatE} switch, then as noted above, the program works.
26886 Why is this? If we examine the task body, it is apparent that the task cannot
26888 @code{accept} statement until after elaboration has been completed, because
26889 the corresponding entry call comes from the main program, not earlier.
26890 This is why the dynamic model works here. But that's really giving
26891 up on a precise analysis, and we prefer to take this approach only if we cannot
26893 problem in any other manner. So let us examine two ways to reorganize
26894 the program to avoid the potential elaboration problem.
26897 Split library tasks into separate packages.
26899 Write separate packages, so that library tasks are isolated from
26900 other declarations as much as possible. Let us look at a variation on
26903 @smallexample @c ada
26911 package body Decls1 is
26912 task body Lib_Task is
26920 type My_Int is new Integer;
26921 function Ident (M : My_Int) return My_Int;
26925 package body Decls2 is
26926 function Ident (M : My_Int) return My_Int is
26934 procedure Put_Val (Arg : Decls2.My_Int);
26938 package body Utils is
26939 procedure Put_Val (Arg : Decls2.My_Int) is
26941 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
26948 Decls1.Lib_Task.Start;
26953 All we have done is to split @code{Decls} into two packages, one
26954 containing the library task, and one containing everything else. Now
26955 there is no cycle, and the program compiles, binds, links and executes
26956 using the default static model of elaboration.
26959 Declare separate task types.
26961 A significant part of the problem arises because of the use of the
26962 single task declaration form. This means that the elaboration of
26963 the task type, and the elaboration of the task itself (i.e. the
26964 creation of the task) happen at the same time. A good rule
26965 of style in Ada is to always create explicit task types. By
26966 following the additional step of placing task objects in separate
26967 packages from the task type declaration, many elaboration problems
26968 are avoided. Here is another modified example of the example program:
26970 @smallexample @c ada
26972 task type Lib_Task_Type is
26976 type My_Int is new Integer;
26978 function Ident (M : My_Int) return My_Int;
26982 package body Decls is
26983 task body Lib_Task_Type is
26989 function Ident (M : My_Int) return My_Int is
26997 procedure Put_Val (Arg : Decls.My_Int);
27001 package body Utils is
27002 procedure Put_Val (Arg : Decls.My_Int) is
27004 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
27010 Lib_Task : Decls.Lib_Task_Type;
27016 Declst.Lib_Task.Start;
27021 What we have done here is to replace the @code{task} declaration in
27022 package @code{Decls} with a @code{task type} declaration. Then we
27023 introduce a separate package @code{Declst} to contain the actual
27024 task object. This separates the elaboration issues for
27025 the @code{task type}
27026 declaration, which causes no trouble, from the elaboration issues
27027 of the task object, which is also unproblematic, since it is now independent
27028 of the elaboration of @code{Utils}.
27029 This separation of concerns also corresponds to
27030 a generally sound engineering principle of separating declarations
27031 from instances. This version of the program also compiles, binds, links,
27032 and executes, generating the expected output.
27035 Use No_Entry_Calls_In_Elaboration_Code restriction.
27036 @cindex No_Entry_Calls_In_Elaboration_Code
27038 The previous two approaches described how a program can be restructured
27039 to avoid the special problems caused by library task bodies. in practice,
27040 however, such restructuring may be difficult to apply to existing legacy code,
27041 so we must consider solutions that do not require massive rewriting.
27043 Let us consider more carefully why our original sample program works
27044 under the dynamic model of elaboration. The reason is that the code
27045 in the task body blocks immediately on the @code{accept}
27046 statement. Now of course there is nothing to prohibit elaboration
27047 code from making entry calls (for example from another library level task),
27048 so we cannot tell in isolation that
27049 the task will not execute the accept statement during elaboration.
27051 However, in practice it is very unusual to see elaboration code
27052 make any entry calls, and the pattern of tasks starting
27053 at elaboration time and then immediately blocking on @code{accept} or
27054 @code{select} statements is very common. What this means is that
27055 the compiler is being too pessimistic when it analyzes the
27056 whole package body as though it might be executed at elaboration
27059 If we know that the elaboration code contains no entry calls, (a very safe
27060 assumption most of the time, that could almost be made the default
27061 behavior), then we can compile all units of the program under control
27062 of the following configuration pragma:
27065 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
27069 This pragma can be placed in the @file{gnat.adc} file in the usual
27070 manner. If we take our original unmodified program and compile it
27071 in the presence of a @file{gnat.adc} containing the above pragma,
27072 then once again, we can compile, bind, link, and execute, obtaining
27073 the expected result. In the presence of this pragma, the compiler does
27074 not trace calls in a task body, that appear after the first @code{accept}
27075 or @code{select} statement, and therefore does not report a potential
27076 circularity in the original program.
27078 The compiler will check to the extent it can that the above
27079 restriction is not violated, but it is not always possible to do a
27080 complete check at compile time, so it is important to use this
27081 pragma only if the stated restriction is in fact met, that is to say
27082 no task receives an entry call before elaboration of all units is completed.
27086 @node Mixing Elaboration Models
27087 @section Mixing Elaboration Models
27089 So far, we have assumed that the entire program is either compiled
27090 using the dynamic model or static model, ensuring consistency. It
27091 is possible to mix the two models, but rules have to be followed
27092 if this mixing is done to ensure that elaboration checks are not
27095 The basic rule is that @emph{a unit compiled with the static model cannot
27096 be @code{with'ed} by a unit compiled with the dynamic model}. The
27097 reason for this is that in the static model, a unit assumes that
27098 its clients guarantee to use (the equivalent of) pragma
27099 @code{Elaborate_All} so that no elaboration checks are required
27100 in inner subprograms, and this assumption is violated if the
27101 client is compiled with dynamic checks.
27103 The precise rule is as follows. A unit that is compiled with dynamic
27104 checks can only @code{with} a unit that meets at least one of the
27105 following criteria:
27110 The @code{with'ed} unit is itself compiled with dynamic elaboration
27111 checks (that is with the @option{-gnatE} switch.
27114 The @code{with'ed} unit is an internal GNAT implementation unit from
27115 the System, Interfaces, Ada, or GNAT hierarchies.
27118 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
27121 The @code{with'ing} unit (that is the client) has an explicit pragma
27122 @code{Elaborate_All} for the @code{with'ed} unit.
27127 If this rule is violated, that is if a unit with dynamic elaboration
27128 checks @code{with's} a unit that does not meet one of the above four
27129 criteria, then the binder (@code{gnatbind}) will issue a warning
27130 similar to that in the following example:
27133 warning: "x.ads" has dynamic elaboration checks and with's
27134 warning: "y.ads" which has static elaboration checks
27138 These warnings indicate that the rule has been violated, and that as a result
27139 elaboration checks may be missed in the resulting executable file.
27140 This warning may be suppressed using the @option{-ws} binder switch
27141 in the usual manner.
27143 One useful application of this mixing rule is in the case of a subsystem
27144 which does not itself @code{with} units from the remainder of the
27145 application. In this case, the entire subsystem can be compiled with
27146 dynamic checks to resolve a circularity in the subsystem, while
27147 allowing the main application that uses this subsystem to be compiled
27148 using the more reliable default static model.
27150 @node What to Do If the Default Elaboration Behavior Fails
27151 @section What to Do If the Default Elaboration Behavior Fails
27154 If the binder cannot find an acceptable order, it outputs detailed
27155 diagnostics. For example:
27161 error: elaboration circularity detected
27162 info: "proc (body)" must be elaborated before "pack (body)"
27163 info: reason: Elaborate_All probably needed in unit "pack (body)"
27164 info: recompile "pack (body)" with -gnatwl
27165 info: for full details
27166 info: "proc (body)"
27167 info: is needed by its spec:
27168 info: "proc (spec)"
27169 info: which is withed by:
27170 info: "pack (body)"
27171 info: "pack (body)" must be elaborated before "proc (body)"
27172 info: reason: pragma Elaborate in unit "proc (body)"
27178 In this case we have a cycle that the binder cannot break. On the one
27179 hand, there is an explicit pragma Elaborate in @code{proc} for
27180 @code{pack}. This means that the body of @code{pack} must be elaborated
27181 before the body of @code{proc}. On the other hand, there is elaboration
27182 code in @code{pack} that calls a subprogram in @code{proc}. This means
27183 that for maximum safety, there should really be a pragma
27184 Elaborate_All in @code{pack} for @code{proc} which would require that
27185 the body of @code{proc} be elaborated before the body of
27186 @code{pack}. Clearly both requirements cannot be satisfied.
27187 Faced with a circularity of this kind, you have three different options.
27190 @item Fix the program
27191 The most desirable option from the point of view of long-term maintenance
27192 is to rearrange the program so that the elaboration problems are avoided.
27193 One useful technique is to place the elaboration code into separate
27194 child packages. Another is to move some of the initialization code to
27195 explicitly called subprograms, where the program controls the order
27196 of initialization explicitly. Although this is the most desirable option,
27197 it may be impractical and involve too much modification, especially in
27198 the case of complex legacy code.
27200 @item Perform dynamic checks
27201 If the compilations are done using the
27203 (dynamic elaboration check) switch, then GNAT behaves in a quite different
27204 manner. Dynamic checks are generated for all calls that could possibly result
27205 in raising an exception. With this switch, the compiler does not generate
27206 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
27207 exactly as specified in the @cite{Ada Reference Manual}.
27208 The binder will generate
27209 an executable program that may or may not raise @code{Program_Error}, and then
27210 it is the programmer's job to ensure that it does not raise an exception. Note
27211 that it is important to compile all units with the switch, it cannot be used
27214 @item Suppress checks
27215 The drawback of dynamic checks is that they generate a
27216 significant overhead at run time, both in space and time. If you
27217 are absolutely sure that your program cannot raise any elaboration
27218 exceptions, and you still want to use the dynamic elaboration model,
27219 then you can use the configuration pragma
27220 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
27221 example this pragma could be placed in the @file{gnat.adc} file.
27223 @item Suppress checks selectively
27224 When you know that certain calls or instantiations in elaboration code cannot
27225 possibly lead to an elaboration error, and the binder nevertheless complains
27226 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
27227 elaboration circularities, it is possible to remove those warnings locally and
27228 obtain a program that will bind. Clearly this can be unsafe, and it is the
27229 responsibility of the programmer to make sure that the resulting program has no
27230 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
27231 used with different granularity to suppress warnings and break elaboration
27236 Place the pragma that names the called subprogram in the declarative part
27237 that contains the call.
27240 Place the pragma in the declarative part, without naming an entity. This
27241 disables warnings on all calls in the corresponding declarative region.
27244 Place the pragma in the package spec that declares the called subprogram,
27245 and name the subprogram. This disables warnings on all elaboration calls to
27249 Place the pragma in the package spec that declares the called subprogram,
27250 without naming any entity. This disables warnings on all elaboration calls to
27251 all subprograms declared in this spec.
27253 @item Use Pragma Elaborate
27254 As previously described in section @xref{Treatment of Pragma Elaborate},
27255 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
27256 that no elaboration checks are required on calls to the designated unit.
27257 There may be cases in which the caller knows that no transitive calls
27258 can occur, so that a @code{pragma Elaborate} will be sufficient in a
27259 case where @code{pragma Elaborate_All} would cause a circularity.
27263 These five cases are listed in order of decreasing safety, and therefore
27264 require increasing programmer care in their application. Consider the
27267 @smallexample @c adanocomment
27269 function F1 return Integer;
27274 function F2 return Integer;
27275 function Pure (x : integer) return integer;
27276 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
27277 -- pragma Suppress (Elaboration_Check); -- (4)
27281 package body Pack1 is
27282 function F1 return Integer is
27286 Val : integer := Pack2.Pure (11); -- Elab. call (1)
27289 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
27290 -- pragma Suppress(Elaboration_Check); -- (2)
27292 X1 := Pack2.F2 + 1; -- Elab. call (2)
27297 package body Pack2 is
27298 function F2 return Integer is
27302 function Pure (x : integer) return integer is
27304 return x ** 3 - 3 * x;
27308 with Pack1, Ada.Text_IO;
27311 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
27314 In the absence of any pragmas, an attempt to bind this program produces
27315 the following diagnostics:
27321 error: elaboration circularity detected
27322 info: "pack1 (body)" must be elaborated before "pack1 (body)"
27323 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
27324 info: recompile "pack1 (body)" with -gnatwl for full details
27325 info: "pack1 (body)"
27326 info: must be elaborated along with its spec:
27327 info: "pack1 (spec)"
27328 info: which is withed by:
27329 info: "pack2 (body)"
27330 info: which must be elaborated along with its spec:
27331 info: "pack2 (spec)"
27332 info: which is withed by:
27333 info: "pack1 (body)"
27336 The sources of the circularity are the two calls to @code{Pack2.Pure} and
27337 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
27338 F2 is safe, even though F2 calls F1, because the call appears after the
27339 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
27340 remove the warning on the call. It is also possible to use pragma (2)
27341 because there are no other potentially unsafe calls in the block.
27344 The call to @code{Pure} is safe because this function does not depend on the
27345 state of @code{Pack2}. Therefore any call to this function is safe, and it
27346 is correct to place pragma (3) in the corresponding package spec.
27349 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
27350 warnings on all calls to functions declared therein. Note that this is not
27351 necessarily safe, and requires more detailed examination of the subprogram
27352 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
27353 be already elaborated.
27357 It is hard to generalize on which of these four approaches should be
27358 taken. Obviously if it is possible to fix the program so that the default
27359 treatment works, this is preferable, but this may not always be practical.
27360 It is certainly simple enough to use
27362 but the danger in this case is that, even if the GNAT binder
27363 finds a correct elaboration order, it may not always do so,
27364 and certainly a binder from another Ada compiler might not. A
27365 combination of testing and analysis (for which the warnings generated
27368 switch can be useful) must be used to ensure that the program is free
27369 of errors. One switch that is useful in this testing is the
27370 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
27373 Normally the binder tries to find an order that has the best chance
27374 of avoiding elaboration problems. However, if this switch is used, the binder
27375 plays a devil's advocate role, and tries to choose the order that
27376 has the best chance of failing. If your program works even with this
27377 switch, then it has a better chance of being error free, but this is still
27380 For an example of this approach in action, consider the C-tests (executable
27381 tests) from the ACVC suite. If these are compiled and run with the default
27382 treatment, then all but one of them succeed without generating any error
27383 diagnostics from the binder. However, there is one test that fails, and
27384 this is not surprising, because the whole point of this test is to ensure
27385 that the compiler can handle cases where it is impossible to determine
27386 a correct order statically, and it checks that an exception is indeed
27387 raised at run time.
27389 This one test must be compiled and run using the
27391 switch, and then it passes. Alternatively, the entire suite can
27392 be run using this switch. It is never wrong to run with the dynamic
27393 elaboration switch if your code is correct, and we assume that the
27394 C-tests are indeed correct (it is less efficient, but efficiency is
27395 not a factor in running the ACVC tests.)
27397 @node Elaboration for Access-to-Subprogram Values
27398 @section Elaboration for Access-to-Subprogram Values
27399 @cindex Access-to-subprogram
27402 Access-to-subprogram types (introduced in Ada 95) complicate
27403 the handling of elaboration. The trouble is that it becomes
27404 impossible to tell at compile time which procedure
27405 is being called. This means that it is not possible for the binder
27406 to analyze the elaboration requirements in this case.
27408 If at the point at which the access value is created
27409 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
27410 the body of the subprogram is
27411 known to have been elaborated, then the access value is safe, and its use
27412 does not require a check. This may be achieved by appropriate arrangement
27413 of the order of declarations if the subprogram is in the current unit,
27414 or, if the subprogram is in another unit, by using pragma
27415 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
27416 on the referenced unit.
27418 If the referenced body is not known to have been elaborated at the point
27419 the access value is created, then any use of the access value must do a
27420 dynamic check, and this dynamic check will fail and raise a
27421 @code{Program_Error} exception if the body has not been elaborated yet.
27422 GNAT will generate the necessary checks, and in addition, if the
27424 switch is set, will generate warnings that such checks are required.
27426 The use of dynamic dispatching for tagged types similarly generates
27427 a requirement for dynamic checks, and premature calls to any primitive
27428 operation of a tagged type before the body of the operation has been
27429 elaborated, will result in the raising of @code{Program_Error}.
27431 @node Summary of Procedures for Elaboration Control
27432 @section Summary of Procedures for Elaboration Control
27433 @cindex Elaboration control
27436 First, compile your program with the default options, using none of
27437 the special elaboration control switches. If the binder successfully
27438 binds your program, then you can be confident that, apart from issues
27439 raised by the use of access-to-subprogram types and dynamic dispatching,
27440 the program is free of elaboration errors. If it is important that the
27441 program be portable, then use the
27443 switch to generate warnings about missing @code{Elaborate} or
27444 @code{Elaborate_All} pragmas, and supply the missing pragmas.
27446 If the program fails to bind using the default static elaboration
27447 handling, then you can fix the program to eliminate the binder
27448 message, or recompile the entire program with the
27449 @option{-gnatE} switch to generate dynamic elaboration checks,
27450 and, if you are sure there really are no elaboration problems,
27451 use a global pragma @code{Suppress (Elaboration_Check)}.
27453 @node Other Elaboration Order Considerations
27454 @section Other Elaboration Order Considerations
27456 This section has been entirely concerned with the issue of finding a valid
27457 elaboration order, as defined by the Ada Reference Manual. In a case
27458 where several elaboration orders are valid, the task is to find one
27459 of the possible valid elaboration orders (and the static model in GNAT
27460 will ensure that this is achieved).
27462 The purpose of the elaboration rules in the Ada Reference Manual is to
27463 make sure that no entity is accessed before it has been elaborated. For
27464 a subprogram, this means that the spec and body must have been elaborated
27465 before the subprogram is called. For an object, this means that the object
27466 must have been elaborated before its value is read or written. A violation
27467 of either of these two requirements is an access before elaboration order,
27468 and this section has been all about avoiding such errors.
27470 In the case where more than one order of elaboration is possible, in the
27471 sense that access before elaboration errors are avoided, then any one of
27472 the orders is ``correct'' in the sense that it meets the requirements of
27473 the Ada Reference Manual, and no such error occurs.
27475 However, it may be the case for a given program, that there are
27476 constraints on the order of elaboration that come not from consideration
27477 of avoiding elaboration errors, but rather from extra-lingual logic
27478 requirements. Consider this example:
27480 @smallexample @c ada
27481 with Init_Constants;
27482 package Constants is
27487 package Init_Constants is
27488 procedure P; -- require a body
27489 end Init_Constants;
27492 package body Init_Constants is
27493 procedure P is begin null; end;
27497 end Init_Constants;
27501 Z : Integer := Constants.X + Constants.Y;
27505 with Text_IO; use Text_IO;
27508 Put_Line (Calc.Z'Img);
27513 In this example, there is more than one valid order of elaboration. For
27514 example both the following are correct orders:
27517 Init_Constants spec
27520 Init_Constants body
27525 Init_Constants spec
27526 Init_Constants body
27533 There is no language rule to prefer one or the other, both are correct
27534 from an order of elaboration point of view. But the programmatic effects
27535 of the two orders are very different. In the first, the elaboration routine
27536 of @code{Calc} initializes @code{Z} to zero, and then the main program
27537 runs with this value of zero. But in the second order, the elaboration
27538 routine of @code{Calc} runs after the body of Init_Constants has set
27539 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
27542 One could perhaps by applying pretty clever non-artificial intelligence
27543 to the situation guess that it is more likely that the second order of
27544 elaboration is the one desired, but there is no formal linguistic reason
27545 to prefer one over the other. In fact in this particular case, GNAT will
27546 prefer the second order, because of the rule that bodies are elaborated
27547 as soon as possible, but it's just luck that this is what was wanted
27548 (if indeed the second order was preferred).
27550 If the program cares about the order of elaboration routines in a case like
27551 this, it is important to specify the order required. In this particular
27552 case, that could have been achieved by adding to the spec of Calc:
27554 @smallexample @c ada
27555 pragma Elaborate_All (Constants);
27559 which requires that the body (if any) and spec of @code{Constants},
27560 as well as the body and spec of any unit @code{with}'ed by
27561 @code{Constants} be elaborated before @code{Calc} is elaborated.
27563 Clearly no automatic method can always guess which alternative you require,
27564 and if you are working with legacy code that had constraints of this kind
27565 which were not properly specified by adding @code{Elaborate} or
27566 @code{Elaborate_All} pragmas, then indeed it is possible that two different
27567 compilers can choose different orders.
27569 However, GNAT does attempt to diagnose the common situation where there
27570 are uninitialized variables in the visible part of a package spec, and the
27571 corresponding package body has an elaboration block that directly or
27572 indirectly initialized one or more of these variables. This is the situation
27573 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
27574 a warning that suggests this addition if it detects this situation.
27576 The @code{gnatbind}
27577 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
27578 out problems. This switch causes bodies to be elaborated as late as possible
27579 instead of as early as possible. In the example above, it would have forced
27580 the choice of the first elaboration order. If you get different results
27581 when using this switch, and particularly if one set of results is right,
27582 and one is wrong as far as you are concerned, it shows that you have some
27583 missing @code{Elaborate} pragmas. For the example above, we have the
27587 gnatmake -f -q main
27590 gnatmake -f -q main -bargs -p
27596 It is of course quite unlikely that both these results are correct, so
27597 it is up to you in a case like this to investigate the source of the
27598 difference, by looking at the two elaboration orders that are chosen,
27599 and figuring out which is correct, and then adding the necessary
27600 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
27604 @c *******************************
27605 @node Conditional Compilation
27606 @appendix Conditional Compilation
27607 @c *******************************
27608 @cindex Conditional compilation
27611 It is often necessary to arrange for a single source program
27612 to serve multiple purposes, where it is compiled in different
27613 ways to achieve these different goals. Some examples of the
27614 need for this feature are
27617 @item Adapting a program to a different hardware environment
27618 @item Adapting a program to a different target architecture
27619 @item Turning debugging features on and off
27620 @item Arranging for a program to compile with different compilers
27624 In C, or C++, the typical approach would be to use the preprocessor
27625 that is defined as part of the language. The Ada language does not
27626 contain such a feature. This is not an oversight, but rather a very
27627 deliberate design decision, based on the experience that overuse of
27628 the preprocessing features in C and C++ can result in programs that
27629 are extremely difficult to maintain. For example, if we have ten
27630 switches that can be on or off, this means that there are a thousand
27631 separate programs, any one of which might not even be syntactically
27632 correct, and even if syntactically correct, the resulting program
27633 might not work correctly. Testing all combinations can quickly become
27636 Nevertheless, the need to tailor programs certainly exists, and in
27637 this Appendix we will discuss how this can
27638 be achieved using Ada in general, and GNAT in particular.
27641 * Use of Boolean Constants::
27642 * Debugging - A Special Case::
27643 * Conditionalizing Declarations::
27644 * Use of Alternative Implementations::
27648 @node Use of Boolean Constants
27649 @section Use of Boolean Constants
27652 In the case where the difference is simply which code
27653 sequence is executed, the cleanest solution is to use Boolean
27654 constants to control which code is executed.
27656 @smallexample @c ada
27658 FP_Initialize_Required : constant Boolean := True;
27660 if FP_Initialize_Required then
27667 Not only will the code inside the @code{if} statement not be executed if
27668 the constant Boolean is @code{False}, but it will also be completely
27669 deleted from the program.
27670 However, the code is only deleted after the @code{if} statement
27671 has been checked for syntactic and semantic correctness.
27672 (In contrast, with preprocessors the code is deleted before the
27673 compiler ever gets to see it, so it is not checked until the switch
27675 @cindex Preprocessors (contrasted with conditional compilation)
27677 Typically the Boolean constants will be in a separate package,
27680 @smallexample @c ada
27683 FP_Initialize_Required : constant Boolean := True;
27684 Reset_Available : constant Boolean := False;
27691 The @code{Config} package exists in multiple forms for the various targets,
27692 with an appropriate script selecting the version of @code{Config} needed.
27693 Then any other unit requiring conditional compilation can do a @code{with}
27694 of @code{Config} to make the constants visible.
27697 @node Debugging - A Special Case
27698 @section Debugging - A Special Case
27701 A common use of conditional code is to execute statements (for example
27702 dynamic checks, or output of intermediate results) under control of a
27703 debug switch, so that the debugging behavior can be turned on and off.
27704 This can be done using a Boolean constant to control whether the code
27707 @smallexample @c ada
27710 Put_Line ("got to the first stage!");
27718 @smallexample @c ada
27720 if Debugging and then Temperature > 999.0 then
27721 raise Temperature_Crazy;
27727 Since this is a common case, there are special features to deal with
27728 this in a convenient manner. For the case of tests, Ada 2005 has added
27729 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
27730 @cindex pragma @code{Assert}
27731 on the @code{Assert} pragma that has always been available in GNAT, so this
27732 feature may be used with GNAT even if you are not using Ada 2005 features.
27733 The use of pragma @code{Assert} is described in the
27734 @cite{GNAT Reference Manual}, but as an example, the last test could be written:
27736 @smallexample @c ada
27737 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
27743 @smallexample @c ada
27744 pragma Assert (Temperature <= 999.0);
27748 In both cases, if assertions are active and the temperature is excessive,
27749 the exception @code{Assert_Failure} will be raised, with the given string in
27750 the first case or a string indicating the location of the pragma in the second
27751 case used as the exception message.
27753 You can turn assertions on and off by using the @code{Assertion_Policy}
27755 @cindex pragma @code{Assertion_Policy}
27756 This is an Ada 2005 pragma which is implemented in all modes by
27757 GNAT, but only in the latest versions of GNAT which include Ada 2005
27758 capability. Alternatively, you can use the @option{-gnata} switch
27759 @cindex @option{-gnata} switch
27760 to enable assertions from the command line (this is recognized by all versions
27763 For the example above with the @code{Put_Line}, the GNAT-specific pragma
27764 @code{Debug} can be used:
27765 @cindex pragma @code{Debug}
27767 @smallexample @c ada
27768 pragma Debug (Put_Line ("got to the first stage!"));
27772 If debug pragmas are enabled, the argument, which must be of the form of
27773 a procedure call, is executed (in this case, @code{Put_Line} will be called).
27774 Only one call can be present, but of course a special debugging procedure
27775 containing any code you like can be included in the program and then
27776 called in a pragma @code{Debug} argument as needed.
27778 One advantage of pragma @code{Debug} over the @code{if Debugging then}
27779 construct is that pragma @code{Debug} can appear in declarative contexts,
27780 such as at the very beginning of a procedure, before local declarations have
27783 Debug pragmas are enabled using either the @option{-gnata} switch that also
27784 controls assertions, or with a separate Debug_Policy pragma.
27785 @cindex pragma @code{Debug_Policy}
27786 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
27787 in Ada 95 and Ada 83 programs as well), and is analogous to
27788 pragma @code{Assertion_Policy} to control assertions.
27790 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
27791 and thus they can appear in @file{gnat.adc} if you are not using a
27792 project file, or in the file designated to contain configuration pragmas
27794 They then apply to all subsequent compilations. In practice the use of
27795 the @option{-gnata} switch is often the most convenient method of controlling
27796 the status of these pragmas.
27798 Note that a pragma is not a statement, so in contexts where a statement
27799 sequence is required, you can't just write a pragma on its own. You have
27800 to add a @code{null} statement.
27802 @smallexample @c ada
27805 ... -- some statements
27807 pragma Assert (Num_Cases < 10);
27814 @node Conditionalizing Declarations
27815 @section Conditionalizing Declarations
27818 In some cases, it may be necessary to conditionalize declarations to meet
27819 different requirements. For example we might want a bit string whose length
27820 is set to meet some hardware message requirement.
27822 In some cases, it may be possible to do this using declare blocks controlled
27823 by conditional constants:
27825 @smallexample @c ada
27827 if Small_Machine then
27829 X : Bit_String (1 .. 10);
27835 X : Large_Bit_String (1 .. 1000);
27844 Note that in this approach, both declarations are analyzed by the
27845 compiler so this can only be used where both declarations are legal,
27846 even though one of them will not be used.
27848 Another approach is to define integer constants, e.g. @code{Bits_Per_Word}, or
27849 Boolean constants, e.g. @code{Little_Endian}, and then write declarations
27850 that are parameterized by these constants. For example
27852 @smallexample @c ada
27855 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
27861 If @code{Bits_Per_Word} is set to 32, this generates either
27863 @smallexample @c ada
27866 Field1 at 0 range 0 .. 32;
27872 for the big endian case, or
27874 @smallexample @c ada
27877 Field1 at 0 range 10 .. 32;
27883 for the little endian case. Since a powerful subset of Ada expression
27884 notation is usable for creating static constants, clever use of this
27885 feature can often solve quite difficult problems in conditionalizing
27886 compilation (note incidentally that in Ada 95, the little endian
27887 constant was introduced as @code{System.Default_Bit_Order}, so you do not
27888 need to define this one yourself).
27891 @node Use of Alternative Implementations
27892 @section Use of Alternative Implementations
27895 In some cases, none of the approaches described above are adequate. This
27896 can occur for example if the set of declarations required is radically
27897 different for two different configurations.
27899 In this situation, the official Ada way of dealing with conditionalizing
27900 such code is to write separate units for the different cases. As long as
27901 this does not result in excessive duplication of code, this can be done
27902 without creating maintenance problems. The approach is to share common
27903 code as far as possible, and then isolate the code and declarations
27904 that are different. Subunits are often a convenient method for breaking
27905 out a piece of a unit that is to be conditionalized, with separate files
27906 for different versions of the subunit for different targets, where the
27907 build script selects the right one to give to the compiler.
27908 @cindex Subunits (and conditional compilation)
27910 As an example, consider a situation where a new feature in Ada 2005
27911 allows something to be done in a really nice way. But your code must be able
27912 to compile with an Ada 95 compiler. Conceptually you want to say:
27914 @smallexample @c ada
27917 ... neat Ada 2005 code
27919 ... not quite as neat Ada 95 code
27925 where @code{Ada_2005} is a Boolean constant.
27927 But this won't work when @code{Ada_2005} is set to @code{False},
27928 since the @code{then} clause will be illegal for an Ada 95 compiler.
27929 (Recall that although such unreachable code would eventually be deleted
27930 by the compiler, it still needs to be legal. If it uses features
27931 introduced in Ada 2005, it will be illegal in Ada 95.)
27933 So instead we write
27935 @smallexample @c ada
27936 procedure Insert is separate;
27940 Then we have two files for the subunit @code{Insert}, with the two sets of
27942 If the package containing this is called @code{File_Queries}, then we might
27946 @item @file{file_queries-insert-2005.adb}
27947 @item @file{file_queries-insert-95.adb}
27951 and the build script renames the appropriate file to
27954 file_queries-insert.adb
27958 and then carries out the compilation.
27960 This can also be done with project files' naming schemes. For example:
27962 @smallexample @c project
27963 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
27967 Note also that with project files it is desirable to use a different extension
27968 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
27969 conflict may arise through another commonly used feature: to declare as part
27970 of the project a set of directories containing all the sources obeying the
27971 default naming scheme.
27973 The use of alternative units is certainly feasible in all situations,
27974 and for example the Ada part of the GNAT run-time is conditionalized
27975 based on the target architecture using this approach. As a specific example,
27976 consider the implementation of the AST feature in VMS. There is one
27984 which is the same for all architectures, and three bodies:
27988 used for all non-VMS operating systems
27989 @item s-asthan-vms-alpha.adb
27990 used for VMS on the Alpha
27991 @item s-asthan-vms-ia64.adb
27992 used for VMS on the ia64
27996 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
27997 this operating system feature is not available, and the two remaining
27998 versions interface with the corresponding versions of VMS to provide
27999 VMS-compatible AST handling. The GNAT build script knows the architecture
28000 and operating system, and automatically selects the right version,
28001 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
28003 Another style for arranging alternative implementations is through Ada's
28004 access-to-subprogram facility.
28005 In case some functionality is to be conditionally included,
28006 you can declare an access-to-procedure variable @code{Ref} that is initialized
28007 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
28009 In some library package, set @code{Ref} to @code{Proc'Access} for some
28010 procedure @code{Proc} that performs the relevant processing.
28011 The initialization only occurs if the library package is included in the
28013 The same idea can also be implemented using tagged types and dispatching
28017 @node Preprocessing
28018 @section Preprocessing
28019 @cindex Preprocessing
28022 Although it is quite possible to conditionalize code without the use of
28023 C-style preprocessing, as described earlier in this section, it is
28024 nevertheless convenient in some cases to use the C approach. Moreover,
28025 older Ada compilers have often provided some preprocessing capability,
28026 so legacy code may depend on this approach, even though it is not
28029 To accommodate such use, GNAT provides a preprocessor (modeled to a large
28030 extent on the various preprocessors that have been used
28031 with legacy code on other compilers, to enable easier transition).
28033 The preprocessor may be used in two separate modes. It can be used quite
28034 separately from the compiler, to generate a separate output source file
28035 that is then fed to the compiler as a separate step. This is the
28036 @code{gnatprep} utility, whose use is fully described in
28037 @ref{Preprocessing Using gnatprep}.
28038 @cindex @code{gnatprep}
28040 The preprocessing language allows such constructs as
28044 #if DEBUG or PRIORITY > 4 then
28045 bunch of declarations
28047 completely different bunch of declarations
28053 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
28054 defined either on the command line or in a separate file.
28056 The other way of running the preprocessor is even closer to the C style and
28057 often more convenient. In this approach the preprocessing is integrated into
28058 the compilation process. The compiler is fed the preprocessor input which
28059 includes @code{#if} lines etc, and then the compiler carries out the
28060 preprocessing internally and processes the resulting output.
28061 For more details on this approach, see @ref{Integrated Preprocessing}.
28064 @c *******************************
28065 @node Inline Assembler
28066 @appendix Inline Assembler
28067 @c *******************************
28070 If you need to write low-level software that interacts directly
28071 with the hardware, Ada provides two ways to incorporate assembly
28072 language code into your program. First, you can import and invoke
28073 external routines written in assembly language, an Ada feature fully
28074 supported by GNAT@. However, for small sections of code it may be simpler
28075 or more efficient to include assembly language statements directly
28076 in your Ada source program, using the facilities of the implementation-defined
28077 package @code{System.Machine_Code}, which incorporates the gcc
28078 Inline Assembler. The Inline Assembler approach offers a number of advantages,
28079 including the following:
28082 @item No need to use non-Ada tools
28083 @item Consistent interface over different targets
28084 @item Automatic usage of the proper calling conventions
28085 @item Access to Ada constants and variables
28086 @item Definition of intrinsic routines
28087 @item Possibility of inlining a subprogram comprising assembler code
28088 @item Code optimizer can take Inline Assembler code into account
28091 This chapter presents a series of examples to show you how to use
28092 the Inline Assembler. Although it focuses on the Intel x86,
28093 the general approach applies also to other processors.
28094 It is assumed that you are familiar with Ada
28095 and with assembly language programming.
28098 * Basic Assembler Syntax::
28099 * A Simple Example of Inline Assembler::
28100 * Output Variables in Inline Assembler::
28101 * Input Variables in Inline Assembler::
28102 * Inlining Inline Assembler Code::
28103 * Other Asm Functionality::
28106 @c ---------------------------------------------------------------------------
28107 @node Basic Assembler Syntax
28108 @section Basic Assembler Syntax
28111 The assembler used by GNAT and gcc is based not on the Intel assembly
28112 language, but rather on a language that descends from the AT&T Unix
28113 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
28114 The following table summarizes the main features of @emph{as} syntax
28115 and points out the differences from the Intel conventions.
28116 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
28117 pre-processor) documentation for further information.
28120 @item Register names
28121 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
28123 Intel: No extra punctuation; for example @code{eax}
28125 @item Immediate operand
28126 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
28128 Intel: No extra punctuation; for example @code{4}
28131 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
28133 Intel: No extra punctuation; for example @code{loc}
28135 @item Memory contents
28136 gcc / @emph{as}: No extra punctuation; for example @code{loc}
28138 Intel: Square brackets; for example @code{[loc]}
28140 @item Register contents
28141 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
28143 Intel: Square brackets; for example @code{[eax]}
28145 @item Hexadecimal numbers
28146 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
28148 Intel: Trailing ``h''; for example @code{A0h}
28151 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
28154 Intel: Implicit, deduced by assembler; for example @code{mov}
28156 @item Instruction repetition
28157 gcc / @emph{as}: Split into two lines; for example
28163 Intel: Keep on one line; for example @code{rep stosl}
28165 @item Order of operands
28166 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
28168 Intel: Destination first; for example @code{mov eax, 4}
28171 @c ---------------------------------------------------------------------------
28172 @node A Simple Example of Inline Assembler
28173 @section A Simple Example of Inline Assembler
28176 The following example will generate a single assembly language statement,
28177 @code{nop}, which does nothing. Despite its lack of run-time effect,
28178 the example will be useful in illustrating the basics of
28179 the Inline Assembler facility.
28181 @smallexample @c ada
28183 with System.Machine_Code; use System.Machine_Code;
28184 procedure Nothing is
28191 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
28192 here it takes one parameter, a @emph{template string} that must be a static
28193 expression and that will form the generated instruction.
28194 @code{Asm} may be regarded as a compile-time procedure that parses
28195 the template string and additional parameters (none here),
28196 from which it generates a sequence of assembly language instructions.
28198 The examples in this chapter will illustrate several of the forms
28199 for invoking @code{Asm}; a complete specification of the syntax
28200 is found in the @cite{GNAT Reference Manual}.
28202 Under the standard GNAT conventions, the @code{Nothing} procedure
28203 should be in a file named @file{nothing.adb}.
28204 You can build the executable in the usual way:
28208 However, the interesting aspect of this example is not its run-time behavior
28209 but rather the generated assembly code.
28210 To see this output, invoke the compiler as follows:
28212 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
28214 where the options are:
28218 compile only (no bind or link)
28220 generate assembler listing
28221 @item -fomit-frame-pointer
28222 do not set up separate stack frames
28224 do not add runtime checks
28227 This gives a human-readable assembler version of the code. The resulting
28228 file will have the same name as the Ada source file, but with a @code{.s}
28229 extension. In our example, the file @file{nothing.s} has the following
28234 .file "nothing.adb"
28236 ___gnu_compiled_ada:
28239 .globl __ada_nothing
28251 The assembly code you included is clearly indicated by
28252 the compiler, between the @code{#APP} and @code{#NO_APP}
28253 delimiters. The character before the 'APP' and 'NOAPP'
28254 can differ on different targets. For example, GNU/Linux uses '#APP' while
28255 on NT you will see '/APP'.
28257 If you make a mistake in your assembler code (such as using the
28258 wrong size modifier, or using a wrong operand for the instruction) GNAT
28259 will report this error in a temporary file, which will be deleted when
28260 the compilation is finished. Generating an assembler file will help
28261 in such cases, since you can assemble this file separately using the
28262 @emph{as} assembler that comes with gcc.
28264 Assembling the file using the command
28267 as @file{nothing.s}
28270 will give you error messages whose lines correspond to the assembler
28271 input file, so you can easily find and correct any mistakes you made.
28272 If there are no errors, @emph{as} will generate an object file
28273 @file{nothing.out}.
28275 @c ---------------------------------------------------------------------------
28276 @node Output Variables in Inline Assembler
28277 @section Output Variables in Inline Assembler
28280 The examples in this section, showing how to access the processor flags,
28281 illustrate how to specify the destination operands for assembly language
28284 @smallexample @c ada
28286 with Interfaces; use Interfaces;
28287 with Ada.Text_IO; use Ada.Text_IO;
28288 with System.Machine_Code; use System.Machine_Code;
28289 procedure Get_Flags is
28290 Flags : Unsigned_32;
28293 Asm ("pushfl" & LF & HT & -- push flags on stack
28294 "popl %%eax" & LF & HT & -- load eax with flags
28295 "movl %%eax, %0", -- store flags in variable
28296 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28297 Put_Line ("Flags register:" & Flags'Img);
28302 In order to have a nicely aligned assembly listing, we have separated
28303 multiple assembler statements in the Asm template string with linefeed
28304 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
28305 The resulting section of the assembly output file is:
28312 movl %eax, -40(%ebp)
28317 It would have been legal to write the Asm invocation as:
28320 Asm ("pushfl popl %%eax movl %%eax, %0")
28323 but in the generated assembler file, this would come out as:
28327 pushfl popl %eax movl %eax, -40(%ebp)
28331 which is not so convenient for the human reader.
28333 We use Ada comments
28334 at the end of each line to explain what the assembler instructions
28335 actually do. This is a useful convention.
28337 When writing Inline Assembler instructions, you need to precede each register
28338 and variable name with a percent sign. Since the assembler already requires
28339 a percent sign at the beginning of a register name, you need two consecutive
28340 percent signs for such names in the Asm template string, thus @code{%%eax}.
28341 In the generated assembly code, one of the percent signs will be stripped off.
28343 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
28344 variables: operands you later define using @code{Input} or @code{Output}
28345 parameters to @code{Asm}.
28346 An output variable is illustrated in
28347 the third statement in the Asm template string:
28351 The intent is to store the contents of the eax register in a variable that can
28352 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
28353 necessarily work, since the compiler might optimize by using a register
28354 to hold Flags, and the expansion of the @code{movl} instruction would not be
28355 aware of this optimization. The solution is not to store the result directly
28356 but rather to advise the compiler to choose the correct operand form;
28357 that is the purpose of the @code{%0} output variable.
28359 Information about the output variable is supplied in the @code{Outputs}
28360 parameter to @code{Asm}:
28362 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28365 The output is defined by the @code{Asm_Output} attribute of the target type;
28366 the general format is
28368 Type'Asm_Output (constraint_string, variable_name)
28371 The constraint string directs the compiler how
28372 to store/access the associated variable. In the example
28374 Unsigned_32'Asm_Output ("=m", Flags);
28376 the @code{"m"} (memory) constraint tells the compiler that the variable
28377 @code{Flags} should be stored in a memory variable, thus preventing
28378 the optimizer from keeping it in a register. In contrast,
28380 Unsigned_32'Asm_Output ("=r", Flags);
28382 uses the @code{"r"} (register) constraint, telling the compiler to
28383 store the variable in a register.
28385 If the constraint is preceded by the equal character (@strong{=}), it tells
28386 the compiler that the variable will be used to store data into it.
28388 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
28389 allowing the optimizer to choose whatever it deems best.
28391 There are a fairly large number of constraints, but the ones that are
28392 most useful (for the Intel x86 processor) are the following:
28398 global (i.e. can be stored anywhere)
28416 use one of eax, ebx, ecx or edx
28418 use one of eax, ebx, ecx, edx, esi or edi
28421 The full set of constraints is described in the gcc and @emph{as}
28422 documentation; note that it is possible to combine certain constraints
28423 in one constraint string.
28425 You specify the association of an output variable with an assembler operand
28426 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
28428 @smallexample @c ada
28430 Asm ("pushfl" & LF & HT & -- push flags on stack
28431 "popl %%eax" & LF & HT & -- load eax with flags
28432 "movl %%eax, %0", -- store flags in variable
28433 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28437 @code{%0} will be replaced in the expanded code by the appropriate operand,
28439 the compiler decided for the @code{Flags} variable.
28441 In general, you may have any number of output variables:
28444 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
28446 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
28447 of @code{Asm_Output} attributes
28451 @smallexample @c ada
28453 Asm ("movl %%eax, %0" & LF & HT &
28454 "movl %%ebx, %1" & LF & HT &
28456 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
28457 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
28458 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
28462 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
28463 in the Ada program.
28465 As a variation on the @code{Get_Flags} example, we can use the constraints
28466 string to direct the compiler to store the eax register into the @code{Flags}
28467 variable, instead of including the store instruction explicitly in the
28468 @code{Asm} template string:
28470 @smallexample @c ada
28472 with Interfaces; use Interfaces;
28473 with Ada.Text_IO; use Ada.Text_IO;
28474 with System.Machine_Code; use System.Machine_Code;
28475 procedure Get_Flags_2 is
28476 Flags : Unsigned_32;
28479 Asm ("pushfl" & LF & HT & -- push flags on stack
28480 "popl %%eax", -- save flags in eax
28481 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
28482 Put_Line ("Flags register:" & Flags'Img);
28488 The @code{"a"} constraint tells the compiler that the @code{Flags}
28489 variable will come from the eax register. Here is the resulting code:
28497 movl %eax,-40(%ebp)
28502 The compiler generated the store of eax into Flags after
28503 expanding the assembler code.
28505 Actually, there was no need to pop the flags into the eax register;
28506 more simply, we could just pop the flags directly into the program variable:
28508 @smallexample @c ada
28510 with Interfaces; use Interfaces;
28511 with Ada.Text_IO; use Ada.Text_IO;
28512 with System.Machine_Code; use System.Machine_Code;
28513 procedure Get_Flags_3 is
28514 Flags : Unsigned_32;
28517 Asm ("pushfl" & LF & HT & -- push flags on stack
28518 "pop %0", -- save flags in Flags
28519 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28520 Put_Line ("Flags register:" & Flags'Img);
28525 @c ---------------------------------------------------------------------------
28526 @node Input Variables in Inline Assembler
28527 @section Input Variables in Inline Assembler
28530 The example in this section illustrates how to specify the source operands
28531 for assembly language statements.
28532 The program simply increments its input value by 1:
28534 @smallexample @c ada
28536 with Interfaces; use Interfaces;
28537 with Ada.Text_IO; use Ada.Text_IO;
28538 with System.Machine_Code; use System.Machine_Code;
28539 procedure Increment is
28541 function Incr (Value : Unsigned_32) return Unsigned_32 is
28542 Result : Unsigned_32;
28545 Inputs => Unsigned_32'Asm_Input ("a", Value),
28546 Outputs => Unsigned_32'Asm_Output ("=a", Result));
28550 Value : Unsigned_32;
28554 Put_Line ("Value before is" & Value'Img);
28555 Value := Incr (Value);
28556 Put_Line ("Value after is" & Value'Img);
28561 The @code{Outputs} parameter to @code{Asm} specifies
28562 that the result will be in the eax register and that it is to be stored
28563 in the @code{Result} variable.
28565 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
28566 but with an @code{Asm_Input} attribute.
28567 The @code{"="} constraint, indicating an output value, is not present.
28569 You can have multiple input variables, in the same way that you can have more
28570 than one output variable.
28572 The parameter count (%0, %1) etc, now starts at the first input
28573 statement, and continues with the output statements.
28574 When both parameters use the same variable, the
28575 compiler will treat them as the same %n operand, which is the case here.
28577 Just as the @code{Outputs} parameter causes the register to be stored into the
28578 target variable after execution of the assembler statements, so does the
28579 @code{Inputs} parameter cause its variable to be loaded into the register
28580 before execution of the assembler statements.
28582 Thus the effect of the @code{Asm} invocation is:
28584 @item load the 32-bit value of @code{Value} into eax
28585 @item execute the @code{incl %eax} instruction
28586 @item store the contents of eax into the @code{Result} variable
28589 The resulting assembler file (with @option{-O2} optimization) contains:
28592 _increment__incr.1:
28605 @c ---------------------------------------------------------------------------
28606 @node Inlining Inline Assembler Code
28607 @section Inlining Inline Assembler Code
28610 For a short subprogram such as the @code{Incr} function in the previous
28611 section, the overhead of the call and return (creating / deleting the stack
28612 frame) can be significant, compared to the amount of code in the subprogram
28613 body. A solution is to apply Ada's @code{Inline} pragma to the subprogram,
28614 which directs the compiler to expand invocations of the subprogram at the
28615 point(s) of call, instead of setting up a stack frame for out-of-line calls.
28616 Here is the resulting program:
28618 @smallexample @c ada
28620 with Interfaces; use Interfaces;
28621 with Ada.Text_IO; use Ada.Text_IO;
28622 with System.Machine_Code; use System.Machine_Code;
28623 procedure Increment_2 is
28625 function Incr (Value : Unsigned_32) return Unsigned_32 is
28626 Result : Unsigned_32;
28629 Inputs => Unsigned_32'Asm_Input ("a", Value),
28630 Outputs => Unsigned_32'Asm_Output ("=a", Result));
28633 pragma Inline (Increment);
28635 Value : Unsigned_32;
28639 Put_Line ("Value before is" & Value'Img);
28640 Value := Increment (Value);
28641 Put_Line ("Value after is" & Value'Img);
28646 Compile the program with both optimization (@option{-O2}) and inlining
28647 enabled (@option{-gnatpn} instead of @option{-gnatp}).
28649 The @code{Incr} function is still compiled as usual, but at the
28650 point in @code{Increment} where our function used to be called:
28655 call _increment__incr.1
28660 the code for the function body directly appears:
28673 thus saving the overhead of stack frame setup and an out-of-line call.
28675 @c ---------------------------------------------------------------------------
28676 @node Other Asm Functionality
28677 @section Other @code{Asm} Functionality
28680 This section describes two important parameters to the @code{Asm}
28681 procedure: @code{Clobber}, which identifies register usage;
28682 and @code{Volatile}, which inhibits unwanted optimizations.
28685 * The Clobber Parameter::
28686 * The Volatile Parameter::
28689 @c ---------------------------------------------------------------------------
28690 @node The Clobber Parameter
28691 @subsection The @code{Clobber} Parameter
28694 One of the dangers of intermixing assembly language and a compiled language
28695 such as Ada is that the compiler needs to be aware of which registers are
28696 being used by the assembly code. In some cases, such as the earlier examples,
28697 the constraint string is sufficient to indicate register usage (e.g.,
28699 the eax register). But more generally, the compiler needs an explicit
28700 identification of the registers that are used by the Inline Assembly
28703 Using a register that the compiler doesn't know about
28704 could be a side effect of an instruction (like @code{mull}
28705 storing its result in both eax and edx).
28706 It can also arise from explicit register usage in your
28707 assembly code; for example:
28710 Asm ("movl %0, %%ebx" & LF & HT &
28712 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
28713 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
28717 where the compiler (since it does not analyze the @code{Asm} template string)
28718 does not know you are using the ebx register.
28720 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
28721 to identify the registers that will be used by your assembly code:
28725 Asm ("movl %0, %%ebx" & LF & HT &
28727 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
28728 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28733 The Clobber parameter is a static string expression specifying the
28734 register(s) you are using. Note that register names are @emph{not} prefixed
28735 by a percent sign. Also, if more than one register is used then their names
28736 are separated by commas; e.g., @code{"eax, ebx"}
28738 The @code{Clobber} parameter has several additional uses:
28740 @item Use ``register'' name @code{cc} to indicate that flags might have changed
28741 @item Use ``register'' name @code{memory} if you changed a memory location
28744 @c ---------------------------------------------------------------------------
28745 @node The Volatile Parameter
28746 @subsection The @code{Volatile} Parameter
28747 @cindex Volatile parameter
28750 Compiler optimizations in the presence of Inline Assembler may sometimes have
28751 unwanted effects. For example, when an @code{Asm} invocation with an input
28752 variable is inside a loop, the compiler might move the loading of the input
28753 variable outside the loop, regarding it as a one-time initialization.
28755 If this effect is not desired, you can disable such optimizations by setting
28756 the @code{Volatile} parameter to @code{True}; for example:
28758 @smallexample @c ada
28760 Asm ("movl %0, %%ebx" & LF & HT &
28762 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
28763 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28769 By default, @code{Volatile} is set to @code{False} unless there is no
28770 @code{Outputs} parameter.
28772 Although setting @code{Volatile} to @code{True} prevents unwanted
28773 optimizations, it will also disable other optimizations that might be
28774 important for efficiency. In general, you should set @code{Volatile}
28775 to @code{True} only if the compiler's optimizations have created
28777 @c END OF INLINE ASSEMBLER CHAPTER
28778 @c ===============================
28780 @c ***********************************
28781 @c * Compatibility and Porting Guide *
28782 @c ***********************************
28783 @node Compatibility and Porting Guide
28784 @appendix Compatibility and Porting Guide
28787 This chapter describes the compatibility issues that may arise between
28788 GNAT and other Ada compilation systems (including those for Ada 83),
28789 and shows how GNAT can expedite porting
28790 applications developed in other Ada environments.
28793 * Compatibility with Ada 83::
28794 * Compatibility between Ada 95 and Ada 2005::
28795 * Implementation-dependent characteristics::
28796 * Compatibility with Other Ada Systems::
28797 * Representation Clauses::
28799 @c Brief section is only in non-VMS version
28800 @c Full chapter is in VMS version
28801 * Compatibility with HP Ada 83::
28804 * Transitioning to 64-Bit GNAT for OpenVMS::
28808 @node Compatibility with Ada 83
28809 @section Compatibility with Ada 83
28810 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
28813 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83. In
28814 particular, the design intention was that the difficulties associated
28815 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
28816 that occur when moving from one Ada 83 system to another.
28818 However, there are a number of points at which there are minor
28819 incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains
28820 full details of these issues,
28821 and should be consulted for a complete treatment.
28823 following subsections treat the most likely issues to be encountered.
28826 * Legal Ada 83 programs that are illegal in Ada 95::
28827 * More deterministic semantics::
28828 * Changed semantics::
28829 * Other language compatibility issues::
28832 @node Legal Ada 83 programs that are illegal in Ada 95
28833 @subsection Legal Ada 83 programs that are illegal in Ada 95
28835 Some legal Ada 83 programs are illegal (i.e. they will fail to compile) in
28836 Ada 95 and thus also in Ada 2005:
28839 @item Character literals
28840 Some uses of character literals are ambiguous. Since Ada 95 has introduced
28841 @code{Wide_Character} as a new predefined character type, some uses of
28842 character literals that were legal in Ada 83 are illegal in Ada 95.
28844 @smallexample @c ada
28845 for Char in 'A' .. 'Z' loop ... end loop;
28849 The problem is that @code{'A'} and @code{'Z'} could be from either
28850 @code{Character} or @code{Wide_Character}. The simplest correction
28851 is to make the type explicit; e.g.:
28852 @smallexample @c ada
28853 for Char in Character range 'A' .. 'Z' loop ... end loop;
28856 @item New reserved words
28857 The identifiers @code{abstract}, @code{aliased}, @code{protected},
28858 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
28859 Existing Ada 83 code using any of these identifiers must be edited to
28860 use some alternative name.
28862 @item Freezing rules
28863 The rules in Ada 95 are slightly different with regard to the point at
28864 which entities are frozen, and representation pragmas and clauses are
28865 not permitted past the freeze point. This shows up most typically in
28866 the form of an error message complaining that a representation item
28867 appears too late, and the appropriate corrective action is to move
28868 the item nearer to the declaration of the entity to which it refers.
28870 A particular case is that representation pragmas
28873 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
28875 cannot be applied to a subprogram body. If necessary, a separate subprogram
28876 declaration must be introduced to which the pragma can be applied.
28878 @item Optional bodies for library packages
28879 In Ada 83, a package that did not require a package body was nevertheless
28880 allowed to have one. This lead to certain surprises in compiling large
28881 systems (situations in which the body could be unexpectedly ignored by the
28882 binder). In Ada 95, if a package does not require a body then it is not
28883 permitted to have a body. To fix this problem, simply remove a redundant
28884 body if it is empty, or, if it is non-empty, introduce a dummy declaration
28885 into the spec that makes the body required. One approach is to add a private
28886 part to the package declaration (if necessary), and define a parameterless
28887 procedure called @code{Requires_Body}, which must then be given a dummy
28888 procedure body in the package body, which then becomes required.
28889 Another approach (assuming that this does not introduce elaboration
28890 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
28891 since one effect of this pragma is to require the presence of a package body.
28893 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
28894 In Ada 95, the exception @code{Numeric_Error} is a renaming of
28895 @code{Constraint_Error}.
28896 This means that it is illegal to have separate exception handlers for
28897 the two exceptions. The fix is simply to remove the handler for the
28898 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
28899 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
28901 @item Indefinite subtypes in generics
28902 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
28903 as the actual for a generic formal private type, but then the instantiation
28904 would be illegal if there were any instances of declarations of variables
28905 of this type in the generic body. In Ada 95, to avoid this clear violation
28906 of the methodological principle known as the ``contract model'',
28907 the generic declaration explicitly indicates whether
28908 or not such instantiations are permitted. If a generic formal parameter
28909 has explicit unknown discriminants, indicated by using @code{(<>)} after the
28910 type name, then it can be instantiated with indefinite types, but no
28911 stand-alone variables can be declared of this type. Any attempt to declare
28912 such a variable will result in an illegality at the time the generic is
28913 declared. If the @code{(<>)} notation is not used, then it is illegal
28914 to instantiate the generic with an indefinite type.
28915 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
28916 It will show up as a compile time error, and
28917 the fix is usually simply to add the @code{(<>)} to the generic declaration.
28920 @node More deterministic semantics
28921 @subsection More deterministic semantics
28925 Conversions from real types to integer types round away from 0. In Ada 83
28926 the conversion Integer(2.5) could deliver either 2 or 3 as its value. This
28927 implementation freedom was intended to support unbiased rounding in
28928 statistical applications, but in practice it interfered with portability.
28929 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
28930 is required. Numeric code may be affected by this change in semantics.
28931 Note, though, that this issue is no worse than already existed in Ada 83
28932 when porting code from one vendor to another.
28935 The Real-Time Annex introduces a set of policies that define the behavior of
28936 features that were implementation dependent in Ada 83, such as the order in
28937 which open select branches are executed.
28940 @node Changed semantics
28941 @subsection Changed semantics
28944 The worst kind of incompatibility is one where a program that is legal in
28945 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
28946 possible in Ada 83. Fortunately this is extremely rare, but the one
28947 situation that you should be alert to is the change in the predefined type
28948 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
28951 @item Range of type @code{Character}
28952 The range of @code{Standard.Character} is now the full 256 characters
28953 of Latin-1, whereas in most Ada 83 implementations it was restricted
28954 to 128 characters. Although some of the effects of
28955 this change will be manifest in compile-time rejection of legal
28956 Ada 83 programs it is possible for a working Ada 83 program to have
28957 a different effect in Ada 95, one that was not permitted in Ada 83.
28958 As an example, the expression
28959 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
28960 delivers @code{255} as its value.
28961 In general, you should look at the logic of any
28962 character-processing Ada 83 program and see whether it needs to be adapted
28963 to work correctly with Latin-1. Note that the predefined Ada 95 API has a
28964 character handling package that may be relevant if code needs to be adapted
28965 to account for the additional Latin-1 elements.
28966 The desirable fix is to
28967 modify the program to accommodate the full character set, but in some cases
28968 it may be convenient to define a subtype or derived type of Character that
28969 covers only the restricted range.
28973 @node Other language compatibility issues
28974 @subsection Other language compatibility issues
28977 @item @option{-gnat83} switch
28978 All implementations of GNAT provide a switch that causes GNAT to operate
28979 in Ada 83 mode. In this mode, some but not all compatibility problems
28980 of the type described above are handled automatically. For example, the
28981 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
28982 as identifiers as in Ada 83.
28984 in practice, it is usually advisable to make the necessary modifications
28985 to the program to remove the need for using this switch.
28986 See @ref{Compiling Different Versions of Ada}.
28988 @item Support for removed Ada 83 pragmas and attributes
28989 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
28990 generally because they were replaced by other mechanisms. Ada 95 and Ada 2005
28991 compilers are allowed, but not required, to implement these missing
28992 elements. In contrast with some other compilers, GNAT implements all
28993 such pragmas and attributes, eliminating this compatibility concern. These
28994 include @code{pragma Interface} and the floating point type attributes
28995 (@code{Emax}, @code{Mantissa}, etc.), among other items.
28999 @node Compatibility between Ada 95 and Ada 2005
29000 @section Compatibility between Ada 95 and Ada 2005
29001 @cindex Compatibility between Ada 95 and Ada 2005
29004 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
29005 a number of incompatibilities. Several are enumerated below;
29006 for a complete description please see the
29007 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
29008 @cite{Rationale for Ada 2005}.
29011 @item New reserved words.
29012 The words @code{interface}, @code{overriding} and @code{synchronized} are
29013 reserved in Ada 2005.
29014 A pre-Ada 2005 program that uses any of these as an identifier will be
29017 @item New declarations in predefined packages.
29018 A number of packages in the predefined environment contain new declarations:
29019 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
29020 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
29021 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
29022 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
29023 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
29024 If an Ada 95 program does a @code{with} and @code{use} of any of these
29025 packages, the new declarations may cause name clashes.
29027 @item Access parameters.
29028 A nondispatching subprogram with an access parameter cannot be renamed
29029 as a dispatching operation. This was permitted in Ada 95.
29031 @item Access types, discriminants, and constraints.
29032 Rule changes in this area have led to some incompatibilities; for example,
29033 constrained subtypes of some access types are not permitted in Ada 2005.
29035 @item Aggregates for limited types.
29036 The allowance of aggregates for limited types in Ada 2005 raises the
29037 possibility of ambiguities in legal Ada 95 programs, since additional types
29038 now need to be considered in expression resolution.
29040 @item Fixed-point multiplication and division.
29041 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
29042 were legal in Ada 95 and invoked the predefined versions of these operations,
29044 The ambiguity may be resolved either by applying a type conversion to the
29045 expression, or by explicitly invoking the operation from package
29048 @item Return-by-reference types.
29049 The Ada 95 return-by-reference mechanism has been removed. Instead, the user
29050 can declare a function returning a value from an anonymous access type.
29054 @node Implementation-dependent characteristics
29055 @section Implementation-dependent characteristics
29057 Although the Ada language defines the semantics of each construct as
29058 precisely as practical, in some situations (for example for reasons of
29059 efficiency, or where the effect is heavily dependent on the host or target
29060 platform) the implementation is allowed some freedom. In porting Ada 83
29061 code to GNAT, you need to be aware of whether / how the existing code
29062 exercised such implementation dependencies. Such characteristics fall into
29063 several categories, and GNAT offers specific support in assisting the
29064 transition from certain Ada 83 compilers.
29067 * Implementation-defined pragmas::
29068 * Implementation-defined attributes::
29070 * Elaboration order::
29071 * Target-specific aspects::
29074 @node Implementation-defined pragmas
29075 @subsection Implementation-defined pragmas
29078 Ada compilers are allowed to supplement the language-defined pragmas, and
29079 these are a potential source of non-portability. All GNAT-defined pragmas
29080 are described in the GNAT Reference Manual, and these include several that
29081 are specifically intended to correspond to other vendors' Ada 83 pragmas.
29082 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
29084 compatibility with HP Ada 83, GNAT supplies the pragmas
29085 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
29086 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
29087 and @code{Volatile}.
29088 Other relevant pragmas include @code{External} and @code{Link_With}.
29089 Some vendor-specific
29090 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
29092 avoiding compiler rejection of units that contain such pragmas; they are not
29093 relevant in a GNAT context and hence are not otherwise implemented.
29095 @node Implementation-defined attributes
29096 @subsection Implementation-defined attributes
29098 Analogous to pragmas, the set of attributes may be extended by an
29099 implementation. All GNAT-defined attributes are described in the
29100 @cite{GNAT Reference Manual}, and these include several that are specifically
29102 to correspond to other vendors' Ada 83 attributes. For migrating from VADS,
29103 the attribute @code{VADS_Size} may be useful. For compatibility with HP
29104 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
29108 @subsection Libraries
29110 Vendors may supply libraries to supplement the standard Ada API. If Ada 83
29111 code uses vendor-specific libraries then there are several ways to manage
29112 this in Ada 95 or Ada 2005:
29115 If the source code for the libraries (specifications and bodies) are
29116 available, then the libraries can be migrated in the same way as the
29119 If the source code for the specifications but not the bodies are
29120 available, then you can reimplement the bodies.
29122 Some features introduced by Ada 95 obviate the need for library support. For
29123 example most Ada 83 vendors supplied a package for unsigned integers. The
29124 Ada 95 modular type feature is the preferred way to handle this need, so
29125 instead of migrating or reimplementing the unsigned integer package it may
29126 be preferable to retrofit the application using modular types.
29129 @node Elaboration order
29130 @subsection Elaboration order
29132 The implementation can choose any elaboration order consistent with the unit
29133 dependency relationship. This freedom means that some orders can result in
29134 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
29135 to invoke a subprogram its body has been elaborated, or to instantiate a
29136 generic before the generic body has been elaborated. By default GNAT
29137 attempts to choose a safe order (one that will not encounter access before
29138 elaboration problems) by implicitly inserting @code{Elaborate} or
29139 @code{Elaborate_All} pragmas where
29140 needed. However, this can lead to the creation of elaboration circularities
29141 and a resulting rejection of the program by gnatbind. This issue is
29142 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
29143 In brief, there are several
29144 ways to deal with this situation:
29148 Modify the program to eliminate the circularities, e.g. by moving
29149 elaboration-time code into explicitly-invoked procedures
29151 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
29152 @code{Elaborate} pragmas, and then inhibit the generation of implicit
29153 @code{Elaborate_All}
29154 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
29155 (by selectively suppressing elaboration checks via pragma
29156 @code{Suppress(Elaboration_Check)} when it is safe to do so).
29159 @node Target-specific aspects
29160 @subsection Target-specific aspects
29162 Low-level applications need to deal with machine addresses, data
29163 representations, interfacing with assembler code, and similar issues. If
29164 such an Ada 83 application is being ported to different target hardware (for
29165 example where the byte endianness has changed) then you will need to
29166 carefully examine the program logic; the porting effort will heavily depend
29167 on the robustness of the original design. Moreover, Ada 95 (and thus
29168 Ada 2005) are sometimes
29169 incompatible with typical Ada 83 compiler practices regarding implicit
29170 packing, the meaning of the Size attribute, and the size of access values.
29171 GNAT's approach to these issues is described in @ref{Representation Clauses}.
29173 @node Compatibility with Other Ada Systems
29174 @section Compatibility with Other Ada Systems
29177 If programs avoid the use of implementation dependent and
29178 implementation defined features, as documented in the @cite{Ada
29179 Reference Manual}, there should be a high degree of portability between
29180 GNAT and other Ada systems. The following are specific items which
29181 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
29182 compilers, but do not affect porting code to GNAT@.
29183 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
29184 the following issues may or may not arise for Ada 2005 programs
29185 when other compilers appear.)
29188 @item Ada 83 Pragmas and Attributes
29189 Ada 95 compilers are allowed, but not required, to implement the missing
29190 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
29191 GNAT implements all such pragmas and attributes, eliminating this as
29192 a compatibility concern, but some other Ada 95 compilers reject these
29193 pragmas and attributes.
29195 @item Specialized Needs Annexes
29196 GNAT implements the full set of special needs annexes. At the
29197 current time, it is the only Ada 95 compiler to do so. This means that
29198 programs making use of these features may not be portable to other Ada
29199 95 compilation systems.
29201 @item Representation Clauses
29202 Some other Ada 95 compilers implement only the minimal set of
29203 representation clauses required by the Ada 95 reference manual. GNAT goes
29204 far beyond this minimal set, as described in the next section.
29207 @node Representation Clauses
29208 @section Representation Clauses
29211 The Ada 83 reference manual was quite vague in describing both the minimal
29212 required implementation of representation clauses, and also their precise
29213 effects. Ada 95 (and thus also Ada 2005) are much more explicit, but the
29214 minimal set of capabilities required is still quite limited.
29216 GNAT implements the full required set of capabilities in
29217 Ada 95 and Ada 2005, but also goes much further, and in particular
29218 an effort has been made to be compatible with existing Ada 83 usage to the
29219 greatest extent possible.
29221 A few cases exist in which Ada 83 compiler behavior is incompatible with
29222 the requirements in Ada 95 (and thus also Ada 2005). These are instances of
29223 intentional or accidental dependence on specific implementation dependent
29224 characteristics of these Ada 83 compilers. The following is a list of
29225 the cases most likely to arise in existing Ada 83 code.
29228 @item Implicit Packing
29229 Some Ada 83 compilers allowed a Size specification to cause implicit
29230 packing of an array or record. This could cause expensive implicit
29231 conversions for change of representation in the presence of derived
29232 types, and the Ada design intends to avoid this possibility.
29233 Subsequent AI's were issued to make it clear that such implicit
29234 change of representation in response to a Size clause is inadvisable,
29235 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
29236 Reference Manuals as implementation advice that is followed by GNAT@.
29237 The problem will show up as an error
29238 message rejecting the size clause. The fix is simply to provide
29239 the explicit pragma @code{Pack}, or for more fine tuned control, provide
29240 a Component_Size clause.
29242 @item Meaning of Size Attribute
29243 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
29244 the minimal number of bits required to hold values of the type. For example,
29245 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
29246 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and
29247 some 32 in this situation. This problem will usually show up as a compile
29248 time error, but not always. It is a good idea to check all uses of the
29249 'Size attribute when porting Ada 83 code. The GNAT specific attribute
29250 Object_Size can provide a useful way of duplicating the behavior of
29251 some Ada 83 compiler systems.
29253 @item Size of Access Types
29254 A common assumption in Ada 83 code is that an access type is in fact a pointer,
29255 and that therefore it will be the same size as a System.Address value. This
29256 assumption is true for GNAT in most cases with one exception. For the case of
29257 a pointer to an unconstrained array type (where the bounds may vary from one
29258 value of the access type to another), the default is to use a ``fat pointer'',
29259 which is represented as two separate pointers, one to the bounds, and one to
29260 the array. This representation has a number of advantages, including improved
29261 efficiency. However, it may cause some difficulties in porting existing Ada 83
29262 code which makes the assumption that, for example, pointers fit in 32 bits on
29263 a machine with 32-bit addressing.
29265 To get around this problem, GNAT also permits the use of ``thin pointers'' for
29266 access types in this case (where the designated type is an unconstrained array
29267 type). These thin pointers are indeed the same size as a System.Address value.
29268 To specify a thin pointer, use a size clause for the type, for example:
29270 @smallexample @c ada
29271 type X is access all String;
29272 for X'Size use Standard'Address_Size;
29276 which will cause the type X to be represented using a single pointer.
29277 When using this representation, the bounds are right behind the array.
29278 This representation is slightly less efficient, and does not allow quite
29279 such flexibility in the use of foreign pointers or in using the
29280 Unrestricted_Access attribute to create pointers to non-aliased objects.
29281 But for any standard portable use of the access type it will work in
29282 a functionally correct manner and allow porting of existing code.
29283 Note that another way of forcing a thin pointer representation
29284 is to use a component size clause for the element size in an array,
29285 or a record representation clause for an access field in a record.
29289 @c This brief section is only in the non-VMS version
29290 @c The complete chapter on HP Ada is in the VMS version
29291 @node Compatibility with HP Ada 83
29292 @section Compatibility with HP Ada 83
29295 The VMS version of GNAT fully implements all the pragmas and attributes
29296 provided by HP Ada 83, as well as providing the standard HP Ada 83
29297 libraries, including Starlet. In addition, data layouts and parameter
29298 passing conventions are highly compatible. This means that porting
29299 existing HP Ada 83 code to GNAT in VMS systems should be easier than
29300 most other porting efforts. The following are some of the most
29301 significant differences between GNAT and HP Ada 83.
29304 @item Default floating-point representation
29305 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
29306 it is VMS format. GNAT does implement the necessary pragmas
29307 (Long_Float, Float_Representation) for changing this default.
29310 The package System in GNAT exactly corresponds to the definition in the
29311 Ada 95 reference manual, which means that it excludes many of the
29312 HP Ada 83 extensions. However, a separate package Aux_DEC is provided
29313 that contains the additional definitions, and a special pragma,
29314 Extend_System allows this package to be treated transparently as an
29315 extension of package System.
29318 The definitions provided by Aux_DEC are exactly compatible with those
29319 in the HP Ada 83 version of System, with one exception.
29320 HP Ada provides the following declarations:
29322 @smallexample @c ada
29323 TO_ADDRESS (INTEGER)
29324 TO_ADDRESS (UNSIGNED_LONGWORD)
29325 TO_ADDRESS (@i{universal_integer})
29329 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
29330 an extension to Ada 83 not strictly compatible with the reference manual.
29331 In GNAT, we are constrained to be exactly compatible with the standard,
29332 and this means we cannot provide this capability. In HP Ada 83, the
29333 point of this definition is to deal with a call like:
29335 @smallexample @c ada
29336 TO_ADDRESS (16#12777#);
29340 Normally, according to the Ada 83 standard, one would expect this to be
29341 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
29342 of TO_ADDRESS@. However, in HP Ada 83, there is no ambiguity, since the
29343 definition using @i{universal_integer} takes precedence.
29345 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
29346 is not possible to be 100% compatible. Since there are many programs using
29347 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
29348 to change the name of the function in the UNSIGNED_LONGWORD case, so the
29349 declarations provided in the GNAT version of AUX_Dec are:
29351 @smallexample @c ada
29352 function To_Address (X : Integer) return Address;
29353 pragma Pure_Function (To_Address);
29355 function To_Address_Long (X : Unsigned_Longword)
29357 pragma Pure_Function (To_Address_Long);
29361 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
29362 change the name to TO_ADDRESS_LONG@.
29364 @item Task_Id values
29365 The Task_Id values assigned will be different in the two systems, and GNAT
29366 does not provide a specified value for the Task_Id of the environment task,
29367 which in GNAT is treated like any other declared task.
29371 For full details on these and other less significant compatibility issues,
29372 see appendix E of the HP publication entitled @cite{HP Ada, Technical
29373 Overview and Comparison on HP Platforms}.
29375 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
29376 attributes are recognized, although only a subset of them can sensibly
29377 be implemented. The description of pragmas in the
29378 @cite{GNAT Reference Manual}
29379 indicates whether or not they are applicable to non-VMS systems.
29383 @node Transitioning to 64-Bit GNAT for OpenVMS
29384 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
29387 This section is meant to assist users of pre-2006 @value{EDITION}
29388 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
29389 the version of the GNAT technology supplied in 2006 and later for
29390 OpenVMS on both Alpha and I64.
29393 * Introduction to transitioning::
29394 * Migration of 32 bit code::
29395 * Taking advantage of 64 bit addressing::
29396 * Technical details::
29399 @node Introduction to transitioning
29400 @subsection Introduction
29403 64-bit @value{EDITION} for Open VMS has been designed to meet
29408 Providing a full conforming implementation of Ada 95 and Ada 2005
29411 Allowing maximum backward compatibility, thus easing migration of existing
29415 Supplying a path for exploiting the full 64-bit address range
29419 Ada's strong typing semantics has made it
29420 impractical to have different 32-bit and 64-bit modes. As soon as
29421 one object could possibly be outside the 32-bit address space, this
29422 would make it necessary for the @code{System.Address} type to be 64 bits.
29423 In particular, this would cause inconsistencies if 32-bit code is
29424 called from 64-bit code that raises an exception.
29426 This issue has been resolved by always using 64-bit addressing
29427 at the system level, but allowing for automatic conversions between
29428 32-bit and 64-bit addresses where required. Thus users who
29429 do not currently require 64-bit addressing capabilities, can
29430 recompile their code with only minimal changes (and indeed
29431 if the code is written in portable Ada, with no assumptions about
29432 the size of the @code{Address} type, then no changes at all are necessary).
29434 this approach provides a simple, gradual upgrade path to future
29435 use of larger memories than available for 32-bit systems.
29436 Also, newly written applications or libraries will by default
29437 be fully compatible with future systems exploiting 64-bit
29438 addressing capabilities.
29440 @ref{Migration of 32 bit code}, will focus on porting applications
29441 that do not require more than 2 GB of
29442 addressable memory. This code will be referred to as
29443 @emph{32-bit code}.
29444 For applications intending to exploit the full 64-bit address space,
29445 @ref{Taking advantage of 64 bit addressing},
29446 will consider further changes that may be required.
29447 Such code will be referred to below as @emph{64-bit code}.
29449 @node Migration of 32 bit code
29450 @subsection Migration of 32-bit code
29455 * Unchecked conversions::
29456 * Predefined constants::
29457 * Interfacing with C::
29458 * Experience with source compatibility::
29461 @node Address types
29462 @subsubsection Address types
29465 To solve the problem of mixing 64-bit and 32-bit addressing,
29466 while maintaining maximum backward compatibility, the following
29467 approach has been taken:
29471 @code{System.Address} always has a size of 64 bits
29474 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
29478 Since @code{System.Short_Address} is a subtype of @code{System.Address},
29479 a @code{Short_Address}
29480 may be used where an @code{Address} is required, and vice versa, without
29481 needing explicit type conversions.
29482 By virtue of the Open VMS parameter passing conventions,
29484 and exported subprograms that have 32-bit address parameters are
29485 compatible with those that have 64-bit address parameters.
29486 (See @ref{Making code 64 bit clean} for details.)
29488 The areas that may need attention are those where record types have
29489 been defined that contain components of the type @code{System.Address}, and
29490 where objects of this type are passed to code expecting a record layout with
29493 Different compilers on different platforms cannot be
29494 expected to represent the same type in the same way,
29495 since alignment constraints
29496 and other system-dependent properties affect the compiler's decision.
29497 For that reason, Ada code
29498 generally uses representation clauses to specify the expected
29499 layout where required.
29501 If such a representation clause uses 32 bits for a component having
29502 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
29503 will detect that error and produce a specific diagnostic message.
29504 The developer should then determine whether the representation
29505 should be 64 bits or not and make either of two changes:
29506 change the size to 64 bits and leave the type as @code{System.Address}, or
29507 leave the size as 32 bits and change the type to @code{System.Short_Address}.
29508 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
29509 required in any code setting or accessing the field; the compiler will
29510 automatically perform any needed conversions between address
29514 @subsubsection Access types
29517 By default, objects designated by access values are always
29518 allocated in the 32-bit
29519 address space. Thus legacy code will never contain
29520 any objects that are not addressable with 32-bit addresses, and
29521 the compiler will never raise exceptions as result of mixing
29522 32-bit and 64-bit addresses.
29524 However, the access values themselves are represented in 64 bits, for optimum
29525 performance and future compatibility with 64-bit code. As was
29526 the case with @code{System.Address}, the compiler will give an error message
29527 if an object or record component has a representation clause that
29528 requires the access value to fit in 32 bits. In such a situation,
29529 an explicit size clause for the access type, specifying 32 bits,
29530 will have the desired effect.
29532 General access types (declared with @code{access all}) can never be
29533 32 bits, as values of such types must be able to refer to any object
29534 of the designated type,
29535 including objects residing outside the 32-bit address range.
29536 Existing Ada 83 code will not contain such type definitions,
29537 however, since general access types were introduced in Ada 95.
29539 @node Unchecked conversions
29540 @subsubsection Unchecked conversions
29543 In the case of an @code{Unchecked_Conversion} where the source type is a
29544 64-bit access type or the type @code{System.Address}, and the target
29545 type is a 32-bit type, the compiler will generate a warning.
29546 Even though the generated code will still perform the required
29547 conversions, it is highly recommended in these cases to use
29548 respectively a 32-bit access type or @code{System.Short_Address}
29549 as the source type.
29551 @node Predefined constants
29552 @subsubsection Predefined constants
29555 The following table shows the correspondence between pre-2006 versions of
29556 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
29559 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
29560 @item @b{Constant} @tab @b{Old} @tab @b{New}
29561 @item @code{System.Word_Size} @tab 32 @tab 64
29562 @item @code{System.Memory_Size} @tab 2**32 @tab 2**64
29563 @item @code{System.Short_Memory_Size} @tab 2**32 @tab 2**32
29564 @item @code{System.Address_Size} @tab 32 @tab 64
29568 If you need to refer to the specific
29569 memory size of a 32-bit implementation, instead of the
29570 actual memory size, use @code{System.Short_Memory_Size}
29571 rather than @code{System.Memory_Size}.
29572 Similarly, references to @code{System.Address_Size} may need
29573 to be replaced by @code{System.Short_Address'Size}.
29574 The program @command{gnatfind} may be useful for locating
29575 references to the above constants, so that you can verify that they
29578 @node Interfacing with C
29579 @subsubsection Interfacing with C
29582 In order to minimize the impact of the transition to 64-bit addresses on
29583 legacy programs, some fundamental types in the @code{Interfaces.C}
29584 package hierarchy continue to be represented in 32 bits.
29585 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
29586 This eases integration with the default HP C layout choices, for example
29587 as found in the system routines in @code{DECC$SHR.EXE}.
29588 Because of this implementation choice, the type fully compatible with
29589 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
29590 Depending on the context the compiler will issue a
29591 warning or an error when type @code{Address} is used, alerting the user to a
29592 potential problem. Otherwise 32-bit programs that use
29593 @code{Interfaces.C} should normally not require code modifications
29595 The other issue arising with C interfacing concerns pragma @code{Convention}.
29596 For VMS 64-bit systems, there is an issue of the appropriate default size
29597 of C convention pointers in the absence of an explicit size clause. The HP
29598 C compiler can choose either 32 or 64 bits depending on compiler options.
29599 GNAT chooses 32-bits rather than 64-bits in the default case where no size
29600 clause is given. This proves a better choice for porting 32-bit legacy
29601 applications. In order to have a 64-bit representation, it is necessary to
29602 specify a size representation clause. For example:
29604 @smallexample @c ada
29605 type int_star is access Interfaces.C.int;
29606 pragma Convention(C, int_star);
29607 for int_star'Size use 64; -- Necessary to get 64 and not 32 bits
29610 @node Experience with source compatibility
29611 @subsubsection Experience with source compatibility
29614 The Security Server and STARLET on I64 provide an interesting ``test case''
29615 for source compatibility issues, since it is in such system code
29616 where assumptions about @code{Address} size might be expected to occur.
29617 Indeed, there were a small number of occasions in the Security Server
29618 file @file{jibdef.ads}
29619 where a representation clause for a record type specified
29620 32 bits for a component of type @code{Address}.
29621 All of these errors were detected by the compiler.
29622 The repair was obvious and immediate; to simply replace @code{Address} by
29623 @code{Short_Address}.
29625 In the case of STARLET, there were several record types that should
29626 have had representation clauses but did not. In these record types
29627 there was an implicit assumption that an @code{Address} value occupied
29629 These compiled without error, but their usage resulted in run-time error
29630 returns from STARLET system calls.
29631 Future GNAT technology enhancements may include a tool that detects and flags
29632 these sorts of potential source code porting problems.
29634 @c ****************************************
29635 @node Taking advantage of 64 bit addressing
29636 @subsection Taking advantage of 64-bit addressing
29639 * Making code 64 bit clean::
29640 * Allocating memory from the 64 bit storage pool::
29641 * Restrictions on use of 64 bit objects::
29642 * Using 64 bit storage pools by default::
29643 * General access types::
29644 * STARLET and other predefined libraries::
29647 @node Making code 64 bit clean
29648 @subsubsection Making code 64-bit clean
29651 In order to prevent problems that may occur when (parts of) a
29652 system start using memory outside the 32-bit address range,
29653 we recommend some additional guidelines:
29657 For imported subprograms that take parameters of the
29658 type @code{System.Address}, ensure that these subprograms can
29659 indeed handle 64-bit addresses. If not, or when in doubt,
29660 change the subprogram declaration to specify
29661 @code{System.Short_Address} instead.
29664 Resolve all warnings related to size mismatches in
29665 unchecked conversions. Failing to do so causes
29666 erroneous execution if the source object is outside
29667 the 32-bit address space.
29670 (optional) Explicitly use the 32-bit storage pool
29671 for access types used in a 32-bit context, or use
29672 generic access types where possible
29673 (@pxref{Restrictions on use of 64 bit objects}).
29677 If these rules are followed, the compiler will automatically insert
29678 any necessary checks to ensure that no addresses or access values
29679 passed to 32-bit code ever refer to objects outside the 32-bit
29681 Any attempt to do this will raise @code{Constraint_Error}.
29683 @node Allocating memory from the 64 bit storage pool
29684 @subsubsection Allocating memory from the 64-bit storage pool
29687 For any access type @code{T} that potentially requires memory allocations
29688 beyond the 32-bit address space,
29689 use the following representation clause:
29691 @smallexample @c ada
29692 for T'Storage_Pool use System.Pool_64;
29695 @node Restrictions on use of 64 bit objects
29696 @subsubsection Restrictions on use of 64-bit objects
29699 Taking the address of an object allocated from a 64-bit storage pool,
29700 and then passing this address to a subprogram expecting
29701 @code{System.Short_Address},
29702 or assigning it to a variable of type @code{Short_Address}, will cause
29703 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
29704 (@pxref{Making code 64 bit clean}), or checks are suppressed,
29705 no exception is raised and execution
29706 will become erroneous.
29708 @node Using 64 bit storage pools by default
29709 @subsubsection Using 64-bit storage pools by default
29712 In some cases it may be desirable to have the compiler allocate
29713 from 64-bit storage pools by default. This may be the case for
29714 libraries that are 64-bit clean, but may be used in both 32-bit
29715 and 64-bit contexts. For these cases the following configuration
29716 pragma may be specified:
29718 @smallexample @c ada
29719 pragma Pool_64_Default;
29723 Any code compiled in the context of this pragma will by default
29724 use the @code{System.Pool_64} storage pool. This default may be overridden
29725 for a specific access type @code{T} by the representation clause:
29727 @smallexample @c ada
29728 for T'Storage_Pool use System.Pool_32;
29732 Any object whose address may be passed to a subprogram with a
29733 @code{Short_Address} argument, or assigned to a variable of type
29734 @code{Short_Address}, needs to be allocated from this pool.
29736 @node General access types
29737 @subsubsection General access types
29740 Objects designated by access values from a
29741 general access type (declared with @code{access all}) are never allocated
29742 from a 64-bit storage pool. Code that uses general access types will
29743 accept objects allocated in either 32-bit or 64-bit address spaces,
29744 but never allocate objects outside the 32-bit address space.
29745 Using general access types ensures maximum compatibility with both
29746 32-bit and 64-bit code.
29748 @node STARLET and other predefined libraries
29749 @subsubsection STARLET and other predefined libraries
29752 All code that comes as part of GNAT is 64-bit clean, but the
29753 restrictions given in @ref{Restrictions on use of 64 bit objects},
29754 still apply. Look at the package
29755 specifications to see in which contexts objects allocated
29756 in 64-bit address space are acceptable.
29758 @node Technical details
29759 @subsection Technical details
29762 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
29763 Ada standard with respect to the type of @code{System.Address}. Previous
29764 versions of GNAT Pro have defined this type as private and implemented it as a
29767 In order to allow defining @code{System.Short_Address} as a proper subtype,
29768 and to match the implicit sign extension in parameter passing,
29769 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
29770 visible (i.e., non-private) integer type.
29771 Standard operations on the type, such as the binary operators ``+'', ``-'',
29772 etc., that take @code{Address} operands and return an @code{Address} result,
29773 have been hidden by declaring these
29774 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
29775 ambiguities that would otherwise result from overloading.
29776 (Note that, although @code{Address} is a visible integer type,
29777 good programming practice dictates against exploiting the type's
29778 integer properties such as literals, since this will compromise
29781 Defining @code{Address} as a visible integer type helps achieve
29782 maximum compatibility for existing Ada code,
29783 without sacrificing the capabilities of the 64-bit architecture.
29786 @c ************************************************
29788 @node Microsoft Windows Topics
29789 @appendix Microsoft Windows Topics
29795 This chapter describes topics that are specific to the Microsoft Windows
29796 platforms (NT, 2000, and XP Professional).
29799 * Using GNAT on Windows::
29800 * Using a network installation of GNAT::
29801 * CONSOLE and WINDOWS subsystems::
29802 * Temporary Files::
29803 * Mixed-Language Programming on Windows::
29804 * Windows Calling Conventions::
29805 * Introduction to Dynamic Link Libraries (DLLs)::
29806 * Using DLLs with GNAT::
29807 * Building DLLs with GNAT::
29808 * Building DLLs with GNAT Project files::
29809 * Building DLLs with gnatdll::
29810 * GNAT and Windows Resources::
29811 * Debugging a DLL::
29812 * Setting Stack Size from gnatlink::
29813 * Setting Heap Size from gnatlink::
29816 @node Using GNAT on Windows
29817 @section Using GNAT on Windows
29820 One of the strengths of the GNAT technology is that its tool set
29821 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
29822 @code{gdb} debugger, etc.) is used in the same way regardless of the
29825 On Windows this tool set is complemented by a number of Microsoft-specific
29826 tools that have been provided to facilitate interoperability with Windows
29827 when this is required. With these tools:
29832 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
29836 You can use any Dynamically Linked Library (DLL) in your Ada code (both
29837 relocatable and non-relocatable DLLs are supported).
29840 You can build Ada DLLs for use in other applications. These applications
29841 can be written in a language other than Ada (e.g., C, C++, etc). Again both
29842 relocatable and non-relocatable Ada DLLs are supported.
29845 You can include Windows resources in your Ada application.
29848 You can use or create COM/DCOM objects.
29852 Immediately below are listed all known general GNAT-for-Windows restrictions.
29853 Other restrictions about specific features like Windows Resources and DLLs
29854 are listed in separate sections below.
29859 It is not possible to use @code{GetLastError} and @code{SetLastError}
29860 when tasking, protected records, or exceptions are used. In these
29861 cases, in order to implement Ada semantics, the GNAT run-time system
29862 calls certain Win32 routines that set the last error variable to 0 upon
29863 success. It should be possible to use @code{GetLastError} and
29864 @code{SetLastError} when tasking, protected record, and exception
29865 features are not used, but it is not guaranteed to work.
29868 It is not possible to link against Microsoft libraries except for
29869 import libraries. The library must be built to be compatible with
29870 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
29871 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
29872 not be compatible with the GNAT runtime. Even if the library is
29873 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
29876 When the compilation environment is located on FAT32 drives, users may
29877 experience recompilations of the source files that have not changed if
29878 Daylight Saving Time (DST) state has changed since the last time files
29879 were compiled. NTFS drives do not have this problem.
29882 No components of the GNAT toolset use any entries in the Windows
29883 registry. The only entries that can be created are file associations and
29884 PATH settings, provided the user has chosen to create them at installation
29885 time, as well as some minimal book-keeping information needed to correctly
29886 uninstall or integrate different GNAT products.
29889 @node Using a network installation of GNAT
29890 @section Using a network installation of GNAT
29893 Make sure the system on which GNAT is installed is accessible from the
29894 current machine, i.e. the install location is shared over the network.
29895 Shared resources are accessed on Windows by means of UNC paths, which
29896 have the format @code{\\server\sharename\path}
29898 In order to use such a network installation, simply add the UNC path of the
29899 @file{bin} directory of your GNAT installation in front of your PATH. For
29900 example, if GNAT is installed in @file{\GNAT} directory of a share location
29901 called @file{c-drive} on a machine @file{LOKI}, the following command will
29904 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
29906 Be aware that every compilation using the network installation results in the
29907 transfer of large amounts of data across the network and will likely cause
29908 serious performance penalty.
29910 @node CONSOLE and WINDOWS subsystems
29911 @section CONSOLE and WINDOWS subsystems
29912 @cindex CONSOLE Subsystem
29913 @cindex WINDOWS Subsystem
29917 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
29918 (which is the default subsystem) will always create a console when
29919 launching the application. This is not something desirable when the
29920 application has a Windows GUI. To get rid of this console the
29921 application must be using the @code{WINDOWS} subsystem. To do so
29922 the @option{-mwindows} linker option must be specified.
29925 $ gnatmake winprog -largs -mwindows
29928 @node Temporary Files
29929 @section Temporary Files
29930 @cindex Temporary files
29933 It is possible to control where temporary files gets created by setting
29934 the TMP environment variable. The file will be created:
29937 @item Under the directory pointed to by the TMP environment variable if
29938 this directory exists.
29940 @item Under c:\temp, if the TMP environment variable is not set (or not
29941 pointing to a directory) and if this directory exists.
29943 @item Under the current working directory otherwise.
29947 This allows you to determine exactly where the temporary
29948 file will be created. This is particularly useful in networked
29949 environments where you may not have write access to some
29952 @node Mixed-Language Programming on Windows
29953 @section Mixed-Language Programming on Windows
29956 Developing pure Ada applications on Windows is no different than on
29957 other GNAT-supported platforms. However, when developing or porting an
29958 application that contains a mix of Ada and C/C++, the choice of your
29959 Windows C/C++ development environment conditions your overall
29960 interoperability strategy.
29962 If you use @command{gcc} to compile the non-Ada part of your application,
29963 there are no Windows-specific restrictions that affect the overall
29964 interoperability with your Ada code. If you plan to use
29965 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
29966 the following limitations:
29970 You cannot link your Ada code with an object or library generated with
29971 Microsoft tools if these use the @code{.tls} section (Thread Local
29972 Storage section) since the GNAT linker does not yet support this section.
29975 You cannot link your Ada code with an object or library generated with
29976 Microsoft tools if these use I/O routines other than those provided in
29977 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
29978 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
29979 libraries can cause a conflict with @code{msvcrt.dll} services. For
29980 instance Visual C++ I/O stream routines conflict with those in
29985 If you do want to use the Microsoft tools for your non-Ada code and hit one
29986 of the above limitations, you have two choices:
29990 Encapsulate your non Ada code in a DLL to be linked with your Ada
29991 application. In this case, use the Microsoft or whatever environment to
29992 build the DLL and use GNAT to build your executable
29993 (@pxref{Using DLLs with GNAT}).
29996 Or you can encapsulate your Ada code in a DLL to be linked with the
29997 other part of your application. In this case, use GNAT to build the DLL
29998 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
29999 environment to build your executable.
30002 @node Windows Calling Conventions
30003 @section Windows Calling Conventions
30008 * C Calling Convention::
30009 * Stdcall Calling Convention::
30010 * Win32 Calling Convention::
30011 * DLL Calling Convention::
30015 When a subprogram @code{F} (caller) calls a subprogram @code{G}
30016 (callee), there are several ways to push @code{G}'s parameters on the
30017 stack and there are several possible scenarios to clean up the stack
30018 upon @code{G}'s return. A calling convention is an agreed upon software
30019 protocol whereby the responsibilities between the caller (@code{F}) and
30020 the callee (@code{G}) are clearly defined. Several calling conventions
30021 are available for Windows:
30025 @code{C} (Microsoft defined)
30028 @code{Stdcall} (Microsoft defined)
30031 @code{Win32} (GNAT specific)
30034 @code{DLL} (GNAT specific)
30037 @node C Calling Convention
30038 @subsection @code{C} Calling Convention
30041 This is the default calling convention used when interfacing to C/C++
30042 routines compiled with either @command{gcc} or Microsoft Visual C++.
30044 In the @code{C} calling convention subprogram parameters are pushed on the
30045 stack by the caller from right to left. The caller itself is in charge of
30046 cleaning up the stack after the call. In addition, the name of a routine
30047 with @code{C} calling convention is mangled by adding a leading underscore.
30049 The name to use on the Ada side when importing (or exporting) a routine
30050 with @code{C} calling convention is the name of the routine. For
30051 instance the C function:
30054 int get_val (long);
30058 should be imported from Ada as follows:
30060 @smallexample @c ada
30062 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30063 pragma Import (C, Get_Val, External_Name => "get_val");
30068 Note that in this particular case the @code{External_Name} parameter could
30069 have been omitted since, when missing, this parameter is taken to be the
30070 name of the Ada entity in lower case. When the @code{Link_Name} parameter
30071 is missing, as in the above example, this parameter is set to be the
30072 @code{External_Name} with a leading underscore.
30074 When importing a variable defined in C, you should always use the @code{C}
30075 calling convention unless the object containing the variable is part of a
30076 DLL (in which case you should use the @code{Stdcall} calling
30077 convention, @pxref{Stdcall Calling Convention}).
30079 @node Stdcall Calling Convention
30080 @subsection @code{Stdcall} Calling Convention
30083 This convention, which was the calling convention used for Pascal
30084 programs, is used by Microsoft for all the routines in the Win32 API for
30085 efficiency reasons. It must be used to import any routine for which this
30086 convention was specified.
30088 In the @code{Stdcall} calling convention subprogram parameters are pushed
30089 on the stack by the caller from right to left. The callee (and not the
30090 caller) is in charge of cleaning the stack on routine exit. In addition,
30091 the name of a routine with @code{Stdcall} calling convention is mangled by
30092 adding a leading underscore (as for the @code{C} calling convention) and a
30093 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
30094 bytes) of the parameters passed to the routine.
30096 The name to use on the Ada side when importing a C routine with a
30097 @code{Stdcall} calling convention is the name of the C routine. The leading
30098 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
30099 the compiler. For instance the Win32 function:
30102 @b{APIENTRY} int get_val (long);
30106 should be imported from Ada as follows:
30108 @smallexample @c ada
30110 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30111 pragma Import (Stdcall, Get_Val);
30112 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
30117 As for the @code{C} calling convention, when the @code{External_Name}
30118 parameter is missing, it is taken to be the name of the Ada entity in lower
30119 case. If instead of writing the above import pragma you write:
30121 @smallexample @c ada
30123 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30124 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
30129 then the imported routine is @code{_retrieve_val@@4}. However, if instead
30130 of specifying the @code{External_Name} parameter you specify the
30131 @code{Link_Name} as in the following example:
30133 @smallexample @c ada
30135 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30136 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
30141 then the imported routine is @code{retrieve_val}, that is, there is no
30142 decoration at all. No leading underscore and no Stdcall suffix
30143 @code{@@}@code{@i{nn}}.
30146 This is especially important as in some special cases a DLL's entry
30147 point name lacks a trailing @code{@@}@code{@i{nn}} while the exported
30148 name generated for a call has it.
30151 It is also possible to import variables defined in a DLL by using an
30152 import pragma for a variable. As an example, if a DLL contains a
30153 variable defined as:
30160 then, to access this variable from Ada you should write:
30162 @smallexample @c ada
30164 My_Var : Interfaces.C.int;
30165 pragma Import (Stdcall, My_Var);
30170 Note that to ease building cross-platform bindings this convention
30171 will be handled as a @code{C} calling convention on non Windows platforms.
30173 @node Win32 Calling Convention
30174 @subsection @code{Win32} Calling Convention
30177 This convention, which is GNAT-specific is fully equivalent to the
30178 @code{Stdcall} calling convention described above.
30180 @node DLL Calling Convention
30181 @subsection @code{DLL} Calling Convention
30184 This convention, which is GNAT-specific is fully equivalent to the
30185 @code{Stdcall} calling convention described above.
30187 @node Introduction to Dynamic Link Libraries (DLLs)
30188 @section Introduction to Dynamic Link Libraries (DLLs)
30192 A Dynamically Linked Library (DLL) is a library that can be shared by
30193 several applications running under Windows. A DLL can contain any number of
30194 routines and variables.
30196 One advantage of DLLs is that you can change and enhance them without
30197 forcing all the applications that depend on them to be relinked or
30198 recompiled. However, you should be aware than all calls to DLL routines are
30199 slower since, as you will understand below, such calls are indirect.
30201 To illustrate the remainder of this section, suppose that an application
30202 wants to use the services of a DLL @file{API.dll}. To use the services
30203 provided by @file{API.dll} you must statically link against the DLL or
30204 an import library which contains a jump table with an entry for each
30205 routine and variable exported by the DLL. In the Microsoft world this
30206 import library is called @file{API.lib}. When using GNAT this import
30207 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
30208 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
30210 After you have linked your application with the DLL or the import library
30211 and you run your application, here is what happens:
30215 Your application is loaded into memory.
30218 The DLL @file{API.dll} is mapped into the address space of your
30219 application. This means that:
30223 The DLL will use the stack of the calling thread.
30226 The DLL will use the virtual address space of the calling process.
30229 The DLL will allocate memory from the virtual address space of the calling
30233 Handles (pointers) can be safely exchanged between routines in the DLL
30234 routines and routines in the application using the DLL.
30238 The entries in the jump table (from the import library @file{libAPI.dll.a}
30239 or @file{API.lib} or automatically created when linking against a DLL)
30240 which is part of your application are initialized with the addresses
30241 of the routines and variables in @file{API.dll}.
30244 If present in @file{API.dll}, routines @code{DllMain} or
30245 @code{DllMainCRTStartup} are invoked. These routines typically contain
30246 the initialization code needed for the well-being of the routines and
30247 variables exported by the DLL.
30251 There is an additional point which is worth mentioning. In the Windows
30252 world there are two kind of DLLs: relocatable and non-relocatable
30253 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
30254 in the target application address space. If the addresses of two
30255 non-relocatable DLLs overlap and these happen to be used by the same
30256 application, a conflict will occur and the application will run
30257 incorrectly. Hence, when possible, it is always preferable to use and
30258 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
30259 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
30260 User's Guide) removes the debugging symbols from the DLL but the DLL can
30261 still be relocated.
30263 As a side note, an interesting difference between Microsoft DLLs and
30264 Unix shared libraries, is the fact that on most Unix systems all public
30265 routines are exported by default in a Unix shared library, while under
30266 Windows it is possible (but not required) to list exported routines in
30267 a definition file (@pxref{The Definition File}).
30269 @node Using DLLs with GNAT
30270 @section Using DLLs with GNAT
30273 * Creating an Ada Spec for the DLL Services::
30274 * Creating an Import Library::
30278 To use the services of a DLL, say @file{API.dll}, in your Ada application
30283 The Ada spec for the routines and/or variables you want to access in
30284 @file{API.dll}. If not available this Ada spec must be built from the C/C++
30285 header files provided with the DLL.
30288 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
30289 mentioned an import library is a statically linked library containing the
30290 import table which will be filled at load time to point to the actual
30291 @file{API.dll} routines. Sometimes you don't have an import library for the
30292 DLL you want to use. The following sections will explain how to build
30293 one. Note that this is optional.
30296 The actual DLL, @file{API.dll}.
30300 Once you have all the above, to compile an Ada application that uses the
30301 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
30302 you simply issue the command
30305 $ gnatmake my_ada_app -largs -lAPI
30309 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
30310 tells the GNAT linker to look first for a library named @file{API.lib}
30311 (Microsoft-style name) and if not found for a libraries named
30312 @file{libAPI.dll.a}, @file{API.dll.a} or @file{libAPI.a}.
30313 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
30314 contains the following pragma
30316 @smallexample @c ada
30317 pragma Linker_Options ("-lAPI");
30321 you do not have to add @option{-largs -lAPI} at the end of the
30322 @command{gnatmake} command.
30324 If any one of the items above is missing you will have to create it
30325 yourself. The following sections explain how to do so using as an
30326 example a fictitious DLL called @file{API.dll}.
30328 @node Creating an Ada Spec for the DLL Services
30329 @subsection Creating an Ada Spec for the DLL Services
30332 A DLL typically comes with a C/C++ header file which provides the
30333 definitions of the routines and variables exported by the DLL. The Ada
30334 equivalent of this header file is a package spec that contains definitions
30335 for the imported entities. If the DLL you intend to use does not come with
30336 an Ada spec you have to generate one such spec yourself. For example if
30337 the header file of @file{API.dll} is a file @file{api.h} containing the
30338 following two definitions:
30350 then the equivalent Ada spec could be:
30352 @smallexample @c ada
30355 with Interfaces.C.Strings;
30360 function Get (Str : C.Strings.Chars_Ptr) return C.int;
30363 pragma Import (C, Get);
30364 pragma Import (DLL, Some_Var);
30371 Note that a variable is
30372 @strong{always imported with a Stdcall convention}. A function
30373 can have @code{C} or @code{Stdcall} convention.
30374 (@pxref{Windows Calling Conventions}).
30376 @node Creating an Import Library
30377 @subsection Creating an Import Library
30378 @cindex Import library
30381 * The Definition File::
30382 * GNAT-Style Import Library::
30383 * Microsoft-Style Import Library::
30387 If a Microsoft-style import library @file{API.lib} or a GNAT-style
30388 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
30389 with @file{API.dll} you can skip this section. You can also skip this
30390 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
30391 as in this case it is possible to link directly against the
30392 DLL. Otherwise read on.
30394 @node The Definition File
30395 @subsubsection The Definition File
30396 @cindex Definition file
30400 As previously mentioned, and unlike Unix systems, the list of symbols
30401 that are exported from a DLL must be provided explicitly in Windows.
30402 The main goal of a definition file is precisely that: list the symbols
30403 exported by a DLL. A definition file (usually a file with a @code{.def}
30404 suffix) has the following structure:
30410 [DESCRIPTION @i{string}]
30420 @item LIBRARY @i{name}
30421 This section, which is optional, gives the name of the DLL.
30423 @item DESCRIPTION @i{string}
30424 This section, which is optional, gives a description string that will be
30425 embedded in the import library.
30428 This section gives the list of exported symbols (procedures, functions or
30429 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
30430 section of @file{API.def} looks like:
30444 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
30445 (@pxref{Windows Calling Conventions}) for a Stdcall
30446 calling convention function in the exported symbols list.
30449 There can actually be other sections in a definition file, but these
30450 sections are not relevant to the discussion at hand.
30452 @node GNAT-Style Import Library
30453 @subsubsection GNAT-Style Import Library
30456 To create a static import library from @file{API.dll} with the GNAT tools
30457 you should proceed as follows:
30461 Create the definition file @file{API.def} (@pxref{The Definition File}).
30462 For that use the @code{dll2def} tool as follows:
30465 $ dll2def API.dll > API.def
30469 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
30470 to standard output the list of entry points in the DLL. Note that if
30471 some routines in the DLL have the @code{Stdcall} convention
30472 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
30473 suffix then you'll have to edit @file{api.def} to add it, and specify
30474 @code{-k} to @code{gnatdll} when creating the import library.
30477 Here are some hints to find the right @code{@@}@i{nn} suffix.
30481 If you have the Microsoft import library (.lib), it is possible to get
30482 the right symbols by using Microsoft @code{dumpbin} tool (see the
30483 corresponding Microsoft documentation for further details).
30486 $ dumpbin /exports api.lib
30490 If you have a message about a missing symbol at link time the compiler
30491 tells you what symbol is expected. You just have to go back to the
30492 definition file and add the right suffix.
30496 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
30497 (@pxref{Using gnatdll}) as follows:
30500 $ gnatdll -e API.def -d API.dll
30504 @code{gnatdll} takes as input a definition file @file{API.def} and the
30505 name of the DLL containing the services listed in the definition file
30506 @file{API.dll}. The name of the static import library generated is
30507 computed from the name of the definition file as follows: if the
30508 definition file name is @i{xyz}@code{.def}, the import library name will
30509 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
30510 @option{-e} could have been removed because the name of the definition
30511 file (before the ``@code{.def}'' suffix) is the same as the name of the
30512 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
30515 @node Microsoft-Style Import Library
30516 @subsubsection Microsoft-Style Import Library
30519 With GNAT you can either use a GNAT-style or Microsoft-style import
30520 library. A Microsoft import library is needed only if you plan to make an
30521 Ada DLL available to applications developed with Microsoft
30522 tools (@pxref{Mixed-Language Programming on Windows}).
30524 To create a Microsoft-style import library for @file{API.dll} you
30525 should proceed as follows:
30529 Create the definition file @file{API.def} from the DLL. For this use either
30530 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
30531 tool (see the corresponding Microsoft documentation for further details).
30534 Build the actual import library using Microsoft's @code{lib} utility:
30537 $ lib -machine:IX86 -def:API.def -out:API.lib
30541 If you use the above command the definition file @file{API.def} must
30542 contain a line giving the name of the DLL:
30549 See the Microsoft documentation for further details about the usage of
30553 @node Building DLLs with GNAT
30554 @section Building DLLs with GNAT
30555 @cindex DLLs, building
30558 This section explain how to build DLLs using the GNAT built-in DLL
30559 support. With the following procedure it is straight forward to build
30560 and use DLLs with GNAT.
30564 @item building object files
30566 The first step is to build all objects files that are to be included
30567 into the DLL. This is done by using the standard @command{gnatmake} tool.
30569 @item building the DLL
30571 To build the DLL you must use @command{gcc}'s @code{-shared}
30572 option. It is quite simple to use this method:
30575 $ gcc -shared -o api.dll obj1.o obj2.o ...
30578 It is important to note that in this case all symbols found in the
30579 object files are automatically exported. It is possible to restrict
30580 the set of symbols to export by passing to @command{gcc} a definition
30581 file, @pxref{The Definition File}. For example:
30584 $ gcc -shared -o api.dll api.def obj1.o obj2.o ...
30587 If you use a definition file you must export the elaboration procedures
30588 for every package that required one. Elaboration procedures are named
30589 using the package name followed by "_E".
30591 @item preparing DLL to be used
30593 For the DLL to be used by client programs the bodies must be hidden
30594 from it and the .ali set with read-only attribute. This is very important
30595 otherwise GNAT will recompile all packages and will not actually use
30596 the code in the DLL. For example:
30600 $ copy *.ads *.ali api.dll apilib
30601 $ attrib +R apilib\*.ali
30606 At this point it is possible to use the DLL by directly linking
30607 against it. Note that you must use the GNAT shared runtime when using
30608 GNAT shared libraries. This is achieved by using @code{-shared} binder's
30612 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
30615 @node Building DLLs with GNAT Project files
30616 @section Building DLLs with GNAT Project files
30617 @cindex DLLs, building
30620 There is nothing specific to Windows in the build process.
30621 @pxref{Library Projects}.
30624 Due to a system limitation, it is not possible under Windows to create threads
30625 when inside the @code{DllMain} routine which is used for auto-initialization
30626 of shared libraries, so it is not possible to have library level tasks in SALs.
30628 @node Building DLLs with gnatdll
30629 @section Building DLLs with gnatdll
30630 @cindex DLLs, building
30633 * Limitations When Using Ada DLLs from Ada::
30634 * Exporting Ada Entities::
30635 * Ada DLLs and Elaboration::
30636 * Ada DLLs and Finalization::
30637 * Creating a Spec for Ada DLLs::
30638 * Creating the Definition File::
30643 Note that it is preferred to use the built-in GNAT DLL support
30644 (@pxref{Building DLLs with GNAT}) or GNAT Project files
30645 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
30647 This section explains how to build DLLs containing Ada code using
30648 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
30649 remainder of this section.
30651 The steps required to build an Ada DLL that is to be used by Ada as well as
30652 non-Ada applications are as follows:
30656 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
30657 @code{Stdcall} calling convention to avoid any Ada name mangling for the
30658 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
30659 skip this step if you plan to use the Ada DLL only from Ada applications.
30662 Your Ada code must export an initialization routine which calls the routine
30663 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
30664 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
30665 routine exported by the Ada DLL must be invoked by the clients of the DLL
30666 to initialize the DLL.
30669 When useful, the DLL should also export a finalization routine which calls
30670 routine @code{adafinal} generated by @command{gnatbind} to perform the
30671 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
30672 The finalization routine exported by the Ada DLL must be invoked by the
30673 clients of the DLL when the DLL services are no further needed.
30676 You must provide a spec for the services exported by the Ada DLL in each
30677 of the programming languages to which you plan to make the DLL available.
30680 You must provide a definition file listing the exported entities
30681 (@pxref{The Definition File}).
30684 Finally you must use @code{gnatdll} to produce the DLL and the import
30685 library (@pxref{Using gnatdll}).
30689 Note that a relocatable DLL stripped using the @code{strip}
30690 binutils tool will not be relocatable anymore. To build a DLL without
30691 debug information pass @code{-largs -s} to @code{gnatdll}. This
30692 restriction does not apply to a DLL built using a Library Project.
30693 @pxref{Library Projects}.
30695 @node Limitations When Using Ada DLLs from Ada
30696 @subsection Limitations When Using Ada DLLs from Ada
30699 When using Ada DLLs from Ada applications there is a limitation users
30700 should be aware of. Because on Windows the GNAT run time is not in a DLL of
30701 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
30702 each Ada DLL includes the services of the GNAT run time that are necessary
30703 to the Ada code inside the DLL. As a result, when an Ada program uses an
30704 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
30705 one in the main program.
30707 It is therefore not possible to exchange GNAT run-time objects between the
30708 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
30709 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
30712 It is completely safe to exchange plain elementary, array or record types,
30713 Windows object handles, etc.
30715 @node Exporting Ada Entities
30716 @subsection Exporting Ada Entities
30717 @cindex Export table
30720 Building a DLL is a way to encapsulate a set of services usable from any
30721 application. As a result, the Ada entities exported by a DLL should be
30722 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
30723 any Ada name mangling. As an example here is an Ada package
30724 @code{API}, spec and body, exporting two procedures, a function, and a
30727 @smallexample @c ada
30730 with Interfaces.C; use Interfaces;
30732 Count : C.int := 0;
30733 function Factorial (Val : C.int) return C.int;
30735 procedure Initialize_API;
30736 procedure Finalize_API;
30737 -- Initialization & Finalization routines. More in the next section.
30739 pragma Export (C, Initialize_API);
30740 pragma Export (C, Finalize_API);
30741 pragma Export (C, Count);
30742 pragma Export (C, Factorial);
30748 @smallexample @c ada
30751 package body API is
30752 function Factorial (Val : C.int) return C.int is
30755 Count := Count + 1;
30756 for K in 1 .. Val loop
30762 procedure Initialize_API is
30764 pragma Import (C, Adainit);
30767 end Initialize_API;
30769 procedure Finalize_API is
30770 procedure Adafinal;
30771 pragma Import (C, Adafinal);
30781 If the Ada DLL you are building will only be used by Ada applications
30782 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
30783 convention. As an example, the previous package could be written as
30786 @smallexample @c ada
30790 Count : Integer := 0;
30791 function Factorial (Val : Integer) return Integer;
30793 procedure Initialize_API;
30794 procedure Finalize_API;
30795 -- Initialization and Finalization routines.
30801 @smallexample @c ada
30804 package body API is
30805 function Factorial (Val : Integer) return Integer is
30806 Fact : Integer := 1;
30808 Count := Count + 1;
30809 for K in 1 .. Val loop
30816 -- The remainder of this package body is unchanged.
30823 Note that if you do not export the Ada entities with a @code{C} or
30824 @code{Stdcall} convention you will have to provide the mangled Ada names
30825 in the definition file of the Ada DLL
30826 (@pxref{Creating the Definition File}).
30828 @node Ada DLLs and Elaboration
30829 @subsection Ada DLLs and Elaboration
30830 @cindex DLLs and elaboration
30833 The DLL that you are building contains your Ada code as well as all the
30834 routines in the Ada library that are needed by it. The first thing a
30835 user of your DLL must do is elaborate the Ada code
30836 (@pxref{Elaboration Order Handling in GNAT}).
30838 To achieve this you must export an initialization routine
30839 (@code{Initialize_API} in the previous example), which must be invoked
30840 before using any of the DLL services. This elaboration routine must call
30841 the Ada elaboration routine @code{adainit} generated by the GNAT binder
30842 (@pxref{Binding with Non-Ada Main Programs}). See the body of
30843 @code{Initialize_Api} for an example. Note that the GNAT binder is
30844 automatically invoked during the DLL build process by the @code{gnatdll}
30845 tool (@pxref{Using gnatdll}).
30847 When a DLL is loaded, Windows systematically invokes a routine called
30848 @code{DllMain}. It would therefore be possible to call @code{adainit}
30849 directly from @code{DllMain} without having to provide an explicit
30850 initialization routine. Unfortunately, it is not possible to call
30851 @code{adainit} from the @code{DllMain} if your program has library level
30852 tasks because access to the @code{DllMain} entry point is serialized by
30853 the system (that is, only a single thread can execute ``through'' it at a
30854 time), which means that the GNAT run time will deadlock waiting for the
30855 newly created task to complete its initialization.
30857 @node Ada DLLs and Finalization
30858 @subsection Ada DLLs and Finalization
30859 @cindex DLLs and finalization
30862 When the services of an Ada DLL are no longer needed, the client code should
30863 invoke the DLL finalization routine, if available. The DLL finalization
30864 routine is in charge of releasing all resources acquired by the DLL. In the
30865 case of the Ada code contained in the DLL, this is achieved by calling
30866 routine @code{adafinal} generated by the GNAT binder
30867 (@pxref{Binding with Non-Ada Main Programs}).
30868 See the body of @code{Finalize_Api} for an
30869 example. As already pointed out the GNAT binder is automatically invoked
30870 during the DLL build process by the @code{gnatdll} tool
30871 (@pxref{Using gnatdll}).
30873 @node Creating a Spec for Ada DLLs
30874 @subsection Creating a Spec for Ada DLLs
30877 To use the services exported by the Ada DLL from another programming
30878 language (e.g. C), you have to translate the specs of the exported Ada
30879 entities in that language. For instance in the case of @code{API.dll},
30880 the corresponding C header file could look like:
30885 extern int *_imp__count;
30886 #define count (*_imp__count)
30887 int factorial (int);
30893 It is important to understand that when building an Ada DLL to be used by
30894 other Ada applications, you need two different specs for the packages
30895 contained in the DLL: one for building the DLL and the other for using
30896 the DLL. This is because the @code{DLL} calling convention is needed to
30897 use a variable defined in a DLL, but when building the DLL, the variable
30898 must have either the @code{Ada} or @code{C} calling convention. As an
30899 example consider a DLL comprising the following package @code{API}:
30901 @smallexample @c ada
30905 Count : Integer := 0;
30907 -- Remainder of the package omitted.
30914 After producing a DLL containing package @code{API}, the spec that
30915 must be used to import @code{API.Count} from Ada code outside of the
30918 @smallexample @c ada
30923 pragma Import (DLL, Count);
30929 @node Creating the Definition File
30930 @subsection Creating the Definition File
30933 The definition file is the last file needed to build the DLL. It lists
30934 the exported symbols. As an example, the definition file for a DLL
30935 containing only package @code{API} (where all the entities are exported
30936 with a @code{C} calling convention) is:
30951 If the @code{C} calling convention is missing from package @code{API},
30952 then the definition file contains the mangled Ada names of the above
30953 entities, which in this case are:
30962 api__initialize_api
30967 @node Using gnatdll
30968 @subsection Using @code{gnatdll}
30972 * gnatdll Example::
30973 * gnatdll behind the Scenes::
30978 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
30979 and non-Ada sources that make up your DLL have been compiled.
30980 @code{gnatdll} is actually in charge of two distinct tasks: build the
30981 static import library for the DLL and the actual DLL. The form of the
30982 @code{gnatdll} command is
30986 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
30991 where @i{list-of-files} is a list of ALI and object files. The object
30992 file list must be the exact list of objects corresponding to the non-Ada
30993 sources whose services are to be included in the DLL. The ALI file list
30994 must be the exact list of ALI files for the corresponding Ada sources
30995 whose services are to be included in the DLL. If @i{list-of-files} is
30996 missing, only the static import library is generated.
30999 You may specify any of the following switches to @code{gnatdll}:
31002 @item -a[@var{address}]
31003 @cindex @option{-a} (@code{gnatdll})
31004 Build a non-relocatable DLL at @var{address}. If @var{address} is not
31005 specified the default address @var{0x11000000} will be used. By default,
31006 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
31007 advise the reader to build relocatable DLL.
31009 @item -b @var{address}
31010 @cindex @option{-b} (@code{gnatdll})
31011 Set the relocatable DLL base address. By default the address is
31014 @item -bargs @var{opts}
31015 @cindex @option{-bargs} (@code{gnatdll})
31016 Binder options. Pass @var{opts} to the binder.
31018 @item -d @var{dllfile}
31019 @cindex @option{-d} (@code{gnatdll})
31020 @var{dllfile} is the name of the DLL. This switch must be present for
31021 @code{gnatdll} to do anything. The name of the generated import library is
31022 obtained algorithmically from @var{dllfile} as shown in the following
31023 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
31024 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
31025 by option @option{-e}) is obtained algorithmically from @var{dllfile}
31026 as shown in the following example:
31027 if @var{dllfile} is @code{xyz.dll}, the definition
31028 file used is @code{xyz.def}.
31030 @item -e @var{deffile}
31031 @cindex @option{-e} (@code{gnatdll})
31032 @var{deffile} is the name of the definition file.
31035 @cindex @option{-g} (@code{gnatdll})
31036 Generate debugging information. This information is stored in the object
31037 file and copied from there to the final DLL file by the linker,
31038 where it can be read by the debugger. You must use the
31039 @option{-g} switch if you plan on using the debugger or the symbolic
31043 @cindex @option{-h} (@code{gnatdll})
31044 Help mode. Displays @code{gnatdll} switch usage information.
31047 @cindex @option{-I} (@code{gnatdll})
31048 Direct @code{gnatdll} to search the @var{dir} directory for source and
31049 object files needed to build the DLL.
31050 (@pxref{Search Paths and the Run-Time Library (RTL)}).
31053 @cindex @option{-k} (@code{gnatdll})
31054 Removes the @code{@@}@i{nn} suffix from the import library's exported
31055 names, but keeps them for the link names. You must specify this
31056 option if you want to use a @code{Stdcall} function in a DLL for which
31057 the @code{@@}@i{nn} suffix has been removed. This is the case for most
31058 of the Windows NT DLL for example. This option has no effect when
31059 @option{-n} option is specified.
31061 @item -l @var{file}
31062 @cindex @option{-l} (@code{gnatdll})
31063 The list of ALI and object files used to build the DLL are listed in
31064 @var{file}, instead of being given in the command line. Each line in
31065 @var{file} contains the name of an ALI or object file.
31068 @cindex @option{-n} (@code{gnatdll})
31069 No Import. Do not create the import library.
31072 @cindex @option{-q} (@code{gnatdll})
31073 Quiet mode. Do not display unnecessary messages.
31076 @cindex @option{-v} (@code{gnatdll})
31077 Verbose mode. Display extra information.
31079 @item -largs @var{opts}
31080 @cindex @option{-largs} (@code{gnatdll})
31081 Linker options. Pass @var{opts} to the linker.
31084 @node gnatdll Example
31085 @subsubsection @code{gnatdll} Example
31088 As an example the command to build a relocatable DLL from @file{api.adb}
31089 once @file{api.adb} has been compiled and @file{api.def} created is
31092 $ gnatdll -d api.dll api.ali
31096 The above command creates two files: @file{libapi.dll.a} (the import
31097 library) and @file{api.dll} (the actual DLL). If you want to create
31098 only the DLL, just type:
31101 $ gnatdll -d api.dll -n api.ali
31105 Alternatively if you want to create just the import library, type:
31108 $ gnatdll -d api.dll
31111 @node gnatdll behind the Scenes
31112 @subsubsection @code{gnatdll} behind the Scenes
31115 This section details the steps involved in creating a DLL. @code{gnatdll}
31116 does these steps for you. Unless you are interested in understanding what
31117 goes on behind the scenes, you should skip this section.
31119 We use the previous example of a DLL containing the Ada package @code{API},
31120 to illustrate the steps necessary to build a DLL. The starting point is a
31121 set of objects that will make up the DLL and the corresponding ALI
31122 files. In the case of this example this means that @file{api.o} and
31123 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
31128 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
31129 the information necessary to generate relocation information for the
31135 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
31140 In addition to the base file, the @command{gnatlink} command generates an
31141 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
31142 asks @command{gnatlink} to generate the routines @code{DllMain} and
31143 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
31144 is loaded into memory.
31147 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
31148 export table (@file{api.exp}). The export table contains the relocation
31149 information in a form which can be used during the final link to ensure
31150 that the Windows loader is able to place the DLL anywhere in memory.
31154 $ dlltool --dllname api.dll --def api.def --base-file api.base \
31155 --output-exp api.exp
31160 @code{gnatdll} builds the base file using the new export table. Note that
31161 @command{gnatbind} must be called once again since the binder generated file
31162 has been deleted during the previous call to @command{gnatlink}.
31167 $ gnatlink api -o api.jnk api.exp -mdll
31168 -Wl,--base-file,api.base
31173 @code{gnatdll} builds the new export table using the new base file and
31174 generates the DLL import library @file{libAPI.dll.a}.
31178 $ dlltool --dllname api.dll --def api.def --base-file api.base \
31179 --output-exp api.exp --output-lib libAPI.a
31184 Finally @code{gnatdll} builds the relocatable DLL using the final export
31190 $ gnatlink api api.exp -o api.dll -mdll
31195 @node Using dlltool
31196 @subsubsection Using @code{dlltool}
31199 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
31200 DLLs and static import libraries. This section summarizes the most
31201 common @code{dlltool} switches. The form of the @code{dlltool} command
31205 $ dlltool [@var{switches}]
31209 @code{dlltool} switches include:
31212 @item --base-file @var{basefile}
31213 @cindex @option{--base-file} (@command{dlltool})
31214 Read the base file @var{basefile} generated by the linker. This switch
31215 is used to create a relocatable DLL.
31217 @item --def @var{deffile}
31218 @cindex @option{--def} (@command{dlltool})
31219 Read the definition file.
31221 @item --dllname @var{name}
31222 @cindex @option{--dllname} (@command{dlltool})
31223 Gives the name of the DLL. This switch is used to embed the name of the
31224 DLL in the static import library generated by @code{dlltool} with switch
31225 @option{--output-lib}.
31228 @cindex @option{-k} (@command{dlltool})
31229 Kill @code{@@}@i{nn} from exported names
31230 (@pxref{Windows Calling Conventions}
31231 for a discussion about @code{Stdcall}-style symbols.
31234 @cindex @option{--help} (@command{dlltool})
31235 Prints the @code{dlltool} switches with a concise description.
31237 @item --output-exp @var{exportfile}
31238 @cindex @option{--output-exp} (@command{dlltool})
31239 Generate an export file @var{exportfile}. The export file contains the
31240 export table (list of symbols in the DLL) and is used to create the DLL.
31242 @item --output-lib @i{libfile}
31243 @cindex @option{--output-lib} (@command{dlltool})
31244 Generate a static import library @var{libfile}.
31247 @cindex @option{-v} (@command{dlltool})
31250 @item --as @i{assembler-name}
31251 @cindex @option{--as} (@command{dlltool})
31252 Use @i{assembler-name} as the assembler. The default is @code{as}.
31255 @node GNAT and Windows Resources
31256 @section GNAT and Windows Resources
31257 @cindex Resources, windows
31260 * Building Resources::
31261 * Compiling Resources::
31262 * Using Resources::
31266 Resources are an easy way to add Windows specific objects to your
31267 application. The objects that can be added as resources include:
31296 This section explains how to build, compile and use resources.
31298 @node Building Resources
31299 @subsection Building Resources
31300 @cindex Resources, building
31303 A resource file is an ASCII file. By convention resource files have an
31304 @file{.rc} extension.
31305 The easiest way to build a resource file is to use Microsoft tools
31306 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
31307 @code{dlgedit.exe} to build dialogs.
31308 It is always possible to build an @file{.rc} file yourself by writing a
31311 It is not our objective to explain how to write a resource file. A
31312 complete description of the resource script language can be found in the
31313 Microsoft documentation.
31315 @node Compiling Resources
31316 @subsection Compiling Resources
31319 @cindex Resources, compiling
31322 This section describes how to build a GNAT-compatible (COFF) object file
31323 containing the resources. This is done using the Resource Compiler
31324 @code{windres} as follows:
31327 $ windres -i myres.rc -o myres.o
31331 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
31332 file. You can specify an alternate preprocessor (usually named
31333 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
31334 parameter. A list of all possible options may be obtained by entering
31335 the command @code{windres} @option{--help}.
31337 It is also possible to use the Microsoft resource compiler @code{rc.exe}
31338 to produce a @file{.res} file (binary resource file). See the
31339 corresponding Microsoft documentation for further details. In this case
31340 you need to use @code{windres} to translate the @file{.res} file to a
31341 GNAT-compatible object file as follows:
31344 $ windres -i myres.res -o myres.o
31347 @node Using Resources
31348 @subsection Using Resources
31349 @cindex Resources, using
31352 To include the resource file in your program just add the
31353 GNAT-compatible object file for the resource(s) to the linker
31354 arguments. With @command{gnatmake} this is done by using the @option{-largs}
31358 $ gnatmake myprog -largs myres.o
31361 @node Debugging a DLL
31362 @section Debugging a DLL
31363 @cindex DLL debugging
31366 * Program and DLL Both Built with GCC/GNAT::
31367 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
31371 Debugging a DLL is similar to debugging a standard program. But
31372 we have to deal with two different executable parts: the DLL and the
31373 program that uses it. We have the following four possibilities:
31377 The program and the DLL are built with @code{GCC/GNAT}.
31379 The program is built with foreign tools and the DLL is built with
31382 The program is built with @code{GCC/GNAT} and the DLL is built with
31388 In this section we address only cases one and two above.
31389 There is no point in trying to debug
31390 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
31391 information in it. To do so you must use a debugger compatible with the
31392 tools suite used to build the DLL.
31394 @node Program and DLL Both Built with GCC/GNAT
31395 @subsection Program and DLL Both Built with GCC/GNAT
31398 This is the simplest case. Both the DLL and the program have @code{GDB}
31399 compatible debugging information. It is then possible to break anywhere in
31400 the process. Let's suppose here that the main procedure is named
31401 @code{ada_main} and that in the DLL there is an entry point named
31405 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
31406 program must have been built with the debugging information (see GNAT -g
31407 switch). Here are the step-by-step instructions for debugging it:
31410 @item Launch @code{GDB} on the main program.
31416 @item Start the program and stop at the beginning of the main procedure
31423 This step is required to be able to set a breakpoint inside the DLL. As long
31424 as the program is not run, the DLL is not loaded. This has the
31425 consequence that the DLL debugging information is also not loaded, so it is not
31426 possible to set a breakpoint in the DLL.
31428 @item Set a breakpoint inside the DLL
31431 (gdb) break ada_dll
31438 At this stage a breakpoint is set inside the DLL. From there on
31439 you can use the standard approach to debug the whole program
31440 (@pxref{Running and Debugging Ada Programs}).
31443 @c This used to work, probably because the DLLs were non-relocatable
31444 @c keep this section around until the problem is sorted out.
31446 To break on the @code{DllMain} routine it is not possible to follow
31447 the procedure above. At the time the program stop on @code{ada_main}
31448 the @code{DllMain} routine as already been called. Either you can use
31449 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
31452 @item Launch @code{GDB} on the main program.
31458 @item Load DLL symbols
31461 (gdb) add-sym api.dll
31464 @item Set a breakpoint inside the DLL
31467 (gdb) break ada_dll.adb:45
31470 Note that at this point it is not possible to break using the routine symbol
31471 directly as the program is not yet running. The solution is to break
31472 on the proper line (break in @file{ada_dll.adb} line 45).
31474 @item Start the program
31483 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
31484 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
31487 * Debugging the DLL Directly::
31488 * Attaching to a Running Process::
31492 In this case things are slightly more complex because it is not possible to
31493 start the main program and then break at the beginning to load the DLL and the
31494 associated DLL debugging information. It is not possible to break at the
31495 beginning of the program because there is no @code{GDB} debugging information,
31496 and therefore there is no direct way of getting initial control. This
31497 section addresses this issue by describing some methods that can be used
31498 to break somewhere in the DLL to debug it.
31501 First suppose that the main procedure is named @code{main} (this is for
31502 example some C code built with Microsoft Visual C) and that there is a
31503 DLL named @code{test.dll} containing an Ada entry point named
31507 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
31508 been built with debugging information (see GNAT -g option).
31510 @node Debugging the DLL Directly
31511 @subsubsection Debugging the DLL Directly
31515 Find out the executable starting address
31518 $ objdump --file-header main.exe
31521 The starting address is reported on the last line. For example:
31524 main.exe: file format pei-i386
31525 architecture: i386, flags 0x0000010a:
31526 EXEC_P, HAS_DEBUG, D_PAGED
31527 start address 0x00401010
31531 Launch the debugger on the executable.
31538 Set a breakpoint at the starting address, and launch the program.
31541 $ (gdb) break *0x00401010
31545 The program will stop at the given address.
31548 Set a breakpoint on a DLL subroutine.
31551 (gdb) break ada_dll.adb:45
31554 Or if you want to break using a symbol on the DLL, you need first to
31555 select the Ada language (language used by the DLL).
31558 (gdb) set language ada
31559 (gdb) break ada_dll
31563 Continue the program.
31570 This will run the program until it reaches the breakpoint that has been
31571 set. From that point you can use the standard way to debug a program
31572 as described in (@pxref{Running and Debugging Ada Programs}).
31577 It is also possible to debug the DLL by attaching to a running process.
31579 @node Attaching to a Running Process
31580 @subsubsection Attaching to a Running Process
31581 @cindex DLL debugging, attach to process
31584 With @code{GDB} it is always possible to debug a running process by
31585 attaching to it. It is possible to debug a DLL this way. The limitation
31586 of this approach is that the DLL must run long enough to perform the
31587 attach operation. It may be useful for instance to insert a time wasting
31588 loop in the code of the DLL to meet this criterion.
31592 @item Launch the main program @file{main.exe}.
31598 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
31599 that the process PID for @file{main.exe} is 208.
31607 @item Attach to the running process to be debugged.
31613 @item Load the process debugging information.
31616 (gdb) symbol-file main.exe
31619 @item Break somewhere in the DLL.
31622 (gdb) break ada_dll
31625 @item Continue process execution.
31634 This last step will resume the process execution, and stop at
31635 the breakpoint we have set. From there you can use the standard
31636 approach to debug a program as described in
31637 (@pxref{Running and Debugging Ada Programs}).
31639 @node Setting Stack Size from gnatlink
31640 @section Setting Stack Size from @command{gnatlink}
31643 It is possible to specify the program stack size at link time. On modern
31644 versions of Windows, starting with XP, this is mostly useful to set the size of
31645 the main stack (environment task). The other task stacks are set with pragma
31646 Storage_Size or with the @command{gnatbind -d} command.
31648 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
31649 reserve size of individual tasks, the link-time stack size applies to all
31650 tasks, and pragma Storage_Size has no effect.
31651 In particular, Stack Overflow checks are made against this
31652 link-time specified size.
31654 This setting can be done with
31655 @command{gnatlink} using either:
31659 @item using @option{-Xlinker} linker option
31662 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
31665 This sets the stack reserve size to 0x10000 bytes and the stack commit
31666 size to 0x1000 bytes.
31668 @item using @option{-Wl} linker option
31671 $ gnatlink hello -Wl,--stack=0x1000000
31674 This sets the stack reserve size to 0x1000000 bytes. Note that with
31675 @option{-Wl} option it is not possible to set the stack commit size
31676 because the coma is a separator for this option.
31680 @node Setting Heap Size from gnatlink
31681 @section Setting Heap Size from @command{gnatlink}
31684 Under Windows systems, it is possible to specify the program heap size from
31685 @command{gnatlink} using either:
31689 @item using @option{-Xlinker} linker option
31692 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
31695 This sets the heap reserve size to 0x10000 bytes and the heap commit
31696 size to 0x1000 bytes.
31698 @item using @option{-Wl} linker option
31701 $ gnatlink hello -Wl,--heap=0x1000000
31704 This sets the heap reserve size to 0x1000000 bytes. Note that with
31705 @option{-Wl} option it is not possible to set the heap commit size
31706 because the coma is a separator for this option.
31712 @c **********************************
31713 @c * GNU Free Documentation License *
31714 @c **********************************
31716 @c GNU Free Documentation License
31718 @node Index,,GNU Free Documentation License, Top
31724 @c Put table of contents at end, otherwise it precedes the "title page" in
31725 @c the .txt version
31726 @c Edit the pdf file to move the contents to the beginning, after the title