1 \input texinfo @c -*-texinfo-*-
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
6 @c GNAT DOCUMENTATION o
10 @c Copyright (C) 1992-2005 Ada Core Technologies, Inc. o
12 @c GNAT is free software; you can redistribute it and/or modify it under o
13 @c terms of the GNU General Public License as published by the Free Soft- o
14 @c ware Foundation; either version 2, or (at your option) any later ver- o
15 @c sion. GNAT is distributed in the hope that it will be useful, but WITH- o
16 @c OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY o
17 @c or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License o
18 @c for more details. You should have received a copy of the GNU General o
19 @c Public License distributed with GNAT; see file COPYING. If not, write o
20 @c to the Free Software Foundation, 51 Franklin Street, Fifth Floor, o
21 @c Boston, MA 02110-1301, USA. o
23 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
25 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
27 @c GNAT_UGN Style Guide
29 @c 1. Always put a @noindent on the line before the first paragraph
30 @c after any of these commands:
42 @c 2. DO NOT use @example. Use @smallexample instead.
43 @c a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
44 @c context. These can interfere with the readability of the texi
45 @c source file. Instead, use one of the following annotated
46 @c @smallexample commands, and preprocess the texi file with the
47 @c ada2texi tool (which generates appropriate highlighting):
48 @c @smallexample @c ada
49 @c @smallexample @c adanocomment
50 @c @smallexample @c projectfile
51 @c b) The "@c ada" markup will result in boldface for reserved words
52 @c and italics for comments
53 @c c) The "@c adanocomment" markup will result only in boldface for
54 @c reserved words (comments are left alone)
55 @c d) The "@c projectfile" markup is like "@c ada" except that the set
56 @c of reserved words include the new reserved words for project files
58 @c 3. Each @chapter, @section, @subsection, @subsubsection, etc.
59 @c command must be preceded by two empty lines
61 @c 4. The @item command should be on a line of its own if it is in an
62 @c @itemize or @enumerate command.
64 @c 5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
67 @c 6. DO NOT put trailing spaces at the end of a line. Such spaces will
68 @c cause the document build to fail.
70 @c 7. DO NOT use @cartouche for examples that are longer than around 10 lines.
71 @c This command inhibits page breaks, so long examples in a @cartouche can
72 @c lead to large, ugly patches of empty space on a page.
74 @c NOTE: This file should be submitted to xgnatugn with either the vms flag
75 @c or the unw flag set. The unw flag covers topics for both Unix and
78 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
81 @setfilename gnat_ugn_vms.info
85 @setfilename gnat_ugn_unw.info
93 @set FILE gnat_ugn_unw
98 @set FILE gnat_ugn_vms
101 @settitle @value{EDITION} User's Guide @value{PLATFORM}
102 @dircategory GNU Ada tools
104 * @value{EDITION} User's Guide (@value{FILE}) @value{PLATFORM}
107 @include gcc-common.texi
109 @setchapternewpage odd
114 Copyright @copyright{} 1995-2005, Free Software Foundation
116 Permission is granted to copy, distribute and/or modify this document
117 under the terms of the GNU Free Documentation License, Version 1.2
118 or any later version published by the Free Software Foundation;
119 with the Invariant Sections being ``GNU Free Documentation License'', with the
120 Front-Cover Texts being
121 ``@value{EDITION} User's Guide'',
122 and with no Back-Cover Texts.
123 A copy of the license is included in the section entitled
124 ``GNU Free Documentation License''.
129 @title @value{EDITION} User's Guide
134 @titlefont{@i{@value{PLATFORM}}}
140 @subtitle GNAT, The GNU Ada 95 Compiler
141 @subtitle GCC version @value{version-GCC}
146 @vskip 0pt plus 1filll
153 @node Top, About This Guide, (dir), (dir)
154 @top @value{EDITION} User's Guide
157 @value{EDITION} User's Guide @value{PLATFORM}
160 GNAT, The GNU Ada 95 Compiler@*
161 GCC version @value{version-GCC}@*
168 * Getting Started with GNAT::
169 * The GNAT Compilation Model::
170 * Compiling Using gcc::
171 * Binding Using gnatbind::
172 * Linking Using gnatlink::
173 * The GNAT Make Program gnatmake::
174 * Improving Performance::
175 * Renaming Files Using gnatchop::
176 * Configuration Pragmas::
177 * Handling Arbitrary File Naming Conventions Using gnatname::
178 * GNAT Project Manager::
179 * The Cross-Referencing Tools gnatxref and gnatfind::
180 * The GNAT Pretty-Printer gnatpp::
181 * The GNAT Metric Tool gnatmetric::
182 * File Name Krunching Using gnatkr::
183 * Preprocessing Using gnatprep::
185 * The GNAT Run-Time Library Builder gnatlbr::
187 * The GNAT Library Browser gnatls::
188 * Cleaning Up Using gnatclean::
190 * GNAT and Libraries::
191 * Using the GNU make Utility::
193 * Memory Management Issues::
194 * Creating Sample Bodies Using gnatstub::
195 * Other Utility Programs::
196 * Running and Debugging Ada Programs::
198 * Compatibility with DEC Ada::
200 * Platform-Specific Information for the Run-Time Libraries::
201 * Example of Binder Output File::
202 * Elaboration Order Handling in GNAT::
204 * Compatibility and Porting Guide::
206 * Microsoft Windows Topics::
208 * GNU Free Documentation License::
211 --- The Detailed Node Listing ---
215 * What This Guide Contains::
216 * What You Should Know before Reading This Guide::
217 * Related Information::
220 Getting Started with GNAT
223 * Running a Simple Ada Program::
224 * Running a Program with Multiple Units::
225 * Using the gnatmake Utility::
227 * Editing with Emacs::
230 * Introduction to GPS::
231 * Introduction to Glide and GVD::
234 The GNAT Compilation Model
236 * Source Representation::
237 * Foreign Language Representation::
238 * File Naming Rules::
239 * Using Other File Names::
240 * Alternative File Naming Schemes::
241 * Generating Object Files::
242 * Source Dependencies::
243 * The Ada Library Information Files::
244 * Binding an Ada Program::
245 * Mixed Language Programming::
246 * Building Mixed Ada & C++ Programs::
247 * Comparison between GNAT and C/C++ Compilation Models::
248 * Comparison between GNAT and Conventional Ada Library Models::
250 * Placement of temporary files::
253 Foreign Language Representation
256 * Other 8-Bit Codes::
257 * Wide Character Encodings::
259 Compiling Ada Programs With gcc
261 * Compiling Programs::
263 * Search Paths and the Run-Time Library (RTL)::
264 * Order of Compilation Issues::
269 * Output and Error Message Control::
270 * Warning Message Control::
271 * Debugging and Assertion Control::
272 * Validity Checking::
275 * Stack Overflow Checking::
276 * Using gcc for Syntax Checking::
277 * Using gcc for Semantic Checking::
278 * Compiling Different Versions of Ada::
279 * Character Set Control::
280 * File Naming Control::
281 * Subprogram Inlining Control::
282 * Auxiliary Output Control::
283 * Debugging Control::
284 * Exception Handling Control::
285 * Units to Sources Mapping Files::
286 * Integrated Preprocessing::
291 Binding Ada Programs With gnatbind
294 * Switches for gnatbind::
295 * Command-Line Access::
296 * Search Paths for gnatbind::
297 * Examples of gnatbind Usage::
299 Switches for gnatbind
301 * Consistency-Checking Modes::
302 * Binder Error Message Control::
303 * Elaboration Control::
305 * Binding with Non-Ada Main Programs::
306 * Binding Programs with No Main Subprogram::
308 Linking Using gnatlink
311 * Switches for gnatlink::
312 * Setting Stack Size from gnatlink::
313 * Setting Heap Size from gnatlink::
315 The GNAT Make Program gnatmake
318 * Switches for gnatmake::
319 * Mode Switches for gnatmake::
320 * Notes on the Command Line::
321 * How gnatmake Works::
322 * Examples of gnatmake Usage::
324 Improving Performance
325 * Performance Considerations::
326 * Reducing the Size of Ada Executables with gnatelim::
328 Performance Considerations
329 * Controlling Run-Time Checks::
330 * Use of Restrictions::
331 * Optimization Levels::
332 * Debugging Optimized Code::
333 * Inlining of Subprograms::
334 * Other Optimization Switches::
335 * Optimization and Strict Aliasing::
337 * Coverage Analysis::
340 Reducing the Size of Ada Executables with gnatelim
343 * Correcting the List of Eliminate Pragmas::
344 * Making Your Executables Smaller::
345 * Summary of the gnatelim Usage Cycle::
347 Renaming Files Using gnatchop
349 * Handling Files with Multiple Units::
350 * Operating gnatchop in Compilation Mode::
351 * Command Line for gnatchop::
352 * Switches for gnatchop::
353 * Examples of gnatchop Usage::
355 Configuration Pragmas
357 * Handling of Configuration Pragmas::
358 * The Configuration Pragmas Files::
360 Handling Arbitrary File Naming Conventions Using gnatname
362 * Arbitrary File Naming Conventions::
364 * Switches for gnatname::
365 * Examples of gnatname Usage::
370 * Examples of Project Files::
371 * Project File Syntax::
372 * Objects and Sources in Project Files::
373 * Importing Projects::
374 * Project Extension::
375 * Project Hierarchy Extension::
376 * External References in Project Files::
377 * Packages in Project Files::
378 * Variables from Imported Projects::
381 * Stand-alone Library Projects::
382 * Switches Related to Project Files::
383 * Tools Supporting Project Files::
384 * An Extended Example::
385 * Project File Complete Syntax::
387 The Cross-Referencing Tools gnatxref and gnatfind
389 * gnatxref Switches::
390 * gnatfind Switches::
391 * Project Files for gnatxref and gnatfind::
392 * Regular Expressions in gnatfind and gnatxref::
393 * Examples of gnatxref Usage::
394 * Examples of gnatfind Usage::
396 The GNAT Pretty-Printer gnatpp
398 * Switches for gnatpp::
401 The GNAT Metrics Tool gnatmetric
403 * Switches for gnatmetric::
405 File Name Krunching Using gnatkr
410 * Examples of gnatkr Usage::
412 Preprocessing Using gnatprep
415 * Switches for gnatprep::
416 * Form of Definitions File::
417 * Form of Input Text for gnatprep::
420 The GNAT Run-Time Library Builder gnatlbr
423 * Switches for gnatlbr::
424 * Examples of gnatlbr Usage::
427 The GNAT Library Browser gnatls
430 * Switches for gnatls::
431 * Examples of gnatls Usage::
433 Cleaning Up Using gnatclean
435 * Running gnatclean::
436 * Switches for gnatclean::
437 @c * Examples of gnatclean Usage::
443 * Introduction to Libraries in GNAT::
444 * General Ada Libraries::
445 * Stand-alone Ada Libraries::
446 * Rebuilding the GNAT Run-Time Library::
448 Using the GNU make Utility
450 * Using gnatmake in a Makefile::
451 * Automatically Creating a List of Directories::
452 * Generating the Command Line Switches::
453 * Overcoming Command Line Length Limits::
456 Memory Management Issues
458 * Some Useful Memory Pools::
459 * The GNAT Debug Pool Facility::
464 Some Useful Memory Pools
466 The GNAT Debug Pool Facility
472 * Switches for gnatmem::
473 * Example of gnatmem Usage::
476 Sample Bodies Using gnatstub
479 * Switches for gnatstub::
481 Other Utility Programs
483 * Using Other Utility Programs with GNAT::
484 * The External Symbol Naming Scheme of GNAT::
486 * Ada Mode for Glide::
488 * Converting Ada Files to html with gnathtml::
490 Running and Debugging Ada Programs
492 * The GNAT Debugger GDB::
494 * Introduction to GDB Commands::
495 * Using Ada Expressions::
496 * Calling User-Defined Subprograms::
497 * Using the Next Command in a Function::
500 * Debugging Generic Units::
501 * GNAT Abnormal Termination or Failure to Terminate::
502 * Naming Conventions for GNAT Source Files::
503 * Getting Internal Debugging Information::
511 Compatibility with DEC Ada
513 * Ada 95 Compatibility::
514 * Differences in the Definition of Package System::
515 * Language-Related Features::
516 * The Package STANDARD::
517 * The Package SYSTEM::
518 * Tasking and Task-Related Features::
519 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
520 * Pragmas and Pragma-Related Features::
521 * Library of Predefined Units::
523 * Main Program Definition::
524 * Implementation-Defined Attributes::
525 * Compiler and Run-Time Interfacing::
526 * Program Compilation and Library Management::
528 * Implementation Limits::
531 Language-Related Features
533 * Integer Types and Representations::
534 * Floating-Point Types and Representations::
535 * Pragmas Float_Representation and Long_Float::
536 * Fixed-Point Types and Representations::
537 * Record and Array Component Alignment::
539 * Other Representation Clauses::
541 Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
543 * Assigning Task IDs::
544 * Task IDs and Delays::
545 * Task-Related Pragmas::
546 * Scheduling and Task Priority::
548 * External Interrupts::
550 Pragmas and Pragma-Related Features
552 * Restrictions on the Pragma INLINE::
553 * Restrictions on the Pragma INTERFACE::
554 * Restrictions on the Pragma SYSTEM_NAME::
556 Library of Predefined Units
558 * Changes to DECLIB::
562 * Shared Libraries and Options Files::
566 Platform-Specific Information for the Run-Time Libraries
568 * Summary of Run-Time Configurations::
569 * Specifying a Run-Time Library::
570 * Choosing the Scheduling Policy::
571 * Solaris-Specific Considerations::
572 * IRIX-Specific Considerations::
573 * Linux-Specific Considerations::
574 * AIX-Specific Considerations::
576 Example of Binder Output File
578 Elaboration Order Handling in GNAT
580 * Elaboration Code in Ada 95::
581 * Checking the Elaboration Order in Ada 95::
582 * Controlling the Elaboration Order in Ada 95::
583 * Controlling Elaboration in GNAT - Internal Calls::
584 * Controlling Elaboration in GNAT - External Calls::
585 * Default Behavior in GNAT - Ensuring Safety::
586 * Treatment of Pragma Elaborate::
587 * Elaboration Issues for Library Tasks::
588 * Mixing Elaboration Models::
589 * What to Do If the Default Elaboration Behavior Fails::
590 * Elaboration for Access-to-Subprogram Values::
591 * Summary of Procedures for Elaboration Control::
592 * Other Elaboration Order Considerations::
596 * Basic Assembler Syntax::
597 * A Simple Example of Inline Assembler::
598 * Output Variables in Inline Assembler::
599 * Input Variables in Inline Assembler::
600 * Inlining Inline Assembler Code::
601 * Other Asm Functionality::
603 Compatibility and Porting Guide
605 * Compatibility with Ada 83::
606 * Implementation-dependent characteristics::
607 * Compatibility with DEC Ada 83::
608 * Compatibility with Other Ada 95 Systems::
609 * Representation Clauses::
611 * Transitioning from Alpha to Integrity OpenVMS::
615 Microsoft Windows Topics
617 * Using GNAT on Windows::
618 * CONSOLE and WINDOWS subsystems::
620 * Mixed-Language Programming on Windows::
621 * Windows Calling Conventions::
622 * Introduction to Dynamic Link Libraries (DLLs)::
623 * Using DLLs with GNAT::
624 * Building DLLs with GNAT::
625 * GNAT and Windows Resources::
627 * GNAT and COM/DCOM Objects::
634 @node About This Guide
635 @unnumbered About This Guide
639 This guide describes the use of @value{EDITION},
640 a full language compiler for the Ada
641 95 programming language, implemented on HP's Alpha and
642 Integrity (ia64) OpenVMS platforms.
645 This guide describes the use of @value{EDITION},
646 a compiler and software development
647 toolset for the full Ada 95 programming language.
649 It describes the features of the compiler and tools, and details
650 how to use them to build Ada 95 applications.
653 For ease of exposition, ``GNAT Pro'' will be referred to simply as
654 ``GNAT'' in the remainder of this document.
658 * What This Guide Contains::
659 * What You Should Know before Reading This Guide::
660 * Related Information::
664 @node What This Guide Contains
665 @unnumberedsec What This Guide Contains
668 This guide contains the following chapters:
672 @ref{Getting Started with GNAT}, describes how to get started compiling
673 and running Ada programs with the GNAT Ada programming environment.
675 @ref{The GNAT Compilation Model}, describes the compilation model used
679 @ref{Compiling Using gcc}, describes how to compile
680 Ada programs with @command{gcc}, the Ada compiler.
683 @ref{Binding Using gnatbind}, describes how to
684 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
688 @ref{Linking Using gnatlink},
689 describes @command{gnatlink}, a
690 program that provides for linking using the GNAT run-time library to
691 construct a program. @command{gnatlink} can also incorporate foreign language
692 object units into the executable.
695 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
696 utility that automatically determines the set of sources
697 needed by an Ada compilation unit, and executes the necessary compilations
701 @ref{Improving Performance}, shows various techniques for making your
702 Ada program run faster or take less space.
703 It discusses the effect of the compiler's optimization switch and
704 also describes the @command{gnatelim} tool.
707 @ref{Renaming Files Using gnatchop}, describes
708 @code{gnatchop}, a utility that allows you to preprocess a file that
709 contains Ada source code, and split it into one or more new files, one
710 for each compilation unit.
713 @ref{Configuration Pragmas}, describes the configuration pragmas
717 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
718 shows how to override the default GNAT file naming conventions,
719 either for an individual unit or globally.
722 @ref{GNAT Project Manager}, describes how to use project files
723 to organize large projects.
726 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
727 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
728 way to navigate through sources.
731 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
732 version of an Ada source file with control over casing, indentation,
733 comment placement, and other elements of program presentation style.
736 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
737 metrics for an Ada source file, such as the number of types and subprograms,
738 and assorted complexity measures.
741 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
742 file name krunching utility, used to handle shortened
743 file names on operating systems with a limit on the length of names.
746 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
747 preprocessor utility that allows a single source file to be used to
748 generate multiple or parameterized source files, by means of macro
753 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
754 a tool for rebuilding the GNAT run time with user-supplied
755 configuration pragmas.
759 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
760 utility that displays information about compiled units, including dependences
761 on the corresponding sources files, and consistency of compilations.
764 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
765 to delete files that are produced by the compiler, binder and linker.
769 @ref{GNAT and Libraries}, describes the process of creating and using
770 Libraries with GNAT. It also describes how to recompile the GNAT run-time
774 @ref{Using the GNU make Utility}, describes some techniques for using
775 the GNAT toolset in Makefiles.
779 @ref{Memory Management Issues}, describes some useful predefined storage pools
780 and in particular the GNAT Debug Pool facility, which helps detect incorrect
783 It also describes @command{gnatmem}, a utility that monitors dynamic
784 allocation and deallocation and helps detect ``memory leaks''.
788 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
789 a utility that generates empty but compilable bodies for library units.
792 @ref{Other Utility Programs}, discusses several other GNAT utilities,
793 including @code{gnathtml}.
796 @ref{Running and Debugging Ada Programs}, describes how to run and debug
801 @ref{Compatibility with DEC Ada}, details the compatibility of GNAT with
802 DEC Ada 83 @footnote{``DEC Ada'' refers to the legacy product originally
803 developed by Digital Equipment Corporation and currently supported by HP.}
808 @ref{Platform-Specific Information for the Run-Time Libraries},
809 describes the various run-time
810 libraries supported by GNAT on various platforms and explains how to
811 choose a particular library.
814 @ref{Example of Binder Output File}, shows the source code for the binder
815 output file for a sample program.
818 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
819 you deal with elaboration order issues.
822 @ref{Inline Assembler}, shows how to use the inline assembly facility
826 @ref{Compatibility and Porting Guide}, includes sections on compatibility
827 of GNAT with other Ada 83 and Ada 95 compilation systems, to assist
828 in porting code from other environments.
832 @ref{Microsoft Windows Topics}, presents information relevant to the
833 Microsoft Windows platform.
837 @c *************************************************
838 @node What You Should Know before Reading This Guide
839 @c *************************************************
840 @unnumberedsec What You Should Know before Reading This Guide
842 @cindex Ada 95 Language Reference Manual
844 This user's guide assumes that you are familiar with Ada 95 language, as
845 described in the International Standard ANSI/ISO/IEC-8652:1995, January
848 @node Related Information
849 @unnumberedsec Related Information
852 For further information about related tools, refer to the following
857 @cite{GNAT Reference Manual}, which contains all reference
858 material for the GNAT implementation of Ada 95.
862 @cite{Using the GNAT Programming System}, which describes the GPS
863 integrated development environment.
866 @cite{GNAT Programming System Tutorial}, which introduces the
867 main GPS features through examples.
871 @cite{Ada 95 Language Reference Manual}, which contains all reference
872 material for the Ada 95 programming language.
875 @cite{Debugging with GDB}
877 , located in the GNU:[DOCS] directory,
879 contains all details on the use of the GNU source-level debugger.
882 @cite{GNU Emacs Manual}
884 , located in the GNU:[DOCS] directory if the EMACS kit is installed,
886 contains full information on the extensible editor and programming
893 @unnumberedsec Conventions
895 @cindex Typographical conventions
898 Following are examples of the typographical and graphic conventions used
903 @code{Functions}, @code{utility program names}, @code{standard names},
910 @file{File Names}, @file{button names}, and @file{field names}.
919 [optional information or parameters]
922 Examples are described by text
924 and then shown this way.
929 Commands that are entered by the user are preceded in this manual by the
930 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
931 uses this sequence as a prompt, then the commands will appear exactly as
932 you see them in the manual. If your system uses some other prompt, then
933 the command will appear with the @code{$} replaced by whatever prompt
934 character you are using.
937 Full file names are shown with the ``@code{/}'' character
938 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
939 If you are using GNAT on a Windows platform, please note that
940 the ``@code{\}'' character should be used instead.
943 @c ****************************
944 @node Getting Started with GNAT
945 @chapter Getting Started with GNAT
948 This chapter describes some simple ways of using GNAT to build
949 executable Ada programs.
951 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
952 show how to use the command line environment.
953 @ref{Introduction to Glide and GVD}, provides a brief
954 introduction to the visually-oriented IDE for GNAT.
955 Supplementing Glide on some platforms is GPS, the
956 GNAT Programming System, which offers a richer graphical
957 ``look and feel'', enhanced configurability, support for
958 development in other programming language, comprehensive
959 browsing features, and many other capabilities.
960 For information on GPS please refer to
961 @cite{Using the GNAT Programming System}.
966 * Running a Simple Ada Program::
967 * Running a Program with Multiple Units::
968 * Using the gnatmake Utility::
970 * Editing with Emacs::
973 * Introduction to GPS::
974 * Introduction to Glide and GVD::
979 @section Running GNAT
982 Three steps are needed to create an executable file from an Ada source
987 The source file(s) must be compiled.
989 The file(s) must be bound using the GNAT binder.
991 All appropriate object files must be linked to produce an executable.
995 All three steps are most commonly handled by using the @command{gnatmake}
996 utility program that, given the name of the main program, automatically
997 performs the necessary compilation, binding and linking steps.
999 @node Running a Simple Ada Program
1000 @section Running a Simple Ada Program
1003 Any text editor may be used to prepare an Ada program.
1006 used, the optional Ada mode may be helpful in laying out the program.
1009 program text is a normal text file. We will suppose in our initial
1010 example that you have used your editor to prepare the following
1011 standard format text file:
1013 @smallexample @c ada
1015 with Ada.Text_IO; use Ada.Text_IO;
1018 Put_Line ("Hello WORLD!");
1024 This file should be named @file{hello.adb}.
1025 With the normal default file naming conventions, GNAT requires
1027 contain a single compilation unit whose file name is the
1029 with periods replaced by hyphens; the
1030 extension is @file{ads} for a
1031 spec and @file{adb} for a body.
1032 You can override this default file naming convention by use of the
1033 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1034 Alternatively, if you want to rename your files according to this default
1035 convention, which is probably more convenient if you will be using GNAT
1036 for all your compilations, then the @code{gnatchop} utility
1037 can be used to generate correctly-named source files
1038 (@pxref{Renaming Files Using gnatchop}).
1040 You can compile the program using the following command (@code{$} is used
1041 as the command prompt in the examples in this document):
1048 @command{gcc} is the command used to run the compiler. This compiler is
1049 capable of compiling programs in several languages, including Ada 95 and
1050 C. It assumes that you have given it an Ada program if the file extension is
1051 either @file{.ads} or @file{.adb}, and it will then call
1052 the GNAT compiler to compile the specified file.
1055 The @option{-c} switch is required. It tells @command{gcc} to only do a
1056 compilation. (For C programs, @command{gcc} can also do linking, but this
1057 capability is not used directly for Ada programs, so the @option{-c}
1058 switch must always be present.)
1061 This compile command generates a file
1062 @file{hello.o}, which is the object
1063 file corresponding to your Ada program. It also generates
1064 an ``Ada Library Information'' file @file{hello.ali},
1065 which contains additional information used to check
1066 that an Ada program is consistent.
1067 To build an executable file,
1068 use @code{gnatbind} to bind the program
1069 and @command{gnatlink} to link it. The
1070 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1071 @file{ALI} file, but the default extension of @file{.ali} can
1072 be omitted. This means that in the most common case, the argument
1073 is simply the name of the main program:
1081 A simpler method of carrying out these steps is to use
1083 a master program that invokes all the required
1084 compilation, binding and linking tools in the correct order. In particular,
1085 @command{gnatmake} automatically recompiles any sources that have been
1086 modified since they were last compiled, or sources that depend
1087 on such modified sources, so that ``version skew'' is avoided.
1088 @cindex Version skew (avoided by @command{gnatmake})
1091 $ gnatmake hello.adb
1095 The result is an executable program called @file{hello}, which can be
1103 assuming that the current directory is on the search path
1104 for executable programs.
1107 and, if all has gone well, you will see
1114 appear in response to this command.
1116 @c ****************************************
1117 @node Running a Program with Multiple Units
1118 @section Running a Program with Multiple Units
1121 Consider a slightly more complicated example that has three files: a
1122 main program, and the spec and body of a package:
1124 @smallexample @c ada
1127 package Greetings is
1132 with Ada.Text_IO; use Ada.Text_IO;
1133 package body Greetings is
1136 Put_Line ("Hello WORLD!");
1139 procedure Goodbye is
1141 Put_Line ("Goodbye WORLD!");
1158 Following the one-unit-per-file rule, place this program in the
1159 following three separate files:
1163 spec of package @code{Greetings}
1166 body of package @code{Greetings}
1169 body of main program
1173 To build an executable version of
1174 this program, we could use four separate steps to compile, bind, and link
1175 the program, as follows:
1179 $ gcc -c greetings.adb
1185 Note that there is no required order of compilation when using GNAT.
1186 In particular it is perfectly fine to compile the main program first.
1187 Also, it is not necessary to compile package specs in the case where
1188 there is an accompanying body; you only need to compile the body. If you want
1189 to submit these files to the compiler for semantic checking and not code
1190 generation, then use the
1191 @option{-gnatc} switch:
1194 $ gcc -c greetings.ads -gnatc
1198 Although the compilation can be done in separate steps as in the
1199 above example, in practice it is almost always more convenient
1200 to use the @command{gnatmake} tool. All you need to know in this case
1201 is the name of the main program's source file. The effect of the above four
1202 commands can be achieved with a single one:
1205 $ gnatmake gmain.adb
1209 In the next section we discuss the advantages of using @command{gnatmake} in
1212 @c *****************************
1213 @node Using the gnatmake Utility
1214 @section Using the @command{gnatmake} Utility
1217 If you work on a program by compiling single components at a time using
1218 @command{gcc}, you typically keep track of the units you modify. In order to
1219 build a consistent system, you compile not only these units, but also any
1220 units that depend on the units you have modified.
1221 For example, in the preceding case,
1222 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1223 you edit @file{greetings.ads}, you must recompile both
1224 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1225 units that depend on @file{greetings.ads}.
1227 @code{gnatbind} will warn you if you forget one of these compilation
1228 steps, so that it is impossible to generate an inconsistent program as a
1229 result of forgetting to do a compilation. Nevertheless it is tedious and
1230 error-prone to keep track of dependencies among units.
1231 One approach to handle the dependency-bookkeeping is to use a
1232 makefile. However, makefiles present maintenance problems of their own:
1233 if the dependencies change as you change the program, you must make
1234 sure that the makefile is kept up-to-date manually, which is also an
1235 error-prone process.
1237 The @command{gnatmake} utility takes care of these details automatically.
1238 Invoke it using either one of the following forms:
1241 $ gnatmake gmain.adb
1242 $ gnatmake ^gmain^GMAIN^
1246 The argument is the name of the file containing the main program;
1247 you may omit the extension. @command{gnatmake}
1248 examines the environment, automatically recompiles any files that need
1249 recompiling, and binds and links the resulting set of object files,
1250 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1251 In a large program, it
1252 can be extremely helpful to use @command{gnatmake}, because working out by hand
1253 what needs to be recompiled can be difficult.
1255 Note that @command{gnatmake}
1256 takes into account all the Ada 95 rules that
1257 establish dependencies among units. These include dependencies that result
1258 from inlining subprogram bodies, and from
1259 generic instantiation. Unlike some other
1260 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1261 found by the compiler on a previous compilation, which may possibly
1262 be wrong when sources change. @command{gnatmake} determines the exact set of
1263 dependencies from scratch each time it is run.
1266 @node Editing with Emacs
1267 @section Editing with Emacs
1271 Emacs is an extensible self-documenting text editor that is available in a
1272 separate VMSINSTAL kit.
1274 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1275 click on the Emacs Help menu and run the Emacs Tutorial.
1276 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1277 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1279 Documentation on Emacs and other tools is available in Emacs under the
1280 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1281 use the middle mouse button to select a topic (e.g. Emacs).
1283 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1284 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1285 get to the Emacs manual.
1286 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1289 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1290 which is sufficiently extensible to provide for a complete programming
1291 environment and shell for the sophisticated user.
1295 @node Introduction to GPS
1296 @section Introduction to GPS
1297 @cindex GPS (GNAT Programming System)
1298 @cindex GNAT Programming System (GPS)
1300 Although the command line interface (@command{gnatmake}, etc.) alone
1301 is sufficient, a graphical Interactive Development
1302 Environment can make it easier for you to compose, navigate, and debug
1303 programs. This section describes the main features of GPS
1304 (``GNAT Programming System''), the GNAT graphical IDE.
1305 You will see how to use GPS to build and debug an executable, and
1306 you will also learn some of the basics of the GNAT ``project'' facility.
1308 GPS enables you to do much more than is presented here;
1309 e.g., you can produce a call graph, interface to a third-party
1310 Version Control System, and inspect the generated assembly language
1312 Indeed, GPS also supports languages other than Ada.
1313 Such additional information, and an explanation of all of the GPS menu
1314 items. may be found in the on-line help, which includes
1315 a user's guide and a tutorial (these are also accessible from the GNAT
1319 * Building a New Program with GPS::
1320 * Simple Debugging with GPS::
1323 @node Building a New Program with GPS
1324 @subsection Building a New Program with GPS
1326 GPS invokes the GNAT compilation tools using information
1327 contained in a @emph{project} (also known as a @emph{project file}):
1328 a collection of properties such
1329 as source directories, identities of main subprograms, tool switches, etc.,
1330 and their associated values.
1331 See @ref{GNAT Project Manager} for details.
1332 In order to run GPS, you will need to either create a new project
1333 or else open an existing one.
1335 This section will explain how you can use GPS to create a project,
1336 to associate Ada source files with a project, and to build and run
1340 @item @emph{Creating a project}
1342 Invoke GPS, either from the command line or the platform's IDE.
1343 After it starts, GPS will display a ``Welcome'' screen with three
1348 @code{Start with default project in directory}
1351 @code{Create new project with wizard}
1354 @code{Open existing project}
1358 Select @code{Create new project with wizard} and press @code{OK}.
1359 A new window will appear. In the text box labeled with
1360 @code{Enter the name of the project to create}, type @file{sample}
1361 as the project name.
1362 In the next box, browse to choose the directory in which you
1363 would like to create the project file.
1364 After selecting an appropriate directory, press @code{Forward}.
1366 A window will appear with the title
1367 @code{Version Control System Configuration}.
1368 Simply press @code{Forward}.
1370 A window will appear with the title
1371 @code{Please select the source directories for this project}.
1372 The directory that you specified for the project file will be selected
1373 by default as the one to use for sources; simply press @code{Forward}.
1375 A window will appear with the title
1376 @code{Please select the build directory for this project}.
1377 The directory that you specified for the project file will be selected
1378 by default for object files and executables;
1379 simply press @code{Forward}.
1381 A window will appear with the title
1382 @code{Please select the main units for this project}.
1383 You will supply this information later, after creating the source file.
1384 Simply press @code{Forward} for now.
1386 A window will appear with the title
1387 @code{Please select the switches to build the project}.
1388 Press @code{Apply}. This will create a project file named
1389 @file{sample.prj} in the directory that you had specified.
1391 @item @emph{Creating and saving the source file}
1393 After you create the new project, a GPS window will appear, which is
1394 partitioned into two main sections:
1398 A @emph{Workspace area}, initially greyed out, which you will use for
1399 creating and editing source files
1402 Directly below, a @emph{Messages area}, which initially displays a
1403 ``Welcome'' message.
1404 (If the Messages area is not visible, drag its border upward to expand it.)
1408 Select @code{File} on the menu bar, and then the @code{New} command.
1409 The Workspace area will become white, and you can now
1410 enter the source program explicitly.
1411 Type the following text
1413 @smallexample @c ada
1415 with Ada.Text_IO; use Ada.Text_IO;
1418 Put_Line("Hello from GPS!");
1424 Select @code{File}, then @code{Save As}, and enter the source file name
1426 The file will be saved in the same directory you specified as the
1427 location of the default project file.
1429 @item @emph{Updating the project file}
1431 You need to add the new source file to the project.
1433 the @code{Project} menu and then @code{Edit project properties}.
1434 Click the @code{Main files} tab on the left, and then the
1436 Choose @file{hello.adb} from the list, and press @code{Open}.
1437 The project settings window will reflect this action.
1440 @item @emph{Building and running the program}
1442 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1443 and select @file{hello.adb}.
1444 The Messages window will display the resulting invocations of @command{gcc},
1445 @command{gnatbind}, and @command{gnatlink}
1446 (reflecting the default switch settings from the
1447 project file that you created) and then a ``successful compilation/build''
1450 To run the program, choose the @code{Build} menu, then @code{Run}, and
1451 select @command{hello}.
1452 An @emph{Arguments Selection} window will appear.
1453 There are no command line arguments, so just click @code{OK}.
1455 The Messages window will now display the program's output (the string
1456 @code{Hello from GPS}), and at the bottom of the GPS window a status
1457 update is displayed (@code{Run: hello}).
1458 Close the GPS window (or select @code{File}, then @code{Exit}) to
1459 terminate this GPS session.
1462 @node Simple Debugging with GPS
1463 @subsection Simple Debugging with GPS
1465 This section illustrates basic debugging techniques (setting breakpoints,
1466 examining/modifying variables, single stepping).
1469 @item @emph{Opening a project}
1471 Start GPS and select @code{Open existing project}; browse to
1472 specify the project file @file{sample.prj} that you had created in the
1475 @item @emph{Creating a source file}
1477 Select @code{File}, then @code{New}, and type in the following program:
1479 @smallexample @c ada
1481 with Ada.Text_IO; use Ada.Text_IO;
1482 procedure Example is
1483 Line : String (1..80);
1486 Put_Line("Type a line of text at each prompt; an empty line to exit");
1490 Put_Line (Line (1..N) );
1498 Select @code{File}, then @code{Save as}, and enter the file name
1501 @item @emph{Updating the project file}
1503 Add @code{Example} as a new main unit for the project:
1506 Select @code{Project}, then @code{Edit Project Properties}.
1509 Select the @code{Main files} tab, click @code{Add}, then
1510 select the file @file{example.adb} from the list, and
1512 You will see the file name appear in the list of main units
1518 @item @emph{Building/running the executable}
1520 To build the executable
1521 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1523 Run the program to see its effect (in the Messages area).
1524 Each line that you enter is displayed; an empty line will
1525 cause the loop to exit and the program to terminate.
1527 @item @emph{Debugging the program}
1529 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1530 which are required for debugging, are on by default when you create
1532 Thus unless you intentionally remove these settings, you will be able
1533 to debug any program that you develop using GPS.
1536 @item @emph{Initializing}
1538 Select @code{Debug}, then @code{Initialize}, then @file{example}
1540 @item @emph{Setting a breakpoint}
1542 After performing the initialization step, you will observe a small
1543 icon to the right of each line number.
1544 This serves as a toggle for breakpoints; clicking the icon will
1545 set a breakpoint at the corresponding line (the icon will change to
1546 a red circle with an ``x''), and clicking it again
1547 will remove the breakpoint / reset the icon.
1549 For purposes of this example, set a breakpoint at line 10 (the
1550 statement @code{Put_Line@ (Line@ (1..N));}
1552 @item @emph{Starting program execution}
1554 Select @code{Debug}, then @code{Run}. When the
1555 @code{Program Arguments} window appears, click @code{OK}.
1556 A console window will appear; enter some line of text,
1557 e.g. @code{abcde}, at the prompt.
1558 The program will pause execution when it gets to the
1559 breakpoint, and the corresponding line is highlighted.
1561 @item @emph{Examining a variable}
1563 Move the mouse over one of the occurrences of the variable @code{N}.
1564 You will see the value (5) displayed, in ``tool tip'' fashion.
1565 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1566 You will see information about @code{N} appear in the @code{Debugger Data}
1567 pane, showing the value as 5.
1569 @item @emph{Assigning a new value to a variable}
1571 Right click on the @code{N} in the @code{Debugger Data} pane, and
1572 select @code{Set value of N}.
1573 When the input window appears, enter the value @code{4} and click
1575 This value does not automatically appear in the @code{Debugger Data}
1576 pane; to see it, right click again on the @code{N} in the
1577 @code{Debugger Data} pane and select @code{Update value}.
1578 The new value, 4, will appear in red.
1580 @item @emph{Single stepping}
1582 Select @code{Debug}, then @code{Next}.
1583 This will cause the next statement to be executed, in this case the
1584 call of @code{Put_Line} with the string slice.
1585 Notice in the console window that the displayed string is simply
1586 @code{abcd} and not @code{abcde} which you had entered.
1587 This is because the upper bound of the slice is now 4 rather than 5.
1589 @item @emph{Removing a breakpoint}
1591 Toggle the breakpoint icon at line 10.
1593 @item @emph{Resuming execution from a breakpoint}
1595 Select @code{Debug}, then @code{Continue}.
1596 The program will reach the next iteration of the loop, and
1597 wait for input after displaying the prompt.
1598 This time, just hit the @kbd{Enter} key.
1599 The value of @code{N} will be 0, and the program will terminate.
1600 The console window will disappear.
1604 @node Introduction to Glide and GVD
1605 @section Introduction to Glide and GVD
1609 This section describes the main features of Glide,
1610 a GNAT graphical IDE, and also shows how to use the basic commands in GVD,
1611 the GNU Visual Debugger.
1612 These tools may be present in addition to, or in place of, GPS on some
1614 Additional information on Glide and GVD may be found
1615 in the on-line help for these tools.
1618 * Building a New Program with Glide::
1619 * Simple Debugging with GVD::
1620 * Other Glide Features::
1623 @node Building a New Program with Glide
1624 @subsection Building a New Program with Glide
1626 The simplest way to invoke Glide is to enter @command{glide}
1627 at the command prompt. It will generally be useful to issue this
1628 as a background command, thus allowing you to continue using
1629 your command window for other purposes while Glide is running:
1636 Glide will start up with an initial screen displaying the top-level menu items
1637 as well as some other information. The menu selections are as follows
1639 @item @code{Buffers}
1650 For this introductory example, you will need to create a new Ada source file.
1651 First, select the @code{Files} menu. This will pop open a menu with around
1652 a dozen or so items. To create a file, select the @code{Open file...} choice.
1653 Depending on the platform, you may see a pop-up window where you can browse
1654 to an appropriate directory and then enter the file name, or else simply
1655 see a line at the bottom of the Glide window where you can likewise enter
1656 the file name. Note that in Glide, when you attempt to open a non-existent
1657 file, the effect is to create a file with that name. For this example enter
1658 @file{hello.adb} as the name of the file.
1660 A new buffer will now appear, occupying the entire Glide window,
1661 with the file name at the top. The menu selections are slightly different
1662 from the ones you saw on the opening screen; there is an @code{Entities} item,
1663 and in place of @code{Glide} there is now an @code{Ada} item. Glide uses
1664 the file extension to identify the source language, so @file{adb} indicates
1667 You will enter some of the source program lines explicitly,
1668 and use the syntax-oriented template mechanism to enter other lines.
1669 First, type the following text:
1671 with Ada.Text_IO; use Ada.Text_IO;
1677 Observe that Glide uses different colors to distinguish reserved words from
1678 identifiers. Also, after the @code{procedure Hello is} line, the cursor is
1679 automatically indented in anticipation of declarations. When you enter
1680 @code{begin}, Glide recognizes that there are no declarations and thus places
1681 @code{begin} flush left. But after the @code{begin} line the cursor is again
1682 indented, where the statement(s) will be placed.
1684 The main part of the program will be a @code{for} loop. Instead of entering
1685 the text explicitly, however, use a statement template. Select the @code{Ada}
1686 item on the top menu bar, move the mouse to the @code{Statements} item,
1687 and you will see a large selection of alternatives. Choose @code{for loop}.
1688 You will be prompted (at the bottom of the buffer) for a loop name;
1689 simply press the @key{Enter} key since a loop name is not needed.
1690 You should see the beginning of a @code{for} loop appear in the source
1691 program window. You will now be prompted for the name of the loop variable;
1692 enter a line with the identifier @code{ind} (lower case). Note that,
1693 by default, Glide capitalizes the name (you can override such behavior
1694 if you wish, although this is outside the scope of this introduction).
1695 Next, Glide prompts you for the loop range; enter a line containing
1696 @code{1..5} and you will see this also appear in the source program,
1697 together with the remaining elements of the @code{for} loop syntax.
1699 Next enter the statement (with an intentional error, a missing semicolon)
1700 that will form the body of the loop:
1702 Put_Line("Hello, World" & Integer'Image(I))
1706 Finally, type @code{end Hello;} as the last line in the program.
1707 Now save the file: choose the @code{File} menu item, and then the
1708 @code{Save buffer} selection. You will see a message at the bottom
1709 of the buffer confirming that the file has been saved.
1711 You are now ready to attempt to build the program. Select the @code{Ada}
1712 item from the top menu bar. Although we could choose simply to compile
1713 the file, we will instead attempt to do a build (which invokes
1714 @command{gnatmake}) since, if the compile is successful, we want to build
1715 an executable. Thus select @code{Ada build}. This will fail because of the
1716 compilation error, and you will notice that the Glide window has been split:
1717 the top window contains the source file, and the bottom window contains the
1718 output from the GNAT tools. Glide allows you to navigate from a compilation
1719 error to the source file position corresponding to the error: click the
1720 middle mouse button (or simultaneously press the left and right buttons,
1721 on a two-button mouse) on the diagnostic line in the tool window. The
1722 focus will shift to the source window, and the cursor will be positioned
1723 on the character at which the error was detected.
1725 Correct the error: type in a semicolon to terminate the statement.
1726 Although you can again save the file explicitly, you can also simply invoke
1727 @code{Ada} @result{} @code{Build} and you will be prompted to save the file.
1728 This time the build will succeed; the tool output window shows you the
1729 options that are supplied by default. The GNAT tools' output (e.g.
1730 object and ALI files, executable) will go in the directory from which
1733 To execute the program, choose @code{Ada} and then @code{Run}.
1734 You should see the program's output displayed in the bottom window:
1744 @node Simple Debugging with GVD
1745 @subsection Simple Debugging with GVD
1748 This section describes how to set breakpoints, examine/modify variables,
1749 and step through execution.
1751 In order to enable debugging, you need to pass the @option{-g} switch
1752 to both the compiler and to @command{gnatlink}. If you are using
1753 the command line, passing @option{-g} to @command{gnatmake} will have
1754 this effect. You can then launch GVD, e.g. on the @code{hello} program,
1755 by issuing the command:
1762 If you are using Glide, then @option{-g} is passed to the relevant tools
1763 by default when you do a build. Start the debugger by selecting the
1764 @code{Ada} menu item, and then @code{Debug}.
1766 GVD comes up in a multi-part window. One pane shows the names of files
1767 comprising your executable; another pane shows the source code of the current
1768 unit (initially your main subprogram), another pane shows the debugger output
1769 and user interactions, and the fourth pane (the data canvas at the top
1770 of the window) displays data objects that you have selected.
1772 To the left of the source file pane, you will notice green dots adjacent
1773 to some lines. These are lines for which object code exists and where
1774 breakpoints can thus be set. You set/reset a breakpoint by clicking
1775 the green dot. When a breakpoint is set, the dot is replaced by an @code{X}
1776 in a red circle. Clicking the circle toggles the breakpoint off,
1777 and the red circle is replaced by the green dot.
1779 For this example, set a breakpoint at the statement where @code{Put_Line}
1782 Start program execution by selecting the @code{Run} button on the top menu bar.
1783 (The @code{Start} button will also start your program, but it will
1784 cause program execution to break at the entry to your main subprogram.)
1785 Evidence of reaching the breakpoint will appear: the source file line will be
1786 highlighted, and the debugger interactions pane will display
1789 You can examine the values of variables in several ways. Move the mouse
1790 over an occurrence of @code{Ind} in the @code{for} loop, and you will see
1791 the value (now @code{1}) displayed. Alternatively, right-click on @code{Ind}
1792 and select @code{Display Ind}; a box showing the variable's name and value
1793 will appear in the data canvas.
1795 Although a loop index is a constant with respect to Ada semantics,
1796 you can change its value in the debugger. Right-click in the box
1797 for @code{Ind}, and select the @code{Set Value of Ind} item.
1798 Enter @code{2} as the new value, and press @command{OK}.
1799 The box for @code{Ind} shows the update.
1801 Press the @code{Step} button on the top menu bar; this will step through
1802 one line of program text (the invocation of @code{Put_Line}), and you can
1803 observe the effect of having modified @code{Ind} since the value displayed
1806 Remove the breakpoint, and resume execution by selecting the @code{Cont}
1807 button. You will see the remaining output lines displayed in the debugger
1808 interaction window, along with a message confirming normal program
1811 @node Other Glide Features
1812 @subsection Other Glide Features
1815 You may have observed that some of the menu selections contain abbreviations;
1816 e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu.
1817 These are @emph{shortcut keys} that you can use instead of selecting
1818 menu items. The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means
1819 @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead
1820 of selecting @code{Files} and then @code{Open file...}.
1822 To abort a Glide command, type @key{Ctrl-g}.
1824 If you want Glide to start with an existing source file, you can either
1825 launch Glide as above and then open the file via @code{Files} @result{}
1826 @code{Open file...}, or else simply pass the name of the source file
1827 on the command line:
1834 While you are using Glide, a number of @emph{buffers} exist.
1835 You create some explicitly; e.g., when you open/create a file.
1836 Others arise as an effect of the commands that you issue; e.g., the buffer
1837 containing the output of the tools invoked during a build. If a buffer
1838 is hidden, you can bring it into a visible window by first opening
1839 the @code{Buffers} menu and then selecting the desired entry.
1841 If a buffer occupies only part of the Glide screen and you want to expand it
1842 to fill the entire screen, then click in the buffer and then select
1843 @code{Files} @result{} @code{One Window}.
1845 If a window is occupied by one buffer and you want to split the window
1846 to bring up a second buffer, perform the following steps:
1848 @item Select @code{Files} @result{} @code{Split Window};
1849 this will produce two windows each of which holds the original buffer
1850 (these are not copies, but rather different views of the same buffer contents)
1852 @item With the focus in one of the windows,
1853 select the desired buffer from the @code{Buffers} menu
1857 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1860 @node The GNAT Compilation Model
1861 @chapter The GNAT Compilation Model
1862 @cindex GNAT compilation model
1863 @cindex Compilation model
1866 * Source Representation::
1867 * Foreign Language Representation::
1868 * File Naming Rules::
1869 * Using Other File Names::
1870 * Alternative File Naming Schemes::
1871 * Generating Object Files::
1872 * Source Dependencies::
1873 * The Ada Library Information Files::
1874 * Binding an Ada Program::
1875 * Mixed Language Programming::
1876 * Building Mixed Ada & C++ Programs::
1877 * Comparison between GNAT and C/C++ Compilation Models::
1878 * Comparison between GNAT and Conventional Ada Library Models::
1880 * Placement of temporary files::
1885 This chapter describes the compilation model used by GNAT. Although
1886 similar to that used by other languages, such as C and C++, this model
1887 is substantially different from the traditional Ada compilation models,
1888 which are based on a library. The model is initially described without
1889 reference to the library-based model. If you have not previously used an
1890 Ada compiler, you need only read the first part of this chapter. The
1891 last section describes and discusses the differences between the GNAT
1892 model and the traditional Ada compiler models. If you have used other
1893 Ada compilers, this section will help you to understand those
1894 differences, and the advantages of the GNAT model.
1896 @node Source Representation
1897 @section Source Representation
1901 Ada source programs are represented in standard text files, using
1902 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1903 7-bit ASCII set, plus additional characters used for
1904 representing foreign languages (@pxref{Foreign Language Representation}
1905 for support of non-USA character sets). The format effector characters
1906 are represented using their standard ASCII encodings, as follows:
1911 Vertical tab, @code{16#0B#}
1915 Horizontal tab, @code{16#09#}
1919 Carriage return, @code{16#0D#}
1923 Line feed, @code{16#0A#}
1927 Form feed, @code{16#0C#}
1931 Source files are in standard text file format. In addition, GNAT will
1932 recognize a wide variety of stream formats, in which the end of
1933 physical lines is marked by any of the following sequences:
1934 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1935 in accommodating files that are imported from other operating systems.
1937 @cindex End of source file
1938 @cindex Source file, end
1940 The end of a source file is normally represented by the physical end of
1941 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1942 recognized as signalling the end of the source file. Again, this is
1943 provided for compatibility with other operating systems where this
1944 code is used to represent the end of file.
1946 Each file contains a single Ada compilation unit, including any pragmas
1947 associated with the unit. For example, this means you must place a
1948 package declaration (a package @dfn{spec}) and the corresponding body in
1949 separate files. An Ada @dfn{compilation} (which is a sequence of
1950 compilation units) is represented using a sequence of files. Similarly,
1951 you will place each subunit or child unit in a separate file.
1953 @node Foreign Language Representation
1954 @section Foreign Language Representation
1957 GNAT supports the standard character sets defined in Ada 95 as well as
1958 several other non-standard character sets for use in localized versions
1959 of the compiler (@pxref{Character Set Control}).
1962 * Other 8-Bit Codes::
1963 * Wide Character Encodings::
1971 The basic character set is Latin-1. This character set is defined by ISO
1972 standard 8859, part 1. The lower half (character codes @code{16#00#}
1973 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1974 is used to represent additional characters. These include extended letters
1975 used by European languages, such as French accents, the vowels with umlauts
1976 used in German, and the extra letter A-ring used in Swedish.
1978 @findex Ada.Characters.Latin_1
1979 For a complete list of Latin-1 codes and their encodings, see the source
1980 file of library unit @code{Ada.Characters.Latin_1} in file
1981 @file{a-chlat1.ads}.
1982 You may use any of these extended characters freely in character or
1983 string literals. In addition, the extended characters that represent
1984 letters can be used in identifiers.
1986 @node Other 8-Bit Codes
1987 @subsection Other 8-Bit Codes
1990 GNAT also supports several other 8-bit coding schemes:
1993 @item ISO 8859-2 (Latin-2)
1996 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1999 @item ISO 8859-3 (Latin-3)
2002 Latin-3 letters allowed in identifiers, with uppercase and lowercase
2005 @item ISO 8859-4 (Latin-4)
2008 Latin-4 letters allowed in identifiers, with uppercase and lowercase
2011 @item ISO 8859-5 (Cyrillic)
2014 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
2015 lowercase equivalence.
2017 @item ISO 8859-15 (Latin-9)
2020 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
2021 lowercase equivalence
2023 @item IBM PC (code page 437)
2024 @cindex code page 437
2025 This code page is the normal default for PCs in the U.S. It corresponds
2026 to the original IBM PC character set. This set has some, but not all, of
2027 the extended Latin-1 letters, but these letters do not have the same
2028 encoding as Latin-1. In this mode, these letters are allowed in
2029 identifiers with uppercase and lowercase equivalence.
2031 @item IBM PC (code page 850)
2032 @cindex code page 850
2033 This code page is a modification of 437 extended to include all the
2034 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
2035 mode, all these letters are allowed in identifiers with uppercase and
2036 lowercase equivalence.
2038 @item Full Upper 8-bit
2039 Any character in the range 80-FF allowed in identifiers, and all are
2040 considered distinct. In other words, there are no uppercase and lowercase
2041 equivalences in this range. This is useful in conjunction with
2042 certain encoding schemes used for some foreign character sets (e.g.
2043 the typical method of representing Chinese characters on the PC).
2046 No upper-half characters in the range 80-FF are allowed in identifiers.
2047 This gives Ada 83 compatibility for identifier names.
2051 For precise data on the encodings permitted, and the uppercase and lowercase
2052 equivalences that are recognized, see the file @file{csets.adb} in
2053 the GNAT compiler sources. You will need to obtain a full source release
2054 of GNAT to obtain this file.
2056 @node Wide Character Encodings
2057 @subsection Wide Character Encodings
2060 GNAT allows wide character codes to appear in character and string
2061 literals, and also optionally in identifiers, by means of the following
2062 possible encoding schemes:
2067 In this encoding, a wide character is represented by the following five
2075 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2076 characters (using uppercase letters) of the wide character code. For
2077 example, ESC A345 is used to represent the wide character with code
2079 This scheme is compatible with use of the full Wide_Character set.
2081 @item Upper-Half Coding
2082 @cindex Upper-Half Coding
2083 The wide character with encoding @code{16#abcd#} where the upper bit is on
2084 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
2085 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
2086 character, but is not required to be in the upper half. This method can
2087 be also used for shift-JIS or EUC, where the internal coding matches the
2090 @item Shift JIS Coding
2091 @cindex Shift JIS Coding
2092 A wide character is represented by a two-character sequence,
2094 @code{16#cd#}, with the restrictions described for upper-half encoding as
2095 described above. The internal character code is the corresponding JIS
2096 character according to the standard algorithm for Shift-JIS
2097 conversion. Only characters defined in the JIS code set table can be
2098 used with this encoding method.
2102 A wide character is represented by a two-character sequence
2104 @code{16#cd#}, with both characters being in the upper half. The internal
2105 character code is the corresponding JIS character according to the EUC
2106 encoding algorithm. Only characters defined in the JIS code set table
2107 can be used with this encoding method.
2110 A wide character is represented using
2111 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
2112 10646-1/Am.2. Depending on the character value, the representation
2113 is a one, two, or three byte sequence:
2118 16#0000#-16#007f#: 2#0xxxxxxx#
2119 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
2120 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
2125 where the xxx bits correspond to the left-padded bits of the
2126 16-bit character value. Note that all lower half ASCII characters
2127 are represented as ASCII bytes and all upper half characters and
2128 other wide characters are represented as sequences of upper-half
2129 (The full UTF-8 scheme allows for encoding 31-bit characters as
2130 6-byte sequences, but in this implementation, all UTF-8 sequences
2131 of four or more bytes length will be treated as illegal).
2132 @item Brackets Coding
2133 In this encoding, a wide character is represented by the following eight
2141 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2142 characters (using uppercase letters) of the wide character code. For
2143 example, [``A345''] is used to represent the wide character with code
2144 @code{16#A345#}. It is also possible (though not required) to use the
2145 Brackets coding for upper half characters. For example, the code
2146 @code{16#A3#} can be represented as @code{[``A3'']}.
2148 This scheme is compatible with use of the full Wide_Character set,
2149 and is also the method used for wide character encoding in the standard
2150 ACVC (Ada Compiler Validation Capability) test suite distributions.
2155 Note: Some of these coding schemes do not permit the full use of the
2156 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
2157 use of the upper half of the Latin-1 set.
2159 @node File Naming Rules
2160 @section File Naming Rules
2163 The default file name is determined by the name of the unit that the
2164 file contains. The name is formed by taking the full expanded name of
2165 the unit and replacing the separating dots with hyphens and using
2166 ^lowercase^uppercase^ for all letters.
2168 An exception arises if the file name generated by the above rules starts
2169 with one of the characters
2176 and the second character is a
2177 minus. In this case, the character ^tilde^dollar sign^ is used in place
2178 of the minus. The reason for this special rule is to avoid clashes with
2179 the standard names for child units of the packages System, Ada,
2180 Interfaces, and GNAT, which use the prefixes
2189 The file extension is @file{.ads} for a spec and
2190 @file{.adb} for a body. The following list shows some
2191 examples of these rules.
2198 @item arith_functions.ads
2199 Arith_Functions (package spec)
2200 @item arith_functions.adb
2201 Arith_Functions (package body)
2203 Func.Spec (child package spec)
2205 Func.Spec (child package body)
2207 Sub (subunit of Main)
2208 @item ^a~bad.adb^A$BAD.ADB^
2209 A.Bad (child package body)
2213 Following these rules can result in excessively long
2214 file names if corresponding
2215 unit names are long (for example, if child units or subunits are
2216 heavily nested). An option is available to shorten such long file names
2217 (called file name ``krunching''). This may be particularly useful when
2218 programs being developed with GNAT are to be used on operating systems
2219 with limited file name lengths. @xref{Using gnatkr}.
2221 Of course, no file shortening algorithm can guarantee uniqueness over
2222 all possible unit names; if file name krunching is used, it is your
2223 responsibility to ensure no name clashes occur. Alternatively you
2224 can specify the exact file names that you want used, as described
2225 in the next section. Finally, if your Ada programs are migrating from a
2226 compiler with a different naming convention, you can use the gnatchop
2227 utility to produce source files that follow the GNAT naming conventions.
2228 (For details @pxref{Renaming Files Using gnatchop}.)
2230 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2231 systems, case is not significant. So for example on @code{Windows XP}
2232 if the canonical name is @code{main-sub.adb}, you can use the file name
2233 @code{Main-Sub.adb} instead. However, case is significant for other
2234 operating systems, so for example, if you want to use other than
2235 canonically cased file names on a Unix system, you need to follow
2236 the procedures described in the next section.
2238 @node Using Other File Names
2239 @section Using Other File Names
2243 In the previous section, we have described the default rules used by
2244 GNAT to determine the file name in which a given unit resides. It is
2245 often convenient to follow these default rules, and if you follow them,
2246 the compiler knows without being explicitly told where to find all
2249 However, in some cases, particularly when a program is imported from
2250 another Ada compiler environment, it may be more convenient for the
2251 programmer to specify which file names contain which units. GNAT allows
2252 arbitrary file names to be used by means of the Source_File_Name pragma.
2253 The form of this pragma is as shown in the following examples:
2254 @cindex Source_File_Name pragma
2256 @smallexample @c ada
2258 pragma Source_File_Name (My_Utilities.Stacks,
2259 Spec_File_Name => "myutilst_a.ada");
2260 pragma Source_File_name (My_Utilities.Stacks,
2261 Body_File_Name => "myutilst.ada");
2266 As shown in this example, the first argument for the pragma is the unit
2267 name (in this example a child unit). The second argument has the form
2268 of a named association. The identifier
2269 indicates whether the file name is for a spec or a body;
2270 the file name itself is given by a string literal.
2272 The source file name pragma is a configuration pragma, which means that
2273 normally it will be placed in the @file{gnat.adc}
2274 file used to hold configuration
2275 pragmas that apply to a complete compilation environment.
2276 For more details on how the @file{gnat.adc} file is created and used
2277 see @ref{Handling of Configuration Pragmas}.
2278 @cindex @file{gnat.adc}
2281 GNAT allows completely arbitrary file names to be specified using the
2282 source file name pragma. However, if the file name specified has an
2283 extension other than @file{.ads} or @file{.adb} it is necessary to use
2284 a special syntax when compiling the file. The name in this case must be
2285 preceded by the special sequence @code{-x} followed by a space and the name
2286 of the language, here @code{ada}, as in:
2289 $ gcc -c -x ada peculiar_file_name.sim
2294 @command{gnatmake} handles non-standard file names in the usual manner (the
2295 non-standard file name for the main program is simply used as the
2296 argument to gnatmake). Note that if the extension is also non-standard,
2297 then it must be included in the gnatmake command, it may not be omitted.
2299 @node Alternative File Naming Schemes
2300 @section Alternative File Naming Schemes
2301 @cindex File naming schemes, alternative
2304 In the previous section, we described the use of the @code{Source_File_Name}
2305 pragma to allow arbitrary names to be assigned to individual source files.
2306 However, this approach requires one pragma for each file, and especially in
2307 large systems can result in very long @file{gnat.adc} files, and also create
2308 a maintenance problem.
2310 GNAT also provides a facility for specifying systematic file naming schemes
2311 other than the standard default naming scheme previously described. An
2312 alternative scheme for naming is specified by the use of
2313 @code{Source_File_Name} pragmas having the following format:
2314 @cindex Source_File_Name pragma
2316 @smallexample @c ada
2317 pragma Source_File_Name (
2318 Spec_File_Name => FILE_NAME_PATTERN
2319 [,Casing => CASING_SPEC]
2320 [,Dot_Replacement => STRING_LITERAL]);
2322 pragma Source_File_Name (
2323 Body_File_Name => FILE_NAME_PATTERN
2324 [,Casing => CASING_SPEC]
2325 [,Dot_Replacement => STRING_LITERAL]);
2327 pragma Source_File_Name (
2328 Subunit_File_Name => FILE_NAME_PATTERN
2329 [,Casing => CASING_SPEC]
2330 [,Dot_Replacement => STRING_LITERAL]);
2332 FILE_NAME_PATTERN ::= STRING_LITERAL
2333 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2337 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2338 It contains a single asterisk character, and the unit name is substituted
2339 systematically for this asterisk. The optional parameter
2340 @code{Casing} indicates
2341 whether the unit name is to be all upper-case letters, all lower-case letters,
2342 or mixed-case. If no
2343 @code{Casing} parameter is used, then the default is all
2344 ^lower-case^upper-case^.
2346 The optional @code{Dot_Replacement} string is used to replace any periods
2347 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2348 argument is used then separating dots appear unchanged in the resulting
2350 Although the above syntax indicates that the
2351 @code{Casing} argument must appear
2352 before the @code{Dot_Replacement} argument, but it
2353 is also permissible to write these arguments in the opposite order.
2355 As indicated, it is possible to specify different naming schemes for
2356 bodies, specs, and subunits. Quite often the rule for subunits is the
2357 same as the rule for bodies, in which case, there is no need to give
2358 a separate @code{Subunit_File_Name} rule, and in this case the
2359 @code{Body_File_name} rule is used for subunits as well.
2361 The separate rule for subunits can also be used to implement the rather
2362 unusual case of a compilation environment (e.g. a single directory) which
2363 contains a subunit and a child unit with the same unit name. Although
2364 both units cannot appear in the same partition, the Ada Reference Manual
2365 allows (but does not require) the possibility of the two units coexisting
2366 in the same environment.
2368 The file name translation works in the following steps:
2373 If there is a specific @code{Source_File_Name} pragma for the given unit,
2374 then this is always used, and any general pattern rules are ignored.
2377 If there is a pattern type @code{Source_File_Name} pragma that applies to
2378 the unit, then the resulting file name will be used if the file exists. If
2379 more than one pattern matches, the latest one will be tried first, and the
2380 first attempt resulting in a reference to a file that exists will be used.
2383 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2384 for which the corresponding file exists, then the standard GNAT default
2385 naming rules are used.
2390 As an example of the use of this mechanism, consider a commonly used scheme
2391 in which file names are all lower case, with separating periods copied
2392 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2393 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2396 @smallexample @c ada
2397 pragma Source_File_Name
2398 (Spec_File_Name => "*.1.ada");
2399 pragma Source_File_Name
2400 (Body_File_Name => "*.2.ada");
2404 The default GNAT scheme is actually implemented by providing the following
2405 default pragmas internally:
2407 @smallexample @c ada
2408 pragma Source_File_Name
2409 (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2410 pragma Source_File_Name
2411 (Body_File_Name => "*.adb", Dot_Replacement => "-");
2415 Our final example implements a scheme typically used with one of the
2416 Ada 83 compilers, where the separator character for subunits was ``__''
2417 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2418 by adding @file{.ADA}, and subunits by
2419 adding @file{.SEP}. All file names were
2420 upper case. Child units were not present of course since this was an
2421 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2422 the same double underscore separator for child units.
2424 @smallexample @c ada
2425 pragma Source_File_Name
2426 (Spec_File_Name => "*_.ADA",
2427 Dot_Replacement => "__",
2428 Casing = Uppercase);
2429 pragma Source_File_Name
2430 (Body_File_Name => "*.ADA",
2431 Dot_Replacement => "__",
2432 Casing = Uppercase);
2433 pragma Source_File_Name
2434 (Subunit_File_Name => "*.SEP",
2435 Dot_Replacement => "__",
2436 Casing = Uppercase);
2439 @node Generating Object Files
2440 @section Generating Object Files
2443 An Ada program consists of a set of source files, and the first step in
2444 compiling the program is to generate the corresponding object files.
2445 These are generated by compiling a subset of these source files.
2446 The files you need to compile are the following:
2450 If a package spec has no body, compile the package spec to produce the
2451 object file for the package.
2454 If a package has both a spec and a body, compile the body to produce the
2455 object file for the package. The source file for the package spec need
2456 not be compiled in this case because there is only one object file, which
2457 contains the code for both the spec and body of the package.
2460 For a subprogram, compile the subprogram body to produce the object file
2461 for the subprogram. The spec, if one is present, is as usual in a
2462 separate file, and need not be compiled.
2466 In the case of subunits, only compile the parent unit. A single object
2467 file is generated for the entire subunit tree, which includes all the
2471 Compile child units independently of their parent units
2472 (though, of course, the spec of all the ancestor unit must be present in order
2473 to compile a child unit).
2477 Compile generic units in the same manner as any other units. The object
2478 files in this case are small dummy files that contain at most the
2479 flag used for elaboration checking. This is because GNAT always handles generic
2480 instantiation by means of macro expansion. However, it is still necessary to
2481 compile generic units, for dependency checking and elaboration purposes.
2485 The preceding rules describe the set of files that must be compiled to
2486 generate the object files for a program. Each object file has the same
2487 name as the corresponding source file, except that the extension is
2490 You may wish to compile other files for the purpose of checking their
2491 syntactic and semantic correctness. For example, in the case where a
2492 package has a separate spec and body, you would not normally compile the
2493 spec. However, it is convenient in practice to compile the spec to make
2494 sure it is error-free before compiling clients of this spec, because such
2495 compilations will fail if there is an error in the spec.
2497 GNAT provides an option for compiling such files purely for the
2498 purposes of checking correctness; such compilations are not required as
2499 part of the process of building a program. To compile a file in this
2500 checking mode, use the @option{-gnatc} switch.
2502 @node Source Dependencies
2503 @section Source Dependencies
2506 A given object file clearly depends on the source file which is compiled
2507 to produce it. Here we are using @dfn{depends} in the sense of a typical
2508 @code{make} utility; in other words, an object file depends on a source
2509 file if changes to the source file require the object file to be
2511 In addition to this basic dependency, a given object may depend on
2512 additional source files as follows:
2516 If a file being compiled @code{with}'s a unit @var{X}, the object file
2517 depends on the file containing the spec of unit @var{X}. This includes
2518 files that are @code{with}'ed implicitly either because they are parents
2519 of @code{with}'ed child units or they are run-time units required by the
2520 language constructs used in a particular unit.
2523 If a file being compiled instantiates a library level generic unit, the
2524 object file depends on both the spec and body files for this generic
2528 If a file being compiled instantiates a generic unit defined within a
2529 package, the object file depends on the body file for the package as
2530 well as the spec file.
2534 @cindex @option{-gnatn} switch
2535 If a file being compiled contains a call to a subprogram for which
2536 pragma @code{Inline} applies and inlining is activated with the
2537 @option{-gnatn} switch, the object file depends on the file containing the
2538 body of this subprogram as well as on the file containing the spec. Note
2539 that for inlining to actually occur as a result of the use of this switch,
2540 it is necessary to compile in optimizing mode.
2542 @cindex @option{-gnatN} switch
2543 The use of @option{-gnatN} activates a more extensive inlining optimization
2544 that is performed by the front end of the compiler. This inlining does
2545 not require that the code generation be optimized. Like @option{-gnatn},
2546 the use of this switch generates additional dependencies.
2548 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
2549 to specify both options.
2552 If an object file O depends on the proper body of a subunit through inlining
2553 or instantiation, it depends on the parent unit of the subunit. This means that
2554 any modification of the parent unit or one of its subunits affects the
2558 The object file for a parent unit depends on all its subunit body files.
2561 The previous two rules meant that for purposes of computing dependencies and
2562 recompilation, a body and all its subunits are treated as an indivisible whole.
2565 These rules are applied transitively: if unit @code{A} @code{with}'s
2566 unit @code{B}, whose elaboration calls an inlined procedure in package
2567 @code{C}, the object file for unit @code{A} will depend on the body of
2568 @code{C}, in file @file{c.adb}.
2570 The set of dependent files described by these rules includes all the
2571 files on which the unit is semantically dependent, as described in the
2572 Ada 95 Language Reference Manual. However, it is a superset of what the
2573 ARM describes, because it includes generic, inline, and subunit dependencies.
2575 An object file must be recreated by recompiling the corresponding source
2576 file if any of the source files on which it depends are modified. For
2577 example, if the @code{make} utility is used to control compilation,
2578 the rule for an Ada object file must mention all the source files on
2579 which the object file depends, according to the above definition.
2580 The determination of the necessary
2581 recompilations is done automatically when one uses @command{gnatmake}.
2584 @node The Ada Library Information Files
2585 @section The Ada Library Information Files
2586 @cindex Ada Library Information files
2587 @cindex @file{ALI} files
2590 Each compilation actually generates two output files. The first of these
2591 is the normal object file that has a @file{.o} extension. The second is a
2592 text file containing full dependency information. It has the same
2593 name as the source file, but an @file{.ali} extension.
2594 This file is known as the Ada Library Information (@file{ALI}) file.
2595 The following information is contained in the @file{ALI} file.
2599 Version information (indicates which version of GNAT was used to compile
2600 the unit(s) in question)
2603 Main program information (including priority and time slice settings,
2604 as well as the wide character encoding used during compilation).
2607 List of arguments used in the @command{gcc} command for the compilation
2610 Attributes of the unit, including configuration pragmas used, an indication
2611 of whether the compilation was successful, exception model used etc.
2614 A list of relevant restrictions applying to the unit (used for consistency)
2618 Categorization information (e.g. use of pragma @code{Pure}).
2621 Information on all @code{with}'ed units, including presence of
2622 @code{Elaborate} or @code{Elaborate_All} pragmas.
2625 Information from any @code{Linker_Options} pragmas used in the unit
2628 Information on the use of @code{Body_Version} or @code{Version}
2629 attributes in the unit.
2632 Dependency information. This is a list of files, together with
2633 time stamp and checksum information. These are files on which
2634 the unit depends in the sense that recompilation is required
2635 if any of these units are modified.
2638 Cross-reference data. Contains information on all entities referenced
2639 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2640 provide cross-reference information.
2645 For a full detailed description of the format of the @file{ALI} file,
2646 see the source of the body of unit @code{Lib.Writ}, contained in file
2647 @file{lib-writ.adb} in the GNAT compiler sources.
2649 @node Binding an Ada Program
2650 @section Binding an Ada Program
2653 When using languages such as C and C++, once the source files have been
2654 compiled the only remaining step in building an executable program
2655 is linking the object modules together. This means that it is possible to
2656 link an inconsistent version of a program, in which two units have
2657 included different versions of the same header.
2659 The rules of Ada do not permit such an inconsistent program to be built.
2660 For example, if two clients have different versions of the same package,
2661 it is illegal to build a program containing these two clients.
2662 These rules are enforced by the GNAT binder, which also determines an
2663 elaboration order consistent with the Ada rules.
2665 The GNAT binder is run after all the object files for a program have
2666 been created. It is given the name of the main program unit, and from
2667 this it determines the set of units required by the program, by reading the
2668 corresponding ALI files. It generates error messages if the program is
2669 inconsistent or if no valid order of elaboration exists.
2671 If no errors are detected, the binder produces a main program, in Ada by
2672 default, that contains calls to the elaboration procedures of those
2673 compilation unit that require them, followed by
2674 a call to the main program. This Ada program is compiled to generate the
2675 object file for the main program. The name of
2676 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2677 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2680 Finally, the linker is used to build the resulting executable program,
2681 using the object from the main program from the bind step as well as the
2682 object files for the Ada units of the program.
2684 @node Mixed Language Programming
2685 @section Mixed Language Programming
2686 @cindex Mixed Language Programming
2689 This section describes how to develop a mixed-language program,
2690 specifically one that comprises units in both Ada and C.
2693 * Interfacing to C::
2694 * Calling Conventions::
2697 @node Interfacing to C
2698 @subsection Interfacing to C
2700 Interfacing Ada with a foreign language such as C involves using
2701 compiler directives to import and/or export entity definitions in each
2702 language---using @code{extern} statements in C, for instance, and the
2703 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada. For
2704 a full treatment of these topics, read Appendix B, section 1 of the Ada
2705 95 Language Reference Manual.
2707 There are two ways to build a program using GNAT that contains some Ada
2708 sources and some foreign language sources, depending on whether or not
2709 the main subprogram is written in Ada. Here is a source example with
2710 the main subprogram in Ada:
2716 void print_num (int num)
2718 printf ("num is %d.\n", num);
2724 /* num_from_Ada is declared in my_main.adb */
2725 extern int num_from_Ada;
2729 return num_from_Ada;
2733 @smallexample @c ada
2735 procedure My_Main is
2737 -- Declare then export an Integer entity called num_from_Ada
2738 My_Num : Integer := 10;
2739 pragma Export (C, My_Num, "num_from_Ada");
2741 -- Declare an Ada function spec for Get_Num, then use
2742 -- C function get_num for the implementation.
2743 function Get_Num return Integer;
2744 pragma Import (C, Get_Num, "get_num");
2746 -- Declare an Ada procedure spec for Print_Num, then use
2747 -- C function print_num for the implementation.
2748 procedure Print_Num (Num : Integer);
2749 pragma Import (C, Print_Num, "print_num");
2752 Print_Num (Get_Num);
2758 To build this example, first compile the foreign language files to
2759 generate object files:
2766 Then, compile the Ada units to produce a set of object files and ALI
2769 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2773 Run the Ada binder on the Ada main program:
2775 gnatbind my_main.ali
2779 Link the Ada main program, the Ada objects and the other language
2782 gnatlink my_main.ali file1.o file2.o
2786 The last three steps can be grouped in a single command:
2788 gnatmake my_main.adb -largs file1.o file2.o
2791 @cindex Binder output file
2793 If the main program is in a language other than Ada, then you may have
2794 more than one entry point into the Ada subsystem. You must use a special
2795 binder option to generate callable routines that initialize and
2796 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2797 Calls to the initialization and finalization routines must be inserted
2798 in the main program, or some other appropriate point in the code. The
2799 call to initialize the Ada units must occur before the first Ada
2800 subprogram is called, and the call to finalize the Ada units must occur
2801 after the last Ada subprogram returns. The binder will place the
2802 initialization and finalization subprograms into the
2803 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2804 sources. To illustrate, we have the following example:
2808 extern void adainit (void);
2809 extern void adafinal (void);
2810 extern int add (int, int);
2811 extern int sub (int, int);
2813 int main (int argc, char *argv[])
2819 /* Should print "21 + 7 = 28" */
2820 printf ("%d + %d = %d\n", a, b, add (a, b));
2821 /* Should print "21 - 7 = 14" */
2822 printf ("%d - %d = %d\n", a, b, sub (a, b));
2828 @smallexample @c ada
2831 function Add (A, B : Integer) return Integer;
2832 pragma Export (C, Add, "add");
2836 package body Unit1 is
2837 function Add (A, B : Integer) return Integer is
2845 function Sub (A, B : Integer) return Integer;
2846 pragma Export (C, Sub, "sub");
2850 package body Unit2 is
2851 function Sub (A, B : Integer) return Integer is
2860 The build procedure for this application is similar to the last
2861 example's. First, compile the foreign language files to generate object
2864 ^gcc -c main.c^gcc -c main.c^
2868 Next, compile the Ada units to produce a set of object files and ALI
2871 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2872 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2876 Run the Ada binder on every generated ALI file. Make sure to use the
2877 @option{-n} option to specify a foreign main program:
2879 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2883 Link the Ada main program, the Ada objects and the foreign language
2884 objects. You need only list the last ALI file here:
2886 gnatlink unit2.ali main.o -o exec_file
2889 This procedure yields a binary executable called @file{exec_file}.
2892 @node Calling Conventions
2893 @subsection Calling Conventions
2894 @cindex Foreign Languages
2895 @cindex Calling Conventions
2896 GNAT follows standard calling sequence conventions and will thus interface
2897 to any other language that also follows these conventions. The following
2898 Convention identifiers are recognized by GNAT:
2901 @cindex Interfacing to Ada
2902 @cindex Other Ada compilers
2903 @cindex Convention Ada
2905 This indicates that the standard Ada calling sequence will be
2906 used and all Ada data items may be passed without any limitations in the
2907 case where GNAT is used to generate both the caller and callee. It is also
2908 possible to mix GNAT generated code and code generated by another Ada
2909 compiler. In this case, the data types should be restricted to simple
2910 cases, including primitive types. Whether complex data types can be passed
2911 depends on the situation. Probably it is safe to pass simple arrays, such
2912 as arrays of integers or floats. Records may or may not work, depending
2913 on whether both compilers lay them out identically. Complex structures
2914 involving variant records, access parameters, tasks, or protected types,
2915 are unlikely to be able to be passed.
2917 Note that in the case of GNAT running
2918 on a platform that supports DEC Ada 83, a higher degree of compatibility
2919 can be guaranteed, and in particular records are layed out in an identical
2920 manner in the two compilers. Note also that if output from two different
2921 compilers is mixed, the program is responsible for dealing with elaboration
2922 issues. Probably the safest approach is to write the main program in the
2923 version of Ada other than GNAT, so that it takes care of its own elaboration
2924 requirements, and then call the GNAT-generated adainit procedure to ensure
2925 elaboration of the GNAT components. Consult the documentation of the other
2926 Ada compiler for further details on elaboration.
2928 However, it is not possible to mix the tasking run time of GNAT and
2929 DEC Ada 83, All the tasking operations must either be entirely within
2930 GNAT compiled sections of the program, or entirely within DEC Ada 83
2931 compiled sections of the program.
2933 @cindex Interfacing to Assembly
2934 @cindex Convention Assembler
2936 Specifies assembler as the convention. In practice this has the
2937 same effect as convention Ada (but is not equivalent in the sense of being
2938 considered the same convention).
2940 @cindex Convention Asm
2943 Equivalent to Assembler.
2945 @cindex Interfacing to COBOL
2946 @cindex Convention COBOL
2949 Data will be passed according to the conventions described
2950 in section B.4 of the Ada 95 Reference Manual.
2953 @cindex Interfacing to C
2954 @cindex Convention C
2956 Data will be passed according to the conventions described
2957 in section B.3 of the Ada 95 Reference Manual.
2959 @findex C varargs function
2960 @cindex Intefacing to C varargs function
2961 @cindex varargs function interfaces
2962 @item C varargs function
2963 In C, @code{varargs} allows a function to take a variable number of
2964 arguments. There is no direct equivalent in this to Ada. One
2965 approach that can be used is to create a C wrapper for each
2966 different profile and then interface to this C wrapper. For
2967 example, to print an @code{int} value using @code{printf},
2968 create a C function @code{printfi} that takes two arguments, a
2969 pointer to a string and an int, and calls @code{printf}.
2970 Then in the Ada program, use pragma @code{Import} to
2971 interface to printfi.
2973 It may work on some platforms to directly interface to
2974 a @code{varargs} function by providing a specific Ada profile
2975 for a a particular call. However, this does not work on
2976 all platforms, since there is no guarantee that the
2977 calling sequence for a two argument normal C function
2978 is the same as for calling a @code{varargs} C function with
2979 the same two arguments.
2981 @cindex Convention Default
2986 @cindex Convention External
2992 @cindex Interfacing to C++
2993 @cindex Convention C++
2995 This stands for C++. For most purposes this is identical to C.
2996 See the separate description of the specialized GNAT pragmas relating to
2997 C++ interfacing for further details.
3000 @cindex Interfacing to Fortran
3001 @cindex Convention Fortran
3003 Data will be passed according to the conventions described
3004 in section B.5 of the Ada 95 Reference Manual.
3007 This applies to an intrinsic operation, as defined in the Ada 95
3008 Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram,
3009 this means that the body of the subprogram is provided by the compiler itself,
3010 usually by means of an efficient code sequence, and that the user does not
3011 supply an explicit body for it. In an application program, the pragma can
3012 only be applied to the following two sets of names, which the GNAT compiler
3017 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_-
3018 Arithmetic. The corresponding subprogram declaration must have
3019 two formal parameters. The
3020 first one must be a signed integer type or a modular type with a binary
3021 modulus, and the second parameter must be of type Natural.
3022 The return type must be the same as the type of the first argument. The size
3023 of this type can only be 8, 16, 32, or 64.
3024 @item binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
3025 The corresponding operator declaration must have parameters and result type
3026 that have the same root numeric type (for example, all three are long_float
3027 types). This simplifies the definition of operations that use type checking
3028 to perform dimensional checks:
3030 @smallexample @c ada
3031 type Distance is new Long_Float;
3032 type Time is new Long_Float;
3033 type Velocity is new Long_Float;
3034 function "/" (D : Distance; T : Time)
3036 pragma Import (Intrinsic, "/");
3040 This common idiom is often programmed with a generic definition and an
3041 explicit body. The pragma makes it simpler to introduce such declarations.
3042 It incurs no overhead in compilation time or code size, because it is
3043 implemented as a single machine instruction.
3049 @cindex Convention Stdcall
3051 This is relevant only to NT/Win95 implementations of GNAT,
3052 and specifies that the Stdcall calling sequence will be used, as defined
3053 by the NT API. Nevertheless, to ease building cross-platform bindings this
3054 convention will be handled as a C calling convention on non Windows
3058 @cindex Convention DLL
3060 This is equivalent to Stdcall.
3063 @cindex Convention Win32
3065 This is equivalent to Stdcall.
3069 @cindex Convention Stubbed
3071 This is a special convention that indicates that the compiler
3072 should provide a stub body that raises @code{Program_Error}.
3076 GNAT additionally provides a useful pragma @code{Convention_Identifier}
3077 that can be used to parametrize conventions and allow additional synonyms
3078 to be specified. For example if you have legacy code in which the convention
3079 identifier Fortran77 was used for Fortran, you can use the configuration
3082 @smallexample @c ada
3083 pragma Convention_Identifier (Fortran77, Fortran);
3087 And from now on the identifier Fortran77 may be used as a convention
3088 identifier (for example in an @code{Import} pragma) with the same
3091 @node Building Mixed Ada & C++ Programs
3092 @section Building Mixed Ada & C++ Programs
3095 A programmer inexperienced with mixed-language development may find that
3096 building an application containing both Ada and C++ code can be a
3097 challenge. As a matter of fact, interfacing with C++ has not been
3098 standardized in the Ada 95 Reference Manual due to the immaturity of --
3099 and lack of standards for -- C++ at the time. This section gives a few
3100 hints that should make this task easier. The first section addresses
3101 the differences regarding interfacing with C. The second section
3102 looks into the delicate problem of linking the complete application from
3103 its Ada and C++ parts. The last section gives some hints on how the GNAT
3104 run time can be adapted in order to allow inter-language dispatching
3105 with a new C++ compiler.
3108 * Interfacing to C++::
3109 * Linking a Mixed C++ & Ada Program::
3110 * A Simple Example::
3111 * Adapting the Run Time to a New C++ Compiler::
3114 @node Interfacing to C++
3115 @subsection Interfacing to C++
3118 GNAT supports interfacing with C++ compilers generating code that is
3119 compatible with the standard Application Binary Interface of the given
3123 Interfacing can be done at 3 levels: simple data, subprograms, and
3124 classes. In the first two cases, GNAT offers a specific @var{Convention
3125 CPP} that behaves exactly like @var{Convention C}. Usually, C++ mangles
3126 the names of subprograms, and currently, GNAT does not provide any help
3127 to solve the demangling problem. This problem can be addressed in two
3131 by modifying the C++ code in order to force a C convention using
3132 the @code{extern "C"} syntax.
3135 by figuring out the mangled name and use it as the Link_Name argument of
3140 Interfacing at the class level can be achieved by using the GNAT specific
3141 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
3142 Reference Manual for additional information.
3144 @node Linking a Mixed C++ & Ada Program
3145 @subsection Linking a Mixed C++ & Ada Program
3148 Usually the linker of the C++ development system must be used to link
3149 mixed applications because most C++ systems will resolve elaboration
3150 issues (such as calling constructors on global class instances)
3151 transparently during the link phase. GNAT has been adapted to ease the
3152 use of a foreign linker for the last phase. Three cases can be
3157 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3158 The C++ linker can simply be called by using the C++ specific driver
3159 called @code{c++}. Note that this setup is not very common because it
3160 may involve recompiling the whole GCC tree from sources, which makes it
3161 harder to upgrade the compilation system for one language without
3162 destabilizing the other.
3167 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
3171 Using GNAT and G++ from two different GCC installations: If both
3172 compilers are on the PATH, the previous method may be used. It is
3173 important to note that environment variables such as C_INCLUDE_PATH,
3174 GCC_EXEC_PREFIX, BINUTILS_ROOT, and GCC_ROOT will affect both compilers
3175 at the same time and may make one of the two compilers operate
3176 improperly if set during invocation of the wrong compiler. It is also
3177 very important that the linker uses the proper @file{libgcc.a} GCC
3178 library -- that is, the one from the C++ compiler installation. The
3179 implicit link command as suggested in the gnatmake command from the
3180 former example can be replaced by an explicit link command with the
3181 full-verbosity option in order to verify which library is used:
3184 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3186 If there is a problem due to interfering environment variables, it can
3187 be worked around by using an intermediate script. The following example
3188 shows the proper script to use when GNAT has not been installed at its
3189 default location and g++ has been installed at its default location:
3197 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3201 Using a non-GNU C++ compiler: The commands previously described can be
3202 used to insure that the C++ linker is used. Nonetheless, you need to add
3203 a few more parameters to the link command line, depending on the exception
3206 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3207 to the libgcc libraries are required:
3212 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3213 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3216 Where CC is the name of the non-GNU C++ compiler.
3218 If the @code{zero cost} exception mechanism is used, and the platform
3219 supports automatic registration of exception tables (e.g. Solaris or IRIX),
3220 paths to more objects are required:
3225 CC `gcc -print-file-name=crtbegin.o` $* \
3226 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3227 `gcc -print-file-name=crtend.o`
3228 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3231 If the @code{zero cost} exception mechanism is used, and the platform
3232 doesn't support automatic registration of exception tables (e.g. HP-UX,
3233 Tru64 or AIX), the simple approach described above will not work and
3234 a pre-linking phase using GNAT will be necessary.
3238 @node A Simple Example
3239 @subsection A Simple Example
3241 The following example, provided as part of the GNAT examples, shows how
3242 to achieve procedural interfacing between Ada and C++ in both
3243 directions. The C++ class A has two methods. The first method is exported
3244 to Ada by the means of an extern C wrapper function. The second method
3245 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3246 a limited record with a layout comparable to the C++ class. The Ada
3247 subprogram, in turn, calls the C++ method. So, starting from the C++
3248 main program, the process passes back and forth between the two
3252 Here are the compilation commands:
3254 $ gnatmake -c simple_cpp_interface
3257 $ gnatbind -n simple_cpp_interface
3258 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3259 -lstdc++ ex7.o cpp_main.o
3263 Here are the corresponding sources:
3271 void adainit (void);
3272 void adafinal (void);
3273 void method1 (A *t);
3295 class A : public Origin @{
3297 void method1 (void);
3298 void method2 (int v);
3308 extern "C" @{ void ada_method2 (A *t, int v);@}
3310 void A::method1 (void)
3313 printf ("in A::method1, a_value = %d \n",a_value);
3317 void A::method2 (int v)
3319 ada_method2 (this, v);
3320 printf ("in A::method2, a_value = %d \n",a_value);
3327 printf ("in A::A, a_value = %d \n",a_value);
3331 @b{package} @b{body} Simple_Cpp_Interface @b{is}
3333 @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
3337 @b{end} Ada_Method2;
3339 @b{end} Simple_Cpp_Interface;
3341 @b{package} Simple_Cpp_Interface @b{is}
3342 @b{type} A @b{is} @b{limited}
3347 @b{pragma} Convention (C, A);
3349 @b{procedure} Method1 (This : @b{in} @b{out} A);
3350 @b{pragma} Import (C, Method1);
3352 @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
3353 @b{pragma} Export (C, Ada_Method2);
3355 @b{end} Simple_Cpp_Interface;
3358 @node Adapting the Run Time to a New C++ Compiler
3359 @subsection Adapting the Run Time to a New C++ Compiler
3361 GNAT offers the capability to derive Ada 95 tagged types directly from
3362 preexisting C++ classes and . See ``Interfacing with C++'' in the
3363 @cite{GNAT Reference Manual}. The mechanism used by GNAT for achieving
3365 has been made user configurable through a GNAT library unit
3366 @code{Interfaces.CPP}. The default version of this file is adapted to
3367 the GNU C++ compiler. Internal knowledge of the virtual
3368 table layout used by the new C++ compiler is needed to configure
3369 properly this unit. The Interface of this unit is known by the compiler
3370 and cannot be changed except for the value of the constants defining the
3371 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
3372 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
3373 of this unit for more details.
3375 @node Comparison between GNAT and C/C++ Compilation Models
3376 @section Comparison between GNAT and C/C++ Compilation Models
3379 The GNAT model of compilation is close to the C and C++ models. You can
3380 think of Ada specs as corresponding to header files in C. As in C, you
3381 don't need to compile specs; they are compiled when they are used. The
3382 Ada @code{with} is similar in effect to the @code{#include} of a C
3385 One notable difference is that, in Ada, you may compile specs separately
3386 to check them for semantic and syntactic accuracy. This is not always
3387 possible with C headers because they are fragments of programs that have
3388 less specific syntactic or semantic rules.
3390 The other major difference is the requirement for running the binder,
3391 which performs two important functions. First, it checks for
3392 consistency. In C or C++, the only defense against assembling
3393 inconsistent programs lies outside the compiler, in a makefile, for
3394 example. The binder satisfies the Ada requirement that it be impossible
3395 to construct an inconsistent program when the compiler is used in normal
3398 @cindex Elaboration order control
3399 The other important function of the binder is to deal with elaboration
3400 issues. There are also elaboration issues in C++ that are handled
3401 automatically. This automatic handling has the advantage of being
3402 simpler to use, but the C++ programmer has no control over elaboration.
3403 Where @code{gnatbind} might complain there was no valid order of
3404 elaboration, a C++ compiler would simply construct a program that
3405 malfunctioned at run time.
3407 @node Comparison between GNAT and Conventional Ada Library Models
3408 @section Comparison between GNAT and Conventional Ada Library Models
3411 This section is intended to be useful to Ada programmers who have
3412 previously used an Ada compiler implementing the traditional Ada library
3413 model, as described in the Ada 95 Language Reference Manual. If you
3414 have not used such a system, please go on to the next section.
3416 @cindex GNAT library
3417 In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of
3418 source files themselves acts as the library. Compiling Ada programs does
3419 not generate any centralized information, but rather an object file and
3420 a ALI file, which are of interest only to the binder and linker.
3421 In a traditional system, the compiler reads information not only from
3422 the source file being compiled, but also from the centralized library.
3423 This means that the effect of a compilation depends on what has been
3424 previously compiled. In particular:
3428 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3429 to the version of the unit most recently compiled into the library.
3432 Inlining is effective only if the necessary body has already been
3433 compiled into the library.
3436 Compiling a unit may obsolete other units in the library.
3440 In GNAT, compiling one unit never affects the compilation of any other
3441 units because the compiler reads only source files. Only changes to source
3442 files can affect the results of a compilation. In particular:
3446 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3447 to the source version of the unit that is currently accessible to the
3452 Inlining requires the appropriate source files for the package or
3453 subprogram bodies to be available to the compiler. Inlining is always
3454 effective, independent of the order in which units are complied.
3457 Compiling a unit never affects any other compilations. The editing of
3458 sources may cause previous compilations to be out of date if they
3459 depended on the source file being modified.
3463 The most important result of these differences is that order of compilation
3464 is never significant in GNAT. There is no situation in which one is
3465 required to do one compilation before another. What shows up as order of
3466 compilation requirements in the traditional Ada library becomes, in
3467 GNAT, simple source dependencies; in other words, there is only a set
3468 of rules saying what source files must be present when a file is
3472 @node Placement of temporary files
3473 @section Placement of temporary files
3474 @cindex Temporary files (user control over placement)
3477 GNAT creates temporary files in the directory designated by the environment
3478 variable @env{TMPDIR}.
3479 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3480 for detailed information on how environment variables are resolved.
3481 For most users the easiest way to make use of this feature is to simply
3482 define @env{TMPDIR} as a job level logical name).
3483 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3484 for compiler temporary files, then you can include something like the
3485 following command in your @file{LOGIN.COM} file:
3488 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3492 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3493 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3494 designated by @env{TEMP}.
3495 If none of these environment variables are defined then GNAT uses the
3496 directory designated by the logical name @code{SYS$SCRATCH:}
3497 (by default the user's home directory). If all else fails
3498 GNAT uses the current directory for temporary files.
3501 @c *************************
3502 @node Compiling Using gcc
3503 @chapter Compiling Using @command{gcc}
3506 This chapter discusses how to compile Ada programs using the @command{gcc}
3507 command. It also describes the set of switches
3508 that can be used to control the behavior of the compiler.
3510 * Compiling Programs::
3511 * Switches for gcc::
3512 * Search Paths and the Run-Time Library (RTL)::
3513 * Order of Compilation Issues::
3517 @node Compiling Programs
3518 @section Compiling Programs
3521 The first step in creating an executable program is to compile the units
3522 of the program using the @command{gcc} command. You must compile the
3527 the body file (@file{.adb}) for a library level subprogram or generic
3531 the spec file (@file{.ads}) for a library level package or generic
3532 package that has no body
3535 the body file (@file{.adb}) for a library level package
3536 or generic package that has a body
3541 You need @emph{not} compile the following files
3546 the spec of a library unit which has a body
3553 because they are compiled as part of compiling related units. GNAT
3555 when the corresponding body is compiled, and subunits when the parent is
3558 @cindex cannot generate code
3559 If you attempt to compile any of these files, you will get one of the
3560 following error messages (where fff is the name of the file you compiled):
3563 cannot generate code for file @var{fff} (package spec)
3564 to check package spec, use -gnatc
3566 cannot generate code for file @var{fff} (missing subunits)
3567 to check parent unit, use -gnatc
3569 cannot generate code for file @var{fff} (subprogram spec)
3570 to check subprogram spec, use -gnatc
3572 cannot generate code for file @var{fff} (subunit)
3573 to check subunit, use -gnatc
3577 As indicated by the above error messages, if you want to submit
3578 one of these files to the compiler to check for correct semantics
3579 without generating code, then use the @option{-gnatc} switch.
3581 The basic command for compiling a file containing an Ada unit is
3584 $ gcc -c [@var{switches}] @file{file name}
3588 where @var{file name} is the name of the Ada file (usually
3590 @file{.ads} for a spec or @file{.adb} for a body).
3593 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3595 The result of a successful compilation is an object file, which has the
3596 same name as the source file but an extension of @file{.o} and an Ada
3597 Library Information (ALI) file, which also has the same name as the
3598 source file, but with @file{.ali} as the extension. GNAT creates these
3599 two output files in the current directory, but you may specify a source
3600 file in any directory using an absolute or relative path specification
3601 containing the directory information.
3604 @command{gcc} is actually a driver program that looks at the extensions of
3605 the file arguments and loads the appropriate compiler. For example, the
3606 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3607 These programs are in directories known to the driver program (in some
3608 configurations via environment variables you set), but need not be in
3609 your path. The @command{gcc} driver also calls the assembler and any other
3610 utilities needed to complete the generation of the required object
3613 It is possible to supply several file names on the same @command{gcc}
3614 command. This causes @command{gcc} to call the appropriate compiler for
3615 each file. For example, the following command lists three separate
3616 files to be compiled:
3619 $ gcc -c x.adb y.adb z.c
3623 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3624 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3625 The compiler generates three object files @file{x.o}, @file{y.o} and
3626 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3627 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3630 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3633 @node Switches for gcc
3634 @section Switches for @command{gcc}
3637 The @command{gcc} command accepts switches that control the
3638 compilation process. These switches are fully described in this section.
3639 First we briefly list all the switches, in alphabetical order, then we
3640 describe the switches in more detail in functionally grouped sections.
3642 More switches exist for GCC than those documented here, especially
3643 for specific targets. However, their use is not recommended as
3644 they may change code generation in ways that are incompatible with
3645 the Ada run-time library, or can cause inconsistencies between
3649 * Output and Error Message Control::
3650 * Warning Message Control::
3651 * Debugging and Assertion Control::
3652 * Validity Checking::
3655 * Stack Overflow Checking::
3656 * Using gcc for Syntax Checking::
3657 * Using gcc for Semantic Checking::
3658 * Compiling Different Versions of Ada::
3659 * Character Set Control::
3660 * File Naming Control::
3661 * Subprogram Inlining Control::
3662 * Auxiliary Output Control::
3663 * Debugging Control::
3664 * Exception Handling Control::
3665 * Units to Sources Mapping Files::
3666 * Integrated Preprocessing::
3667 * Code Generation Control::
3676 @cindex @option{-b} (@command{gcc})
3677 @item -b @var{target}
3678 Compile your program to run on @var{target}, which is the name of a
3679 system configuration. You must have a GNAT cross-compiler built if
3680 @var{target} is not the same as your host system.
3683 @cindex @option{-B} (@command{gcc})
3684 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3685 from @var{dir} instead of the default location. Only use this switch
3686 when multiple versions of the GNAT compiler are available. See the
3687 @command{gcc} manual page for further details. You would normally use the
3688 @option{-b} or @option{-V} switch instead.
3691 @cindex @option{-c} (@command{gcc})
3692 Compile. Always use this switch when compiling Ada programs.
3694 Note: for some other languages when using @command{gcc}, notably in
3695 the case of C and C++, it is possible to use
3696 use @command{gcc} without a @option{-c} switch to
3697 compile and link in one step. In the case of GNAT, you
3698 cannot use this approach, because the binder must be run
3699 and @command{gcc} cannot be used to run the GNAT binder.
3703 @cindex @option{-fno-inline} (@command{gcc})
3704 Suppresses all back-end inlining, even if other optimization or inlining
3706 This includes suppression of inlining that results
3707 from the use of the pragma @code{Inline_Always}.
3708 See also @option{-gnatn} and @option{-gnatN}.
3710 @item -fno-strict-aliasing
3711 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3712 Causes the compiler to avoid assumptions regarding non-aliasing
3713 of objects of different types. See
3714 @ref{Optimization and Strict Aliasing} for details.
3717 @cindex @option{-fstack-check} (@command{gcc})
3718 Activates stack checking.
3719 See @ref{Stack Overflow Checking} for details of the use of this option.
3722 @cindex @option{-fstack-usage} (@command{gcc})
3723 Makes the compiler output stack usage information for the program, on a
3724 per-function basis. The description of the format is to be found in
3725 the GCC documentation.
3727 @item -fcallgraph-info
3728 @cindex @option{-fcallgraph-info} (@command{gcc})
3729 Makes the compiler output callgraph information for the program, on a
3730 per-file basis. The information is generated in the VCG format. It can
3731 be decorated with additional, per-node information if other debugging
3732 options are enabled (only works with -fstack-usage as of this writing).
3735 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3736 Generate debugging information. This information is stored in the object
3737 file and copied from there to the final executable file by the linker,
3738 where it can be read by the debugger. You must use the
3739 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3742 @cindex @option{-gnat83} (@command{gcc})
3743 Enforce Ada 83 restrictions.
3746 @cindex @option{-gnat95} (@command{gcc})
3747 Enforce Ada 95 restrictions.
3750 @cindex @option{-gnat05} (@command{gcc})
3751 Allow full Ada 2005 features.
3754 @cindex @option{-gnata} (@command{gcc})
3755 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3756 activated. Note that these pragmas can also be controlled using the
3757 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3760 @cindex @option{-gnatA} (@command{gcc})
3761 Avoid processing @file{gnat.adc}. If a gnat.adc file is present,
3765 @cindex @option{-gnatb} (@command{gcc})
3766 Generate brief messages to @file{stderr} even if verbose mode set.
3769 @cindex @option{-gnatc} (@command{gcc})
3770 Check syntax and semantics only (no code generation attempted).
3773 @cindex @option{-gnatd} (@command{gcc})
3774 Specify debug options for the compiler. The string of characters after
3775 the @option{-gnatd} specify the specific debug options. The possible
3776 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3777 compiler source file @file{debug.adb} for details of the implemented
3778 debug options. Certain debug options are relevant to applications
3779 programmers, and these are documented at appropriate points in this
3783 @cindex @option{-gnatD} (@command{gcc})
3784 Create expanded source files for source level debugging. This switch
3785 also suppress generation of cross-reference information
3786 (see @option{-gnatx}).
3788 @item -gnatec=@var{path}
3789 @cindex @option{-gnatec} (@command{gcc})
3790 Specify a configuration pragma file
3792 (the equal sign is optional)
3794 (@pxref{The Configuration Pragmas Files}).
3796 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
3797 @cindex @option{-gnateD} (@command{gcc})
3798 Defines a symbol, associated with value, for preprocessing.
3799 (@pxref{Integrated Preprocessing}).
3802 @cindex @option{-gnatef} (@command{gcc})
3803 Display full source path name in brief error messages.
3805 @item -gnatem=@var{path}
3806 @cindex @option{-gnatem} (@command{gcc})
3807 Specify a mapping file
3809 (the equal sign is optional)
3811 (@pxref{Units to Sources Mapping Files}).
3813 @item -gnatep=@var{file}
3814 @cindex @option{-gnatep} (@command{gcc})
3815 Specify a preprocessing data file
3817 (the equal sign is optional)
3819 (@pxref{Integrated Preprocessing}).
3822 @cindex @option{-gnatE} (@command{gcc})
3823 Full dynamic elaboration checks.
3826 @cindex @option{-gnatf} (@command{gcc})
3827 Full errors. Multiple errors per line, all undefined references, do not
3828 attempt to suppress cascaded errors.
3831 @cindex @option{-gnatF} (@command{gcc})
3832 Externals names are folded to all uppercase.
3835 @cindex @option{-gnatg} (@command{gcc})
3836 Internal GNAT implementation mode. This should not be used for
3837 applications programs, it is intended only for use by the compiler
3838 and its run-time library. For documentation, see the GNAT sources.
3839 Note that @option{-gnatg} implies @option{-gnatwu} so that warnings
3840 are generated on unreferenced entities, and all warnings are treated
3844 @cindex @option{-gnatG} (@command{gcc})
3845 List generated expanded code in source form.
3847 @item ^-gnath^/HELP^
3848 @cindex @option{^-gnath^/HELP^} (@command{gcc})
3849 Output usage information. The output is written to @file{stdout}.
3851 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3852 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
3853 Identifier character set
3855 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3858 For details of the possible selections for @var{c},
3859 see @ref{Character Set Control}.
3862 @item -gnatk=@var{n}
3863 @cindex @option{-gnatk} (@command{gcc})
3864 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3867 @cindex @option{-gnatl} (@command{gcc})
3868 Output full source listing with embedded error messages.
3870 @item -gnatm=@var{n}
3871 @cindex @option{-gnatm} (@command{gcc})
3872 Limit number of detected error or warning messages to @var{n}
3873 where @var{n} is in the range 1..999_999. The default setting if
3874 no switch is given is 9999. Compilation is terminated if this
3878 @cindex @option{-gnatn} (@command{gcc})
3879 Activate inlining for subprograms for which
3880 pragma @code{inline} is specified. This inlining is performed
3881 by the GCC back-end.
3884 @cindex @option{-gnatN} (@command{gcc})
3885 Activate front end inlining for subprograms for which
3886 pragma @code{Inline} is specified. This inlining is performed
3887 by the front end and will be visible in the
3888 @option{-gnatG} output.
3889 In some cases, this has proved more effective than the back end
3890 inlining resulting from the use of
3893 @option{-gnatN} automatically implies
3894 @option{-gnatn} so it is not necessary
3895 to specify both options. There are a few cases that the back-end inlining
3896 catches that cannot be dealt with in the front-end.
3899 @cindex @option{-gnato} (@command{gcc})
3900 Enable numeric overflow checking (which is not normally enabled by
3901 default). Not that division by zero is a separate check that is not
3902 controlled by this switch (division by zero checking is on by default).
3905 @cindex @option{-gnatp} (@command{gcc})
3906 Suppress all checks.
3909 @cindex @option{-gnatP} (@command{gcc})
3910 Enable polling. This is required on some systems (notably Windows NT) to
3911 obtain asynchronous abort and asynchronous transfer of control capability.
3912 See the description of pragma Polling in the GNAT Reference Manual for
3916 @cindex @option{-gnatq} (@command{gcc})
3917 Don't quit; try semantics, even if parse errors.
3920 @cindex @option{-gnatQ} (@command{gcc})
3921 Don't quit; generate @file{ALI} and tree files even if illegalities.
3923 @item ^-gnatR[0/1/2/3[s]]^/REPRESENTATION_INFO^
3924 @cindex @option{-gnatR} (@command{gcc})
3925 Output representation information for declared types and objects.
3928 @cindex @option{-gnats} (@command{gcc})
3932 @cindex @option{-gnatS} (@command{gcc})
3933 Print package Standard.
3936 @cindex @option{-gnatt} (@command{gcc})
3937 Generate tree output file.
3939 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
3940 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
3941 All compiler tables start at @var{nnn} times usual starting size.
3944 @cindex @option{-gnatu} (@command{gcc})
3945 List units for this compilation.
3948 @cindex @option{-gnatU} (@command{gcc})
3949 Tag all error messages with the unique string ``error:''
3952 @cindex @option{-gnatv} (@command{gcc})
3953 Verbose mode. Full error output with source lines to @file{stdout}.
3956 @cindex @option{-gnatV} (@command{gcc})
3957 Control level of validity checking. See separate section describing
3960 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}[,...])^
3961 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
3963 ^@var{xxx} is a string of option letters that^the list of options^ denotes
3964 the exact warnings that
3965 are enabled or disabled (@pxref{Warning Message Control}).
3967 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
3968 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
3969 Wide character encoding method
3971 (@var{e}=n/h/u/s/e/8).
3974 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
3978 @cindex @option{-gnatx} (@command{gcc})
3979 Suppress generation of cross-reference information.
3981 @item ^-gnaty^/STYLE_CHECKS=(option,option..)^
3982 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
3983 Enable built-in style checks (@pxref{Style Checking}).
3985 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
3986 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
3987 Distribution stub generation and compilation
3989 (@var{m}=r/c for receiver/caller stubs).
3992 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
3993 to be generated and compiled).
3996 @item ^-I^/SEARCH=^@var{dir}
3997 @cindex @option{^-I^/SEARCH^} (@command{gcc})
3999 Direct GNAT to search the @var{dir} directory for source files needed by
4000 the current compilation
4001 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4003 @item ^-I-^/NOCURRENT_DIRECTORY^
4004 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4006 Except for the source file named in the command line, do not look for source
4007 files in the directory containing the source file named in the command line
4008 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4012 @cindex @option{-mbig-switch} (@command{gcc})
4013 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4014 This standard gcc switch causes the compiler to use larger offsets in its
4015 jump table representation for @code{case} statements.
4016 This may result in less efficient code, but is sometimes necessary
4017 (for example on HP-UX targets)
4018 @cindex HP-UX and @option{-mbig-switch} option
4019 in order to compile large and/or nested @code{case} statements.
4022 @cindex @option{-o} (@command{gcc})
4023 This switch is used in @command{gcc} to redirect the generated object file
4024 and its associated ALI file. Beware of this switch with GNAT, because it may
4025 cause the object file and ALI file to have different names which in turn
4026 may confuse the binder and the linker.
4030 @cindex @option{-nostdinc} (@command{gcc})
4031 Inhibit the search of the default location for the GNAT Run Time
4032 Library (RTL) source files.
4035 @cindex @option{-nostdlib} (@command{gcc})
4036 Inhibit the search of the default location for the GNAT Run Time
4037 Library (RTL) ALI files.
4041 @cindex @option{-O} (@command{gcc})
4042 @var{n} controls the optimization level.
4046 No optimization, the default setting if no @option{-O} appears
4049 Normal optimization, the default if you specify @option{-O} without
4050 an operand. A good compromise between code quality and compilation
4054 Extensive optimization, may improve execution time, possibly at the cost of
4055 substantially increased compilation time.
4062 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4063 Equivalent to @option{/OPTIMIZE=NONE}.
4064 This is the default behavior in the absence of an @option{/OPTMIZE}
4067 @item /OPTIMIZE[=(keyword[,...])]
4068 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4069 Selects the level of optimization for your program. The supported
4070 keywords are as follows:
4073 Perform most optimizations, including those that
4075 This is the default if the @option{/OPTMIZE} qualifier is supplied
4076 without keyword options.
4079 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4082 Perform some optimizations, but omit ones that are costly.
4085 Same as @code{SOME}.
4088 Try to unroll loops. This keyword may be specified together with
4089 any keyword above other than @code{NONE}. Loop unrolling
4090 usually, but not always, improves the performance of programs.
4095 @item -pass-exit-codes
4096 @cindex @option{-pass-exit-codes} (@command{gcc})
4097 Catch exit codes from the compiler and use the most meaningful as
4101 @item --RTS=@var{rts-path}
4102 @cindex @option{--RTS} (@command{gcc})
4103 Specifies the default location of the runtime library. Same meaning as the
4104 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4107 @cindex @option{^-S^/ASM^} (@command{gcc})
4108 ^Used in place of @option{-c} to^Used to^
4109 cause the assembler source file to be
4110 generated, using @file{^.s^.S^} as the extension,
4111 instead of the object file.
4112 This may be useful if you need to examine the generated assembly code.
4114 @item ^-fverbose-asm^/VERBOSE_ASM^
4115 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4116 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4117 to cause the generated assembly code file to be annotated with variable
4118 names, making it significantly easier to follow.
4121 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4122 Show commands generated by the @command{gcc} driver. Normally used only for
4123 debugging purposes or if you need to be sure what version of the
4124 compiler you are executing.
4128 @cindex @option{-V} (@command{gcc})
4129 Execute @var{ver} version of the compiler. This is the @command{gcc}
4130 version, not the GNAT version.
4136 You may combine a sequence of GNAT switches into a single switch. For
4137 example, the combined switch
4139 @cindex Combining GNAT switches
4145 is equivalent to specifying the following sequence of switches:
4148 -gnato -gnatf -gnati3
4152 @c NEED TO CHECK THIS FOR VMS
4155 The following restrictions apply to the combination of switches
4160 The switch @option{-gnatc} if combined with other switches must come
4161 first in the string.
4164 The switch @option{-gnats} if combined with other switches must come
4165 first in the string.
4169 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4170 may not be combined with any other switches.
4174 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4175 switch), then all further characters in the switch are interpreted
4176 as style modifiers (see description of @option{-gnaty}).
4179 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4180 switch), then all further characters in the switch are interpreted
4181 as debug flags (see description of @option{-gnatd}).
4184 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4185 switch), then all further characters in the switch are interpreted
4186 as warning mode modifiers (see description of @option{-gnatw}).
4189 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4190 switch), then all further characters in the switch are interpreted
4191 as validity checking options (see description of @option{-gnatV}).
4195 @node Output and Error Message Control
4196 @subsection Output and Error Message Control
4200 The standard default format for error messages is called ``brief format''.
4201 Brief format messages are written to @file{stderr} (the standard error
4202 file) and have the following form:
4205 e.adb:3:04: Incorrect spelling of keyword "function"
4206 e.adb:4:20: ";" should be "is"
4210 The first integer after the file name is the line number in the file,
4211 and the second integer is the column number within the line.
4212 @code{glide} can parse the error messages
4213 and point to the referenced character.
4214 The following switches provide control over the error message
4220 @cindex @option{-gnatv} (@command{gcc})
4223 The v stands for verbose.
4225 The effect of this setting is to write long-format error
4226 messages to @file{stdout} (the standard output file.
4227 The same program compiled with the
4228 @option{-gnatv} switch would generate:
4232 3. funcion X (Q : Integer)
4234 >>> Incorrect spelling of keyword "function"
4237 >>> ";" should be "is"
4242 The vertical bar indicates the location of the error, and the @samp{>>>}
4243 prefix can be used to search for error messages. When this switch is
4244 used the only source lines output are those with errors.
4247 @cindex @option{-gnatl} (@command{gcc})
4249 The @code{l} stands for list.
4251 This switch causes a full listing of
4252 the file to be generated. The output might look as follows:
4258 3. funcion X (Q : Integer)
4260 >>> Incorrect spelling of keyword "function"
4263 >>> ";" should be "is"
4275 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4276 standard output is redirected, a brief summary is written to
4277 @file{stderr} (standard error) giving the number of error messages and
4278 warning messages generated.
4281 @cindex @option{-gnatU} (@command{gcc})
4282 This switch forces all error messages to be preceded by the unique
4283 string ``error:''. This means that error messages take a few more
4284 characters in space, but allows easy searching for and identification
4288 @cindex @option{-gnatb} (@command{gcc})
4290 The @code{b} stands for brief.
4292 This switch causes GNAT to generate the
4293 brief format error messages to @file{stderr} (the standard error
4294 file) as well as the verbose
4295 format message or full listing (which as usual is written to
4296 @file{stdout} (the standard output file).
4298 @item -gnatm^^=^@var{n}
4299 @cindex @option{-gnatm} (@command{gcc})
4301 The @code{m} stands for maximum.
4303 @var{n} is a decimal integer in the
4304 range of 1 to 999 and limits the number of error messages to be
4305 generated. For example, using @option{-gnatm2} might yield
4308 e.adb:3:04: Incorrect spelling of keyword "function"
4309 e.adb:5:35: missing ".."
4310 fatal error: maximum errors reached
4311 compilation abandoned
4315 @cindex @option{-gnatf} (@command{gcc})
4316 @cindex Error messages, suppressing
4318 The @code{f} stands for full.
4320 Normally, the compiler suppresses error messages that are likely to be
4321 redundant. This switch causes all error
4322 messages to be generated. In particular, in the case of
4323 references to undefined variables. If a given variable is referenced
4324 several times, the normal format of messages is
4326 e.adb:7:07: "V" is undefined (more references follow)
4330 where the parenthetical comment warns that there are additional
4331 references to the variable @code{V}. Compiling the same program with the
4332 @option{-gnatf} switch yields
4335 e.adb:7:07: "V" is undefined
4336 e.adb:8:07: "V" is undefined
4337 e.adb:8:12: "V" is undefined
4338 e.adb:8:16: "V" is undefined
4339 e.adb:9:07: "V" is undefined
4340 e.adb:9:12: "V" is undefined
4344 The @option{-gnatf} switch also generates additional information for
4345 some error messages. Some examples are:
4349 Full details on entities not available in high integrity mode
4351 Details on possibly non-portable unchecked conversion
4353 List possible interpretations for ambiguous calls
4355 Additional details on incorrect parameters
4359 @cindex @option{-gnatq} (@command{gcc})
4361 The @code{q} stands for quit (really ``don't quit'').
4363 In normal operation mode, the compiler first parses the program and
4364 determines if there are any syntax errors. If there are, appropriate
4365 error messages are generated and compilation is immediately terminated.
4367 GNAT to continue with semantic analysis even if syntax errors have been
4368 found. This may enable the detection of more errors in a single run. On
4369 the other hand, the semantic analyzer is more likely to encounter some
4370 internal fatal error when given a syntactically invalid tree.
4373 @cindex @option{-gnatQ} (@command{gcc})
4374 In normal operation mode, the @file{ALI} file is not generated if any
4375 illegalities are detected in the program. The use of @option{-gnatQ} forces
4376 generation of the @file{ALI} file. This file is marked as being in
4377 error, so it cannot be used for binding purposes, but it does contain
4378 reasonably complete cross-reference information, and thus may be useful
4379 for use by tools (e.g. semantic browsing tools or integrated development
4380 environments) that are driven from the @file{ALI} file. This switch
4381 implies @option{-gnatq}, since the semantic phase must be run to get a
4382 meaningful ALI file.
4384 In addition, if @option{-gnatt} is also specified, then the tree file is
4385 generated even if there are illegalities. It may be useful in this case
4386 to also specify @option{-gnatq} to ensure that full semantic processing
4387 occurs. The resulting tree file can be processed by ASIS, for the purpose
4388 of providing partial information about illegal units, but if the error
4389 causes the tree to be badly malformed, then ASIS may crash during the
4392 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4393 being in error, @command{gnatmake} will attempt to recompile the source when it
4394 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4396 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4397 since ALI files are never generated if @option{-gnats} is set.
4401 @node Warning Message Control
4402 @subsection Warning Message Control
4403 @cindex Warning messages
4405 In addition to error messages, which correspond to illegalities as defined
4406 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
4409 First, the compiler considers some constructs suspicious and generates a
4410 warning message to alert you to a possible error. Second, if the
4411 compiler detects a situation that is sure to raise an exception at
4412 run time, it generates a warning message. The following shows an example
4413 of warning messages:
4415 e.adb:4:24: warning: creation of object may raise Storage_Error
4416 e.adb:10:17: warning: static value out of range
4417 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4421 GNAT considers a large number of situations as appropriate
4422 for the generation of warning messages. As always, warnings are not
4423 definite indications of errors. For example, if you do an out-of-range
4424 assignment with the deliberate intention of raising a
4425 @code{Constraint_Error} exception, then the warning that may be
4426 issued does not indicate an error. Some of the situations for which GNAT
4427 issues warnings (at least some of the time) are given in the following
4428 list. This list is not complete, and new warnings are often added to
4429 subsequent versions of GNAT. The list is intended to give a general idea
4430 of the kinds of warnings that are generated.
4434 Possible infinitely recursive calls
4437 Out-of-range values being assigned
4440 Possible order of elaboration problems
4446 Fixed-point type declarations with a null range
4449 Direct_IO or Sequential_IO instantiated with a type that has access values
4452 Variables that are never assigned a value
4455 Variables that are referenced before being initialized
4458 Task entries with no corresponding @code{accept} statement
4461 Duplicate accepts for the same task entry in a @code{select}
4464 Objects that take too much storage
4467 Unchecked conversion between types of differing sizes
4470 Missing @code{return} statement along some execution path in a function
4473 Incorrect (unrecognized) pragmas
4476 Incorrect external names
4479 Allocation from empty storage pool
4482 Potentially blocking operation in protected type
4485 Suspicious parenthesization of expressions
4488 Mismatching bounds in an aggregate
4491 Attempt to return local value by reference
4494 Premature instantiation of a generic body
4497 Attempt to pack aliased components
4500 Out of bounds array subscripts
4503 Wrong length on string assignment
4506 Violations of style rules if style checking is enabled
4509 Unused @code{with} clauses
4512 @code{Bit_Order} usage that does not have any effect
4515 @code{Standard.Duration} used to resolve universal fixed expression
4518 Dereference of possibly null value
4521 Declaration that is likely to cause storage error
4524 Internal GNAT unit @code{with}'ed by application unit
4527 Values known to be out of range at compile time
4530 Unreferenced labels and variables
4533 Address overlays that could clobber memory
4536 Unexpected initialization when address clause present
4539 Bad alignment for address clause
4542 Useless type conversions
4545 Redundant assignment statements and other redundant constructs
4548 Useless exception handlers
4551 Accidental hiding of name by child unit
4554 Access before elaboration detected at compile time
4557 A range in a @code{for} loop that is known to be null or might be null
4562 The following switches are available to control the handling of
4568 @emph{Activate all optional errors.}
4569 @cindex @option{-gnatwa} (@command{gcc})
4570 This switch activates most optional warning messages, see remaining list
4571 in this section for details on optional warning messages that can be
4572 individually controlled. The warnings that are not turned on by this
4574 @option{-gnatwd} (implicit dereferencing),
4575 @option{-gnatwh} (hiding),
4576 and @option{-gnatwl} (elaboration warnings).
4577 All other optional warnings are turned on.
4580 @emph{Suppress all optional errors.}
4581 @cindex @option{-gnatwA} (@command{gcc})
4582 This switch suppresses all optional warning messages, see remaining list
4583 in this section for details on optional warning messages that can be
4584 individually controlled.
4587 @emph{Activate warnings on bad fixed values.}
4588 @cindex @option{-gnatwb} (@command{gcc})
4589 @cindex Bad fixed values
4590 @cindex Fixed-point Small value
4592 This switch activates warnings for static fixed-point expressions whose
4593 value is not an exact multiple of Small. Such values are implementation
4594 dependent, since an implementation is free to choose either of the multiples
4595 that surround the value. GNAT always chooses the closer one, but this is not
4596 required behavior, and it is better to specify a value that is an exact
4597 multiple, ensuring predictable execution. The default is that such warnings
4601 @emph{Suppress warnings on bad fixed values.}
4602 @cindex @option{-gnatwB} (@command{gcc})
4603 This switch suppresses warnings for static fixed-point expressions whose
4604 value is not an exact multiple of Small.
4607 @emph{Activate warnings on conditionals.}
4608 @cindex @option{-gnatwc} (@command{gcc})
4609 @cindex Conditionals, constant
4610 This switch activates warnings for conditional expressions used in
4611 tests that are known to be True or False at compile time. The default
4612 is that such warnings are not generated.
4613 Note that this warning does
4614 not get issued for the use of boolean variables or constants whose
4615 values are known at compile time, since this is a standard technique
4616 for conditional compilation in Ada, and this would generate too many
4617 ``false positive'' warnings.
4618 This warning can also be turned on using @option{-gnatwa}.
4621 @emph{Suppress warnings on conditionals.}
4622 @cindex @option{-gnatwC} (@command{gcc})
4623 This switch suppresses warnings for conditional expressions used in
4624 tests that are known to be True or False at compile time.
4627 @emph{Activate warnings on implicit dereferencing.}
4628 @cindex @option{-gnatwd} (@command{gcc})
4629 If this switch is set, then the use of a prefix of an access type
4630 in an indexed component, slice, or selected component without an
4631 explicit @code{.all} will generate a warning. With this warning
4632 enabled, access checks occur only at points where an explicit
4633 @code{.all} appears in the source code (assuming no warnings are
4634 generated as a result of this switch). The default is that such
4635 warnings are not generated.
4636 Note that @option{-gnatwa} does not affect the setting of
4637 this warning option.
4640 @emph{Suppress warnings on implicit dereferencing.}
4641 @cindex @option{-gnatwD} (@command{gcc})
4642 @cindex Implicit dereferencing
4643 @cindex Dereferencing, implicit
4644 This switch suppresses warnings for implicit dereferences in
4645 indexed components, slices, and selected components.
4648 @emph{Treat warnings as errors.}
4649 @cindex @option{-gnatwe} (@command{gcc})
4650 @cindex Warnings, treat as error
4651 This switch causes warning messages to be treated as errors.
4652 The warning string still appears, but the warning messages are counted
4653 as errors, and prevent the generation of an object file.
4656 @emph{Activate warnings on unreferenced formals.}
4657 @cindex @option{-gnatwf} (@command{gcc})
4658 @cindex Formals, unreferenced
4659 This switch causes a warning to be generated if a formal parameter
4660 is not referenced in the body of the subprogram. This warning can
4661 also be turned on using @option{-gnatwa} or @option{-gnatwu}.
4664 @emph{Suppress warnings on unreferenced formals.}
4665 @cindex @option{-gnatwF} (@command{gcc})
4666 This switch suppresses warnings for unreferenced formal
4667 parameters. Note that the
4668 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4669 effect of warning on unreferenced entities other than subprogram
4673 @emph{Activate warnings on unrecognized pragmas.}
4674 @cindex @option{-gnatwg} (@command{gcc})
4675 @cindex Pragmas, unrecognized
4676 This switch causes a warning to be generated if an unrecognized
4677 pragma is encountered. Apart from issuing this warning, the
4678 pragma is ignored and has no effect. This warning can
4679 also be turned on using @option{-gnatwa}. The default
4680 is that such warnings are issued (satisfying the Ada Reference
4681 Manual requirement that such warnings appear).
4684 @emph{Suppress warnings on unrecognized pragmas.}
4685 @cindex @option{-gnatwG} (@command{gcc})
4686 This switch suppresses warnings for unrecognized pragmas.
4689 @emph{Activate warnings on hiding.}
4690 @cindex @option{-gnatwh} (@command{gcc})
4691 @cindex Hiding of Declarations
4692 This switch activates warnings on hiding declarations.
4693 A declaration is considered hiding
4694 if it is for a non-overloadable entity, and it declares an entity with the
4695 same name as some other entity that is directly or use-visible. The default
4696 is that such warnings are not generated.
4697 Note that @option{-gnatwa} does not affect the setting of this warning option.
4700 @emph{Suppress warnings on hiding.}
4701 @cindex @option{-gnatwH} (@command{gcc})
4702 This switch suppresses warnings on hiding declarations.
4705 @emph{Activate warnings on implementation units.}
4706 @cindex @option{-gnatwi} (@command{gcc})
4707 This switch activates warnings for a @code{with} of an internal GNAT
4708 implementation unit, defined as any unit from the @code{Ada},
4709 @code{Interfaces}, @code{GNAT},
4710 ^^@code{DEC},^ or @code{System}
4711 hierarchies that is not
4712 documented in either the Ada Reference Manual or the GNAT
4713 Programmer's Reference Manual. Such units are intended only
4714 for internal implementation purposes and should not be @code{with}'ed
4715 by user programs. The default is that such warnings are generated
4716 This warning can also be turned on using @option{-gnatwa}.
4719 @emph{Disable warnings on implementation units.}
4720 @cindex @option{-gnatwI} (@command{gcc})
4721 This switch disables warnings for a @code{with} of an internal GNAT
4722 implementation unit.
4725 @emph{Activate warnings on obsolescent features (Annex J).}
4726 @cindex @option{-gnatwj} (@command{gcc})
4727 @cindex Features, obsolescent
4728 @cindex Obsolescent features
4729 If this warning option is activated, then warnings are generated for
4730 calls to subprograms marked with @code{pragma Obsolescent} and
4731 for use of features in Annex J of the Ada Reference Manual. In the
4732 case of Annex J, not all features are flagged. In particular use
4733 of the renamed packages (like @code{Text_IO}) and use of package
4734 @code{ASCII} are not flagged, since these are very common and
4735 would generate many annoying positive warnings. The default is that
4736 such warnings are not generated.
4738 In addition to the above cases, warnings are also generated for
4739 GNAT features that have been provided in past versions but which
4740 have been superseded (typically by features in the new Ada standard).
4741 For example, @code{pragma Ravenscar} will be flagged since its
4742 function is replaced by @code{pragma Profile(Ravenscar)}.
4744 Note that this warning option functions differently from the
4745 restriction @code{No_Obsolescent_Features} in two respects.
4746 First, the restriction applies only to annex J features.
4747 Second, the restriction does flag uses of package @code{ASCII}.
4750 @emph{Suppress warnings on obsolescent features (Annex J).}
4751 @cindex @option{-gnatwJ} (@command{gcc})
4752 This switch disables warnings on use of obsolescent features.
4755 @emph{Activate warnings on variables that could be constants.}
4756 @cindex @option{-gnatwk} (@command{gcc})
4757 This switch activates warnings for variables that are initialized but
4758 never modified, and then could be declared constants.
4761 @emph{Suppress warnings on variables that could be constants.}
4762 @cindex @option{-gnatwK} (@command{gcc})
4763 This switch disables warnings on variables that could be declared constants.
4766 @emph{Activate warnings for missing elaboration pragmas.}
4767 @cindex @option{-gnatwl} (@command{gcc})
4768 @cindex Elaboration, warnings
4769 This switch activates warnings on missing
4770 @code{pragma Elaborate_All} statements.
4771 See the section in this guide on elaboration checking for details on
4772 when such pragma should be used. Warnings are also generated if you
4773 are using the static mode of elaboration, and a @code{pragma Elaborate}
4774 is encountered. The default is that such warnings
4776 This warning is not automatically turned on by the use of @option{-gnatwa}.
4779 @emph{Suppress warnings for missing elaboration pragmas.}
4780 @cindex @option{-gnatwL} (@command{gcc})
4781 This switch suppresses warnings on missing pragma Elaborate_All statements.
4782 See the section in this guide on elaboration checking for details on
4783 when such pragma should be used.
4786 @emph{Activate warnings on modified but unreferenced variables.}
4787 @cindex @option{-gnatwm} (@command{gcc})
4788 This switch activates warnings for variables that are assigned (using
4789 an initialization value or with one or more assignment statements) but
4790 whose value is never read. The warning is suppressed for volatile
4791 variables and also for variables that are renamings of other variables
4792 or for which an address clause is given.
4793 This warning can also be turned on using @option{-gnatwa}.
4796 @emph{Disable warnings on modified but unreferenced variables.}
4797 @cindex @option{-gnatwM} (@command{gcc})
4798 This switch disables warnings for variables that are assigned or
4799 initialized, but never read.
4802 @emph{Set normal warnings mode.}
4803 @cindex @option{-gnatwn} (@command{gcc})
4804 This switch sets normal warning mode, in which enabled warnings are
4805 issued and treated as warnings rather than errors. This is the default
4806 mode. the switch @option{-gnatwn} can be used to cancel the effect of
4807 an explicit @option{-gnatws} or
4808 @option{-gnatwe}. It also cancels the effect of the
4809 implicit @option{-gnatwe} that is activated by the
4810 use of @option{-gnatg}.
4813 @emph{Activate warnings on address clause overlays.}
4814 @cindex @option{-gnatwo} (@command{gcc})
4815 @cindex Address Clauses, warnings
4816 This switch activates warnings for possibly unintended initialization
4817 effects of defining address clauses that cause one variable to overlap
4818 another. The default is that such warnings are generated.
4819 This warning can also be turned on using @option{-gnatwa}.
4822 @emph{Suppress warnings on address clause overlays.}
4823 @cindex @option{-gnatwO} (@command{gcc})
4824 This switch suppresses warnings on possibly unintended initialization
4825 effects of defining address clauses that cause one variable to overlap
4829 @emph{Activate warnings on ineffective pragma Inlines.}
4830 @cindex @option{-gnatwp} (@command{gcc})
4831 @cindex Inlining, warnings
4832 This switch activates warnings for failure of front end inlining
4833 (activated by @option{-gnatN}) to inline a particular call. There are
4834 many reasons for not being able to inline a call, including most
4835 commonly that the call is too complex to inline.
4836 This warning can also be turned on using @option{-gnatwa}.
4839 @emph{Suppress warnings on ineffective pragma Inlines.}
4840 @cindex @option{-gnatwP} (@command{gcc})
4841 This switch suppresses warnings on ineffective pragma Inlines. If the
4842 inlining mechanism cannot inline a call, it will simply ignore the
4846 @emph{Activate warnings on redundant constructs.}
4847 @cindex @option{-gnatwr} (@command{gcc})
4848 This switch activates warnings for redundant constructs. The following
4849 is the current list of constructs regarded as redundant:
4850 This warning can also be turned on using @option{-gnatwa}.
4854 Assignment of an item to itself.
4856 Type conversion that converts an expression to its own type.
4858 Use of the attribute @code{Base} where @code{typ'Base} is the same
4861 Use of pragma @code{Pack} when all components are placed by a record
4862 representation clause.
4864 Exception handler containing only a reraise statement (raise with no
4865 operand) which has no effect.
4867 Use of the operator abs on an operand that is known at compile time
4870 Comparison of boolean expressions to an explicit True value.
4874 @emph{Suppress warnings on redundant constructs.}
4875 @cindex @option{-gnatwR} (@command{gcc})
4876 This switch suppresses warnings for redundant constructs.
4879 @emph{Suppress all warnings.}
4880 @cindex @option{-gnatws} (@command{gcc})
4881 This switch completely suppresses the
4882 output of all warning messages from the GNAT front end.
4883 Note that it does not suppress warnings from the @command{gcc} back end.
4884 To suppress these back end warnings as well, use the switch @option{-w}
4885 in addition to @option{-gnatws}.
4888 @emph{Activate warnings on unused entities.}
4889 @cindex @option{-gnatwu} (@command{gcc})
4890 This switch activates warnings to be generated for entities that
4891 are declared but not referenced, and for units that are @code{with}'ed
4893 referenced. In the case of packages, a warning is also generated if
4894 no entities in the package are referenced. This means that if the package
4895 is referenced but the only references are in @code{use}
4896 clauses or @code{renames}
4897 declarations, a warning is still generated. A warning is also generated
4898 for a generic package that is @code{with}'ed but never instantiated.
4899 In the case where a package or subprogram body is compiled, and there
4900 is a @code{with} on the corresponding spec
4901 that is only referenced in the body,
4902 a warning is also generated, noting that the
4903 @code{with} can be moved to the body. The default is that
4904 such warnings are not generated.
4905 This switch also activates warnings on unreferenced formals
4906 (it includes the effect of @option{-gnatwf}).
4907 This warning can also be turned on using @option{-gnatwa}.
4910 @emph{Suppress warnings on unused entities.}
4911 @cindex @option{-gnatwU} (@command{gcc})
4912 This switch suppresses warnings for unused entities and packages.
4913 It also turns off warnings on unreferenced formals (and thus includes
4914 the effect of @option{-gnatwF}).
4917 @emph{Activate warnings on unassigned variables.}
4918 @cindex @option{-gnatwv} (@command{gcc})
4919 @cindex Unassigned variable warnings
4920 This switch activates warnings for access to variables which
4921 may not be properly initialized. The default is that
4922 such warnings are generated.
4925 @emph{Suppress warnings on unassigned variables.}
4926 @cindex @option{-gnatwV} (@command{gcc})
4927 This switch suppresses warnings for access to variables which
4928 may not be properly initialized.
4931 @emph{Activate warnings for Ada 2005 compatibility issues.}
4932 @cindex @option{-gnatwy} (@command{gcc})
4933 @cindex Ada 2005 compatibility issues warnings
4934 For the most part Ada 2005 is upwards compatible with Ada 95,
4935 but there are some exceptions (for example the fact that
4936 @code{interface} is now a reserved word in Ada 2005). This
4937 switch activates several warnings to help in identifying
4938 and correcting such incompatibilities. The default is that
4939 these warnings are generated. Note that at one point Ada 2005
4940 was called Ada 0Y, hence the choice of character.
4943 @emph{Disable warnings for Ada 2005 compatibility issues.}
4944 @cindex @option{-gnatwY} (@command{gcc})
4945 @cindex Ada 2005 compatibility issues warnings
4946 This switch suppresses several warnings intended to help in identifying
4947 incompatibilities between Ada 95 and Ada 2005.
4950 @emph{Activate warnings on Export/Import pragmas.}
4951 @cindex @option{-gnatwx} (@command{gcc})
4952 @cindex Export/Import pragma warnings
4953 This switch activates warnings on Export/Import pragmas when
4954 the compiler detects a possible conflict between the Ada and
4955 foreign language calling sequences. For example, the use of
4956 default parameters in a convention C procedure is dubious
4957 because the C compiler cannot supply the proper default, so
4958 a warning is issued. The default is that such warnings are
4962 @emph{Suppress warnings on Export/Import pragmas.}
4963 @cindex @option{-gnatwX} (@command{gcc})
4964 This switch suppresses warnings on Export/Import pragmas.
4965 The sense of this is that you are telling the compiler that
4966 you know what you are doing in writing the pragma, and it
4967 should not complain at you.
4970 @emph{Activate warnings on unchecked conversions.}
4971 @cindex @option{-gnatwz} (@command{gcc})
4972 @cindex Unchecked_Conversion warnings
4973 This switch activates warnings for unchecked conversions
4974 where the types are known at compile time to have different
4976 is that such warnings are generated.
4979 @emph{Suppress warnings on unchecked conversions.}
4980 @cindex @option{-gnatwZ} (@command{gcc})
4981 This switch suppresses warnings for unchecked conversions
4982 where the types are known at compile time to have different
4985 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
4986 @cindex @option{-Wuninitialized}
4987 The warnings controlled by the @option{-gnatw} switch are generated by the
4988 front end of the compiler. In some cases, the @option{^gcc^GCC^} back end
4989 can provide additional warnings. One such useful warning is provided by
4990 @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^}. This must be used in
4991 conjunction with tunrning on optimization mode. This causes the flow
4992 analysis circuits of the back end optimizer to output additional
4993 warnings about uninitialized variables.
4995 @item ^-w^/NO_BACK_END_WARNINGS^
4997 This switch suppresses warnings from the @option{^gcc^GCC^} back end. It may
4998 be used in conjunction with @option{-gnatws} to ensure that all warnings
4999 are suppressed during the entire compilation process.
5005 A string of warning parameters can be used in the same parameter. For example:
5012 will turn on all optional warnings except for elaboration pragma warnings,
5013 and also specify that warnings should be treated as errors.
5015 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5040 @node Debugging and Assertion Control
5041 @subsection Debugging and Assertion Control
5045 @cindex @option{-gnata} (@command{gcc})
5051 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5052 are ignored. This switch, where @samp{a} stands for assert, causes
5053 @code{Assert} and @code{Debug} pragmas to be activated.
5055 The pragmas have the form:
5059 @b{pragma} Assert (@var{Boolean-expression} [,
5060 @var{static-string-expression}])
5061 @b{pragma} Debug (@var{procedure call})
5066 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5067 If the result is @code{True}, the pragma has no effect (other than
5068 possible side effects from evaluating the expression). If the result is
5069 @code{False}, the exception @code{Assert_Failure} declared in the package
5070 @code{System.Assertions} is
5071 raised (passing @var{static-string-expression}, if present, as the
5072 message associated with the exception). If no string expression is
5073 given the default is a string giving the file name and line number
5076 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5077 @code{pragma Debug} may appear within a declaration sequence, allowing
5078 debugging procedures to be called between declarations.
5081 @item /DEBUG[=debug-level]
5083 Specifies how much debugging information is to be included in
5084 the resulting object file where 'debug-level' is one of the following:
5087 Include both debugger symbol records and traceback
5089 This is the default setting.
5091 Include both debugger symbol records and traceback in
5094 Excludes both debugger symbol records and traceback
5095 the object file. Same as /NODEBUG.
5097 Includes only debugger symbol records in the object
5098 file. Note that this doesn't include traceback information.
5103 @node Validity Checking
5104 @subsection Validity Checking
5105 @findex Validity Checking
5108 The Ada 95 Reference Manual has specific requirements for checking
5109 for invalid values. In particular, RM 13.9.1 requires that the
5110 evaluation of invalid values (for example from unchecked conversions),
5111 not result in erroneous execution. In GNAT, the result of such an
5112 evaluation in normal default mode is to either use the value
5113 unmodified, or to raise Constraint_Error in those cases where use
5114 of the unmodified value would cause erroneous execution. The cases
5115 where unmodified values might lead to erroneous execution are case
5116 statements (where a wild jump might result from an invalid value),
5117 and subscripts on the left hand side (where memory corruption could
5118 occur as a result of an invalid value).
5120 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5123 The @code{x} argument is a string of letters that
5124 indicate validity checks that are performed or not performed in addition
5125 to the default checks described above.
5128 The options allowed for this qualifier
5129 indicate validity checks that are performed or not performed in addition
5130 to the default checks described above.
5136 @emph{All validity checks.}
5137 @cindex @option{-gnatVa} (@command{gcc})
5138 All validity checks are turned on.
5140 That is, @option{-gnatVa} is
5141 equivalent to @option{gnatVcdfimorst}.
5145 @emph{Validity checks for copies.}
5146 @cindex @option{-gnatVc} (@command{gcc})
5147 The right hand side of assignments, and the initializing values of
5148 object declarations are validity checked.
5151 @emph{Default (RM) validity checks.}
5152 @cindex @option{-gnatVd} (@command{gcc})
5153 Some validity checks are done by default following normal Ada semantics
5155 A check is done in case statements that the expression is within the range
5156 of the subtype. If it is not, Constraint_Error is raised.
5157 For assignments to array components, a check is done that the expression used
5158 as index is within the range. If it is not, Constraint_Error is raised.
5159 Both these validity checks may be turned off using switch @option{-gnatVD}.
5160 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5161 switch @option{-gnatVd} will leave the checks turned on.
5162 Switch @option{-gnatVD} should be used only if you are sure that all such
5163 expressions have valid values. If you use this switch and invalid values
5164 are present, then the program is erroneous, and wild jumps or memory
5165 overwriting may occur.
5168 @emph{Validity checks for floating-point values.}
5169 @cindex @option{-gnatVf} (@command{gcc})
5170 In the absence of this switch, validity checking occurs only for discrete
5171 values. If @option{-gnatVf} is specified, then validity checking also applies
5172 for floating-point values, and NaN's and infinities are considered invalid,
5173 as well as out of range values for constrained types. Note that this means
5174 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
5175 in which floating-point values are checked depends on the setting of other
5176 options. For example,
5177 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5178 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5179 (the order does not matter) specifies that floating-point parameters of mode
5180 @code{in} should be validity checked.
5183 @emph{Validity checks for @code{in} mode parameters}
5184 @cindex @option{-gnatVi} (@command{gcc})
5185 Arguments for parameters of mode @code{in} are validity checked in function
5186 and procedure calls at the point of call.
5189 @emph{Validity checks for @code{in out} mode parameters.}
5190 @cindex @option{-gnatVm} (@command{gcc})
5191 Arguments for parameters of mode @code{in out} are validity checked in
5192 procedure calls at the point of call. The @code{'m'} here stands for
5193 modify, since this concerns parameters that can be modified by the call.
5194 Note that there is no specific option to test @code{out} parameters,
5195 but any reference within the subprogram will be tested in the usual
5196 manner, and if an invalid value is copied back, any reference to it
5197 will be subject to validity checking.
5200 @emph{No validity checks.}
5201 @cindex @option{-gnatVn} (@command{gcc})
5202 This switch turns off all validity checking, including the default checking
5203 for case statements and left hand side subscripts. Note that the use of
5204 the switch @option{-gnatp} suppresses all run-time checks, including
5205 validity checks, and thus implies @option{-gnatVn}. When this switch
5206 is used, it cancels any other @option{-gnatV} previously issued.
5209 @emph{Validity checks for operator and attribute operands.}
5210 @cindex @option{-gnatVo} (@command{gcc})
5211 Arguments for predefined operators and attributes are validity checked.
5212 This includes all operators in package @code{Standard},
5213 the shift operators defined as intrinsic in package @code{Interfaces}
5214 and operands for attributes such as @code{Pos}. Checks are also made
5215 on individual component values for composite comparisons.
5218 @emph{Validity checks for parameters.}
5219 @cindex @option{-gnatVp} (@command{gcc})
5220 This controls the treatment of parameters within a subprogram (as opposed
5221 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5222 of parameters on a call. If either of these call options is used, then
5223 normally an assumption is made within a subprogram that the input arguments
5224 have been validity checking at the point of call, and do not need checking
5225 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5226 is not made, and parameters are not assumed to be valid, so their validity
5227 will be checked (or rechecked) within the subprogram.
5230 @emph{Validity checks for function returns.}
5231 @cindex @option{-gnatVr} (@command{gcc})
5232 The expression in @code{return} statements in functions is validity
5236 @emph{Validity checks for subscripts.}
5237 @cindex @option{-gnatVs} (@command{gcc})
5238 All subscripts expressions are checked for validity, whether they appear
5239 on the right side or left side (in default mode only left side subscripts
5240 are validity checked).
5243 @emph{Validity checks for tests.}
5244 @cindex @option{-gnatVt} (@command{gcc})
5245 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5246 statements are checked, as well as guard expressions in entry calls.
5251 The @option{-gnatV} switch may be followed by
5252 ^a string of letters^a list of options^
5253 to turn on a series of validity checking options.
5255 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5256 specifies that in addition to the default validity checking, copies and
5257 function return expressions are to be validity checked.
5258 In order to make it easier
5259 to specify the desired combination of effects,
5261 the upper case letters @code{CDFIMORST} may
5262 be used to turn off the corresponding lower case option.
5265 the prefix @code{NO} on an option turns off the corresponding validity
5268 @item @code{NOCOPIES}
5269 @item @code{NODEFAULT}
5270 @item @code{NOFLOATS}
5271 @item @code{NOIN_PARAMS}
5272 @item @code{NOMOD_PARAMS}
5273 @item @code{NOOPERANDS}
5274 @item @code{NORETURNS}
5275 @item @code{NOSUBSCRIPTS}
5276 @item @code{NOTESTS}
5280 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5281 turns on all validity checking options except for
5282 checking of @code{@b{in out}} procedure arguments.
5284 The specification of additional validity checking generates extra code (and
5285 in the case of @option{-gnatVa} the code expansion can be substantial.
5286 However, these additional checks can be very useful in detecting
5287 uninitialized variables, incorrect use of unchecked conversion, and other
5288 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5289 is useful in conjunction with the extra validity checking, since this
5290 ensures that wherever possible uninitialized variables have invalid values.
5292 See also the pragma @code{Validity_Checks} which allows modification of
5293 the validity checking mode at the program source level, and also allows for
5294 temporary disabling of validity checks.
5296 @node Style Checking
5297 @subsection Style Checking
5298 @findex Style checking
5301 The @option{-gnaty^x^(option,option,...)^} switch
5302 @cindex @option{-gnaty} (@command{gcc})
5303 causes the compiler to
5304 enforce specified style rules. A limited set of style rules has been used
5305 in writing the GNAT sources themselves. This switch allows user programs
5306 to activate all or some of these checks. If the source program fails a
5307 specified style check, an appropriate warning message is given, preceded by
5308 the character sequence ``(style)''.
5310 @code{(option,option,...)} is a sequence of keywords
5313 The string @var{x} is a sequence of letters or digits
5315 indicating the particular style
5316 checks to be performed. The following checks are defined:
5321 @emph{Specify indentation level.}
5322 If a digit from 1-9 appears
5323 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5324 then proper indentation is checked, with the digit indicating the
5325 indentation level required.
5326 The general style of required indentation is as specified by
5327 the examples in the Ada Reference Manual. Full line comments must be
5328 aligned with the @code{--} starting on a column that is a multiple of
5329 the alignment level.
5332 @emph{Check attribute casing.}
5333 If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty}
5334 then attribute names, including the case of keywords such as @code{digits}
5335 used as attributes names, must be written in mixed case, that is, the
5336 initial letter and any letter following an underscore must be uppercase.
5337 All other letters must be lowercase.
5340 @emph{Blanks not allowed at statement end.}
5341 If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then
5342 trailing blanks are not allowed at the end of statements. The purpose of this
5343 rule, together with h (no horizontal tabs), is to enforce a canonical format
5344 for the use of blanks to separate source tokens.
5347 @emph{Check comments.}
5348 If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty}
5349 then comments must meet the following set of rules:
5354 The ``@code{--}'' that starts the column must either start in column one,
5355 or else at least one blank must precede this sequence.
5358 Comments that follow other tokens on a line must have at least one blank
5359 following the ``@code{--}'' at the start of the comment.
5362 Full line comments must have two blanks following the ``@code{--}'' that
5363 starts the comment, with the following exceptions.
5366 A line consisting only of the ``@code{--}'' characters, possibly preceded
5367 by blanks is permitted.
5370 A comment starting with ``@code{--x}'' where @code{x} is a special character
5372 This allows proper processing of the output generated by specialized tools
5373 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5375 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5376 special character is defined as being in one of the ASCII ranges
5377 @code{16#21#..16#2F#} or @code{16#3A#..16#3F#}.
5378 Note that this usage is not permitted
5379 in GNAT implementation units (i.e. when @option{-gnatg} is used).
5382 A line consisting entirely of minus signs, possibly preceded by blanks, is
5383 permitted. This allows the construction of box comments where lines of minus
5384 signs are used to form the top and bottom of the box.
5387 A comment that starts and ends with ``@code{--}'' is permitted as long as at
5388 least one blank follows the initial ``@code{--}''. Together with the preceding
5389 rule, this allows the construction of box comments, as shown in the following
5392 ---------------------------
5393 -- This is a box comment --
5394 -- with two text lines. --
5395 ---------------------------
5399 @item ^d^DOS_LINE_ENDINGS^
5400 @emph{Check no DOS line terminators present.}
5401 If the ^letter d^word DOS_LINE_ENDINGS^ appears in the string after
5402 @option{-gnaty} then all lines must be terminated by a single ASCII.LF
5403 character (in particular the DOS line terminator sequence CR/LF is not
5407 @emph{Check end/exit labels.}
5408 If the ^letter e^word END^ appears in the string after @option{-gnaty} then
5409 optional labels on @code{end} statements ending subprograms and on
5410 @code{exit} statements exiting named loops, are required to be present.
5413 @emph{No form feeds or vertical tabs.}
5414 If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then
5415 neither form feeds nor vertical tab characters are permitted
5419 @emph{No horizontal tabs.}
5420 If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then
5421 horizontal tab characters are not permitted in the source text.
5422 Together with the b (no blanks at end of line) check, this
5423 enforces a canonical form for the use of blanks to separate
5427 @emph{Check if-then layout.}
5428 If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty},
5429 then the keyword @code{then} must appear either on the same
5430 line as corresponding @code{if}, or on a line on its own, lined
5431 up under the @code{if} with at least one non-blank line in between
5432 containing all or part of the condition to be tested.
5435 @emph{Check keyword casing.}
5436 If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then
5437 all keywords must be in lower case (with the exception of keywords
5438 such as @code{digits} used as attribute names to which this check
5442 @emph{Check layout.}
5443 If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then
5444 layout of statement and declaration constructs must follow the
5445 recommendations in the Ada Reference Manual, as indicated by the
5446 form of the syntax rules. For example an @code{else} keyword must
5447 be lined up with the corresponding @code{if} keyword.
5449 There are two respects in which the style rule enforced by this check
5450 option are more liberal than those in the Ada Reference Manual. First
5451 in the case of record declarations, it is permissible to put the
5452 @code{record} keyword on the same line as the @code{type} keyword, and
5453 then the @code{end} in @code{end record} must line up under @code{type}.
5454 For example, either of the following two layouts is acceptable:
5456 @smallexample @c ada
5472 Second, in the case of a block statement, a permitted alternative
5473 is to put the block label on the same line as the @code{declare} or
5474 @code{begin} keyword, and then line the @code{end} keyword up under
5475 the block label. For example both the following are permitted:
5477 @smallexample @c ada
5495 The same alternative format is allowed for loops. For example, both of
5496 the following are permitted:
5498 @smallexample @c ada
5500 Clear : while J < 10 loop
5511 @item ^Lnnn^MAX_NESTING=nnn^
5512 @emph{Set maximum nesting level}
5513 If the sequence ^Lnnn^MAX_NESTING=nnn^, where nnn is a decimal number in
5514 the range 0-999, appears in the string after @option{-gnaty} then the
5515 maximum level of nesting of constructs (including subprograms, loops,
5516 blocks, packages, and conditionals) may not exceed the given value. A
5517 value of zero disconnects this style check.
5519 @item ^m^LINE_LENGTH^
5520 @emph{Check maximum line length.}
5521 If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty}
5522 then the length of source lines must not exceed 79 characters, including
5523 any trailing blanks. The value of 79 allows convenient display on an
5524 80 character wide device or window, allowing for possible special
5525 treatment of 80 character lines. Note that this count is of
5526 characters in the source text. This means that a tab character counts
5527 as one character in this count but a wide character sequence counts as
5528 a single character (however many bytes are needed in the encoding).
5530 @item ^Mnnn^MAX_LENGTH=nnn^
5531 @emph{Set maximum line length.}
5532 If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in
5533 the string after @option{-gnaty} then the length of lines must not exceed the
5536 @item ^n^STANDARD_CASING^
5537 @emph{Check casing of entities in Standard.}
5538 If the ^letter n^word STANDARD_CASING^ appears in the string
5539 after @option{-gnaty} then any identifier from Standard must be cased
5540 to match the presentation in the Ada Reference Manual (for example,
5541 @code{Integer} and @code{ASCII.NUL}).
5543 @item ^o^ORDERED_SUBPROGRAMS^
5544 @emph{Check order of subprogram bodies.}
5545 If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string
5546 after @option{-gnaty} then all subprogram bodies in a given scope
5547 (e.g. a package body) must be in alphabetical order. The ordering
5548 rule uses normal Ada rules for comparing strings, ignoring casing
5549 of letters, except that if there is a trailing numeric suffix, then
5550 the value of this suffix is used in the ordering (e.g. Junk2 comes
5554 @emph{Check pragma casing.}
5555 If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then
5556 pragma names must be written in mixed case, that is, the
5557 initial letter and any letter following an underscore must be uppercase.
5558 All other letters must be lowercase.
5560 @item ^r^REFERENCES^
5561 @emph{Check references.}
5562 If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty}
5563 then all identifier references must be cased in the same way as the
5564 corresponding declaration. No specific casing style is imposed on
5565 identifiers. The only requirement is for consistency of references
5569 @emph{Check separate specs.}
5570 If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then
5571 separate declarations (``specs'') are required for subprograms (a
5572 body is not allowed to serve as its own declaration). The only
5573 exception is that parameterless library level procedures are
5574 not required to have a separate declaration. This exception covers
5575 the most frequent form of main program procedures.
5578 @emph{Check token spacing.}
5579 If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then
5580 the following token spacing rules are enforced:
5585 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
5588 The token @code{=>} must be surrounded by spaces.
5591 The token @code{<>} must be preceded by a space or a left parenthesis.
5594 Binary operators other than @code{**} must be surrounded by spaces.
5595 There is no restriction on the layout of the @code{**} binary operator.
5598 Colon must be surrounded by spaces.
5601 Colon-equal (assignment, initialization) must be surrounded by spaces.
5604 Comma must be the first non-blank character on the line, or be
5605 immediately preceded by a non-blank character, and must be followed
5609 If the token preceding a left parenthesis ends with a letter or digit, then
5610 a space must separate the two tokens.
5613 A right parenthesis must either be the first non-blank character on
5614 a line, or it must be preceded by a non-blank character.
5617 A semicolon must not be preceded by a space, and must not be followed by
5618 a non-blank character.
5621 A unary plus or minus may not be followed by a space.
5624 A vertical bar must be surrounded by spaces.
5627 @item ^u^UNNECESSARY_BLANK_LINES^
5628 @emph{Check unnecessary blank lines.}
5629 Check for unnecessary blank lines. A blank line is considered
5630 unnecessary if it appears at the end of the file, or if more than
5631 one blank line occurs in sequence.
5633 @item ^x^XTRA_PARENS^
5634 @emph{Check extra parentheses.}
5635 Check for the use of an unnecessary extra level of parentheses (C-style)
5636 around conditions in @code{if} statements, @code{while} statements and
5637 @code{exit} statements.
5642 In the above rules, appearing in column one is always permitted, that is,
5643 counts as meeting either a requirement for a required preceding space,
5644 or as meeting a requirement for no preceding space.
5646 Appearing at the end of a line is also always permitted, that is, counts
5647 as meeting either a requirement for a following space, or as meeting
5648 a requirement for no following space.
5651 If any of these style rules is violated, a message is generated giving
5652 details on the violation. The initial characters of such messages are
5653 always ``@code{(style)}''. Note that these messages are treated as warning
5654 messages, so they normally do not prevent the generation of an object
5655 file. The @option{-gnatwe} switch can be used to treat warning messages,
5656 including style messages, as fatal errors.
5660 @option{-gnaty} on its own (that is not
5661 followed by any letters or digits),
5662 is equivalent to @code{gnaty3abcefhiklmnprst}, that is all checking
5663 options enabled with the exception of @option{-gnatyo},
5664 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
5667 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
5668 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
5669 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
5671 an indentation level of 3 is set. This is similar to the standard
5672 checking option that is used for the GNAT sources.
5681 clears any previously set style checks.
5683 @node Run-Time Checks
5684 @subsection Run-Time Checks
5685 @cindex Division by zero
5686 @cindex Access before elaboration
5687 @cindex Checks, division by zero
5688 @cindex Checks, access before elaboration
5691 If you compile with the default options, GNAT will insert many run-time
5692 checks into the compiled code, including code that performs range
5693 checking against constraints, but not arithmetic overflow checking for
5694 integer operations (including division by zero) or checks for access
5695 before elaboration on subprogram calls. All other run-time checks, as
5696 required by the Ada 95 Reference Manual, are generated by default.
5697 The following @command{gcc} switches refine this default behavior:
5702 @cindex @option{-gnatp} (@command{gcc})
5703 @cindex Suppressing checks
5704 @cindex Checks, suppressing
5706 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
5707 had been present in the source. Validity checks are also suppressed (in
5708 other words @option{-gnatp} also implies @option{-gnatVn}.
5709 Use this switch to improve the performance
5710 of the code at the expense of safety in the presence of invalid data or
5714 @cindex @option{-gnato} (@command{gcc})
5715 @cindex Overflow checks
5716 @cindex Check, overflow
5717 Enables overflow checking for integer operations.
5718 This causes GNAT to generate slower and larger executable
5719 programs by adding code to check for overflow (resulting in raising
5720 @code{Constraint_Error} as required by standard Ada
5721 semantics). These overflow checks correspond to situations in which
5722 the true value of the result of an operation may be outside the base
5723 range of the result type. The following example shows the distinction:
5725 @smallexample @c ada
5726 X1 : Integer := Integer'Last;
5727 X2 : Integer range 1 .. 5 := 5;
5728 X3 : Integer := Integer'Last;
5729 X4 : Integer range 1 .. 5 := 5;
5730 F : Float := 2.0E+20;
5739 Here the first addition results in a value that is outside the base range
5740 of Integer, and hence requires an overflow check for detection of the
5741 constraint error. Thus the first assignment to @code{X1} raises a
5742 @code{Constraint_Error} exception only if @option{-gnato} is set.
5744 The second increment operation results in a violation
5745 of the explicit range constraint, and such range checks are always
5746 performed (unless specifically suppressed with a pragma @code{suppress}
5747 or the use of @option{-gnatp}).
5749 The two conversions of @code{F} both result in values that are outside
5750 the base range of type @code{Integer} and thus will raise
5751 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
5752 The fact that the result of the second conversion is assigned to
5753 variable @code{X4} with a restricted range is irrelevant, since the problem
5754 is in the conversion, not the assignment.
5756 Basically the rule is that in the default mode (@option{-gnato} not
5757 used), the generated code assures that all integer variables stay
5758 within their declared ranges, or within the base range if there is
5759 no declared range. This prevents any serious problems like indexes
5760 out of range for array operations.
5762 What is not checked in default mode is an overflow that results in
5763 an in-range, but incorrect value. In the above example, the assignments
5764 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
5765 range of the target variable, but the result is wrong in the sense that
5766 it is too large to be represented correctly. Typically the assignment
5767 to @code{X1} will result in wrap around to the largest negative number.
5768 The conversions of @code{F} will result in some @code{Integer} value
5769 and if that integer value is out of the @code{X4} range then the
5770 subsequent assignment would generate an exception.
5772 @findex Machine_Overflows
5773 Note that the @option{-gnato} switch does not affect the code generated
5774 for any floating-point operations; it applies only to integer
5776 For floating-point, GNAT has the @code{Machine_Overflows}
5777 attribute set to @code{False} and the normal mode of operation is to
5778 generate IEEE NaN and infinite values on overflow or invalid operations
5779 (such as dividing 0.0 by 0.0).
5781 The reason that we distinguish overflow checking from other kinds of
5782 range constraint checking is that a failure of an overflow check can
5783 generate an incorrect value, but cannot cause erroneous behavior. This
5784 is unlike the situation with a constraint check on an array subscript,
5785 where failure to perform the check can result in random memory description,
5786 or the range check on a case statement, where failure to perform the check
5787 can cause a wild jump.
5789 Note again that @option{-gnato} is off by default, so overflow checking is
5790 not performed in default mode. This means that out of the box, with the
5791 default settings, GNAT does not do all the checks expected from the
5792 language description in the Ada Reference Manual. If you want all constraint
5793 checks to be performed, as described in this Manual, then you must
5794 explicitly use the -gnato switch either on the @command{gnatmake} or
5795 @command{gcc} command.
5798 @cindex @option{-gnatE} (@command{gcc})
5799 @cindex Elaboration checks
5800 @cindex Check, elaboration
5801 Enables dynamic checks for access-before-elaboration
5802 on subprogram calls and generic instantiations.
5803 For full details of the effect and use of this switch,
5804 @xref{Compiling Using gcc}.
5809 The setting of these switches only controls the default setting of the
5810 checks. You may modify them using either @code{Suppress} (to remove
5811 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
5814 @node Stack Overflow Checking
5815 @subsection Stack Overflow Checking
5816 @cindex Stack Overflow Checking
5817 @cindex -fstack-check
5820 For most operating systems, @command{gcc} does not perform stack overflow
5821 checking by default. This means that if the main environment task or
5822 some other task exceeds the available stack space, then unpredictable
5823 behavior will occur.
5825 To activate stack checking, compile all units with the gcc option
5826 @option{-fstack-check}. For example:
5829 gcc -c -fstack-check package1.adb
5833 Units compiled with this option will generate extra instructions to check
5834 that any use of the stack (for procedure calls or for declaring local
5835 variables in declare blocks) do not exceed the available stack space.
5836 If the space is exceeded, then a @code{Storage_Error} exception is raised.
5838 For declared tasks, the stack size is always controlled by the size
5839 given in an applicable @code{Storage_Size} pragma (or is set to
5840 the default size if no pragma is used.
5842 For the environment task, the stack size depends on
5843 system defaults and is unknown to the compiler. The stack
5844 may even dynamically grow on some systems, precluding the
5845 normal Ada semantics for stack overflow. In the worst case,
5846 unbounded stack usage, causes unbounded stack expansion
5847 resulting in the system running out of virtual memory.
5849 The stack checking may still work correctly if a fixed
5850 size stack is allocated, but this cannot be guaranteed.
5851 To ensure that a clean exception is signalled for stack
5852 overflow, set the environment variable
5853 @code{GNAT_STACK_LIMIT} to indicate the maximum
5854 stack area that can be used, as in:
5855 @cindex GNAT_STACK_LIMIT
5858 SET GNAT_STACK_LIMIT 1600
5862 The limit is given in kilobytes, so the above declaration would
5863 set the stack limit of the environment task to 1.6 megabytes.
5864 Note that the only purpose of this usage is to limit the amount
5865 of stack used by the environment task. If it is necessary to
5866 increase the amount of stack for the environment task, then this
5867 is an operating systems issue, and must be addressed with the
5868 appropriate operating systems commands.
5870 @node Using gcc for Syntax Checking
5871 @subsection Using @command{gcc} for Syntax Checking
5874 @cindex @option{-gnats} (@command{gcc})
5878 The @code{s} stands for ``syntax''.
5881 Run GNAT in syntax checking only mode. For
5882 example, the command
5885 $ gcc -c -gnats x.adb
5889 compiles file @file{x.adb} in syntax-check-only mode. You can check a
5890 series of files in a single command
5892 , and can use wild cards to specify such a group of files.
5893 Note that you must specify the @option{-c} (compile
5894 only) flag in addition to the @option{-gnats} flag.
5897 You may use other switches in conjunction with @option{-gnats}. In
5898 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
5899 format of any generated error messages.
5901 When the source file is empty or contains only empty lines and/or comments,
5902 the output is a warning:
5905 $ gcc -c -gnats -x ada toto.txt
5906 toto.txt:1:01: warning: empty file, contains no compilation units
5910 Otherwise, the output is simply the error messages, if any. No object file or
5911 ALI file is generated by a syntax-only compilation. Also, no units other
5912 than the one specified are accessed. For example, if a unit @code{X}
5913 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
5914 check only mode does not access the source file containing unit
5917 @cindex Multiple units, syntax checking
5918 Normally, GNAT allows only a single unit in a source file. However, this
5919 restriction does not apply in syntax-check-only mode, and it is possible
5920 to check a file containing multiple compilation units concatenated
5921 together. This is primarily used by the @code{gnatchop} utility
5922 (@pxref{Renaming Files Using gnatchop}).
5925 @node Using gcc for Semantic Checking
5926 @subsection Using @command{gcc} for Semantic Checking
5929 @cindex @option{-gnatc} (@command{gcc})
5933 The @code{c} stands for ``check''.
5935 Causes the compiler to operate in semantic check mode,
5936 with full checking for all illegalities specified in the
5937 Ada 95 Reference Manual, but without generation of any object code
5938 (no object file is generated).
5940 Because dependent files must be accessed, you must follow the GNAT
5941 semantic restrictions on file structuring to operate in this mode:
5945 The needed source files must be accessible
5946 (@pxref{Search Paths and the Run-Time Library (RTL)}).
5949 Each file must contain only one compilation unit.
5952 The file name and unit name must match (@pxref{File Naming Rules}).
5955 The output consists of error messages as appropriate. No object file is
5956 generated. An @file{ALI} file is generated for use in the context of
5957 cross-reference tools, but this file is marked as not being suitable
5958 for binding (since no object file is generated).
5959 The checking corresponds exactly to the notion of
5960 legality in the Ada 95 Reference Manual.
5962 Any unit can be compiled in semantics-checking-only mode, including
5963 units that would not normally be compiled (subunits,
5964 and specifications where a separate body is present).
5967 @node Compiling Different Versions of Ada
5968 @subsection Compiling Different Versions of Ada
5970 @cindex Compatibility with Ada 83
5973 @cindex Ada 2005 mode
5975 GNAT is primarily an Ada 95 compiler, but the switches described in
5976 this section allow operation in Ada 83 compatibility mode, and also
5977 allow the use of a preliminary implementation of many of the expected
5978 new features in Ada 2005, the forthcoming new version of the standard.
5980 @item -gnat83 (Ada 83 Compatibility Mode)
5981 @cindex @option{-gnat83} (@command{gcc})
5982 @cindex ACVC, Ada 83 tests
5985 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
5986 specify that an Ada 83 program is to be compiled in Ada 83 mode. If you specify
5987 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
5988 where this can be done easily.
5989 It is not possible to guarantee this switch does a perfect
5990 job; for example, some subtle tests, such as are
5991 found in earlier ACVC tests (and that have been removed from the ACATS suite
5992 for Ada 95), might not compile correctly.
5993 Nevertheless, this switch may be useful in some circumstances, for example
5994 where, due to contractual reasons, legacy code needs to be maintained
5995 using only Ada 83 features.
5997 With few exceptions (most notably the need to use @code{<>} on
5998 @cindex Generic formal parameters
5999 unconstrained generic formal parameters, the use of the new Ada 95
6000 reserved words, and the use of packages
6001 with optional bodies), it is not necessary to use the
6002 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6003 exceptions, Ada 95 is upwardly compatible with Ada 83. This
6004 means that a correct Ada 83 program is usually also a correct Ada 95
6006 For further information, please refer to @ref{Compatibility and Porting Guide}.
6008 @item -gnat95 (Ada 95 mode)
6009 @cindex @option{-gnat95} (@command{gcc})
6012 GNAT is primarily an Ada 95 compiler, and all current releases of GNAT Pro
6013 compile in Ada 95 mode by default. Typically, Ada 95 is sufficiently upwards
6014 compatible with Ada 83, that legacy Ada 83 programs may be compiled using
6015 this default Ada95 mode without problems (see section above describing the
6016 use of @option{-gnat83} to run in Ada 83 mode).
6018 In Ada 95 mode, the use of Ada 2005 features will in general cause error
6019 messages or warnings. Some specialized releases of GNAT (notably the GAP
6020 academic version) operate in Ada 2005 mode by default (see section below
6021 describing the use of @option{-gnat05} to run in Ada 2005 mode). For such
6022 versions the @option{-gnat95} switch may be used to enforce Ada 95 mode.
6023 This option also can be used to cancel the effect of a previous
6024 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6027 @item -gnat05 (Ada 2005 mode)
6028 @cindex @option{-gnat05} (@command{gcc})
6031 Although GNAT is primarily an Ada 95 compiler, it can be set to operate
6032 in Ada 2005 mode using this option. Although the new standard has not
6033 yet been issued (as of early 2005), many features have been discussed and
6034 approved in ``Ada Issues'' (AI's). For the text of these AI's, see
6035 @url{www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}. Included with GNAT
6036 releases is a file @file{features-ada0y} that describes the current set
6037 of implemented Ada 2005 features.
6039 If these features are used in Ada 95 mode (which is the normal default),
6040 then error messages or warnings may be
6041 generated, reflecting the fact that these new features are otherwise
6042 unauthorized extensions to Ada 95. The use of the @option{-gnat05}
6043 switch (or an equivalent pragma) causes these messages to be suppressed.
6045 Note that some specialized releases of GNAT (notably the GAP academic
6046 version) have Ada 2005 mode on by default, and in such environments,
6047 the Ada 2005 features can be used freely without the use of switches.
6051 @node Character Set Control
6052 @subsection Character Set Control
6054 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6055 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6058 Normally GNAT recognizes the Latin-1 character set in source program
6059 identifiers, as described in the Ada 95 Reference Manual.
6061 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6062 single character ^^or word^ indicating the character set, as follows:
6066 ISO 8859-1 (Latin-1) identifiers
6069 ISO 8859-2 (Latin-2) letters allowed in identifiers
6072 ISO 8859-3 (Latin-3) letters allowed in identifiers
6075 ISO 8859-4 (Latin-4) letters allowed in identifiers
6078 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6081 ISO 8859-15 (Latin-9) letters allowed in identifiers
6084 IBM PC letters (code page 437) allowed in identifiers
6087 IBM PC letters (code page 850) allowed in identifiers
6089 @item ^f^FULL_UPPER^
6090 Full upper-half codes allowed in identifiers
6093 No upper-half codes allowed in identifiers
6096 Wide-character codes (that is, codes greater than 255)
6097 allowed in identifiers
6100 @xref{Foreign Language Representation}, for full details on the
6101 implementation of these character sets.
6103 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6104 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6105 Specify the method of encoding for wide characters.
6106 @var{e} is one of the following:
6111 Hex encoding (brackets coding also recognized)
6114 Upper half encoding (brackets encoding also recognized)
6117 Shift/JIS encoding (brackets encoding also recognized)
6120 EUC encoding (brackets encoding also recognized)
6123 UTF-8 encoding (brackets encoding also recognized)
6126 Brackets encoding only (default value)
6128 For full details on the these encoding
6129 methods see @ref{Wide Character Encodings}.
6130 Note that brackets coding is always accepted, even if one of the other
6131 options is specified, so for example @option{-gnatW8} specifies that both
6132 brackets and @code{UTF-8} encodings will be recognized. The units that are
6133 with'ed directly or indirectly will be scanned using the specified
6134 representation scheme, and so if one of the non-brackets scheme is
6135 used, it must be used consistently throughout the program. However,
6136 since brackets encoding is always recognized, it may be conveniently
6137 used in standard libraries, allowing these libraries to be used with
6138 any of the available coding schemes.
6139 scheme. If no @option{-gnatW?} parameter is present, then the default
6140 representation is Brackets encoding only.
6142 Note that the wide character representation that is specified (explicitly
6143 or by default) for the main program also acts as the default encoding used
6144 for Wide_Text_IO files if not specifically overridden by a WCEM form
6148 @node File Naming Control
6149 @subsection File Naming Control
6152 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6153 @cindex @option{-gnatk} (@command{gcc})
6154 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6155 1-999, indicates the maximum allowable length of a file name (not
6156 including the @file{.ads} or @file{.adb} extension). The default is not
6157 to enable file name krunching.
6159 For the source file naming rules, @xref{File Naming Rules}.
6162 @node Subprogram Inlining Control
6163 @subsection Subprogram Inlining Control
6168 @cindex @option{-gnatn} (@command{gcc})
6170 The @code{n} here is intended to suggest the first syllable of the
6173 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6174 inlining to actually occur, optimization must be enabled. To enable
6175 inlining of subprograms specified by pragma @code{Inline},
6176 you must also specify this switch.
6177 In the absence of this switch, GNAT does not attempt
6178 inlining and does not need to access the bodies of
6179 subprograms for which @code{pragma Inline} is specified if they are not
6180 in the current unit.
6182 If you specify this switch the compiler will access these bodies,
6183 creating an extra source dependency for the resulting object file, and
6184 where possible, the call will be inlined.
6185 For further details on when inlining is possible
6186 see @ref{Inlining of Subprograms}.
6189 @cindex @option{-gnatN} (@command{gcc})
6190 The front end inlining activated by this switch is generally more extensive,
6191 and quite often more effective than the standard @option{-gnatn} inlining mode.
6192 It will also generate additional dependencies.
6194 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
6195 to specify both options.
6198 @node Auxiliary Output Control
6199 @subsection Auxiliary Output Control
6203 @cindex @option{-gnatt} (@command{gcc})
6204 @cindex Writing internal trees
6205 @cindex Internal trees, writing to file
6206 Causes GNAT to write the internal tree for a unit to a file (with the
6207 extension @file{.adt}.
6208 This not normally required, but is used by separate analysis tools.
6210 these tools do the necessary compilations automatically, so you should
6211 not have to specify this switch in normal operation.
6214 @cindex @option{-gnatu} (@command{gcc})
6215 Print a list of units required by this compilation on @file{stdout}.
6216 The listing includes all units on which the unit being compiled depends
6217 either directly or indirectly.
6220 @item -pass-exit-codes
6221 @cindex @option{-pass-exit-codes} (@command{gcc})
6222 If this switch is not used, the exit code returned by @command{gcc} when
6223 compiling multiple files indicates whether all source files have
6224 been successfully used to generate object files or not.
6226 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
6227 exit status and allows an integrated development environment to better
6228 react to a compilation failure. Those exit status are:
6232 There was an error in at least one source file.
6234 At least one source file did not generate an object file.
6236 The compiler died unexpectedly (internal error for example).
6238 An object file has been generated for every source file.
6243 @node Debugging Control
6244 @subsection Debugging Control
6248 @cindex Debugging options
6251 @cindex @option{-gnatd} (@command{gcc})
6252 Activate internal debugging switches. @var{x} is a letter or digit, or
6253 string of letters or digits, which specifies the type of debugging
6254 outputs desired. Normally these are used only for internal development
6255 or system debugging purposes. You can find full documentation for these
6256 switches in the body of the @code{Debug} unit in the compiler source
6257 file @file{debug.adb}.
6261 @cindex @option{-gnatG} (@command{gcc})
6262 This switch causes the compiler to generate auxiliary output containing
6263 a pseudo-source listing of the generated expanded code. Like most Ada
6264 compilers, GNAT works by first transforming the high level Ada code into
6265 lower level constructs. For example, tasking operations are transformed
6266 into calls to the tasking run-time routines. A unique capability of GNAT
6267 is to list this expanded code in a form very close to normal Ada source.
6268 This is very useful in understanding the implications of various Ada
6269 usage on the efficiency of the generated code. There are many cases in
6270 Ada (e.g. the use of controlled types), where simple Ada statements can
6271 generate a lot of run-time code. By using @option{-gnatG} you can identify
6272 these cases, and consider whether it may be desirable to modify the coding
6273 approach to improve efficiency.
6275 The format of the output is very similar to standard Ada source, and is
6276 easily understood by an Ada programmer. The following special syntactic
6277 additions correspond to low level features used in the generated code that
6278 do not have any exact analogies in pure Ada source form. The following
6279 is a partial list of these special constructions. See the specification
6280 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6283 @item new @var{xxx} [storage_pool = @var{yyy}]
6284 Shows the storage pool being used for an allocator.
6286 @item at end @var{procedure-name};
6287 Shows the finalization (cleanup) procedure for a scope.
6289 @item (if @var{expr} then @var{expr} else @var{expr})
6290 Conditional expression equivalent to the @code{x?y:z} construction in C.
6292 @item @var{target}^^^(@var{source})
6293 A conversion with floating-point truncation instead of rounding.
6295 @item @var{target}?(@var{source})
6296 A conversion that bypasses normal Ada semantic checking. In particular
6297 enumeration types and fixed-point types are treated simply as integers.
6299 @item @var{target}?^^^(@var{source})
6300 Combines the above two cases.
6302 @item @var{x} #/ @var{y}
6303 @itemx @var{x} #mod @var{y}
6304 @itemx @var{x} #* @var{y}
6305 @itemx @var{x} #rem @var{y}
6306 A division or multiplication of fixed-point values which are treated as
6307 integers without any kind of scaling.
6309 @item free @var{expr} [storage_pool = @var{xxx}]
6310 Shows the storage pool associated with a @code{free} statement.
6312 @item freeze @var{typename} [@var{actions}]
6313 Shows the point at which @var{typename} is frozen, with possible
6314 associated actions to be performed at the freeze point.
6316 @item reference @var{itype}
6317 Reference (and hence definition) to internal type @var{itype}.
6319 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6320 Intrinsic function call.
6322 @item @var{labelname} : label
6323 Declaration of label @var{labelname}.
6325 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
6326 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6327 @var{expr}, but handled more efficiently).
6329 @item [constraint_error]
6330 Raise the @code{Constraint_Error} exception.
6332 @item @var{expression}'reference
6333 A pointer to the result of evaluating @var{expression}.
6335 @item @var{target-type}!(@var{source-expression})
6336 An unchecked conversion of @var{source-expression} to @var{target-type}.
6338 @item [@var{numerator}/@var{denominator}]
6339 Used to represent internal real literals (that) have no exact
6340 representation in base 2-16 (for example, the result of compile time
6341 evaluation of the expression 1.0/27.0).
6345 @cindex @option{-gnatD} (@command{gcc})
6346 When used in conjunction with @option{-gnatG}, this switch causes
6347 the expanded source, as described above for
6348 @option{-gnatG} to be written to files with names
6349 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6350 instead of to the standard ooutput file. For
6351 example, if the source file name is @file{hello.adb}, then a file
6352 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written. The debugging
6353 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
6354 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6355 you to do source level debugging using the generated code which is
6356 sometimes useful for complex code, for example to find out exactly
6357 which part of a complex construction raised an exception. This switch
6358 also suppress generation of cross-reference information (see
6359 @option{-gnatx}) since otherwise the cross-reference information
6360 would refer to the @file{^.dg^.DG^} file, which would cause
6361 confusion since this is not the original source file.
6363 Note that @option{-gnatD} actually implies @option{-gnatG}
6364 automatically, so it is not necessary to give both options.
6365 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6368 @item -gnatR[0|1|2|3[s]]
6369 @cindex @option{-gnatR} (@command{gcc})
6370 This switch controls output from the compiler of a listing showing
6371 representation information for declared types and objects. For
6372 @option{-gnatR0}, no information is output (equivalent to omitting
6373 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6374 so @option{-gnatR} with no parameter has the same effect), size and alignment
6375 information is listed for declared array and record types. For
6376 @option{-gnatR2}, size and alignment information is listed for all
6377 expression information for values that are computed at run time for
6378 variant records. These symbolic expressions have a mostly obvious
6379 format with #n being used to represent the value of the n'th
6380 discriminant. See source files @file{repinfo.ads/adb} in the
6381 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6382 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
6383 the output is to a file with the name @file{^file.rep^file_REP^} where
6384 file is the name of the corresponding source file.
6387 @item /REPRESENTATION_INFO
6388 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
6389 This qualifier controls output from the compiler of a listing showing
6390 representation information for declared types and objects. For
6391 @option{/REPRESENTATION_INFO=NONE}, no information is output
6392 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6393 @option{/REPRESENTATION_INFO} without option is equivalent to
6394 @option{/REPRESENTATION_INFO=ARRAYS}.
6395 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6396 information is listed for declared array and record types. For
6397 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6398 is listed for all expression information for values that are computed
6399 at run time for variant records. These symbolic expressions have a mostly
6400 obvious format with #n being used to represent the value of the n'th
6401 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6402 @code{GNAT} sources for full details on the format of
6403 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6404 If _FILE is added at the end of an option
6405 (e.g. @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6406 then the output is to a file with the name @file{file_REP} where
6407 file is the name of the corresponding source file.
6411 @cindex @option{-gnatS} (@command{gcc})
6412 The use of the switch @option{-gnatS} for an
6413 Ada compilation will cause the compiler to output a
6414 representation of package Standard in a form very
6415 close to standard Ada. It is not quite possible to
6416 do this entirely in standard Ada (since new
6417 numeric base types cannot be created in standard
6418 Ada), but the output is easily
6419 readable to any Ada programmer, and is useful to
6420 determine the characteristics of target dependent
6421 types in package Standard.
6424 @cindex @option{-gnatx} (@command{gcc})
6425 Normally the compiler generates full cross-referencing information in
6426 the @file{ALI} file. This information is used by a number of tools,
6427 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
6428 suppresses this information. This saves some space and may slightly
6429 speed up compilation, but means that these tools cannot be used.
6432 @node Exception Handling Control
6433 @subsection Exception Handling Control
6436 GNAT uses two methods for handling exceptions at run-time. The
6437 @code{setjmp/longjmp} method saves the context when entering
6438 a frame with an exception handler. Then when an exception is
6439 raised, the context can be restored immediately, without the
6440 need for tracing stack frames. This method provides very fast
6441 exception propagation, but introduces significant overhead for
6442 the use of exception handlers, even if no exception is raised.
6444 The other approach is called ``zero cost'' exception handling.
6445 With this method, the compiler builds static tables to describe
6446 the exception ranges. No dynamic code is required when entering
6447 a frame containing an exception handler. When an exception is
6448 raised, the tables are used to control a back trace of the
6449 subprogram invocation stack to locate the required exception
6450 handler. This method has considerably poorer performance for
6451 the propagation of exceptions, but there is no overhead for
6452 exception handlers if no exception is raised. Note that in this
6453 mode and in the context of mixed Ada and C/C++ programming,
6454 to propagate an exception through a C/C++ code, the C/C++ code
6455 must be compiled with the @option{-funwind-tables} GCC's
6458 The following switches can be used to control which of the
6459 two exception handling methods is used.
6465 @cindex @option{--RTS=sjlj} (@command{gnatmake})
6466 This switch causes the setjmp/longjmp run-time to be used
6467 for exception handling. If this is the default mechanism for the
6468 target (see below), then this has no effect. If the default
6469 mechanism for the target is zero cost exceptions, then
6470 this switch can be used to modify this default, and must be
6471 used for all units in the partition.
6472 This option is rarely used. One case in which it may be
6473 advantageous is if you have an application where exception
6474 raising is common and the overall performance of the
6475 application is improved by favoring exception propagation.
6478 @cindex @option{--RTS=zcx} (@command{gnatmake})
6479 @cindex Zero Cost Exceptions
6480 This switch causes the zero cost approach to be used
6481 for exception handling. If this is the default mechanism for the
6482 target (see below), then this has no effect. If the default
6483 mechanism for the target is setjmp/longjmp exceptions, then
6484 this switch can be used to modify this default, and must be
6485 used for all units in the partition.
6486 This option can only be used if the zero cost approach
6487 is available for the target in use (see below).
6491 The @code{setjmp/longjmp} approach is available on all targets, while
6492 the @code{zero cost} approach is available on selected targets.
6493 To determine whether zero cost exceptions can be used for a
6494 particular target, look at the private part of the file system.ads.
6495 Either @code{GCC_ZCX_Support} or @code{Front_End_ZCX_Support} must
6496 be True to use the zero cost approach. If both of these switches
6497 are set to False, this means that zero cost exception handling
6498 is not yet available for that target. The switch
6499 @code{ZCX_By_Default} indicates the default approach. If this
6500 switch is set to True, then the @code{zero cost} approach is
6503 @node Units to Sources Mapping Files
6504 @subsection Units to Sources Mapping Files
6508 @item -gnatem^^=^@var{path}
6509 @cindex @option{-gnatem} (@command{gcc})
6510 A mapping file is a way to communicate to the compiler two mappings:
6511 from unit names to file names (without any directory information) and from
6512 file names to path names (with full directory information). These mappings
6513 are used by the compiler to short-circuit the path search.
6515 The use of mapping files is not required for correct operation of the
6516 compiler, but mapping files can improve efficiency, particularly when
6517 sources are read over a slow network connection. In normal operation,
6518 you need not be concerned with the format or use of mapping files,
6519 and the @option{-gnatem} switch is not a switch that you would use
6520 explicitly. it is intended only for use by automatic tools such as
6521 @command{gnatmake} running under the project file facility. The
6522 description here of the format of mapping files is provided
6523 for completeness and for possible use by other tools.
6525 A mapping file is a sequence of sets of three lines. In each set,
6526 the first line is the unit name, in lower case, with ``@code{%s}''
6528 specifications and ``@code{%b}'' appended for bodies; the second line is the
6529 file name; and the third line is the path name.
6535 /gnat/project1/sources/main.2.ada
6538 When the switch @option{-gnatem} is specified, the compiler will create
6539 in memory the two mappings from the specified file. If there is any problem
6540 (non existent file, truncated file or duplicate entries), no mapping
6543 Several @option{-gnatem} switches may be specified; however, only the last
6544 one on the command line will be taken into account.
6546 When using a project file, @command{gnatmake} create a temporary mapping file
6547 and communicates it to the compiler using this switch.
6551 @node Integrated Preprocessing
6552 @subsection Integrated Preprocessing
6555 GNAT sources may be preprocessed immediately before compilation; the actual
6556 text of the source is not the text of the source file, but is derived from it
6557 through a process called preprocessing. Integrated preprocessing is specified
6558 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
6559 indicates, through a text file, the preprocessing data to be used.
6560 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
6563 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
6564 used when Integrated Preprocessing is used. The reason is that preprocessing
6565 with another Preprocessing Data file without changing the sources will
6566 not trigger recompilation without this switch.
6569 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
6570 always trigger recompilation for sources that are preprocessed,
6571 because @command{gnatmake} cannot compute the checksum of the source after
6575 The actual preprocessing function is described in details in section
6576 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
6577 preprocessing is triggered and parameterized.
6581 @item -gnatep=@var{file}
6582 @cindex @option{-gnatep} (@command{gcc})
6583 This switch indicates to the compiler the file name (without directory
6584 information) of the preprocessor data file to use. The preprocessor data file
6585 should be found in the source directories.
6588 A preprocessing data file is a text file with significant lines indicating
6589 how should be preprocessed either a specific source or all sources not
6590 mentioned in other lines. A significant line is a non empty, non comment line.
6591 Comments are similar to Ada comments.
6594 Each significant line starts with either a literal string or the character '*'.
6595 A literal string is the file name (without directory information) of the source
6596 to preprocess. A character '*' indicates the preprocessing for all the sources
6597 that are not specified explicitly on other lines (order of the lines is not
6598 significant). It is an error to have two lines with the same file name or two
6599 lines starting with the character '*'.
6602 After the file name or the character '*', another optional literal string
6603 indicating the file name of the definition file to be used for preprocessing
6604 (@pxref{Form of Definitions File}). The definition files are found by the
6605 compiler in one of the source directories. In some cases, when compiling
6606 a source in a directory other than the current directory, if the definition
6607 file is in the current directory, it may be necessary to add the current
6608 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
6609 the compiler would not find the definition file.
6612 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
6613 be found. Those ^switches^switches^ are:
6618 Causes both preprocessor lines and the lines deleted by
6619 preprocessing to be replaced by blank lines, preserving the line number.
6620 This ^switch^switch^ is always implied; however, if specified after @option{-c}
6621 it cancels the effect of @option{-c}.
6624 Causes both preprocessor lines and the lines deleted
6625 by preprocessing to be retained as comments marked
6626 with the special string ``@code{--! }''.
6628 @item -Dsymbol=value
6629 Define or redefine a symbol, associated with value. A symbol is an Ada
6630 identifier, or an Ada reserved word, with the exception of @code{if},
6631 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6632 @code{value} is either a literal string, an Ada identifier or any Ada reserved
6633 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
6634 same name defined in a definition file.
6637 Causes a sorted list of symbol names and values to be
6638 listed on the standard output file.
6641 Causes undefined symbols to be treated as having the value @code{FALSE}
6643 of a preprocessor test. In the absence of this option, an undefined symbol in
6644 a @code{#if} or @code{#elsif} test will be treated as an error.
6649 Examples of valid lines in a preprocessor data file:
6652 "toto.adb" "prep.def" -u
6653 -- preprocess "toto.adb", using definition file "prep.def",
6654 -- undefined symbol are False.
6657 -- preprocess all other sources without a definition file;
6658 -- suppressed lined are commented; symbol VERSION has the value V101.
6660 "titi.adb" "prep2.def" -s
6661 -- preprocess "titi.adb", using definition file "prep2.def";
6662 -- list all symbols with their values.
6665 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
6666 @cindex @option{-gnateD} (@command{gcc})
6667 Define or redefine a preprocessing symbol, associated with value. If no value
6668 is given on the command line, then the value of the symbol is @code{True}.
6669 A symbol is an identifier, following normal Ada (case-insensitive)
6670 rules for its syntax, and value is any sequence (including an empty sequence)
6671 of characters from the set (letters, digits, period, underline).
6672 Ada reserved words may be used as symbols, with the exceptions of @code{if},
6673 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6676 A symbol declared with this ^switch^switch^ on the command line replaces a
6677 symbol with the same name either in a definition file or specified with a
6678 ^switch^switch^ -D in the preprocessor data file.
6681 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
6685 @node Code Generation Control
6686 @subsection Code Generation Control
6690 The GCC technology provides a wide range of target dependent
6691 @option{-m} switches for controlling
6692 details of code generation with respect to different versions of
6693 architectures. This includes variations in instruction sets (e.g.
6694 different members of the power pc family), and different requirements
6695 for optimal arrangement of instructions (e.g. different members of
6696 the x86 family). The list of available @option{-m} switches may be
6697 found in the GCC documentation.
6699 Use of the these @option{-m} switches may in some cases result in improved
6702 The GNAT Pro technology is tested and qualified without any
6703 @option{-m} switches,
6704 so generally the most reliable approach is to avoid the use of these
6705 switches. However, we generally expect most of these switches to work
6706 successfully with GNAT Pro, and many customers have reported successful
6707 use of these options.
6709 Our general advice is to avoid the use of @option{-m} switches unless
6710 special needs lead to requirements in this area. In particular,
6711 there is no point in using @option{-m} switches to improve performance
6712 unless you actually see a performance improvement.
6716 @subsection Return Codes
6717 @cindex Return Codes
6718 @cindex @option{/RETURN_CODES=VMS}
6721 On VMS, GNAT compiled programs return POSIX-style codes by default,
6722 e.g. @option{/RETURN_CODES=POSIX}.
6724 To enable VMS style return codes, use GNAT BIND and LINK with the option
6725 @option{/RETURN_CODES=VMS}. For example:
6728 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
6729 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
6733 Programs built with /RETURN_CODES=VMS are suitable to be called in
6734 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
6735 are suitable for spawning with appropriate GNAT RTL routines.
6739 @node Search Paths and the Run-Time Library (RTL)
6740 @section Search Paths and the Run-Time Library (RTL)
6743 With the GNAT source-based library system, the compiler must be able to
6744 find source files for units that are needed by the unit being compiled.
6745 Search paths are used to guide this process.
6747 The compiler compiles one source file whose name must be given
6748 explicitly on the command line. In other words, no searching is done
6749 for this file. To find all other source files that are needed (the most
6750 common being the specs of units), the compiler examines the following
6751 directories, in the following order:
6755 The directory containing the source file of the main unit being compiled
6756 (the file name on the command line).
6759 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
6760 @command{gcc} command line, in the order given.
6763 @findex ADA_PRJ_INCLUDE_FILE
6764 Each of the directories listed in the text file whose name is given
6765 by the @code{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
6768 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
6769 driver when project files are used. It should not normally be set
6773 @findex ADA_INCLUDE_PATH
6774 Each of the directories listed in the value of the
6775 @code{ADA_INCLUDE_PATH} ^environment variable^logical name^.
6777 Construct this value
6778 exactly as the @code{PATH} environment variable: a list of directory
6779 names separated by colons (semicolons when working with the NT version).
6782 Normally, define this value as a logical name containing a comma separated
6783 list of directory names.
6785 This variable can also be defined by means of an environment string
6786 (an argument to the DEC C exec* set of functions).
6790 DEFINE ANOTHER_PATH FOO:[BAG]
6791 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
6794 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
6795 first, followed by the standard Ada 95
6796 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
6797 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
6798 (Text_IO, Sequential_IO, etc)
6799 instead of the Ada95 packages. Thus, in order to get the Ada 95
6800 packages by default, ADA_INCLUDE_PATH must be redefined.
6804 The content of the @file{ada_source_path} file which is part of the GNAT
6805 installation tree and is used to store standard libraries such as the
6806 GNAT Run Time Library (RTL) source files.
6808 @ref{Installing a library}
6813 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
6814 inhibits the use of the directory
6815 containing the source file named in the command line. You can still
6816 have this directory on your search path, but in this case it must be
6817 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
6819 Specifying the switch @option{-nostdinc}
6820 inhibits the search of the default location for the GNAT Run Time
6821 Library (RTL) source files.
6823 The compiler outputs its object files and ALI files in the current
6826 Caution: The object file can be redirected with the @option{-o} switch;
6827 however, @command{gcc} and @code{gnat1} have not been coordinated on this
6828 so the @file{ALI} file will not go to the right place. Therefore, you should
6829 avoid using the @option{-o} switch.
6833 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
6834 children make up the GNAT RTL, together with the simple @code{System.IO}
6835 package used in the @code{"Hello World"} example. The sources for these units
6836 are needed by the compiler and are kept together in one directory. Not
6837 all of the bodies are needed, but all of the sources are kept together
6838 anyway. In a normal installation, you need not specify these directory
6839 names when compiling or binding. Either the environment variables or
6840 the built-in defaults cause these files to be found.
6842 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
6843 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
6844 consisting of child units of @code{GNAT}. This is a collection of generally
6845 useful types, subprograms, etc. See the @cite{GNAT Reference Manual} for
6848 Besides simplifying access to the RTL, a major use of search paths is
6849 in compiling sources from multiple directories. This can make
6850 development environments much more flexible.
6852 @node Order of Compilation Issues
6853 @section Order of Compilation Issues
6856 If, in our earlier example, there was a spec for the @code{hello}
6857 procedure, it would be contained in the file @file{hello.ads}; yet this
6858 file would not have to be explicitly compiled. This is the result of the
6859 model we chose to implement library management. Some of the consequences
6860 of this model are as follows:
6864 There is no point in compiling specs (except for package
6865 specs with no bodies) because these are compiled as needed by clients. If
6866 you attempt a useless compilation, you will receive an error message.
6867 It is also useless to compile subunits because they are compiled as needed
6871 There are no order of compilation requirements: performing a
6872 compilation never obsoletes anything. The only way you can obsolete
6873 something and require recompilations is to modify one of the
6874 source files on which it depends.
6877 There is no library as such, apart from the ALI files
6878 (@pxref{The Ada Library Information Files}, for information on the format
6879 of these files). For now we find it convenient to create separate ALI files,
6880 but eventually the information therein may be incorporated into the object
6884 When you compile a unit, the source files for the specs of all units
6885 that it @code{with}'s, all its subunits, and the bodies of any generics it
6886 instantiates must be available (reachable by the search-paths mechanism
6887 described above), or you will receive a fatal error message.
6894 The following are some typical Ada compilation command line examples:
6897 @item $ gcc -c xyz.adb
6898 Compile body in file @file{xyz.adb} with all default options.
6901 @item $ gcc -c -O2 -gnata xyz-def.adb
6904 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
6907 Compile the child unit package in file @file{xyz-def.adb} with extensive
6908 optimizations, and pragma @code{Assert}/@code{Debug} statements
6911 @item $ gcc -c -gnatc abc-def.adb
6912 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
6916 @node Binding Using gnatbind
6917 @chapter Binding Using @code{gnatbind}
6921 * Running gnatbind::
6922 * Switches for gnatbind::
6923 * Command-Line Access::
6924 * Search Paths for gnatbind::
6925 * Examples of gnatbind Usage::
6929 This chapter describes the GNAT binder, @code{gnatbind}, which is used
6930 to bind compiled GNAT objects. The @code{gnatbind} program performs
6931 four separate functions:
6935 Checks that a program is consistent, in accordance with the rules in
6936 Chapter 10 of the Ada 95 Reference Manual. In particular, error
6937 messages are generated if a program uses inconsistent versions of a
6941 Checks that an acceptable order of elaboration exists for the program
6942 and issues an error message if it cannot find an order of elaboration
6943 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
6946 Generates a main program incorporating the given elaboration order.
6947 This program is a small Ada package (body and spec) that
6948 must be subsequently compiled
6949 using the GNAT compiler. The necessary compilation step is usually
6950 performed automatically by @command{gnatlink}. The two most important
6951 functions of this program
6952 are to call the elaboration routines of units in an appropriate order
6953 and to call the main program.
6956 Determines the set of object files required by the given main program.
6957 This information is output in the forms of comments in the generated program,
6958 to be read by the @command{gnatlink} utility used to link the Ada application.
6961 @node Running gnatbind
6962 @section Running @code{gnatbind}
6965 The form of the @code{gnatbind} command is
6968 $ gnatbind [@i{switches}] @i{mainprog}[.ali] [@i{switches}]
6972 where @file{@i{mainprog}.adb} is the Ada file containing the main program
6973 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
6974 package in two files whose names are
6975 @file{b~@i{mainprog}.ads}, and @file{b~@i{mainprog}.adb}.
6976 For example, if given the
6977 parameter @file{hello.ali}, for a main program contained in file
6978 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
6979 and @file{b~hello.adb}.
6981 When doing consistency checking, the binder takes into consideration
6982 any source files it can locate. For example, if the binder determines
6983 that the given main program requires the package @code{Pack}, whose
6985 file is @file{pack.ali} and whose corresponding source spec file is
6986 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
6987 (using the same search path conventions as previously described for the
6988 @command{gcc} command). If it can locate this source file, it checks that
6990 or source checksums of the source and its references to in @file{ALI} files
6991 match. In other words, any @file{ALI} files that mentions this spec must have
6992 resulted from compiling this version of the source file (or in the case
6993 where the source checksums match, a version close enough that the
6994 difference does not matter).
6996 @cindex Source files, use by binder
6997 The effect of this consistency checking, which includes source files, is
6998 that the binder ensures that the program is consistent with the latest
6999 version of the source files that can be located at bind time. Editing a
7000 source file without compiling files that depend on the source file cause
7001 error messages to be generated by the binder.
7003 For example, suppose you have a main program @file{hello.adb} and a
7004 package @code{P}, from file @file{p.ads} and you perform the following
7009 Enter @code{gcc -c hello.adb} to compile the main program.
7012 Enter @code{gcc -c p.ads} to compile package @code{P}.
7015 Edit file @file{p.ads}.
7018 Enter @code{gnatbind hello}.
7022 At this point, the file @file{p.ali} contains an out-of-date time stamp
7023 because the file @file{p.ads} has been edited. The attempt at binding
7024 fails, and the binder generates the following error messages:
7027 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7028 error: "p.ads" has been modified and must be recompiled
7032 Now both files must be recompiled as indicated, and then the bind can
7033 succeed, generating a main program. You need not normally be concerned
7034 with the contents of this file, but for reference purposes a sample
7035 binder output file is given in @ref{Example of Binder Output File}.
7037 In most normal usage, the default mode of @command{gnatbind} which is to
7038 generate the main package in Ada, as described in the previous section.
7039 In particular, this means that any Ada programmer can read and understand
7040 the generated main program. It can also be debugged just like any other
7041 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7042 @command{gnatbind} and @command{gnatlink}.
7044 However for some purposes it may be convenient to generate the main
7045 program in C rather than Ada. This may for example be helpful when you
7046 are generating a mixed language program with the main program in C. The
7047 GNAT compiler itself is an example.
7048 The use of the @option{^-C^/BIND_FILE=C^} switch
7049 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7050 be generated in C (and compiled using the gnu C compiler).
7052 @node Switches for gnatbind
7053 @section Switches for @command{gnatbind}
7056 The following switches are available with @code{gnatbind}; details will
7057 be presented in subsequent sections.
7060 * Consistency-Checking Modes::
7061 * Binder Error Message Control::
7062 * Elaboration Control::
7064 * Binding with Non-Ada Main Programs::
7065 * Binding Programs with No Main Subprogram::
7070 @item ^-aO^/OBJECT_SEARCH^
7071 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7072 Specify directory to be searched for ALI files.
7074 @item ^-aI^/SOURCE_SEARCH^
7075 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7076 Specify directory to be searched for source file.
7078 @item ^-A^/BIND_FILE=ADA^
7079 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
7080 Generate binder program in Ada (default)
7082 @item ^-b^/REPORT_ERRORS=BRIEF^
7083 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
7084 Generate brief messages to @file{stderr} even if verbose mode set.
7086 @item ^-c^/NOOUTPUT^
7087 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
7088 Check only, no generation of binder output file.
7090 @item ^-C^/BIND_FILE=C^
7091 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
7092 Generate binder program in C
7094 @item ^-e^/ELABORATION_DEPENDENCIES^
7095 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
7096 Output complete list of elaboration-order dependencies.
7098 @item ^-E^/STORE_TRACEBACKS^
7099 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
7100 Store tracebacks in exception occurrences when the target supports it.
7101 This is the default with the zero cost exception mechanism.
7103 @c The following may get moved to an appendix
7104 This option is currently supported on the following targets:
7105 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
7107 See also the packages @code{GNAT.Traceback} and
7108 @code{GNAT.Traceback.Symbolic} for more information.
7110 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
7111 @command{gcc} option.
7114 @item ^-F^/FORCE_ELABS_FLAGS^
7115 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
7116 Force the checks of elaboration flags. @command{gnatbind} does not normally
7117 generate checks of elaboration flags for the main executable, except when
7118 a Stand-Alone Library is used. However, there are cases when this cannot be
7119 detected by gnatbind. An example is importing an interface of a Stand-Alone
7120 Library through a pragma Import and only specifying through a linker switch
7121 this Stand-Alone Library. This switch is used to guarantee that elaboration
7122 flag checks are generated.
7125 @cindex @option{^-h^/HELP^} (@command{gnatbind})
7126 Output usage (help) information
7129 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7130 Specify directory to be searched for source and ALI files.
7132 @item ^-I-^/NOCURRENT_DIRECTORY^
7133 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
7134 Do not look for sources in the current directory where @code{gnatbind} was
7135 invoked, and do not look for ALI files in the directory containing the
7136 ALI file named in the @code{gnatbind} command line.
7138 @item ^-l^/ORDER_OF_ELABORATION^
7139 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
7140 Output chosen elaboration order.
7142 @item ^-Lxxx^/BUILD_LIBRARY=xxx^
7143 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
7144 Bind the units for library building. In this case the adainit and
7145 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
7146 are renamed to ^xxxinit^XXXINIT^ and
7147 ^xxxfinal^XXXFINAL^.
7148 Implies ^-n^/NOCOMPILE^.
7150 (@xref{GNAT and Libraries}, for more details.)
7153 On OpenVMS, these init and final procedures are exported in uppercase
7154 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
7155 the init procedure will be "TOTOINIT" and the exported name of the final
7156 procedure will be "TOTOFINAL".
7159 @item ^-Mxyz^/RENAME_MAIN=xyz^
7160 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
7161 Rename generated main program from main to xyz
7163 @item ^-m^/ERROR_LIMIT=^@var{n}
7164 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
7165 Limit number of detected errors to @var{n}, where @var{n} is
7166 in the range 1..999_999. The default value if no switch is
7167 given is 9999. Binding is terminated if the limit is exceeded.
7169 Furthermore, under Windows, the sources pointed to by the libraries path
7170 set in the registry are not searched for.
7174 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7178 @cindex @option{-nostdinc} (@command{gnatbind})
7179 Do not look for sources in the system default directory.
7182 @cindex @option{-nostdlib} (@command{gnatbind})
7183 Do not look for library files in the system default directory.
7185 @item --RTS=@var{rts-path}
7186 @cindex @option{--RTS} (@code{gnatbind})
7187 Specifies the default location of the runtime library. Same meaning as the
7188 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
7190 @item ^-o ^/OUTPUT=^@var{file}
7191 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7192 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7193 Note that if this option is used, then linking must be done manually,
7194 gnatlink cannot be used.
7196 @item ^-O^/OBJECT_LIST^
7197 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7200 @item ^-p^/PESSIMISTIC_ELABORATION^
7201 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7202 Pessimistic (worst-case) elaboration order
7204 @item ^-s^/READ_SOURCES=ALL^
7205 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7206 Require all source files to be present.
7208 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7209 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7210 Specifies the value to be used when detecting uninitialized scalar
7211 objects with pragma Initialize_Scalars.
7212 The @var{xxx} ^string specified with the switch^option^ may be either
7214 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7215 @item ``@option{^lo^LOW^}'' for the lowest possible value
7216 @item ``@option{^hi^HIGH^}'' for the highest possible value
7217 @item ``@option{xx}'' for a value consisting of repeated bytes with the
7218 value 16#xx# (i.e. xx is a string of two hexadecimal digits).
7221 In addition, you can specify @option{-Sev} to indicate that the value is
7222 to be set at run time. In this case, the program will look for an environment
7223 @cindex GNAT_INIT_SCALARS
7224 variable of the form @code{GNAT_INIT_SCALARS=xx}, where xx is one
7225 of @option{in/lo/hi/xx} with the same meanings as above.
7226 If no environment variable is found, or if it does not have a valid value,
7227 then the default is @option{in} (invalid values).
7231 @cindex @option{-static} (@code{gnatbind})
7232 Link against a static GNAT run time.
7235 @cindex @option{-shared} (@code{gnatbind})
7236 Link against a shared GNAT run time when available.
7239 @item ^-t^/NOTIME_STAMP_CHECK^
7240 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7241 Tolerate time stamp and other consistency errors
7243 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7244 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7245 Set the time slice value to @var{n} milliseconds. If the system supports
7246 the specification of a specific time slice value, then the indicated value
7247 is used. If the system does not support specific time slice values, but
7248 does support some general notion of round-robin scheduling, then any
7249 non-zero value will activate round-robin scheduling.
7251 A value of zero is treated specially. It turns off time
7252 slicing, and in addition, indicates to the tasking run time that the
7253 semantics should match as closely as possible the Annex D
7254 requirements of the Ada RM, and in particular sets the default
7255 scheduling policy to @code{FIFO_Within_Priorities}.
7257 @item ^-v^/REPORT_ERRORS=VERBOSE^
7258 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7259 Verbose mode. Write error messages, header, summary output to
7264 @cindex @option{-w} (@code{gnatbind})
7265 Warning mode (@var{x}=s/e for suppress/treat as error)
7269 @item /WARNINGS=NORMAL
7270 @cindex @option{/WARNINGS} (@code{gnatbind})
7271 Normal warnings mode. Warnings are issued but ignored
7273 @item /WARNINGS=SUPPRESS
7274 @cindex @option{/WARNINGS} (@code{gnatbind})
7275 All warning messages are suppressed
7277 @item /WARNINGS=ERROR
7278 @cindex @option{/WARNINGS} (@code{gnatbind})
7279 Warning messages are treated as fatal errors
7282 @item ^-x^/READ_SOURCES=NONE^
7283 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7284 Exclude source files (check object consistency only).
7287 @item /READ_SOURCES=AVAILABLE
7288 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7289 Default mode, in which sources are checked for consistency only if
7293 @item ^-z^/ZERO_MAIN^
7294 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7300 You may obtain this listing of switches by running @code{gnatbind} with
7304 @node Consistency-Checking Modes
7305 @subsection Consistency-Checking Modes
7308 As described earlier, by default @code{gnatbind} checks
7309 that object files are consistent with one another and are consistent
7310 with any source files it can locate. The following switches control binder
7315 @item ^-s^/READ_SOURCES=ALL^
7316 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
7317 Require source files to be present. In this mode, the binder must be
7318 able to locate all source files that are referenced, in order to check
7319 their consistency. In normal mode, if a source file cannot be located it
7320 is simply ignored. If you specify this switch, a missing source
7323 @item ^-x^/READ_SOURCES=NONE^
7324 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
7325 Exclude source files. In this mode, the binder only checks that ALI
7326 files are consistent with one another. Source files are not accessed.
7327 The binder runs faster in this mode, and there is still a guarantee that
7328 the resulting program is self-consistent.
7329 If a source file has been edited since it was last compiled, and you
7330 specify this switch, the binder will not detect that the object
7331 file is out of date with respect to the source file. Note that this is the
7332 mode that is automatically used by @command{gnatmake} because in this
7333 case the checking against sources has already been performed by
7334 @command{gnatmake} in the course of compilation (i.e. before binding).
7337 @item /READ_SOURCES=AVAILABLE
7338 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
7339 This is the default mode in which source files are checked if they are
7340 available, and ignored if they are not available.
7344 @node Binder Error Message Control
7345 @subsection Binder Error Message Control
7348 The following switches provide control over the generation of error
7349 messages from the binder:
7353 @item ^-v^/REPORT_ERRORS=VERBOSE^
7354 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7355 Verbose mode. In the normal mode, brief error messages are generated to
7356 @file{stderr}. If this switch is present, a header is written
7357 to @file{stdout} and any error messages are directed to @file{stdout}.
7358 All that is written to @file{stderr} is a brief summary message.
7360 @item ^-b^/REPORT_ERRORS=BRIEF^
7361 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
7362 Generate brief error messages to @file{stderr} even if verbose mode is
7363 specified. This is relevant only when used with the
7364 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
7368 @cindex @option{-m} (@code{gnatbind})
7369 Limits the number of error messages to @var{n}, a decimal integer in the
7370 range 1-999. The binder terminates immediately if this limit is reached.
7373 @cindex @option{-M} (@code{gnatbind})
7374 Renames the generated main program from @code{main} to @code{xxx}.
7375 This is useful in the case of some cross-building environments, where
7376 the actual main program is separate from the one generated
7380 @item ^-ws^/WARNINGS=SUPPRESS^
7381 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
7383 Suppress all warning messages.
7385 @item ^-we^/WARNINGS=ERROR^
7386 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
7387 Treat any warning messages as fatal errors.
7390 @item /WARNINGS=NORMAL
7391 Standard mode with warnings generated, but warnings do not get treated
7395 @item ^-t^/NOTIME_STAMP_CHECK^
7396 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7397 @cindex Time stamp checks, in binder
7398 @cindex Binder consistency checks
7399 @cindex Consistency checks, in binder
7400 The binder performs a number of consistency checks including:
7404 Check that time stamps of a given source unit are consistent
7406 Check that checksums of a given source unit are consistent
7408 Check that consistent versions of @code{GNAT} were used for compilation
7410 Check consistency of configuration pragmas as required
7414 Normally failure of such checks, in accordance with the consistency
7415 requirements of the Ada Reference Manual, causes error messages to be
7416 generated which abort the binder and prevent the output of a binder
7417 file and subsequent link to obtain an executable.
7419 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
7420 into warnings, so that
7421 binding and linking can continue to completion even in the presence of such
7422 errors. The result may be a failed link (due to missing symbols), or a
7423 non-functional executable which has undefined semantics.
7424 @emph{This means that
7425 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
7429 @node Elaboration Control
7430 @subsection Elaboration Control
7433 The following switches provide additional control over the elaboration
7434 order. For full details see @ref{Elaboration Order Handling in GNAT}.
7437 @item ^-p^/PESSIMISTIC_ELABORATION^
7438 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
7439 Normally the binder attempts to choose an elaboration order that is
7440 likely to minimize the likelihood of an elaboration order error resulting
7441 in raising a @code{Program_Error} exception. This switch reverses the
7442 action of the binder, and requests that it deliberately choose an order
7443 that is likely to maximize the likelihood of an elaboration error.
7444 This is useful in ensuring portability and avoiding dependence on
7445 accidental fortuitous elaboration ordering.
7447 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
7449 elaboration checking is used (@option{-gnatE} switch used for compilation).
7450 This is because in the default static elaboration mode, all necessary
7451 @code{Elaborate_All} pragmas are implicitly inserted.
7452 These implicit pragmas are still respected by the binder in
7453 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
7454 safe elaboration order is assured.
7457 @node Output Control
7458 @subsection Output Control
7461 The following switches allow additional control over the output
7462 generated by the binder.
7467 @item ^-A^/BIND_FILE=ADA^
7468 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
7469 Generate binder program in Ada (default). The binder program is named
7470 @file{b~@var{mainprog}.adb} by default. This can be changed with
7471 @option{^-o^/OUTPUT^} @code{gnatbind} option.
7473 @item ^-c^/NOOUTPUT^
7474 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
7475 Check only. Do not generate the binder output file. In this mode the
7476 binder performs all error checks but does not generate an output file.
7478 @item ^-C^/BIND_FILE=C^
7479 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
7480 Generate binder program in C. The binder program is named
7481 @file{b_@var{mainprog}.c}.
7482 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
7485 @item ^-e^/ELABORATION_DEPENDENCIES^
7486 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
7487 Output complete list of elaboration-order dependencies, showing the
7488 reason for each dependency. This output can be rather extensive but may
7489 be useful in diagnosing problems with elaboration order. The output is
7490 written to @file{stdout}.
7493 @cindex @option{^-h^/HELP^} (@code{gnatbind})
7494 Output usage information. The output is written to @file{stdout}.
7496 @item ^-K^/LINKER_OPTION_LIST^
7497 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
7498 Output linker options to @file{stdout}. Includes library search paths,
7499 contents of pragmas Ident and Linker_Options, and libraries added
7502 @item ^-l^/ORDER_OF_ELABORATION^
7503 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
7504 Output chosen elaboration order. The output is written to @file{stdout}.
7506 @item ^-O^/OBJECT_LIST^
7507 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
7508 Output full names of all the object files that must be linked to provide
7509 the Ada component of the program. The output is written to @file{stdout}.
7510 This list includes the files explicitly supplied and referenced by the user
7511 as well as implicitly referenced run-time unit files. The latter are
7512 omitted if the corresponding units reside in shared libraries. The
7513 directory names for the run-time units depend on the system configuration.
7515 @item ^-o ^/OUTPUT=^@var{file}
7516 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
7517 Set name of output file to @var{file} instead of the normal
7518 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
7519 binder generated body filename. In C mode you would normally give
7520 @var{file} an extension of @file{.c} because it will be a C source program.
7521 Note that if this option is used, then linking must be done manually.
7522 It is not possible to use gnatlink in this case, since it cannot locate
7525 @item ^-r^/RESTRICTION_LIST^
7526 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
7527 Generate list of @code{pragma Restrictions} that could be applied to
7528 the current unit. This is useful for code audit purposes, and also may
7529 be used to improve code generation in some cases.
7533 @node Binding with Non-Ada Main Programs
7534 @subsection Binding with Non-Ada Main Programs
7537 In our description so far we have assumed that the main
7538 program is in Ada, and that the task of the binder is to generate a
7539 corresponding function @code{main} that invokes this Ada main
7540 program. GNAT also supports the building of executable programs where
7541 the main program is not in Ada, but some of the called routines are
7542 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
7543 The following switch is used in this situation:
7547 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
7548 No main program. The main program is not in Ada.
7552 In this case, most of the functions of the binder are still required,
7553 but instead of generating a main program, the binder generates a file
7554 containing the following callable routines:
7559 You must call this routine to initialize the Ada part of the program by
7560 calling the necessary elaboration routines. A call to @code{adainit} is
7561 required before the first call to an Ada subprogram.
7563 Note that it is assumed that the basic execution environment must be setup
7564 to be appropriate for Ada execution at the point where the first Ada
7565 subprogram is called. In particular, if the Ada code will do any
7566 floating-point operations, then the FPU must be setup in an appropriate
7567 manner. For the case of the x86, for example, full precision mode is
7568 required. The procedure GNAT.Float_Control.Reset may be used to ensure
7569 that the FPU is in the right state.
7573 You must call this routine to perform any library-level finalization
7574 required by the Ada subprograms. A call to @code{adafinal} is required
7575 after the last call to an Ada subprogram, and before the program
7580 If the @option{^-n^/NOMAIN^} switch
7581 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7582 @cindex Binder, multiple input files
7583 is given, more than one ALI file may appear on
7584 the command line for @code{gnatbind}. The normal @dfn{closure}
7585 calculation is performed for each of the specified units. Calculating
7586 the closure means finding out the set of units involved by tracing
7587 @code{with} references. The reason it is necessary to be able to
7588 specify more than one ALI file is that a given program may invoke two or
7589 more quite separate groups of Ada units.
7591 The binder takes the name of its output file from the last specified ALI
7592 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
7593 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
7594 The output is an Ada unit in source form that can
7595 be compiled with GNAT unless the -C switch is used in which case the
7596 output is a C source file, which must be compiled using the C compiler.
7597 This compilation occurs automatically as part of the @command{gnatlink}
7600 Currently the GNAT run time requires a FPU using 80 bits mode
7601 precision. Under targets where this is not the default it is required to
7602 call GNAT.Float_Control.Reset before using floating point numbers (this
7603 include float computation, float input and output) in the Ada code. A
7604 side effect is that this could be the wrong mode for the foreign code
7605 where floating point computation could be broken after this call.
7607 @node Binding Programs with No Main Subprogram
7608 @subsection Binding Programs with No Main Subprogram
7611 It is possible to have an Ada program which does not have a main
7612 subprogram. This program will call the elaboration routines of all the
7613 packages, then the finalization routines.
7615 The following switch is used to bind programs organized in this manner:
7618 @item ^-z^/ZERO_MAIN^
7619 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7620 Normally the binder checks that the unit name given on the command line
7621 corresponds to a suitable main subprogram. When this switch is used,
7622 a list of ALI files can be given, and the execution of the program
7623 consists of elaboration of these units in an appropriate order.
7626 @node Command-Line Access
7627 @section Command-Line Access
7630 The package @code{Ada.Command_Line} provides access to the command-line
7631 arguments and program name. In order for this interface to operate
7632 correctly, the two variables
7644 are declared in one of the GNAT library routines. These variables must
7645 be set from the actual @code{argc} and @code{argv} values passed to the
7646 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
7647 generates the C main program to automatically set these variables.
7648 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
7649 set these variables. If they are not set, the procedures in
7650 @code{Ada.Command_Line} will not be available, and any attempt to use
7651 them will raise @code{Constraint_Error}. If command line access is
7652 required, your main program must set @code{gnat_argc} and
7653 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
7656 @node Search Paths for gnatbind
7657 @section Search Paths for @code{gnatbind}
7660 The binder takes the name of an ALI file as its argument and needs to
7661 locate source files as well as other ALI files to verify object consistency.
7663 For source files, it follows exactly the same search rules as @command{gcc}
7664 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
7665 directories searched are:
7669 The directory containing the ALI file named in the command line, unless
7670 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
7673 All directories specified by @option{^-I^/SEARCH^}
7674 switches on the @code{gnatbind}
7675 command line, in the order given.
7678 @findex ADA_PRJ_OBJECTS_FILE
7679 Each of the directories listed in the text file whose name is given
7680 by the @code{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
7683 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7684 driver when project files are used. It should not normally be set
7688 @findex ADA_OBJECTS_PATH
7689 Each of the directories listed in the value of the
7690 @code{ADA_OBJECTS_PATH} ^environment variable^logical name^.
7692 Construct this value
7693 exactly as the @code{PATH} environment variable: a list of directory
7694 names separated by colons (semicolons when working with the NT version
7698 Normally, define this value as a logical name containing a comma separated
7699 list of directory names.
7701 This variable can also be defined by means of an environment string
7702 (an argument to the DEC C exec* set of functions).
7706 DEFINE ANOTHER_PATH FOO:[BAG]
7707 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7710 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7711 first, followed by the standard Ada 95
7712 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
7713 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
7714 (Text_IO, Sequential_IO, etc)
7715 instead of the Ada95 packages. Thus, in order to get the Ada 95
7716 packages by default, ADA_OBJECTS_PATH must be redefined.
7720 The content of the @file{ada_object_path} file which is part of the GNAT
7721 installation tree and is used to store standard libraries such as the
7722 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
7725 @ref{Installing a library}
7730 In the binder the switch @option{^-I^/SEARCH^}
7731 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7732 is used to specify both source and
7733 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
7734 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7735 instead if you want to specify
7736 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
7737 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
7738 if you want to specify library paths
7739 only. This means that for the binder
7740 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
7741 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
7742 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
7743 The binder generates the bind file (a C language source file) in the
7744 current working directory.
7750 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7751 children make up the GNAT Run-Time Library, together with the package
7752 GNAT and its children, which contain a set of useful additional
7753 library functions provided by GNAT. The sources for these units are
7754 needed by the compiler and are kept together in one directory. The ALI
7755 files and object files generated by compiling the RTL are needed by the
7756 binder and the linker and are kept together in one directory, typically
7757 different from the directory containing the sources. In a normal
7758 installation, you need not specify these directory names when compiling
7759 or binding. Either the environment variables or the built-in defaults
7760 cause these files to be found.
7762 Besides simplifying access to the RTL, a major use of search paths is
7763 in compiling sources from multiple directories. This can make
7764 development environments much more flexible.
7766 @node Examples of gnatbind Usage
7767 @section Examples of @code{gnatbind} Usage
7770 This section contains a number of examples of using the GNAT binding
7771 utility @code{gnatbind}.
7774 @item gnatbind hello
7775 The main program @code{Hello} (source program in @file{hello.adb}) is
7776 bound using the standard switch settings. The generated main program is
7777 @file{b~hello.adb}. This is the normal, default use of the binder.
7780 @item gnatbind hello -o mainprog.adb
7783 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
7785 The main program @code{Hello} (source program in @file{hello.adb}) is
7786 bound using the standard switch settings. The generated main program is
7787 @file{mainprog.adb} with the associated spec in
7788 @file{mainprog.ads}. Note that you must specify the body here not the
7789 spec, in the case where the output is in Ada. Note that if this option
7790 is used, then linking must be done manually, since gnatlink will not
7791 be able to find the generated file.
7794 @item gnatbind main -C -o mainprog.c -x
7797 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
7799 The main program @code{Main} (source program in
7800 @file{main.adb}) is bound, excluding source files from the
7801 consistency checking, generating
7802 the file @file{mainprog.c}.
7805 @item gnatbind -x main_program -C -o mainprog.c
7806 This command is exactly the same as the previous example. Switches may
7807 appear anywhere in the command line, and single letter switches may be
7808 combined into a single switch.
7812 @item gnatbind -n math dbase -C -o ada-control.c
7815 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
7817 The main program is in a language other than Ada, but calls to
7818 subprograms in packages @code{Math} and @code{Dbase} appear. This call
7819 to @code{gnatbind} generates the file @file{ada-control.c} containing
7820 the @code{adainit} and @code{adafinal} routines to be called before and
7821 after accessing the Ada units.
7824 @c ------------------------------------
7825 @node Linking Using gnatlink
7826 @chapter Linking Using @command{gnatlink}
7827 @c ------------------------------------
7831 This chapter discusses @command{gnatlink}, a tool that links
7832 an Ada program and builds an executable file. This utility
7833 invokes the system linker ^(via the @command{gcc} command)^^
7834 with a correct list of object files and library references.
7835 @command{gnatlink} automatically determines the list of files and
7836 references for the Ada part of a program. It uses the binder file
7837 generated by the @command{gnatbind} to determine this list.
7840 * Running gnatlink::
7841 * Switches for gnatlink::
7842 * Setting Stack Size from gnatlink::
7843 * Setting Heap Size from gnatlink::
7846 @node Running gnatlink
7847 @section Running @command{gnatlink}
7850 The form of the @command{gnatlink} command is
7853 $ gnatlink [@var{switches}] @var{mainprog}[.ali]
7854 [@var{non-Ada objects}] [@var{linker options}]
7858 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
7860 or linker options) may be in any order, provided that no non-Ada object may
7861 be mistaken for a main @file{ALI} file.
7862 Any file name @file{F} without the @file{.ali}
7863 extension will be taken as the main @file{ALI} file if a file exists
7864 whose name is the concatenation of @file{F} and @file{.ali}.
7867 @file{@var{mainprog}.ali} references the ALI file of the main program.
7868 The @file{.ali} extension of this file can be omitted. From this
7869 reference, @command{gnatlink} locates the corresponding binder file
7870 @file{b~@var{mainprog}.adb} and, using the information in this file along
7871 with the list of non-Ada objects and linker options, constructs a
7872 linker command file to create the executable.
7874 The arguments other than the @command{gnatlink} switches and the main
7875 @file{ALI} file are passed to the linker uninterpreted.
7876 They typically include the names of
7877 object files for units written in other languages than Ada and any library
7878 references required to resolve references in any of these foreign language
7879 units, or in @code{Import} pragmas in any Ada units.
7881 @var{linker options} is an optional list of linker specific
7883 The default linker called by gnatlink is @var{gcc} which in
7884 turn calls the appropriate system linker.
7885 Standard options for the linker such as @option{-lmy_lib} or
7886 @option{-Ldir} can be added as is.
7887 For options that are not recognized by
7888 @var{gcc} as linker options, use the @var{gcc} switches @option{-Xlinker} or
7890 Refer to the GCC documentation for
7891 details. Here is an example showing how to generate a linker map:
7895 $ gnatlink my_prog -Wl,-Map,MAPFILE
7900 <<Need example for VMS>>
7903 Using @var{linker options} it is possible to set the program stack and
7904 heap size. See @ref{Setting Stack Size from gnatlink} and
7905 @ref{Setting Heap Size from gnatlink}.
7907 @command{gnatlink} determines the list of objects required by the Ada
7908 program and prepends them to the list of objects passed to the linker.
7909 @command{gnatlink} also gathers any arguments set by the use of
7910 @code{pragma Linker_Options} and adds them to the list of arguments
7911 presented to the linker.
7914 @command{gnatlink} accepts the following types of extra files on the command
7915 line: objects (.OBJ), libraries (.OLB), sharable images (.EXE), and
7916 options files (.OPT). These are recognized and handled according to their
7920 @node Switches for gnatlink
7921 @section Switches for @command{gnatlink}
7924 The following switches are available with the @command{gnatlink} utility:
7929 @item ^-A^/BIND_FILE=ADA^
7930 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
7931 The binder has generated code in Ada. This is the default.
7933 @item ^-C^/BIND_FILE=C^
7934 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
7935 If instead of generating a file in Ada, the binder has generated one in
7936 C, then the linker needs to know about it. Use this switch to signal
7937 to @command{gnatlink} that the binder has generated C code rather than
7940 @item ^-f^/FORCE_OBJECT_FILE_LIST^
7941 @cindex Command line length
7942 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
7943 On some targets, the command line length is limited, and @command{gnatlink}
7944 will generate a separate file for the linker if the list of object files
7946 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
7947 to be generated even if
7948 the limit is not exceeded. This is useful in some cases to deal with
7949 special situations where the command line length is exceeded.
7952 @cindex Debugging information, including
7953 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
7954 The option to include debugging information causes the Ada bind file (in
7955 other words, @file{b~@var{mainprog}.adb}) to be compiled with
7956 @option{^-g^/DEBUG^}.
7957 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
7958 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
7959 Without @option{^-g^/DEBUG^}, the binder removes these files by
7960 default. The same procedure apply if a C bind file was generated using
7961 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
7962 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
7964 @item ^-n^/NOCOMPILE^
7965 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
7966 Do not compile the file generated by the binder. This may be used when
7967 a link is rerun with different options, but there is no need to recompile
7971 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
7972 Causes additional information to be output, including a full list of the
7973 included object files. This switch option is most useful when you want
7974 to see what set of object files are being used in the link step.
7976 @item ^-v -v^/VERBOSE/VERBOSE^
7977 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
7978 Very verbose mode. Requests that the compiler operate in verbose mode when
7979 it compiles the binder file, and that the system linker run in verbose mode.
7981 @item ^-o ^/EXECUTABLE=^@var{exec-name}
7982 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
7983 @var{exec-name} specifies an alternate name for the generated
7984 executable program. If this switch is omitted, the executable has the same
7985 name as the main unit. For example, @code{gnatlink try.ali} creates
7986 an executable called @file{^try^TRY.EXE^}.
7989 @item -b @var{target}
7990 @cindex @option{-b} (@command{gnatlink})
7991 Compile your program to run on @var{target}, which is the name of a
7992 system configuration. You must have a GNAT cross-compiler built if
7993 @var{target} is not the same as your host system.
7996 @cindex @option{-B} (@command{gnatlink})
7997 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
7998 from @var{dir} instead of the default location. Only use this switch
7999 when multiple versions of the GNAT compiler are available. See the
8000 @command{gcc} manual page for further details. You would normally use the
8001 @option{-b} or @option{-V} switch instead.
8003 @item --GCC=@var{compiler_name}
8004 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8005 Program used for compiling the binder file. The default is
8006 @command{gcc}. You need to use quotes around @var{compiler_name} if
8007 @code{compiler_name} contains spaces or other separator characters. As
8008 an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to use
8009 @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8010 inserted after your command name. Thus in the above example the compiler
8011 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8012 If several @option{--GCC=compiler_name} are used, only the last
8013 @var{compiler_name} is taken into account. However, all the additional
8014 switches are also taken into account. Thus,
8015 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8016 @option{--GCC="bar -x -y -z -t"}.
8018 @item --LINK=@var{name}
8019 @cindex @option{--LINK=} (@command{gnatlink})
8020 @var{name} is the name of the linker to be invoked. This is especially
8021 useful in mixed language programs since languages such as C++ require
8022 their own linker to be used. When this switch is omitted, the default
8023 name for the linker is @command{gcc}. When this switch is used, the
8024 specified linker is called instead of @command{gcc} with exactly the same
8025 parameters that would have been passed to @command{gcc} so if the desired
8026 linker requires different parameters it is necessary to use a wrapper
8027 script that massages the parameters before invoking the real linker. It
8028 may be useful to control the exact invocation by using the verbose
8034 @item /DEBUG=TRACEBACK
8035 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
8036 This qualifier causes sufficient information to be included in the
8037 executable file to allow a traceback, but does not include the full
8038 symbol information needed by the debugger.
8040 @item /IDENTIFICATION="<string>"
8041 @code{"<string>"} specifies the string to be stored in the image file
8042 identification field in the image header.
8043 It overrides any pragma @code{Ident} specified string.
8045 @item /NOINHIBIT-EXEC
8046 Generate the executable file even if there are linker warnings.
8048 @item /NOSTART_FILES
8049 Don't link in the object file containing the ``main'' transfer address.
8050 Used when linking with a foreign language main program compiled with a
8054 Prefer linking with object libraries over sharable images, even without
8060 @node Setting Stack Size from gnatlink
8061 @section Setting Stack Size from @command{gnatlink}
8064 Under Windows systems, it is possible to specify the program stack size from
8065 @command{gnatlink} using either:
8069 @item using @option{-Xlinker} linker option
8072 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
8075 This sets the stack reserve size to 0x10000 bytes and the stack commit
8076 size to 0x1000 bytes.
8078 @item using @option{-Wl} linker option
8081 $ gnatlink hello -Wl,--stack=0x1000000
8084 This sets the stack reserve size to 0x1000000 bytes. Note that with
8085 @option{-Wl} option it is not possible to set the stack commit size
8086 because the coma is a separator for this option.
8090 @node Setting Heap Size from gnatlink
8091 @section Setting Heap Size from @command{gnatlink}
8094 Under Windows systems, it is possible to specify the program heap size from
8095 @command{gnatlink} using either:
8099 @item using @option{-Xlinker} linker option
8102 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
8105 This sets the heap reserve size to 0x10000 bytes and the heap commit
8106 size to 0x1000 bytes.
8108 @item using @option{-Wl} linker option
8111 $ gnatlink hello -Wl,--heap=0x1000000
8114 This sets the heap reserve size to 0x1000000 bytes. Note that with
8115 @option{-Wl} option it is not possible to set the heap commit size
8116 because the coma is a separator for this option.
8120 @node The GNAT Make Program gnatmake
8121 @chapter The GNAT Make Program @command{gnatmake}
8125 * Running gnatmake::
8126 * Switches for gnatmake::
8127 * Mode Switches for gnatmake::
8128 * Notes on the Command Line::
8129 * How gnatmake Works::
8130 * Examples of gnatmake Usage::
8133 A typical development cycle when working on an Ada program consists of
8134 the following steps:
8138 Edit some sources to fix bugs.
8144 Compile all sources affected.
8154 The third step can be tricky, because not only do the modified files
8155 @cindex Dependency rules
8156 have to be compiled, but any files depending on these files must also be
8157 recompiled. The dependency rules in Ada can be quite complex, especially
8158 in the presence of overloading, @code{use} clauses, generics and inlined
8161 @command{gnatmake} automatically takes care of the third and fourth steps
8162 of this process. It determines which sources need to be compiled,
8163 compiles them, and binds and links the resulting object files.
8165 Unlike some other Ada make programs, the dependencies are always
8166 accurately recomputed from the new sources. The source based approach of
8167 the GNAT compilation model makes this possible. This means that if
8168 changes to the source program cause corresponding changes in
8169 dependencies, they will always be tracked exactly correctly by
8172 @node Running gnatmake
8173 @section Running @command{gnatmake}
8176 The usual form of the @command{gnatmake} command is
8179 $ gnatmake [@var{switches}] @var{file_name}
8180 [@var{file_names}] [@var{mode_switches}]
8184 The only required argument is one @var{file_name}, which specifies
8185 a compilation unit that is a main program. Several @var{file_names} can be
8186 specified: this will result in several executables being built.
8187 If @code{switches} are present, they can be placed before the first
8188 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8189 If @var{mode_switches} are present, they must always be placed after
8190 the last @var{file_name} and all @code{switches}.
8192 If you are using standard file extensions (.adb and .ads), then the
8193 extension may be omitted from the @var{file_name} arguments. However, if
8194 you are using non-standard extensions, then it is required that the
8195 extension be given. A relative or absolute directory path can be
8196 specified in a @var{file_name}, in which case, the input source file will
8197 be searched for in the specified directory only. Otherwise, the input
8198 source file will first be searched in the directory where
8199 @command{gnatmake} was invoked and if it is not found, it will be search on
8200 the source path of the compiler as described in
8201 @ref{Search Paths and the Run-Time Library (RTL)}.
8203 All @command{gnatmake} output (except when you specify
8204 @option{^-M^/DEPENDENCIES_LIST^}) is to
8205 @file{stderr}. The output produced by the
8206 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8209 @node Switches for gnatmake
8210 @section Switches for @command{gnatmake}
8213 You may specify any of the following switches to @command{gnatmake}:
8218 @item --GCC=@var{compiler_name}
8219 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
8220 Program used for compiling. The default is `@command{gcc}'. You need to use
8221 quotes around @var{compiler_name} if @code{compiler_name} contains
8222 spaces or other separator characters. As an example @option{--GCC="foo -x
8223 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
8224 compiler. Note that switch @option{-c} is always inserted after your
8225 command name. Thus in the above example the compiler command that will
8226 be used by @command{gnatmake} will be @code{foo -c -x -y}.
8227 If several @option{--GCC=compiler_name} are used, only the last
8228 @var{compiler_name} is taken into account. However, all the additional
8229 switches are also taken into account. Thus,
8230 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8231 @option{--GCC="bar -x -y -z -t"}.
8233 @item --GNATBIND=@var{binder_name}
8234 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
8235 Program used for binding. The default is `@code{gnatbind}'. You need to
8236 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8237 or other separator characters. As an example @option{--GNATBIND="bar -x
8238 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
8239 binder. Binder switches that are normally appended by @command{gnatmake} to
8240 `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8242 @item --GNATLINK=@var{linker_name}
8243 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
8244 Program used for linking. The default is `@command{gnatlink}'. You need to
8245 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8246 or other separator characters. As an example @option{--GNATLINK="lan -x
8247 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
8248 linker. Linker switches that are normally appended by @command{gnatmake} to
8249 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
8253 @item ^-a^/ALL_FILES^
8254 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
8255 Consider all files in the make process, even the GNAT internal system
8256 files (for example, the predefined Ada library files), as well as any
8257 locked files. Locked files are files whose ALI file is write-protected.
8259 @command{gnatmake} does not check these files,
8260 because the assumption is that the GNAT internal files are properly up
8261 to date, and also that any write protected ALI files have been properly
8262 installed. Note that if there is an installation problem, such that one
8263 of these files is not up to date, it will be properly caught by the
8265 You may have to specify this switch if you are working on GNAT
8266 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8267 in conjunction with @option{^-f^/FORCE_COMPILE^}
8268 if you need to recompile an entire application,
8269 including run-time files, using special configuration pragmas,
8270 such as a @code{Normalize_Scalars} pragma.
8273 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8276 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8279 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8282 @item ^-b^/ACTIONS=BIND^
8283 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
8284 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8285 compilation and binding, but no link.
8286 Can be combined with @option{^-l^/ACTIONS=LINK^}
8287 to do binding and linking. When not combined with
8288 @option{^-c^/ACTIONS=COMPILE^}
8289 all the units in the closure of the main program must have been previously
8290 compiled and must be up to date. The root unit specified by @var{file_name}
8291 may be given without extension, with the source extension or, if no GNAT
8292 Project File is specified, with the ALI file extension.
8294 @item ^-c^/ACTIONS=COMPILE^
8295 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
8296 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8297 is also specified. Do not perform linking, except if both
8298 @option{^-b^/ACTIONS=BIND^} and
8299 @option{^-l^/ACTIONS=LINK^} are also specified.
8300 If the root unit specified by @var{file_name} is not a main unit, this is the
8301 default. Otherwise @command{gnatmake} will attempt binding and linking
8302 unless all objects are up to date and the executable is more recent than
8306 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
8307 Use a temporary mapping file. A mapping file is a way to communicate to the
8308 compiler two mappings: from unit names to file names (without any directory
8309 information) and from file names to path names (with full directory
8310 information). These mappings are used by the compiler to short-circuit the path
8311 search. When @command{gnatmake} is invoked with this switch, it will create
8312 a temporary mapping file, initially populated by the project manager,
8313 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8314 Each invocation of the compiler will add the newly accessed sources to the
8315 mapping file. This will improve the source search during the next invocation
8318 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8319 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
8320 Use a specific mapping file. The file, specified as a path name (absolute or
8321 relative) by this switch, should already exist, otherwise the switch is
8322 ineffective. The specified mapping file will be communicated to the compiler.
8323 This switch is not compatible with a project file
8324 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8325 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8327 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
8328 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
8329 Put all object files and ALI file in directory @var{dir}.
8330 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
8331 and ALI files go in the current working directory.
8333 This switch cannot be used when using a project file.
8337 @cindex @option{-eL} (@command{gnatmake})
8338 Follow all symbolic links when processing project files.
8341 @item ^-f^/FORCE_COMPILE^
8342 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
8343 Force recompilations. Recompile all sources, even though some object
8344 files may be up to date, but don't recompile predefined or GNAT internal
8345 files or locked files (files with a write-protected ALI file),
8346 unless the @option{^-a^/ALL_FILES^} switch is also specified.
8348 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
8349 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
8350 When using project files, if some errors or warnings are detected during
8351 parsing and verbose mode is not in effect (no use of switch
8352 ^-v^/VERBOSE^), then error lines start with the full path name of the project
8353 file, rather than its simple file name.
8355 @item ^-i^/IN_PLACE^
8356 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
8357 In normal mode, @command{gnatmake} compiles all object files and ALI files
8358 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
8359 then instead object files and ALI files that already exist are overwritten
8360 in place. This means that once a large project is organized into separate
8361 directories in the desired manner, then @command{gnatmake} will automatically
8362 maintain and update this organization. If no ALI files are found on the
8363 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
8364 the new object and ALI files are created in the
8365 directory containing the source being compiled. If another organization
8366 is desired, where objects and sources are kept in different directories,
8367 a useful technique is to create dummy ALI files in the desired directories.
8368 When detecting such a dummy file, @command{gnatmake} will be forced to
8369 recompile the corresponding source file, and it will be put the resulting
8370 object and ALI files in the directory where it found the dummy file.
8372 @item ^-j^/PROCESSES=^@var{n}
8373 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
8374 @cindex Parallel make
8375 Use @var{n} processes to carry out the (re)compilations. On a
8376 multiprocessor machine compilations will occur in parallel. In the
8377 event of compilation errors, messages from various compilations might
8378 get interspersed (but @command{gnatmake} will give you the full ordered
8379 list of failing compiles at the end). If this is problematic, rerun
8380 the make process with n set to 1 to get a clean list of messages.
8382 @item ^-k^/CONTINUE_ON_ERROR^
8383 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
8384 Keep going. Continue as much as possible after a compilation error. To
8385 ease the programmer's task in case of compilation errors, the list of
8386 sources for which the compile fails is given when @command{gnatmake}
8389 If @command{gnatmake} is invoked with several @file{file_names} and with this
8390 switch, if there are compilation errors when building an executable,
8391 @command{gnatmake} will not attempt to build the following executables.
8393 @item ^-l^/ACTIONS=LINK^
8394 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
8395 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
8396 and linking. Linking will not be performed if combined with
8397 @option{^-c^/ACTIONS=COMPILE^}
8398 but not with @option{^-b^/ACTIONS=BIND^}.
8399 When not combined with @option{^-b^/ACTIONS=BIND^}
8400 all the units in the closure of the main program must have been previously
8401 compiled and must be up to date, and the main program needs to have been bound.
8402 The root unit specified by @var{file_name}
8403 may be given without extension, with the source extension or, if no GNAT
8404 Project File is specified, with the ALI file extension.
8406 @item ^-m^/MINIMAL_RECOMPILATION^
8407 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
8408 Specify that the minimum necessary amount of recompilations
8409 be performed. In this mode @command{gnatmake} ignores time
8410 stamp differences when the only
8411 modifications to a source file consist in adding/removing comments,
8412 empty lines, spaces or tabs. This means that if you have changed the
8413 comments in a source file or have simply reformatted it, using this
8414 switch will tell gnatmake not to recompile files that depend on it
8415 (provided other sources on which these files depend have undergone no
8416 semantic modifications). Note that the debugging information may be
8417 out of date with respect to the sources if the @option{-m} switch causes
8418 a compilation to be switched, so the use of this switch represents a
8419 trade-off between compilation time and accurate debugging information.
8421 @item ^-M^/DEPENDENCIES_LIST^
8422 @cindex Dependencies, producing list
8423 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
8424 Check if all objects are up to date. If they are, output the object
8425 dependences to @file{stdout} in a form that can be directly exploited in
8426 a @file{Makefile}. By default, each source file is prefixed with its
8427 (relative or absolute) directory name. This name is whatever you
8428 specified in the various @option{^-aI^/SOURCE_SEARCH^}
8429 and @option{^-I^/SEARCH^} switches. If you use
8430 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
8431 @option{^-q^/QUIET^}
8432 (see below), only the source file names,
8433 without relative paths, are output. If you just specify the
8434 @option{^-M^/DEPENDENCIES_LIST^}
8435 switch, dependencies of the GNAT internal system files are omitted. This
8436 is typically what you want. If you also specify
8437 the @option{^-a^/ALL_FILES^} switch,
8438 dependencies of the GNAT internal files are also listed. Note that
8439 dependencies of the objects in external Ada libraries (see switch
8440 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
8443 @item ^-n^/DO_OBJECT_CHECK^
8444 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
8445 Don't compile, bind, or link. Checks if all objects are up to date.
8446 If they are not, the full name of the first file that needs to be
8447 recompiled is printed.
8448 Repeated use of this option, followed by compiling the indicated source
8449 file, will eventually result in recompiling all required units.
8451 @item ^-o ^/EXECUTABLE=^@var{exec_name}
8452 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
8453 Output executable name. The name of the final executable program will be
8454 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
8455 name for the executable will be the name of the input file in appropriate form
8456 for an executable file on the host system.
8458 This switch cannot be used when invoking @command{gnatmake} with several
8461 @item ^-P^/PROJECT_FILE=^@var{project}
8462 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
8463 Use project file @var{project}. Only one such switch can be used.
8464 @xref{gnatmake and Project Files}.
8467 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
8468 Quiet. When this flag is not set, the commands carried out by
8469 @command{gnatmake} are displayed.
8471 @item ^-s^/SWITCH_CHECK/^
8472 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
8473 Recompile if compiler switches have changed since last compilation.
8474 All compiler switches but -I and -o are taken into account in the
8476 orders between different ``first letter'' switches are ignored, but
8477 orders between same switches are taken into account. For example,
8478 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
8479 is equivalent to @option{-O -g}.
8481 This switch is recommended when Integrated Preprocessing is used.
8484 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
8485 Unique. Recompile at most the main files. It implies -c. Combined with
8486 -f, it is equivalent to calling the compiler directly. Note that using
8487 ^-u^/UNIQUE^ with a project file and no main has a special meaning
8488 (@pxref{Project Files and Main Subprograms}).
8490 @item ^-U^/ALL_PROJECTS^
8491 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
8492 When used without a project file or with one or several mains on the command
8493 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
8494 on the command line, all sources of all project files are checked and compiled
8495 if not up to date, and libraries are rebuilt, if necessary.
8498 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
8499 Verbose. Display the reason for all recompilations @command{gnatmake}
8500 decides are necessary.
8502 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
8503 Indicate the verbosity of the parsing of GNAT project files.
8504 @xref{Switches Related to Project Files}.
8506 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
8507 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
8508 Indicate that sources that are not part of any Project File may be compiled.
8509 Normally, when using Project Files, only sources that are part of a Project
8510 File may be compile. When this switch is used, a source outside of all Project
8511 Files may be compiled. The ALI file and the object file will be put in the
8512 object directory of the main Project. The compilation switches used will only
8513 be those specified on the command line.
8515 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
8516 Indicate that external variable @var{name} has the value @var{value}.
8517 The Project Manager will use this value for occurrences of
8518 @code{external(name)} when parsing the project file.
8519 @xref{Switches Related to Project Files}.
8522 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
8523 No main subprogram. Bind and link the program even if the unit name
8524 given on the command line is a package name. The resulting executable
8525 will execute the elaboration routines of the package and its closure,
8526 then the finalization routines.
8529 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
8530 Enable debugging. This switch is simply passed to the compiler and to the
8536 @item @command{gcc} @asis{switches}
8538 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
8539 is passed to @command{gcc} (e.g. @option{-O}, @option{-gnato,} etc.)
8542 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
8543 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
8544 automatically treated as a compiler switch, and passed on to all
8545 compilations that are carried out.
8550 Source and library search path switches:
8554 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
8555 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
8556 When looking for source files also look in directory @var{dir}.
8557 The order in which source files search is undertaken is
8558 described in @ref{Search Paths and the Run-Time Library (RTL)}.
8560 @item ^-aL^/SKIP_MISSING=^@var{dir}
8561 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
8562 Consider @var{dir} as being an externally provided Ada library.
8563 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
8564 files have been located in directory @var{dir}. This allows you to have
8565 missing bodies for the units in @var{dir} and to ignore out of date bodies
8566 for the same units. You still need to specify
8567 the location of the specs for these units by using the switches
8568 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
8569 or @option{^-I^/SEARCH=^@var{dir}}.
8570 Note: this switch is provided for compatibility with previous versions
8571 of @command{gnatmake}. The easier method of causing standard libraries
8572 to be excluded from consideration is to write-protect the corresponding
8575 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
8576 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
8577 When searching for library and object files, look in directory
8578 @var{dir}. The order in which library files are searched is described in
8579 @ref{Search Paths for gnatbind}.
8581 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
8582 @cindex Search paths, for @command{gnatmake}
8583 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
8584 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
8585 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8587 @item ^-I^/SEARCH=^@var{dir}
8588 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
8589 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
8590 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8592 @item ^-I-^/NOCURRENT_DIRECTORY^
8593 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
8594 @cindex Source files, suppressing search
8595 Do not look for source files in the directory containing the source
8596 file named in the command line.
8597 Do not look for ALI or object files in the directory
8598 where @command{gnatmake} was invoked.
8600 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
8601 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
8602 @cindex Linker libraries
8603 Add directory @var{dir} to the list of directories in which the linker
8604 will search for libraries. This is equivalent to
8605 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
8607 Furthermore, under Windows, the sources pointed to by the libraries path
8608 set in the registry are not searched for.
8612 @cindex @option{-nostdinc} (@command{gnatmake})
8613 Do not look for source files in the system default directory.
8616 @cindex @option{-nostdlib} (@command{gnatmake})
8617 Do not look for library files in the system default directory.
8619 @item --RTS=@var{rts-path}
8620 @cindex @option{--RTS} (@command{gnatmake})
8621 Specifies the default location of the runtime library. GNAT looks for the
8623 in the following directories, and stops as soon as a valid runtime is found
8624 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
8625 @file{ada_object_path} present):
8628 @item <current directory>/$rts_path
8630 @item <default-search-dir>/$rts_path
8632 @item <default-search-dir>/rts-$rts_path
8636 The selected path is handled like a normal RTS path.
8640 @node Mode Switches for gnatmake
8641 @section Mode Switches for @command{gnatmake}
8644 The mode switches (referred to as @code{mode_switches}) allow the
8645 inclusion of switches that are to be passed to the compiler itself, the
8646 binder or the linker. The effect of a mode switch is to cause all
8647 subsequent switches up to the end of the switch list, or up to the next
8648 mode switch, to be interpreted as switches to be passed on to the
8649 designated component of GNAT.
8653 @item -cargs @var{switches}
8654 @cindex @option{-cargs} (@command{gnatmake})
8655 Compiler switches. Here @var{switches} is a list of switches
8656 that are valid switches for @command{gcc}. They will be passed on to
8657 all compile steps performed by @command{gnatmake}.
8659 @item -bargs @var{switches}
8660 @cindex @option{-bargs} (@command{gnatmake})
8661 Binder switches. Here @var{switches} is a list of switches
8662 that are valid switches for @code{gnatbind}. They will be passed on to
8663 all bind steps performed by @command{gnatmake}.
8665 @item -largs @var{switches}
8666 @cindex @option{-largs} (@command{gnatmake})
8667 Linker switches. Here @var{switches} is a list of switches
8668 that are valid switches for @command{gnatlink}. They will be passed on to
8669 all link steps performed by @command{gnatmake}.
8671 @item -margs @var{switches}
8672 @cindex @option{-margs} (@command{gnatmake})
8673 Make switches. The switches are directly interpreted by @command{gnatmake},
8674 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
8678 @node Notes on the Command Line
8679 @section Notes on the Command Line
8682 This section contains some additional useful notes on the operation
8683 of the @command{gnatmake} command.
8687 @cindex Recompilation, by @command{gnatmake}
8688 If @command{gnatmake} finds no ALI files, it recompiles the main program
8689 and all other units required by the main program.
8690 This means that @command{gnatmake}
8691 can be used for the initial compile, as well as during subsequent steps of
8692 the development cycle.
8695 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
8696 is a subunit or body of a generic unit, @command{gnatmake} recompiles
8697 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
8701 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
8702 is used to specify both source and
8703 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8704 instead if you just want to specify
8705 source paths only and @option{^-aO^/OBJECT_SEARCH^}
8706 if you want to specify library paths
8710 @command{gnatmake} will ignore any files whose ALI file is write-protected.
8711 This may conveniently be used to exclude standard libraries from
8712 consideration and in particular it means that the use of the
8713 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
8714 unless @option{^-a^/ALL_FILES^} is also specified.
8717 @command{gnatmake} has been designed to make the use of Ada libraries
8718 particularly convenient. Assume you have an Ada library organized
8719 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
8720 of your Ada compilation units,
8721 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
8722 specs of these units, but no bodies. Then to compile a unit
8723 stored in @code{main.adb}, which uses this Ada library you would just type
8727 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
8730 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
8731 /SKIP_MISSING=@i{[OBJ_DIR]} main
8736 Using @command{gnatmake} along with the
8737 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
8738 switch provides a mechanism for avoiding unnecessary rcompilations. Using
8740 you can update the comments/format of your
8741 source files without having to recompile everything. Note, however, that
8742 adding or deleting lines in a source files may render its debugging
8743 info obsolete. If the file in question is a spec, the impact is rather
8744 limited, as that debugging info will only be useful during the
8745 elaboration phase of your program. For bodies the impact can be more
8746 significant. In all events, your debugger will warn you if a source file
8747 is more recent than the corresponding object, and alert you to the fact
8748 that the debugging information may be out of date.
8751 @node How gnatmake Works
8752 @section How @command{gnatmake} Works
8755 Generally @command{gnatmake} automatically performs all necessary
8756 recompilations and you don't need to worry about how it works. However,
8757 it may be useful to have some basic understanding of the @command{gnatmake}
8758 approach and in particular to understand how it uses the results of
8759 previous compilations without incorrectly depending on them.
8761 First a definition: an object file is considered @dfn{up to date} if the
8762 corresponding ALI file exists and if all the source files listed in the
8763 dependency section of this ALI file have time stamps matching those in
8764 the ALI file. This means that neither the source file itself nor any
8765 files that it depends on have been modified, and hence there is no need
8766 to recompile this file.
8768 @command{gnatmake} works by first checking if the specified main unit is up
8769 to date. If so, no compilations are required for the main unit. If not,
8770 @command{gnatmake} compiles the main program to build a new ALI file that
8771 reflects the latest sources. Then the ALI file of the main unit is
8772 examined to find all the source files on which the main program depends,
8773 and @command{gnatmake} recursively applies the above procedure on all these
8776 This process ensures that @command{gnatmake} only trusts the dependencies
8777 in an existing ALI file if they are known to be correct. Otherwise it
8778 always recompiles to determine a new, guaranteed accurate set of
8779 dependencies. As a result the program is compiled ``upside down'' from what may
8780 be more familiar as the required order of compilation in some other Ada
8781 systems. In particular, clients are compiled before the units on which
8782 they depend. The ability of GNAT to compile in any order is critical in
8783 allowing an order of compilation to be chosen that guarantees that
8784 @command{gnatmake} will recompute a correct set of new dependencies if
8787 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
8788 imported by several of the executables, it will be recompiled at most once.
8790 Note: when using non-standard naming conventions
8791 (@pxref{Using Other File Names}), changing through a configuration pragmas
8792 file the version of a source and invoking @command{gnatmake} to recompile may
8793 have no effect, if the previous version of the source is still accessible
8794 by @command{gnatmake}. It may be necessary to use the switch
8795 ^-f^/FORCE_COMPILE^.
8797 @node Examples of gnatmake Usage
8798 @section Examples of @command{gnatmake} Usage
8801 @item gnatmake hello.adb
8802 Compile all files necessary to bind and link the main program
8803 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
8804 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
8806 @item gnatmake main1 main2 main3
8807 Compile all files necessary to bind and link the main programs
8808 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
8809 (containing unit @code{Main2}) and @file{main3.adb}
8810 (containing unit @code{Main3}) and bind and link the resulting object files
8811 to generate three executable files @file{^main1^MAIN1.EXE^},
8812 @file{^main2^MAIN2.EXE^}
8813 and @file{^main3^MAIN3.EXE^}.
8816 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
8820 @item gnatmake Main_Unit /QUIET
8821 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
8822 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
8824 Compile all files necessary to bind and link the main program unit
8825 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
8826 be done with optimization level 2 and the order of elaboration will be
8827 listed by the binder. @command{gnatmake} will operate in quiet mode, not
8828 displaying commands it is executing.
8831 @c *************************
8832 @node Improving Performance
8833 @chapter Improving Performance
8834 @cindex Improving performance
8837 This chapter presents several topics related to program performance.
8838 It first describes some of the tradeoffs that need to be considered
8839 and some of the techniques for making your program run faster.
8840 It then documents the @command{gnatelim} tool, which can reduce
8841 the size of program executables.
8845 * Performance Considerations::
8846 * Reducing the Size of Ada Executables with gnatelim::
8850 @c *****************************
8851 @node Performance Considerations
8852 @section Performance Considerations
8855 The GNAT system provides a number of options that allow a trade-off
8860 performance of the generated code
8863 speed of compilation
8866 minimization of dependences and recompilation
8869 the degree of run-time checking.
8873 The defaults (if no options are selected) aim at improving the speed
8874 of compilation and minimizing dependences, at the expense of performance
8875 of the generated code:
8882 no inlining of subprogram calls
8885 all run-time checks enabled except overflow and elaboration checks
8889 These options are suitable for most program development purposes. This
8890 chapter describes how you can modify these choices, and also provides
8891 some guidelines on debugging optimized code.
8894 * Controlling Run-Time Checks::
8895 * Use of Restrictions::
8896 * Optimization Levels::
8897 * Debugging Optimized Code::
8898 * Inlining of Subprograms::
8899 * Other Optimization Switches::
8900 * Optimization and Strict Aliasing::
8903 * Coverage Analysis::
8907 @node Controlling Run-Time Checks
8908 @subsection Controlling Run-Time Checks
8911 By default, GNAT generates all run-time checks, except arithmetic overflow
8912 checking for integer operations and checks for access before elaboration on
8913 subprogram calls. The latter are not required in default mode, because all
8914 necessary checking is done at compile time.
8915 @cindex @option{-gnatp} (@command{gcc})
8916 @cindex @option{-gnato} (@command{gcc})
8917 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
8918 be modified. @xref{Run-Time Checks}.
8920 Our experience is that the default is suitable for most development
8923 We treat integer overflow specially because these
8924 are quite expensive and in our experience are not as important as other
8925 run-time checks in the development process. Note that division by zero
8926 is not considered an overflow check, and divide by zero checks are
8927 generated where required by default.
8929 Elaboration checks are off by default, and also not needed by default, since
8930 GNAT uses a static elaboration analysis approach that avoids the need for
8931 run-time checking. This manual contains a full chapter discussing the issue
8932 of elaboration checks, and if the default is not satisfactory for your use,
8933 you should read this chapter.
8935 For validity checks, the minimal checks required by the Ada Reference
8936 Manual (for case statements and assignments to array elements) are on
8937 by default. These can be suppressed by use of the @option{-gnatVn} switch.
8938 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
8939 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
8940 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
8941 are also suppressed entirely if @option{-gnatp} is used.
8943 @cindex Overflow checks
8944 @cindex Checks, overflow
8947 @cindex pragma Suppress
8948 @cindex pragma Unsuppress
8949 Note that the setting of the switches controls the default setting of
8950 the checks. They may be modified using either @code{pragma Suppress} (to
8951 remove checks) or @code{pragma Unsuppress} (to add back suppressed
8952 checks) in the program source.
8954 @node Use of Restrictions
8955 @subsection Use of Restrictions
8958 The use of pragma Restrictions allows you to control which features are
8959 permitted in your program. Apart from the obvious point that if you avoid
8960 relatively expensive features like finalization (enforceable by the use
8961 of pragma Restrictions (No_Finalization), the use of this pragma does not
8962 affect the generated code in most cases.
8964 One notable exception to this rule is that the possibility of task abort
8965 results in some distributed overhead, particularly if finalization or
8966 exception handlers are used. The reason is that certain sections of code
8967 have to be marked as non-abortable.
8969 If you use neither the @code{abort} statement, nor asynchronous transfer
8970 of control (@code{select .. then abort}), then this distributed overhead
8971 is removed, which may have a general positive effect in improving
8972 overall performance. Especially code involving frequent use of tasking
8973 constructs and controlled types will show much improved performance.
8974 The relevant restrictions pragmas are
8977 pragma Restrictions (No_Abort_Statements);
8978 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
8982 It is recommended that these restriction pragmas be used if possible. Note
8983 that this also means that you can write code without worrying about the
8984 possibility of an immediate abort at any point.
8986 @node Optimization Levels
8987 @subsection Optimization Levels
8988 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
8991 The default is optimization off. This results in the fastest compile
8992 times, but GNAT makes absolutely no attempt to optimize, and the
8993 generated programs are considerably larger and slower than when
8994 optimization is enabled. You can use the
8996 @option{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
8999 @code{OPTIMIZE} qualifier
9001 to @command{gcc} to control the optimization level:
9004 @item ^-O0^/OPTIMIZE=NONE^
9005 No optimization (the default);
9006 generates unoptimized code but has
9007 the fastest compilation time.
9009 Note that many other compilers do fairly extensive optimization
9010 even if "no optimization" is specified. When using gcc, it is
9011 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
9012 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
9013 really does mean no optimization at all. This difference between
9014 gcc and other compilers should be kept in mind when doing
9015 performance comparisons.
9017 @item ^-O1^/OPTIMIZE=SOME^
9018 Moderate optimization;
9019 optimizes reasonably well but does not
9020 degrade compilation time significantly.
9022 @item ^-O2^/OPTIMIZE=ALL^
9024 @itemx /OPTIMIZE=DEVELOPMENT
9027 generates highly optimized code and has
9028 the slowest compilation time.
9030 @item ^-O3^/OPTIMIZE=INLINING^
9031 Full optimization as in @option{-O2},
9032 and also attempts automatic inlining of small
9033 subprograms within a unit (@pxref{Inlining of Subprograms}).
9037 Higher optimization levels perform more global transformations on the
9038 program and apply more expensive analysis algorithms in order to generate
9039 faster and more compact code. The price in compilation time, and the
9040 resulting improvement in execution time,
9041 both depend on the particular application and the hardware environment.
9042 You should experiment to find the best level for your application.
9044 Since the precise set of optimizations done at each level will vary from
9045 release to release (and sometime from target to target), it is best to think
9046 of the optimization settings in general terms.
9047 The @cite{Using GNU GCC} manual contains details about
9048 ^the @option{-O} settings and a number of @option{-f} options that^how to^
9049 individually enable or disable specific optimizations.
9051 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
9052 been tested extensively at all optimization levels. There are some bugs
9053 which appear only with optimization turned on, but there have also been
9054 bugs which show up only in @emph{unoptimized} code. Selecting a lower
9055 level of optimization does not improve the reliability of the code
9056 generator, which in practice is highly reliable at all optimization
9059 Note regarding the use of @option{-O3}: The use of this optimization level
9060 is generally discouraged with GNAT, since it often results in larger
9061 executables which run more slowly. See further discussion of this point
9062 in @ref{Inlining of Subprograms}.
9064 @node Debugging Optimized Code
9065 @subsection Debugging Optimized Code
9066 @cindex Debugging optimized code
9067 @cindex Optimization and debugging
9070 Although it is possible to do a reasonable amount of debugging at
9072 non-zero optimization levels,
9073 the higher the level the more likely that
9076 @option{/OPTIMIZE} settings other than @code{NONE},
9077 such settings will make it more likely that
9079 source-level constructs will have been eliminated by optimization.
9080 For example, if a loop is strength-reduced, the loop
9081 control variable may be completely eliminated and thus cannot be
9082 displayed in the debugger.
9083 This can only happen at @option{-O2} or @option{-O3}.
9084 Explicit temporary variables that you code might be eliminated at
9085 ^level^setting^ @option{-O1} or higher.
9087 The use of the @option{^-g^/DEBUG^} switch,
9088 @cindex @option{^-g^/DEBUG^} (@command{gcc})
9089 which is needed for source-level debugging,
9090 affects the size of the program executable on disk,
9091 and indeed the debugging information can be quite large.
9092 However, it has no effect on the generated code (and thus does not
9093 degrade performance)
9095 Since the compiler generates debugging tables for a compilation unit before
9096 it performs optimizations, the optimizing transformations may invalidate some
9097 of the debugging data. You therefore need to anticipate certain
9098 anomalous situations that may arise while debugging optimized code.
9099 These are the most common cases:
9103 @i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next}
9105 the PC bouncing back and forth in the code. This may result from any of
9106 the following optimizations:
9110 @i{Common subexpression elimination:} using a single instance of code for a
9111 quantity that the source computes several times. As a result you
9112 may not be able to stop on what looks like a statement.
9115 @i{Invariant code motion:} moving an expression that does not change within a
9116 loop, to the beginning of the loop.
9119 @i{Instruction scheduling:} moving instructions so as to
9120 overlap loads and stores (typically) with other code, or in
9121 general to move computations of values closer to their uses. Often
9122 this causes you to pass an assignment statement without the assignment
9123 happening and then later bounce back to the statement when the
9124 value is actually needed. Placing a breakpoint on a line of code
9125 and then stepping over it may, therefore, not always cause all the
9126 expected side-effects.
9130 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
9131 two identical pieces of code are merged and the program counter suddenly
9132 jumps to a statement that is not supposed to be executed, simply because
9133 it (and the code following) translates to the same thing as the code
9134 that @emph{was} supposed to be executed. This effect is typically seen in
9135 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
9136 a @code{break} in a C @code{^switch^switch^} statement.
9139 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
9140 There are various reasons for this effect:
9144 In a subprogram prologue, a parameter may not yet have been moved to its
9148 A variable may be dead, and its register re-used. This is
9149 probably the most common cause.
9152 As mentioned above, the assignment of a value to a variable may
9156 A variable may be eliminated entirely by value propagation or
9157 other means. In this case, GCC may incorrectly generate debugging
9158 information for the variable
9162 In general, when an unexpected value appears for a local variable or parameter
9163 you should first ascertain if that value was actually computed by
9164 your program, as opposed to being incorrectly reported by the debugger.
9166 array elements in an object designated by an access value
9167 are generally less of a problem, once you have ascertained that the access
9169 Typically, this means checking variables in the preceding code and in the
9170 calling subprogram to verify that the value observed is explainable from other
9171 values (one must apply the procedure recursively to those
9172 other values); or re-running the code and stopping a little earlier
9173 (perhaps before the call) and stepping to better see how the variable obtained
9174 the value in question; or continuing to step @emph{from} the point of the
9175 strange value to see if code motion had simply moved the variable's
9180 In light of such anomalies, a recommended technique is to use @option{-O0}
9181 early in the software development cycle, when extensive debugging capabilities
9182 are most needed, and then move to @option{-O1} and later @option{-O2} as
9183 the debugger becomes less critical.
9184 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
9185 a release management issue.
9187 Note that if you use @option{-g} you can then use the @command{strip} program
9188 on the resulting executable,
9189 which removes both debugging information and global symbols.
9192 @node Inlining of Subprograms
9193 @subsection Inlining of Subprograms
9196 A call to a subprogram in the current unit is inlined if all the
9197 following conditions are met:
9201 The optimization level is at least @option{-O1}.
9204 The called subprogram is suitable for inlining: It must be small enough
9205 and not contain nested subprograms or anything else that @command{gcc}
9206 cannot support in inlined subprograms.
9209 The call occurs after the definition of the body of the subprogram.
9212 @cindex pragma Inline
9214 Either @code{pragma Inline} applies to the subprogram or it is
9215 small and automatic inlining (optimization level @option{-O3}) is
9220 Calls to subprograms in @code{with}'ed units are normally not inlined.
9221 To achieve this level of inlining, the following conditions must all be
9226 The optimization level is at least @option{-O1}.
9229 The called subprogram is suitable for inlining: It must be small enough
9230 and not contain nested subprograms or anything else @command{gcc} cannot
9231 support in inlined subprograms.
9234 The call appears in a body (not in a package spec).
9237 There is a @code{pragma Inline} for the subprogram.
9240 @cindex @option{-gnatn} (@command{gcc})
9241 The @option{^-gnatn^/INLINE^} switch
9242 is used in the @command{gcc} command line
9245 Note that specifying the @option{-gnatn} switch causes additional
9246 compilation dependencies. Consider the following:
9248 @smallexample @c ada
9268 With the default behavior (no @option{-gnatn} switch specified), the
9269 compilation of the @code{Main} procedure depends only on its own source,
9270 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
9271 means that editing the body of @code{R} does not require recompiling
9274 On the other hand, the call @code{R.Q} is not inlined under these
9275 circumstances. If the @option{-gnatn} switch is present when @code{Main}
9276 is compiled, the call will be inlined if the body of @code{Q} is small
9277 enough, but now @code{Main} depends on the body of @code{R} in
9278 @file{r.adb} as well as on the spec. This means that if this body is edited,
9279 the main program must be recompiled. Note that this extra dependency
9280 occurs whether or not the call is in fact inlined by @command{gcc}.
9282 The use of front end inlining with @option{-gnatN} generates similar
9283 additional dependencies.
9285 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
9286 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
9287 can be used to prevent
9288 all inlining. This switch overrides all other conditions and ensures
9289 that no inlining occurs. The extra dependences resulting from
9290 @option{-gnatn} will still be active, even if
9291 this switch is used to suppress the resulting inlining actions.
9293 Note regarding the use of @option{-O3}: There is no difference in inlining
9294 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
9295 pragma @code{Inline} assuming the use of @option{-gnatn}
9296 or @option{-gnatN} (the switches that activate inlining). If you have used
9297 pragma @code{Inline} in appropriate cases, then it is usually much better
9298 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
9299 in this case only has the effect of inlining subprograms you did not
9300 think should be inlined. We often find that the use of @option{-O3} slows
9301 down code by performing excessive inlining, leading to increased instruction
9302 cache pressure from the increased code size. So the bottom line here is
9303 that you should not automatically assume that @option{-O3} is better than
9304 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
9305 it actually improves performance.
9307 @node Other Optimization Switches
9308 @subsection Other Optimization Switches
9309 @cindex Optimization Switches
9311 Since @code{GNAT} uses the @code{gcc} back end, all the specialized
9312 @code{gcc} optimization switches are potentially usable. These switches
9313 have not been extensively tested with GNAT but can generally be expected
9314 to work. Examples of switches in this category are
9315 @option{-funroll-loops} and
9316 the various target-specific @option{-m} options (in particular, it has been
9317 observed that @option{-march=pentium4} can significantly improve performance
9318 on appropriate machines. For full details of these switches, see the
9321 @node Optimization and Strict Aliasing
9322 @subsection Optimization and Strict Aliasing
9324 @cindex Strict Aliasing
9325 @cindex No_Strict_Aliasing
9328 The strong typing capabilities of Ada allow an optimizer to generate
9329 efficient code in situations where other languages would be forced to
9330 make worst case assumptions preventing such optimizations. Consider
9331 the following example:
9333 @smallexample @c ada
9336 type Int1 is new Integer;
9337 type Int2 is new Integer;
9338 type Int1A is access Int1;
9339 type Int2A is access Int2;
9346 for J in Data'Range loop
9347 if Data (J) = Int1V.all then
9348 Int2V.all := Int2V.all + 1;
9357 In this example, since the variable @code{Int1V} can only access objects
9358 of type @code{Int1}, and @code{Int2V} can only access objects of type
9359 @code{Int2}, there is no possibility that the assignment to
9360 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
9361 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
9362 for all iterations of the loop and avoid the extra memory reference
9363 required to dereference it each time through the loop.
9365 This kind of optimization, called strict aliasing analysis, is
9366 triggered by specifying an optimization level of @option{-O2} or
9367 higher and allows @code{GNAT} to generate more efficient code
9368 when access values are involved.
9370 However, although this optimization is always correct in terms of
9371 the formal semantics of the Ada Reference Manual, difficulties can
9372 arise if features like @code{Unchecked_Conversion} are used to break
9373 the typing system. Consider the following complete program example:
9375 @smallexample @c ada
9378 type int1 is new integer;
9379 type int2 is new integer;
9380 type a1 is access int1;
9381 type a2 is access int2;
9386 function to_a2 (Input : a1) return a2;
9389 with Unchecked_Conversion;
9391 function to_a2 (Input : a1) return a2 is
9393 new Unchecked_Conversion (a1, a2);
9395 return to_a2u (Input);
9401 with Text_IO; use Text_IO;
9403 v1 : a1 := new int1;
9404 v2 : a2 := to_a2 (v1);
9408 put_line (int1'image (v1.all));
9414 This program prints out 0 in @code{-O0} or @code{-O1}
9415 mode, but it prints out 1 in @code{-O2} mode. That's
9416 because in strict aliasing mode, the compiler can and
9417 does assume that the assignment to @code{v2.all} could not
9418 affect the value of @code{v1.all}, since different types
9421 This behavior is not a case of non-conformance with the standard, since
9422 the Ada RM specifies that an unchecked conversion where the resulting
9423 bit pattern is not a correct value of the target type can result in an
9424 abnormal value and attempting to reference an abnormal value makes the
9425 execution of a program erroneous. That's the case here since the result
9426 does not point to an object of type @code{int2}. This means that the
9427 effect is entirely unpredictable.
9429 However, although that explanation may satisfy a language
9430 lawyer, in practice an applications programmer expects an
9431 unchecked conversion involving pointers to create true
9432 aliases and the behavior of printing 1 seems plain wrong.
9433 In this case, the strict aliasing optimization is unwelcome.
9435 Indeed the compiler recognizes this possibility, and the
9436 unchecked conversion generates a warning:
9439 p2.adb:5:07: warning: possible aliasing problem with type "a2"
9440 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
9441 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
9445 Unfortunately the problem is recognized when compiling the body of
9446 package @code{p2}, but the actual "bad" code is generated while
9447 compiling the body of @code{m} and this latter compilation does not see
9448 the suspicious @code{Unchecked_Conversion}.
9450 As implied by the warning message, there are approaches you can use to
9451 avoid the unwanted strict aliasing optimization in a case like this.
9453 One possibility is to simply avoid the use of @code{-O2}, but
9454 that is a bit drastic, since it throws away a number of useful
9455 optimizations that do not involve strict aliasing assumptions.
9457 A less drastic approach is to compile the program using the
9458 option @code{-fno-strict-aliasing}. Actually it is only the
9459 unit containing the dereferencing of the suspicious pointer
9460 that needs to be compiled. So in this case, if we compile
9461 unit @code{m} with this switch, then we get the expected
9462 value of zero printed. Analyzing which units might need
9463 the switch can be painful, so a more reasonable approach
9464 is to compile the entire program with options @code{-O2}
9465 and @code{-fno-strict-aliasing}. If the performance is
9466 satisfactory with this combination of options, then the
9467 advantage is that the entire issue of possible "wrong"
9468 optimization due to strict aliasing is avoided.
9470 To avoid the use of compiler switches, the configuration
9471 pragma @code{No_Strict_Aliasing} with no parameters may be
9472 used to specify that for all access types, the strict
9473 aliasing optimization should be suppressed.
9475 However, these approaches are still overkill, in that they causes
9476 all manipulations of all access values to be deoptimized. A more
9477 refined approach is to concentrate attention on the specific
9478 access type identified as problematic.
9480 First, if a careful analysis of uses of the pointer shows
9481 that there are no possible problematic references, then
9482 the warning can be suppressed by bracketing the
9483 instantiation of @code{Unchecked_Conversion} to turn
9486 @smallexample @c ada
9487 pragma Warnings (Off);
9489 new Unchecked_Conversion (a1, a2);
9490 pragma Warnings (On);
9494 Of course that approach is not appropriate for this particular
9495 example, since indeed there is a problematic reference. In this
9496 case we can take one of two other approaches.
9498 The first possibility is to move the instantiation of unchecked
9499 conversion to the unit in which the type is declared. In
9500 this example, we would move the instantiation of
9501 @code{Unchecked_Conversion} from the body of package
9502 @code{p2} to the spec of package @code{p1}. Now the
9503 warning disappears. That's because any use of the
9504 access type knows there is a suspicious unchecked
9505 conversion, and the strict aliasing optimization
9506 is automatically suppressed for the type.
9508 If it is not practical to move the unchecked conversion to the same unit
9509 in which the destination access type is declared (perhaps because the
9510 source type is not visible in that unit), you may use pragma
9511 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
9512 same declarative sequence as the declaration of the access type:
9514 @smallexample @c ada
9515 type a2 is access int2;
9516 pragma No_Strict_Aliasing (a2);
9520 Here again, the compiler now knows that the strict aliasing optimization
9521 should be suppressed for any reference to type @code{a2} and the
9522 expected behavior is obtained.
9524 Finally, note that although the compiler can generate warnings for
9525 simple cases of unchecked conversions, there are tricker and more
9526 indirect ways of creating type incorrect aliases which the compiler
9527 cannot detect. Examples are the use of address overlays and unchecked
9528 conversions involving composite types containing access types as
9529 components. In such cases, no warnings are generated, but there can
9530 still be aliasing problems. One safe coding practice is to forbid the
9531 use of address clauses for type overlaying, and to allow unchecked
9532 conversion only for primitive types. This is not really a significant
9533 restriction since any possible desired effect can be achieved by
9534 unchecked conversion of access values.
9537 @node Coverage Analysis
9538 @subsection Coverage Analysis
9541 GNAT supports the Digital Performance Coverage Analyzer (PCA), which allows
9542 the user to determine the distribution of execution time across a program,
9543 @pxref{Profiling} for details of usage.
9546 @node Reducing the Size of Ada Executables with gnatelim
9547 @section Reducing the Size of Ada Executables with @code{gnatelim}
9551 This section describes @command{gnatelim}, a tool which detects unused
9552 subprograms and helps the compiler to create a smaller executable for your
9557 * Running gnatelim::
9558 * Correcting the List of Eliminate Pragmas::
9559 * Making Your Executables Smaller::
9560 * Summary of the gnatelim Usage Cycle::
9563 @node About gnatelim
9564 @subsection About @code{gnatelim}
9567 When a program shares a set of Ada
9568 packages with other programs, it may happen that this program uses
9569 only a fraction of the subprograms defined in these packages. The code
9570 created for these unused subprograms increases the size of the executable.
9572 @code{gnatelim} tracks unused subprograms in an Ada program and
9573 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
9574 subprograms that are declared but never called. By placing the list of
9575 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
9576 recompiling your program, you may decrease the size of its executable,
9577 because the compiler will not generate the code for 'eliminated' subprograms.
9578 See GNAT Reference Manual for more information about this pragma.
9580 @code{gnatelim} needs as its input data the name of the main subprogram
9581 and a bind file for a main subprogram.
9583 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
9584 the main subprogram. @code{gnatelim} can work with both Ada and C
9585 bind files; when both are present, it uses the Ada bind file.
9586 The following commands will build the program and create the bind file:
9589 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
9590 $ gnatbind main_prog
9593 Note that @code{gnatelim} needs neither object nor ALI files.
9595 @node Running gnatelim
9596 @subsection Running @code{gnatelim}
9599 @code{gnatelim} has the following command-line interface:
9602 $ gnatelim [options] name
9606 @code{name} should be a name of a source file that contains the main subprogram
9607 of a program (partition).
9609 @code{gnatelim} has the following switches:
9614 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
9615 Quiet mode: by default @code{gnatelim} outputs to the standard error
9616 stream the number of program units left to be processed. This option turns
9620 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
9621 Verbose mode: @code{gnatelim} version information is printed as Ada
9622 comments to the standard output stream. Also, in addition to the number of
9623 program units left @code{gnatelim} will output the name of the current unit
9627 @cindex @option{^-a^/ALL^} (@command{gnatelim})
9628 Also look for subprograms from the GNAT run time that can be eliminated. Note
9629 that when @file{gnat.adc} is produced using this switch, the entire program
9630 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
9632 @item ^-I^/INCLUDE_DIRS=^@var{dir}
9633 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
9634 When looking for source files also look in directory @var{dir}. Specifying
9635 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
9636 sources in the current directory.
9638 @item ^-b^/BIND_FILE=^@var{bind_file}
9639 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
9640 Specifies @var{bind_file} as the bind file to process. If not set, the name
9641 of the bind file is computed from the full expanded Ada name
9642 of a main subprogram.
9644 @item ^-C^/CONFIG_FILE=^@var{config_file}
9645 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
9646 Specifies a file @var{config_file} that contains configuration pragmas. The
9647 file must be specified with full path.
9649 @item ^--GCC^/COMPILER^=@var{compiler_name}
9650 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
9651 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
9652 available on the path.
9654 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
9655 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
9656 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
9657 available on the path.
9661 @code{gnatelim} sends its output to the standard output stream, and all the
9662 tracing and debug information is sent to the standard error stream.
9663 In order to produce a proper GNAT configuration file
9664 @file{gnat.adc}, redirection must be used:
9668 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
9671 $ gnatelim main_prog.adb > gnat.adc
9680 $ gnatelim main_prog.adb >> gnat.adc
9684 in order to append the @code{gnatelim} output to the existing contents of
9688 @node Correcting the List of Eliminate Pragmas
9689 @subsection Correcting the List of Eliminate Pragmas
9692 In some rare cases @code{gnatelim} may try to eliminate
9693 subprograms that are actually called in the program. In this case, the
9694 compiler will generate an error message of the form:
9697 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
9701 You will need to manually remove the wrong @code{Eliminate} pragmas from
9702 the @file{gnat.adc} file. You should recompile your program
9703 from scratch after that, because you need a consistent @file{gnat.adc} file
9704 during the entire compilation.
9706 @node Making Your Executables Smaller
9707 @subsection Making Your Executables Smaller
9710 In order to get a smaller executable for your program you now have to
9711 recompile the program completely with the new @file{gnat.adc} file
9712 created by @code{gnatelim} in your current directory:
9715 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9719 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
9720 recompile everything
9721 with the set of pragmas @code{Eliminate} that you have obtained with
9722 @command{gnatelim}).
9724 Be aware that the set of @code{Eliminate} pragmas is specific to each
9725 program. It is not recommended to merge sets of @code{Eliminate}
9726 pragmas created for different programs in one @file{gnat.adc} file.
9728 @node Summary of the gnatelim Usage Cycle
9729 @subsection Summary of the gnatelim Usage Cycle
9732 Here is a quick summary of the steps to be taken in order to reduce
9733 the size of your executables with @code{gnatelim}. You may use
9734 other GNAT options to control the optimization level,
9735 to produce the debugging information, to set search path, etc.
9742 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
9743 $ gnatbind main_prog
9747 Generate a list of @code{Eliminate} pragmas
9750 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
9753 $ gnatelim main_prog >[>] gnat.adc
9758 Recompile the application
9761 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9766 @c ********************************
9767 @node Renaming Files Using gnatchop
9768 @chapter Renaming Files Using @code{gnatchop}
9772 This chapter discusses how to handle files with multiple units by using
9773 the @code{gnatchop} utility. This utility is also useful in renaming
9774 files to meet the standard GNAT default file naming conventions.
9777 * Handling Files with Multiple Units::
9778 * Operating gnatchop in Compilation Mode::
9779 * Command Line for gnatchop::
9780 * Switches for gnatchop::
9781 * Examples of gnatchop Usage::
9784 @node Handling Files with Multiple Units
9785 @section Handling Files with Multiple Units
9788 The basic compilation model of GNAT requires that a file submitted to the
9789 compiler have only one unit and there be a strict correspondence
9790 between the file name and the unit name.
9792 The @code{gnatchop} utility allows both of these rules to be relaxed,
9793 allowing GNAT to process files which contain multiple compilation units
9794 and files with arbitrary file names. @code{gnatchop}
9795 reads the specified file and generates one or more output files,
9796 containing one unit per file. The unit and the file name correspond,
9797 as required by GNAT.
9799 If you want to permanently restructure a set of ``foreign'' files so that
9800 they match the GNAT rules, and do the remaining development using the
9801 GNAT structure, you can simply use @command{gnatchop} once, generate the
9802 new set of files and work with them from that point on.
9804 Alternatively, if you want to keep your files in the ``foreign'' format,
9805 perhaps to maintain compatibility with some other Ada compilation
9806 system, you can set up a procedure where you use @command{gnatchop} each
9807 time you compile, regarding the source files that it writes as temporary
9808 files that you throw away.
9810 @node Operating gnatchop in Compilation Mode
9811 @section Operating gnatchop in Compilation Mode
9814 The basic function of @code{gnatchop} is to take a file with multiple units
9815 and split it into separate files. The boundary between files is reasonably
9816 clear, except for the issue of comments and pragmas. In default mode, the
9817 rule is that any pragmas between units belong to the previous unit, except
9818 that configuration pragmas always belong to the following unit. Any comments
9819 belong to the following unit. These rules
9820 almost always result in the right choice of
9821 the split point without needing to mark it explicitly and most users will
9822 find this default to be what they want. In this default mode it is incorrect to
9823 submit a file containing only configuration pragmas, or one that ends in
9824 configuration pragmas, to @code{gnatchop}.
9826 However, using a special option to activate ``compilation mode'',
9828 can perform another function, which is to provide exactly the semantics
9829 required by the RM for handling of configuration pragmas in a compilation.
9830 In the absence of configuration pragmas (at the main file level), this
9831 option has no effect, but it causes such configuration pragmas to be handled
9832 in a quite different manner.
9834 First, in compilation mode, if @code{gnatchop} is given a file that consists of
9835 only configuration pragmas, then this file is appended to the
9836 @file{gnat.adc} file in the current directory. This behavior provides
9837 the required behavior described in the RM for the actions to be taken
9838 on submitting such a file to the compiler, namely that these pragmas
9839 should apply to all subsequent compilations in the same compilation
9840 environment. Using GNAT, the current directory, possibly containing a
9841 @file{gnat.adc} file is the representation
9842 of a compilation environment. For more information on the
9843 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
9845 Second, in compilation mode, if @code{gnatchop}
9846 is given a file that starts with
9847 configuration pragmas, and contains one or more units, then these
9848 configuration pragmas are prepended to each of the chopped files. This
9849 behavior provides the required behavior described in the RM for the
9850 actions to be taken on compiling such a file, namely that the pragmas
9851 apply to all units in the compilation, but not to subsequently compiled
9854 Finally, if configuration pragmas appear between units, they are appended
9855 to the previous unit. This results in the previous unit being illegal,
9856 since the compiler does not accept configuration pragmas that follow
9857 a unit. This provides the required RM behavior that forbids configuration
9858 pragmas other than those preceding the first compilation unit of a
9861 For most purposes, @code{gnatchop} will be used in default mode. The
9862 compilation mode described above is used only if you need exactly
9863 accurate behavior with respect to compilations, and you have files
9864 that contain multiple units and configuration pragmas. In this
9865 circumstance the use of @code{gnatchop} with the compilation mode
9866 switch provides the required behavior, and is for example the mode
9867 in which GNAT processes the ACVC tests.
9869 @node Command Line for gnatchop
9870 @section Command Line for @code{gnatchop}
9873 The @code{gnatchop} command has the form:
9876 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
9881 The only required argument is the file name of the file to be chopped.
9882 There are no restrictions on the form of this file name. The file itself
9883 contains one or more Ada units, in normal GNAT format, concatenated
9884 together. As shown, more than one file may be presented to be chopped.
9886 When run in default mode, @code{gnatchop} generates one output file in
9887 the current directory for each unit in each of the files.
9889 @var{directory}, if specified, gives the name of the directory to which
9890 the output files will be written. If it is not specified, all files are
9891 written to the current directory.
9893 For example, given a
9894 file called @file{hellofiles} containing
9896 @smallexample @c ada
9901 with Text_IO; use Text_IO;
9914 $ gnatchop ^hellofiles^HELLOFILES.^
9918 generates two files in the current directory, one called
9919 @file{hello.ads} containing the single line that is the procedure spec,
9920 and the other called @file{hello.adb} containing the remaining text. The
9921 original file is not affected. The generated files can be compiled in
9925 When gnatchop is invoked on a file that is empty or that contains only empty
9926 lines and/or comments, gnatchop will not fail, but will not produce any
9929 For example, given a
9930 file called @file{toto.txt} containing
9932 @smallexample @c ada
9944 $ gnatchop ^toto.txt^TOT.TXT^
9948 will not produce any new file and will result in the following warnings:
9951 toto.txt:1:01: warning: empty file, contains no compilation units
9952 no compilation units found
9953 no source files written
9956 @node Switches for gnatchop
9957 @section Switches for @code{gnatchop}
9960 @command{gnatchop} recognizes the following switches:
9965 @item ^-c^/COMPILATION^
9966 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
9967 Causes @code{gnatchop} to operate in compilation mode, in which
9968 configuration pragmas are handled according to strict RM rules. See
9969 previous section for a full description of this mode.
9973 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
9974 used to parse the given file. Not all @code{xxx} options make sense,
9975 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
9976 process a source file that uses Latin-2 coding for identifiers.
9980 Causes @code{gnatchop} to generate a brief help summary to the standard
9981 output file showing usage information.
9983 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
9984 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
9985 Limit generated file names to the specified number @code{mm}
9987 This is useful if the
9988 resulting set of files is required to be interoperable with systems
9989 which limit the length of file names.
9991 If no value is given, or
9992 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
9993 a default of 39, suitable for OpenVMS Alpha
9997 No space is allowed between the @option{-k} and the numeric value. The numeric
9998 value may be omitted in which case a default of @option{-k8},
10000 with DOS-like file systems, is used. If no @option{-k} switch
10002 there is no limit on the length of file names.
10005 @item ^-p^/PRESERVE^
10006 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
10007 Causes the file ^modification^creation^ time stamp of the input file to be
10008 preserved and used for the time stamp of the output file(s). This may be
10009 useful for preserving coherency of time stamps in an environment where
10010 @code{gnatchop} is used as part of a standard build process.
10013 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
10014 Causes output of informational messages indicating the set of generated
10015 files to be suppressed. Warnings and error messages are unaffected.
10017 @item ^-r^/REFERENCE^
10018 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
10019 @findex Source_Reference
10020 Generate @code{Source_Reference} pragmas. Use this switch if the output
10021 files are regarded as temporary and development is to be done in terms
10022 of the original unchopped file. This switch causes
10023 @code{Source_Reference} pragmas to be inserted into each of the
10024 generated files to refers back to the original file name and line number.
10025 The result is that all error messages refer back to the original
10027 In addition, the debugging information placed into the object file (when
10028 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
10030 also refers back to this original file so that tools like profilers and
10031 debuggers will give information in terms of the original unchopped file.
10033 If the original file to be chopped itself contains
10034 a @code{Source_Reference}
10035 pragma referencing a third file, then gnatchop respects
10036 this pragma, and the generated @code{Source_Reference} pragmas
10037 in the chopped file refer to the original file, with appropriate
10038 line numbers. This is particularly useful when @code{gnatchop}
10039 is used in conjunction with @code{gnatprep} to compile files that
10040 contain preprocessing statements and multiple units.
10042 @item ^-v^/VERBOSE^
10043 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
10044 Causes @code{gnatchop} to operate in verbose mode. The version
10045 number and copyright notice are output, as well as exact copies of
10046 the gnat1 commands spawned to obtain the chop control information.
10048 @item ^-w^/OVERWRITE^
10049 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
10050 Overwrite existing file names. Normally @code{gnatchop} regards it as a
10051 fatal error if there is already a file with the same name as a
10052 file it would otherwise output, in other words if the files to be
10053 chopped contain duplicated units. This switch bypasses this
10054 check, and causes all but the last instance of such duplicated
10055 units to be skipped.
10059 @cindex @option{--GCC=} (@code{gnatchop})
10060 Specify the path of the GNAT parser to be used. When this switch is used,
10061 no attempt is made to add the prefix to the GNAT parser executable.
10065 @node Examples of gnatchop Usage
10066 @section Examples of @code{gnatchop} Usage
10070 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
10073 @item gnatchop -w hello_s.ada prerelease/files
10076 Chops the source file @file{hello_s.ada}. The output files will be
10077 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
10079 files with matching names in that directory (no files in the current
10080 directory are modified).
10082 @item gnatchop ^archive^ARCHIVE.^
10083 Chops the source file @file{^archive^ARCHIVE.^}
10084 into the current directory. One
10085 useful application of @code{gnatchop} is in sending sets of sources
10086 around, for example in email messages. The required sources are simply
10087 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
10089 @code{gnatchop} is used at the other end to reconstitute the original
10092 @item gnatchop file1 file2 file3 direc
10093 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
10094 the resulting files in the directory @file{direc}. Note that if any units
10095 occur more than once anywhere within this set of files, an error message
10096 is generated, and no files are written. To override this check, use the
10097 @option{^-w^/OVERWRITE^} switch,
10098 in which case the last occurrence in the last file will
10099 be the one that is output, and earlier duplicate occurrences for a given
10100 unit will be skipped.
10103 @node Configuration Pragmas
10104 @chapter Configuration Pragmas
10105 @cindex Configuration pragmas
10106 @cindex Pragmas, configuration
10109 In Ada 95, configuration pragmas include those pragmas described as
10110 such in the Ada 95 Reference Manual, as well as
10111 implementation-dependent pragmas that are configuration pragmas. See the
10112 individual descriptions of pragmas in the GNAT Reference Manual for
10113 details on these additional GNAT-specific configuration pragmas. Most
10114 notably, the pragma @code{Source_File_Name}, which allows
10115 specifying non-default names for source files, is a configuration
10116 pragma. The following is a complete list of configuration pragmas
10117 recognized by @code{GNAT}:
10124 Component_Alignment
10130 External_Name_Casing
10131 Float_Representation
10140 Propagate_Exceptions
10143 Restricted_Run_Time
10145 Restrictions_Warnings
10150 Task_Dispatching_Policy
10159 * Handling of Configuration Pragmas::
10160 * The Configuration Pragmas Files::
10163 @node Handling of Configuration Pragmas
10164 @section Handling of Configuration Pragmas
10166 Configuration pragmas may either appear at the start of a compilation
10167 unit, in which case they apply only to that unit, or they may apply to
10168 all compilations performed in a given compilation environment.
10170 GNAT also provides the @code{gnatchop} utility to provide an automatic
10171 way to handle configuration pragmas following the semantics for
10172 compilations (that is, files with multiple units), described in the RM.
10173 See @ref{Operating gnatchop in Compilation Mode} for details.
10174 However, for most purposes, it will be more convenient to edit the
10175 @file{gnat.adc} file that contains configuration pragmas directly,
10176 as described in the following section.
10178 @node The Configuration Pragmas Files
10179 @section The Configuration Pragmas Files
10180 @cindex @file{gnat.adc}
10183 In GNAT a compilation environment is defined by the current
10184 directory at the time that a compile command is given. This current
10185 directory is searched for a file whose name is @file{gnat.adc}. If
10186 this file is present, it is expected to contain one or more
10187 configuration pragmas that will be applied to the current compilation.
10188 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
10191 Configuration pragmas may be entered into the @file{gnat.adc} file
10192 either by running @code{gnatchop} on a source file that consists only of
10193 configuration pragmas, or more conveniently by
10194 direct editing of the @file{gnat.adc} file, which is a standard format
10197 In addition to @file{gnat.adc}, one additional file containing configuration
10198 pragmas may be applied to the current compilation using the switch
10199 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
10200 contains only configuration pragmas. These configuration pragmas are
10201 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
10202 is present and switch @option{-gnatA} is not used).
10204 It is allowed to specify several switches @option{-gnatec}, however only
10205 the last one on the command line will be taken into account.
10207 If you are using project file, a separate mechanism is provided using
10208 project attributes, see @ref{Specifying Configuration Pragmas} for more
10212 Of special interest to GNAT OpenVMS Alpha is the following
10213 configuration pragma:
10215 @smallexample @c ada
10217 pragma Extend_System (Aux_DEC);
10222 In the presence of this pragma, GNAT adds to the definition of the
10223 predefined package SYSTEM all the additional types and subprograms that are
10224 defined in DEC Ada. See @ref{Compatibility with DEC Ada} for details.
10227 @node Handling Arbitrary File Naming Conventions Using gnatname
10228 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
10229 @cindex Arbitrary File Naming Conventions
10232 * Arbitrary File Naming Conventions::
10233 * Running gnatname::
10234 * Switches for gnatname::
10235 * Examples of gnatname Usage::
10238 @node Arbitrary File Naming Conventions
10239 @section Arbitrary File Naming Conventions
10242 The GNAT compiler must be able to know the source file name of a compilation
10243 unit. When using the standard GNAT default file naming conventions
10244 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
10245 does not need additional information.
10248 When the source file names do not follow the standard GNAT default file naming
10249 conventions, the GNAT compiler must be given additional information through
10250 a configuration pragmas file (@pxref{Configuration Pragmas})
10252 When the non standard file naming conventions are well-defined,
10253 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
10254 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
10255 if the file naming conventions are irregular or arbitrary, a number
10256 of pragma @code{Source_File_Name} for individual compilation units
10258 To help maintain the correspondence between compilation unit names and
10259 source file names within the compiler,
10260 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
10263 @node Running gnatname
10264 @section Running @code{gnatname}
10267 The usual form of the @code{gnatname} command is
10270 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
10274 All of the arguments are optional. If invoked without any argument,
10275 @code{gnatname} will display its usage.
10278 When used with at least one naming pattern, @code{gnatname} will attempt to
10279 find all the compilation units in files that follow at least one of the
10280 naming patterns. To find these compilation units,
10281 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
10285 One or several Naming Patterns may be given as arguments to @code{gnatname}.
10286 Each Naming Pattern is enclosed between double quotes.
10287 A Naming Pattern is a regular expression similar to the wildcard patterns
10288 used in file names by the Unix shells or the DOS prompt.
10291 Examples of Naming Patterns are
10300 For a more complete description of the syntax of Naming Patterns,
10301 see the second kind of regular expressions described in @file{g-regexp.ads}
10302 (the ``Glob'' regular expressions).
10305 When invoked with no switches, @code{gnatname} will create a configuration
10306 pragmas file @file{gnat.adc} in the current working directory, with pragmas
10307 @code{Source_File_Name} for each file that contains a valid Ada unit.
10309 @node Switches for gnatname
10310 @section Switches for @code{gnatname}
10313 Switches for @code{gnatname} must precede any specified Naming Pattern.
10316 You may specify any of the following switches to @code{gnatname}:
10321 @item ^-c^/CONFIG_FILE=^@file{file}
10322 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
10323 Create a configuration pragmas file @file{file} (instead of the default
10326 There may be zero, one or more space between @option{-c} and
10329 @file{file} may include directory information. @file{file} must be
10330 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
10331 When a switch @option{^-c^/CONFIG_FILE^} is
10332 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
10334 @item ^-d^/SOURCE_DIRS=^@file{dir}
10335 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
10336 Look for source files in directory @file{dir}. There may be zero, one or more
10337 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
10338 When a switch @option{^-d^/SOURCE_DIRS^}
10339 is specified, the current working directory will not be searched for source
10340 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
10341 or @option{^-D^/DIR_FILES^} switch.
10342 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
10343 If @file{dir} is a relative path, it is relative to the directory of
10344 the configuration pragmas file specified with switch
10345 @option{^-c^/CONFIG_FILE^},
10346 or to the directory of the project file specified with switch
10347 @option{^-P^/PROJECT_FILE^} or,
10348 if neither switch @option{^-c^/CONFIG_FILE^}
10349 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
10350 current working directory. The directory
10351 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
10353 @item ^-D^/DIRS_FILE=^@file{file}
10354 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
10355 Look for source files in all directories listed in text file @file{file}.
10356 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
10358 @file{file} must be an existing, readable text file.
10359 Each non empty line in @file{file} must be a directory.
10360 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
10361 switches @option{^-d^/SOURCE_DIRS^} as there are non empty lines in
10364 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
10365 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
10366 Foreign patterns. Using this switch, it is possible to add sources of languages
10367 other than Ada to the list of sources of a project file.
10368 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
10371 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
10374 will look for Ada units in all files with the @file{.ada} extension,
10375 and will add to the list of file for project @file{prj.gpr} the C files
10376 with extension ".^c^C^".
10379 @cindex @option{^-h^/HELP^} (@code{gnatname})
10380 Output usage (help) information. The output is written to @file{stdout}.
10382 @item ^-P^/PROJECT_FILE=^@file{proj}
10383 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
10384 Create or update project file @file{proj}. There may be zero, one or more space
10385 between @option{-P} and @file{proj}. @file{proj} may include directory
10386 information. @file{proj} must be writable.
10387 There may be only one switch @option{^-P^/PROJECT_FILE^}.
10388 When a switch @option{^-P^/PROJECT_FILE^} is specified,
10389 no switch @option{^-c^/CONFIG_FILE^} may be specified.
10391 @item ^-v^/VERBOSE^
10392 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
10393 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
10394 This includes name of the file written, the name of the directories to search
10395 and, for each file in those directories whose name matches at least one of
10396 the Naming Patterns, an indication of whether the file contains a unit,
10397 and if so the name of the unit.
10399 @item ^-v -v^/VERBOSE /VERBOSE^
10400 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
10401 Very Verbose mode. In addition to the output produced in verbose mode,
10402 for each file in the searched directories whose name matches none of
10403 the Naming Patterns, an indication is given that there is no match.
10405 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
10406 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
10407 Excluded patterns. Using this switch, it is possible to exclude some files
10408 that would match the name patterns. For example,
10410 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
10413 will look for Ada units in all files with the @file{.ada} extension,
10414 except those whose names end with @file{_nt.ada}.
10418 @node Examples of gnatname Usage
10419 @section Examples of @code{gnatname} Usage
10423 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
10429 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
10434 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
10435 and be writable. In addition, the directory
10436 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
10437 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
10440 Note the optional spaces after @option{-c} and @option{-d}.
10445 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
10446 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
10449 $ gnatname /PROJECT_FILE=[HOME.ME]PROJ
10450 /EXCLUDED_PATTERN=*_nt_body.ada
10451 /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
10452 /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
10456 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
10457 even in conjunction with one or several switches
10458 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
10459 are used in this example.
10461 @c *****************************************
10462 @c * G N A T P r o j e c t M a n a g e r *
10463 @c *****************************************
10464 @node GNAT Project Manager
10465 @chapter GNAT Project Manager
10469 * Examples of Project Files::
10470 * Project File Syntax::
10471 * Objects and Sources in Project Files::
10472 * Importing Projects::
10473 * Project Extension::
10474 * Project Hierarchy Extension::
10475 * External References in Project Files::
10476 * Packages in Project Files::
10477 * Variables from Imported Projects::
10479 * Library Projects::
10480 * Stand-alone Library Projects::
10481 * Switches Related to Project Files::
10482 * Tools Supporting Project Files::
10483 * An Extended Example::
10484 * Project File Complete Syntax::
10487 @c ****************
10488 @c * Introduction *
10489 @c ****************
10492 @section Introduction
10495 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
10496 you to manage complex builds involving a number of source files, directories,
10497 and compilation options for different system configurations. In particular,
10498 project files allow you to specify:
10501 The directory or set of directories containing the source files, and/or the
10502 names of the specific source files themselves
10504 The directory in which the compiler's output
10505 (@file{ALI} files, object files, tree files) is to be placed
10507 The directory in which the executable programs is to be placed
10509 ^Switch^Switch^ settings for any of the project-enabled tools
10510 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
10511 @code{gnatfind}); you can apply these settings either globally or to individual
10514 The source files containing the main subprogram(s) to be built
10516 The source programming language(s) (currently Ada and/or C)
10518 Source file naming conventions; you can specify these either globally or for
10519 individual compilation units
10526 @node Project Files
10527 @subsection Project Files
10530 Project files are written in a syntax close to that of Ada, using familiar
10531 notions such as packages, context clauses, declarations, default values,
10532 assignments, and inheritance. Finally, project files can be built
10533 hierarchically from other project files, simplifying complex system
10534 integration and project reuse.
10536 A @dfn{project} is a specific set of values for various compilation properties.
10537 The settings for a given project are described by means of
10538 a @dfn{project file}, which is a text file written in an Ada-like syntax.
10539 Property values in project files are either strings or lists of strings.
10540 Properties that are not explicitly set receive default values. A project
10541 file may interrogate the values of @dfn{external variables} (user-defined
10542 command-line switches or environment variables), and it may specify property
10543 settings conditionally, based on the value of such variables.
10545 In simple cases, a project's source files depend only on other source files
10546 in the same project, or on the predefined libraries. (@emph{Dependence} is
10548 the Ada technical sense; as in one Ada unit @code{with}ing another.) However,
10549 the Project Manager also allows more sophisticated arrangements,
10550 where the source files in one project depend on source files in other
10554 One project can @emph{import} other projects containing needed source files.
10556 You can organize GNAT projects in a hierarchy: a @emph{child} project
10557 can extend a @emph{parent} project, inheriting the parent's source files and
10558 optionally overriding any of them with alternative versions
10562 More generally, the Project Manager lets you structure large development
10563 efforts into hierarchical subsystems, where build decisions are delegated
10564 to the subsystem level, and thus different compilation environments
10565 (^switch^switch^ settings) used for different subsystems.
10567 The Project Manager is invoked through the
10568 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
10569 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
10571 There may be zero, one or more spaces between @option{-P} and
10572 @option{@emph{projectfile}}.
10574 If you want to define (on the command line) an external variable that is
10575 queried by the project file, you must use the
10576 @option{^-X^/EXTERNAT_REFERENCE=^@emph{vbl}=@emph{value}} switch.
10577 The Project Manager parses and interprets the project file, and drives the
10578 invoked tool based on the project settings.
10580 The Project Manager supports a wide range of development strategies,
10581 for systems of all sizes. Here are some typical practices that are
10585 Using a common set of source files, but generating object files in different
10586 directories via different ^switch^switch^ settings
10588 Using a mostly-shared set of source files, but with different versions of
10593 The destination of an executable can be controlled inside a project file
10594 using the @option{^-o^-o^}
10596 In the absence of such a ^switch^switch^ either inside
10597 the project file or on the command line, any executable files generated by
10598 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
10599 in the project file. If no @code{Exec_Dir} is specified, they will be placed
10600 in the object directory of the project.
10602 You can use project files to achieve some of the effects of a source
10603 versioning system (for example, defining separate projects for
10604 the different sets of sources that comprise different releases) but the
10605 Project Manager is independent of any source configuration management tools
10606 that might be used by the developers.
10608 The next section introduces the main features of GNAT's project facility
10609 through a sequence of examples; subsequent sections will present the syntax
10610 and semantics in more detail. A more formal description of the project
10611 facility appears in the GNAT Reference Manual.
10613 @c *****************************
10614 @c * Examples of Project Files *
10615 @c *****************************
10617 @node Examples of Project Files
10618 @section Examples of Project Files
10620 This section illustrates some of the typical uses of project files and
10621 explains their basic structure and behavior.
10624 * Common Sources with Different ^Switches^Switches^ and Directories::
10625 * Using External Variables::
10626 * Importing Other Projects::
10627 * Extending a Project::
10630 @node Common Sources with Different ^Switches^Switches^ and Directories
10631 @subsection Common Sources with Different ^Switches^Switches^ and Directories
10635 * Specifying the Object Directory::
10636 * Specifying the Exec Directory::
10637 * Project File Packages::
10638 * Specifying ^Switch^Switch^ Settings::
10639 * Main Subprograms::
10640 * Executable File Names::
10641 * Source File Naming Conventions::
10642 * Source Language(s)::
10646 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
10647 @file{proc.adb} are in the @file{/common} directory. The file
10648 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
10649 package @code{Pack}. We want to compile these source files under two sets
10650 of ^switches^switches^:
10653 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
10654 and the @option{^-gnata^-gnata^},
10655 @option{^-gnato^-gnato^},
10656 and @option{^-gnatE^-gnatE^} switches to the
10657 compiler; the compiler's output is to appear in @file{/common/debug}
10659 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
10660 to the compiler; the compiler's output is to appear in @file{/common/release}
10664 The GNAT project files shown below, respectively @file{debug.gpr} and
10665 @file{release.gpr} in the @file{/common} directory, achieve these effects.
10678 ^/common/debug^[COMMON.DEBUG]^
10683 ^/common/release^[COMMON.RELEASE]^
10688 Here are the corresponding project files:
10690 @smallexample @c projectfile
10693 for Object_Dir use "debug";
10694 for Main use ("proc");
10697 for ^Default_Switches^Default_Switches^ ("Ada")
10699 for Executable ("proc.adb") use "proc1";
10704 package Compiler is
10705 for ^Default_Switches^Default_Switches^ ("Ada")
10706 use ("-fstack-check",
10709 "^-gnatE^-gnatE^");
10715 @smallexample @c projectfile
10718 for Object_Dir use "release";
10719 for Exec_Dir use ".";
10720 for Main use ("proc");
10722 package Compiler is
10723 for ^Default_Switches^Default_Switches^ ("Ada")
10731 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
10732 insensitive), and analogously the project defined by @file{release.gpr} is
10733 @code{"Release"}. For consistency the file should have the same name as the
10734 project, and the project file's extension should be @code{"gpr"}. These
10735 conventions are not required, but a warning is issued if they are not followed.
10737 If the current directory is @file{^/temp^[TEMP]^}, then the command
10739 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
10743 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
10744 as well as the @code{^proc1^PROC1.EXE^} executable,
10745 using the ^switch^switch^ settings defined in the project file.
10747 Likewise, the command
10749 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
10753 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
10754 and the @code{^proc^PROC.EXE^}
10755 executable in @file{^/common^[COMMON]^},
10756 using the ^switch^switch^ settings from the project file.
10759 @unnumberedsubsubsec Source Files
10762 If a project file does not explicitly specify a set of source directories or
10763 a set of source files, then by default the project's source files are the
10764 Ada source files in the project file directory. Thus @file{pack.ads},
10765 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
10767 @node Specifying the Object Directory
10768 @unnumberedsubsubsec Specifying the Object Directory
10771 Several project properties are modeled by Ada-style @emph{attributes};
10772 a property is defined by supplying the equivalent of an Ada attribute
10773 definition clause in the project file.
10774 A project's object directory is another such a property; the corresponding
10775 attribute is @code{Object_Dir}, and its value is also a string expression,
10776 specified either as absolute or relative. In the later case,
10777 it is relative to the project file directory. Thus the compiler's
10778 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
10779 (for the @code{Debug} project)
10780 and to @file{^/common/release^[COMMON.RELEASE]^}
10781 (for the @code{Release} project).
10782 If @code{Object_Dir} is not specified, then the default is the project file
10785 @node Specifying the Exec Directory
10786 @unnumberedsubsubsec Specifying the Exec Directory
10789 A project's exec directory is another property; the corresponding
10790 attribute is @code{Exec_Dir}, and its value is also a string expression,
10791 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
10792 then the default is the object directory (which may also be the project file
10793 directory if attribute @code{Object_Dir} is not specified). Thus the executable
10794 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
10795 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
10796 and in @file{^/common^[COMMON]^} for the @code{Release} project.
10798 @node Project File Packages
10799 @unnumberedsubsubsec Project File Packages
10802 A GNAT tool that is integrated with the Project Manager is modeled by a
10803 corresponding package in the project file. In the example above,
10804 The @code{Debug} project defines the packages @code{Builder}
10805 (for @command{gnatmake}) and @code{Compiler};
10806 the @code{Release} project defines only the @code{Compiler} package.
10808 The Ada-like package syntax is not to be taken literally. Although packages in
10809 project files bear a surface resemblance to packages in Ada source code, the
10810 notation is simply a way to convey a grouping of properties for a named
10811 entity. Indeed, the package names permitted in project files are restricted
10812 to a predefined set, corresponding to the project-aware tools, and the contents
10813 of packages are limited to a small set of constructs.
10814 The packages in the example above contain attribute definitions.
10816 @node Specifying ^Switch^Switch^ Settings
10817 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
10820 ^Switch^Switch^ settings for a project-aware tool can be specified through
10821 attributes in the package that corresponds to the tool.
10822 The example above illustrates one of the relevant attributes,
10823 @code{^Default_Switches^Default_Switches^}, which is defined in packages
10824 in both project files.
10825 Unlike simple attributes like @code{Source_Dirs},
10826 @code{^Default_Switches^Default_Switches^} is
10827 known as an @emph{associative array}. When you define this attribute, you must
10828 supply an ``index'' (a literal string), and the effect of the attribute
10829 definition is to set the value of the array at the specified index.
10830 For the @code{^Default_Switches^Default_Switches^} attribute,
10831 the index is a programming language (in our case, Ada),
10832 and the value specified (after @code{use}) must be a list
10833 of string expressions.
10835 The attributes permitted in project files are restricted to a predefined set.
10836 Some may appear at project level, others in packages.
10837 For any attribute that is an associative array, the index must always be a
10838 literal string, but the restrictions on this string (e.g., a file name or a
10839 language name) depend on the individual attribute.
10840 Also depending on the attribute, its specified value will need to be either a
10841 string or a string list.
10843 In the @code{Debug} project, we set the switches for two tools,
10844 @command{gnatmake} and the compiler, and thus we include the two corresponding
10845 packages; each package defines the @code{^Default_Switches^Default_Switches^}
10846 attribute with index @code{"Ada"}.
10847 Note that the package corresponding to
10848 @command{gnatmake} is named @code{Builder}. The @code{Release} project is
10849 similar, but only includes the @code{Compiler} package.
10851 In project @code{Debug} above, the ^switches^switches^ starting with
10852 @option{-gnat} that are specified in package @code{Compiler}
10853 could have been placed in package @code{Builder}, since @command{gnatmake}
10854 transmits all such ^switches^switches^ to the compiler.
10856 @node Main Subprograms
10857 @unnumberedsubsubsec Main Subprograms
10860 One of the specifiable properties of a project is a list of files that contain
10861 main subprograms. This property is captured in the @code{Main} attribute,
10862 whose value is a list of strings. If a project defines the @code{Main}
10863 attribute, it is not necessary to identify the main subprogram(s) when
10864 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
10866 @node Executable File Names
10867 @unnumberedsubsubsec Executable File Names
10870 By default, the executable file name corresponding to a main source is
10871 deduced from the main source file name. Through the attributes
10872 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
10873 it is possible to change this default.
10874 In project @code{Debug} above, the executable file name
10875 for main source @file{^proc.adb^PROC.ADB^} is
10876 @file{^proc1^PROC1.EXE^}.
10877 Attribute @code{Executable_Suffix}, when specified, may change the suffix
10878 of the the executable files, when no attribute @code{Executable} applies:
10879 its value replace the platform-specific executable suffix.
10880 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
10881 specify a non default executable file name when several mains are built at once
10882 in a single @command{gnatmake} command.
10884 @node Source File Naming Conventions
10885 @unnumberedsubsubsec Source File Naming Conventions
10888 Since the project files above do not specify any source file naming
10889 conventions, the GNAT defaults are used. The mechanism for defining source
10890 file naming conventions -- a package named @code{Naming} --
10891 is described below (@pxref{Naming Schemes}).
10893 @node Source Language(s)
10894 @unnumberedsubsubsec Source Language(s)
10897 Since the project files do not specify a @code{Languages} attribute, by
10898 default the GNAT tools assume that the language of the project file is Ada.
10899 More generally, a project can comprise source files
10900 in Ada, C, and/or other languages.
10902 @node Using External Variables
10903 @subsection Using External Variables
10906 Instead of supplying different project files for debug and release, we can
10907 define a single project file that queries an external variable (set either
10908 on the command line or via an ^environment variable^logical name^) in order to
10909 conditionally define the appropriate settings. Again, assume that the
10910 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
10911 located in directory @file{^/common^[COMMON]^}. The following project file,
10912 @file{build.gpr}, queries the external variable named @code{STYLE} and
10913 defines an object directory and ^switch^switch^ settings based on whether
10914 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
10915 the default is @code{"deb"}.
10917 @smallexample @c projectfile
10920 for Main use ("proc");
10922 type Style_Type is ("deb", "rel");
10923 Style : Style_Type := external ("STYLE", "deb");
10927 for Object_Dir use "debug";
10930 for Object_Dir use "release";
10931 for Exec_Dir use ".";
10940 for ^Default_Switches^Default_Switches^ ("Ada")
10942 for Executable ("proc") use "proc1";
10951 package Compiler is
10955 for ^Default_Switches^Default_Switches^ ("Ada")
10956 use ("^-gnata^-gnata^",
10958 "^-gnatE^-gnatE^");
10961 for ^Default_Switches^Default_Switches^ ("Ada")
10972 @code{Style_Type} is an example of a @emph{string type}, which is the project
10973 file analog of an Ada enumeration type but whose components are string literals
10974 rather than identifiers. @code{Style} is declared as a variable of this type.
10976 The form @code{external("STYLE", "deb")} is known as an
10977 @emph{external reference}; its first argument is the name of an
10978 @emph{external variable}, and the second argument is a default value to be
10979 used if the external variable doesn't exist. You can define an external
10980 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
10981 or you can use ^an environment variable^a logical name^
10982 as an external variable.
10984 Each @code{case} construct is expanded by the Project Manager based on the
10985 value of @code{Style}. Thus the command
10988 gnatmake -P/common/build.gpr -XSTYLE=deb
10994 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
10999 is equivalent to the @command{gnatmake} invocation using the project file
11000 @file{debug.gpr} in the earlier example. So is the command
11002 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
11006 since @code{"deb"} is the default for @code{STYLE}.
11012 gnatmake -P/common/build.gpr -XSTYLE=rel
11018 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
11023 is equivalent to the @command{gnatmake} invocation using the project file
11024 @file{release.gpr} in the earlier example.
11026 @node Importing Other Projects
11027 @subsection Importing Other Projects
11028 @cindex @code{ADA_PROJECT_PATH}
11031 A compilation unit in a source file in one project may depend on compilation
11032 units in source files in other projects. To compile this unit under
11033 control of a project file, the
11034 dependent project must @emph{import} the projects containing the needed source
11036 This effect is obtained using syntax similar to an Ada @code{with} clause,
11037 but where @code{with}ed entities are strings that denote project files.
11039 As an example, suppose that the two projects @code{GUI_Proj} and
11040 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
11041 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
11042 and @file{^/comm^[COMM]^}, respectively.
11043 Suppose that the source files for @code{GUI_Proj} are
11044 @file{gui.ads} and @file{gui.adb}, and that the source files for
11045 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
11046 files is located in its respective project file directory. Schematically:
11065 We want to develop an application in directory @file{^/app^[APP]^} that
11066 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
11067 the corresponding project files (e.g. the ^switch^switch^ settings
11068 and object directory).
11069 Skeletal code for a main procedure might be something like the following:
11071 @smallexample @c ada
11074 procedure App_Main is
11083 Here is a project file, @file{app_proj.gpr}, that achieves the desired
11086 @smallexample @c projectfile
11088 with "/gui/gui_proj", "/comm/comm_proj";
11089 project App_Proj is
11090 for Main use ("app_main");
11096 Building an executable is achieved through the command:
11098 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
11101 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
11102 in the directory where @file{app_proj.gpr} resides.
11104 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
11105 (as illustrated above) the @code{with} clause can omit the extension.
11107 Our example specified an absolute path for each imported project file.
11108 Alternatively, the directory name of an imported object can be omitted
11112 The imported project file is in the same directory as the importing project
11115 You have defined ^an environment variable^a logical name^
11116 that includes the directory containing
11117 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
11118 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
11119 directory names separated by colons (semicolons on Windows).
11123 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
11124 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
11127 @smallexample @c projectfile
11129 with "gui_proj", "comm_proj";
11130 project App_Proj is
11131 for Main use ("app_main");
11137 Importing other projects can create ambiguities.
11138 For example, the same unit might be present in different imported projects, or
11139 it might be present in both the importing project and in an imported project.
11140 Both of these conditions are errors. Note that in the current version of
11141 the Project Manager, it is illegal to have an ambiguous unit even if the
11142 unit is never referenced by the importing project. This restriction may be
11143 relaxed in a future release.
11145 @node Extending a Project
11146 @subsection Extending a Project
11149 In large software systems it is common to have multiple
11150 implementations of a common interface; in Ada terms, multiple versions of a
11151 package body for the same specification. For example, one implementation
11152 might be safe for use in tasking programs, while another might only be used
11153 in sequential applications. This can be modeled in GNAT using the concept
11154 of @emph{project extension}. If one project (the ``child'') @emph{extends}
11155 another project (the ``parent'') then by default all source files of the
11156 parent project are inherited by the child, but the child project can
11157 override any of the parent's source files with new versions, and can also
11158 add new files. This facility is the project analog of a type extension in
11159 Object-Oriented Programming. Project hierarchies are permitted (a child
11160 project may be the parent of yet another project), and a project that
11161 inherits one project can also import other projects.
11163 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
11164 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
11165 @file{pack.adb}, and @file{proc.adb}:
11178 Note that the project file can simply be empty (that is, no attribute or
11179 package is defined):
11181 @smallexample @c projectfile
11183 project Seq_Proj is
11189 implying that its source files are all the Ada source files in the project
11192 Suppose we want to supply an alternate version of @file{pack.adb}, in
11193 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
11194 @file{pack.ads} and @file{proc.adb}. We can define a project
11195 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
11199 ^/tasking^[TASKING]^
11205 project Tasking_Proj extends "/seq/seq_proj" is
11211 The version of @file{pack.adb} used in a build depends on which project file
11214 Note that we could have obtained the desired behavior using project import
11215 rather than project inheritance; a @code{base} project would contain the
11216 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
11217 import @code{base} and add @file{pack.adb}, and likewise a tasking project
11218 would import @code{base} and add a different version of @file{pack.adb}. The
11219 choice depends on whether other sources in the original project need to be
11220 overridden. If they do, then project extension is necessary, otherwise,
11221 importing is sufficient.
11224 In a project file that extends another project file, it is possible to
11225 indicate that an inherited source is not part of the sources of the extending
11226 project. This is necessary sometimes when a package spec has been overloaded
11227 and no longer requires a body: in this case, it is necessary to indicate that
11228 the inherited body is not part of the sources of the project, otherwise there
11229 will be a compilation error when compiling the spec.
11231 For that purpose, the attribute @code{Locally_Removed_Files} is used.
11232 Its value is a string list: a list of file names.
11234 @smallexample @c @projectfile
11235 project B extends "a" is
11236 for Source_Files use ("pkg.ads");
11237 -- New spec of Pkg does not need a completion
11238 for Locally_Removed_Files use ("pkg.adb");
11242 Attribute @code{Locally_Removed_Files} may also be used to check if a source
11243 is still needed: if it is possible to build using @command{gnatmake} when such
11244 a source is put in attribute @code{Locally_Removed_Files} of a project P, then
11245 it is possible to remove the source completely from a system that includes
11248 @c ***********************
11249 @c * Project File Syntax *
11250 @c ***********************
11252 @node Project File Syntax
11253 @section Project File Syntax
11262 * Associative Array Attributes::
11263 * case Constructions::
11267 This section describes the structure of project files.
11269 A project may be an @emph{independent project}, entirely defined by a single
11270 project file. Any Ada source file in an independent project depends only
11271 on the predefined library and other Ada source files in the same project.
11274 A project may also @dfn{depend on} other projects, in either or both of
11275 the following ways:
11277 @item It may import any number of projects
11278 @item It may extend at most one other project
11282 The dependence relation is a directed acyclic graph (the subgraph reflecting
11283 the ``extends'' relation is a tree).
11285 A project's @dfn{immediate sources} are the source files directly defined by
11286 that project, either implicitly by residing in the project file's directory,
11287 or explicitly through any of the source-related attributes described below.
11288 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
11289 of @var{proj} together with the immediate sources (unless overridden) of any
11290 project on which @var{proj} depends (either directly or indirectly).
11293 @subsection Basic Syntax
11296 As seen in the earlier examples, project files have an Ada-like syntax.
11297 The minimal project file is:
11298 @smallexample @c projectfile
11307 The identifier @code{Empty} is the name of the project.
11308 This project name must be present after the reserved
11309 word @code{end} at the end of the project file, followed by a semi-colon.
11311 Any name in a project file, such as the project name or a variable name,
11312 has the same syntax as an Ada identifier.
11314 The reserved words of project files are the Ada reserved words plus
11315 @code{extends}, @code{external}, and @code{project}. Note that the only Ada
11316 reserved words currently used in project file syntax are:
11344 Comments in project files have the same syntax as in Ada, two consecutives
11345 hyphens through the end of the line.
11348 @subsection Packages
11351 A project file may contain @emph{packages}. The name of a package must be one
11352 of the identifiers from the following list. A package
11353 with a given name may only appear once in a project file. Package names are
11354 case insensitive. The following package names are legal:
11370 @code{Cross_Reference}
11374 @code{Pretty_Printer}
11384 @code{Language_Processing}
11388 In its simplest form, a package may be empty:
11390 @smallexample @c projectfile
11400 A package may contain @emph{attribute declarations},
11401 @emph{variable declarations} and @emph{case constructions}, as will be
11404 When there is ambiguity between a project name and a package name,
11405 the name always designates the project. To avoid possible confusion, it is
11406 always a good idea to avoid naming a project with one of the
11407 names allowed for packages or any name that starts with @code{gnat}.
11410 @subsection Expressions
11413 An @emph{expression} is either a @emph{string expression} or a
11414 @emph{string list expression}.
11416 A @emph{string expression} is either a @emph{simple string expression} or a
11417 @emph{compound string expression}.
11419 A @emph{simple string expression} is one of the following:
11421 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
11422 @item A string-valued variable reference (@pxref{Variables})
11423 @item A string-valued attribute reference (@pxref{Attributes})
11424 @item An external reference (@pxref{External References in Project Files})
11428 A @emph{compound string expression} is a concatenation of string expressions,
11429 using the operator @code{"&"}
11431 Path & "/" & File_Name & ".ads"
11435 A @emph{string list expression} is either a
11436 @emph{simple string list expression} or a
11437 @emph{compound string list expression}.
11439 A @emph{simple string list expression} is one of the following:
11441 @item A parenthesized list of zero or more string expressions,
11442 separated by commas
11444 File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
11447 @item A string list-valued variable reference
11448 @item A string list-valued attribute reference
11452 A @emph{compound string list expression} is the concatenation (using
11453 @code{"&"}) of a simple string list expression and an expression. Note that
11454 each term in a compound string list expression, except the first, may be
11455 either a string expression or a string list expression.
11457 @smallexample @c projectfile
11459 File_Name_List := () & File_Name; -- One string in this list
11460 Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
11462 Big_List := File_Name_List & Extended_File_Name_List;
11463 -- Concatenation of two string lists: three strings
11464 Illegal_List := "gnat.adc" & Extended_File_Name_List;
11465 -- Illegal: must start with a string list
11470 @subsection String Types
11473 A @emph{string type declaration} introduces a discrete set of string literals.
11474 If a string variable is declared to have this type, its value
11475 is restricted to the given set of literals.
11477 Here is an example of a string type declaration:
11479 @smallexample @c projectfile
11480 type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
11484 Variables of a string type are called @emph{typed variables}; all other
11485 variables are called @emph{untyped variables}. Typed variables are
11486 particularly useful in @code{case} constructions, to support conditional
11487 attribute declarations.
11488 (@pxref{case Constructions}).
11490 The string literals in the list are case sensitive and must all be different.
11491 They may include any graphic characters allowed in Ada, including spaces.
11493 A string type may only be declared at the project level, not inside a package.
11495 A string type may be referenced by its name if it has been declared in the same
11496 project file, or by an expanded name whose prefix is the name of the project
11497 in which it is declared.
11500 @subsection Variables
11503 A variable may be declared at the project file level, or within a package.
11504 Here are some examples of variable declarations:
11506 @smallexample @c projectfile
11508 This_OS : OS := external ("OS"); -- a typed variable declaration
11509 That_OS := "GNU/Linux"; -- an untyped variable declaration
11514 The syntax of a @emph{typed variable declaration} is identical to the Ada
11515 syntax for an object declaration. By contrast, the syntax of an untyped
11516 variable declaration is identical to an Ada assignment statement. In fact,
11517 variable declarations in project files have some of the characteristics of
11518 an assignment, in that successive declarations for the same variable are
11519 allowed. Untyped variable declarations do establish the expected kind of the
11520 variable (string or string list), and successive declarations for it must
11521 respect the initial kind.
11524 A string variable declaration (typed or untyped) declares a variable
11525 whose value is a string. This variable may be used as a string expression.
11526 @smallexample @c projectfile
11527 File_Name := "readme.txt";
11528 Saved_File_Name := File_Name & ".saved";
11532 A string list variable declaration declares a variable whose value is a list
11533 of strings. The list may contain any number (zero or more) of strings.
11535 @smallexample @c projectfile
11537 List_With_One_Element := ("^-gnaty^-gnaty^");
11538 List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
11539 Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
11540 "pack2.ada", "util_.ada", "util.ada");
11544 The same typed variable may not be declared more than once at project level,
11545 and it may not be declared more than once in any package; it is in effect
11548 The same untyped variable may be declared several times. Declarations are
11549 elaborated in the order in which they appear, so the new value replaces
11550 the old one, and any subsequent reference to the variable uses the new value.
11551 However, as noted above, if a variable has been declared as a string, all
11553 declarations must give it a string value. Similarly, if a variable has
11554 been declared as a string list, all subsequent declarations
11555 must give it a string list value.
11557 A @emph{variable reference} may take several forms:
11560 @item The simple variable name, for a variable in the current package (if any)
11561 or in the current project
11562 @item An expanded name, whose prefix is a context name.
11566 A @emph{context} may be one of the following:
11569 @item The name of an existing package in the current project
11570 @item The name of an imported project of the current project
11571 @item The name of an ancestor project (i.e., a project extended by the current
11572 project, either directly or indirectly)
11573 @item An expanded name whose prefix is an imported/parent project name, and
11574 whose selector is a package name in that project.
11578 A variable reference may be used in an expression.
11581 @subsection Attributes
11584 A project (and its packages) may have @emph{attributes} that define
11585 the project's properties. Some attributes have values that are strings;
11586 others have values that are string lists.
11588 There are two categories of attributes: @emph{simple attributes}
11589 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
11591 Legal project attribute names, and attribute names for each legal package are
11592 listed below. Attributes names are case-insensitive.
11594 The following attributes are defined on projects (all are simple attributes):
11596 @multitable @columnfractions .4 .3
11597 @item @emph{Attribute Name}
11599 @item @code{Source_Files}
11601 @item @code{Source_Dirs}
11603 @item @code{Source_List_File}
11605 @item @code{Object_Dir}
11607 @item @code{Exec_Dir}
11609 @item @code{Locally_Removed_Files}
11613 @item @code{Languages}
11615 @item @code{Main_Language}
11617 @item @code{Library_Dir}
11619 @item @code{Library_Name}
11621 @item @code{Library_Kind}
11623 @item @code{Library_Version}
11625 @item @code{Library_Interface}
11627 @item @code{Library_Auto_Init}
11629 @item @code{Library_Options}
11631 @item @code{Library_GCC}
11636 The following attributes are defined for package @code{Naming}
11637 (@pxref{Naming Schemes}):
11639 @multitable @columnfractions .4 .2 .2 .2
11640 @item Attribute Name @tab Category @tab Index @tab Value
11641 @item @code{Spec_Suffix}
11642 @tab associative array
11645 @item @code{Body_Suffix}
11646 @tab associative array
11649 @item @code{Separate_Suffix}
11650 @tab simple attribute
11653 @item @code{Casing}
11654 @tab simple attribute
11657 @item @code{Dot_Replacement}
11658 @tab simple attribute
11662 @tab associative array
11666 @tab associative array
11669 @item @code{Specification_Exceptions}
11670 @tab associative array
11673 @item @code{Implementation_Exceptions}
11674 @tab associative array
11680 The following attributes are defined for packages @code{Builder},
11681 @code{Compiler}, @code{Binder},
11682 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
11683 (@pxref{^Switches^Switches^ and Project Files}).
11685 @multitable @columnfractions .4 .2 .2 .2
11686 @item Attribute Name @tab Category @tab Index @tab Value
11687 @item @code{^Default_Switches^Default_Switches^}
11688 @tab associative array
11691 @item @code{^Switches^Switches^}
11692 @tab associative array
11698 In addition, package @code{Compiler} has a single string attribute
11699 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
11700 string attribute @code{Global_Configuration_Pragmas}.
11703 Each simple attribute has a default value: the empty string (for string-valued
11704 attributes) and the empty list (for string list-valued attributes).
11706 An attribute declaration defines a new value for an attribute.
11708 Examples of simple attribute declarations:
11710 @smallexample @c projectfile
11711 for Object_Dir use "objects";
11712 for Source_Dirs use ("units", "test/drivers");
11716 The syntax of a @dfn{simple attribute declaration} is similar to that of an
11717 attribute definition clause in Ada.
11719 Attributes references may be appear in expressions.
11720 The general form for such a reference is @code{<entity>'<attribute>}:
11721 Associative array attributes are functions. Associative
11722 array attribute references must have an argument that is a string literal.
11726 @smallexample @c projectfile
11728 Naming'Dot_Replacement
11729 Imported_Project'Source_Dirs
11730 Imported_Project.Naming'Casing
11731 Builder'^Default_Switches^Default_Switches^("Ada")
11735 The prefix of an attribute may be:
11737 @item @code{project} for an attribute of the current project
11738 @item The name of an existing package of the current project
11739 @item The name of an imported project
11740 @item The name of a parent project that is extended by the current project
11741 @item An expanded name whose prefix is imported/parent project name,
11742 and whose selector is a package name
11747 @smallexample @c projectfile
11750 for Source_Dirs use project'Source_Dirs & "units";
11751 for Source_Dirs use project'Source_Dirs & "test/drivers"
11757 In the first attribute declaration, initially the attribute @code{Source_Dirs}
11758 has the default value: an empty string list. After this declaration,
11759 @code{Source_Dirs} is a string list of one element: @code{"units"}.
11760 After the second attribute declaration @code{Source_Dirs} is a string list of
11761 two elements: @code{"units"} and @code{"test/drivers"}.
11763 Note: this example is for illustration only. In practice,
11764 the project file would contain only one attribute declaration:
11766 @smallexample @c projectfile
11767 for Source_Dirs use ("units", "test/drivers");
11770 @node Associative Array Attributes
11771 @subsection Associative Array Attributes
11774 Some attributes are defined as @emph{associative arrays}. An associative
11775 array may be regarded as a function that takes a string as a parameter
11776 and delivers a string or string list value as its result.
11778 Here are some examples of single associative array attribute associations:
11780 @smallexample @c projectfile
11781 for Body ("main") use "Main.ada";
11782 for ^Switches^Switches^ ("main.ada")
11784 "^-gnatv^-gnatv^");
11785 for ^Switches^Switches^ ("main.ada")
11786 use Builder'^Switches^Switches^ ("main.ada")
11791 Like untyped variables and simple attributes, associative array attributes
11792 may be declared several times. Each declaration supplies a new value for the
11793 attribute, and replaces the previous setting.
11796 An associative array attribute may be declared as a full associative array
11797 declaration, with the value of the same attribute in an imported or extended
11800 @smallexample @c projectfile
11802 for Default_Switches use Default.Builder'Default_Switches;
11807 In this example, @code{Default} must be either an project imported by the
11808 current project, or the project that the current project extends. If the
11809 attribute is in a package (in this case, in package @code{Builder}), the same
11810 package needs to be specified.
11813 A full associative array declaration replaces any other declaration for the
11814 attribute, including other full associative array declaration. Single
11815 associative array associations may be declare after a full associative
11816 declaration, modifying the value for a single association of the attribute.
11818 @node case Constructions
11819 @subsection @code{case} Constructions
11822 A @code{case} construction is used in a project file to effect conditional
11824 Here is a typical example:
11826 @smallexample @c projectfile
11829 type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
11831 OS : OS_Type := external ("OS", "GNU/Linux");
11835 package Compiler is
11837 when "GNU/Linux" | "Unix" =>
11838 for ^Default_Switches^Default_Switches^ ("Ada")
11839 use ("^-gnath^-gnath^");
11841 for ^Default_Switches^Default_Switches^ ("Ada")
11842 use ("^-gnatP^-gnatP^");
11851 The syntax of a @code{case} construction is based on the Ada case statement
11852 (although there is no @code{null} construction for empty alternatives).
11854 The case expression must a typed string variable.
11855 Each alternative comprises the reserved word @code{when}, either a list of
11856 literal strings separated by the @code{"|"} character or the reserved word
11857 @code{others}, and the @code{"=>"} token.
11858 Each literal string must belong to the string type that is the type of the
11860 An @code{others} alternative, if present, must occur last.
11862 After each @code{=>}, there are zero or more constructions. The only
11863 constructions allowed in a case construction are other case constructions and
11864 attribute declarations. String type declarations, variable declarations and
11865 package declarations are not allowed.
11867 The value of the case variable is often given by an external reference
11868 (@pxref{External References in Project Files}).
11870 @c ****************************************
11871 @c * Objects and Sources in Project Files *
11872 @c ****************************************
11874 @node Objects and Sources in Project Files
11875 @section Objects and Sources in Project Files
11878 * Object Directory::
11880 * Source Directories::
11881 * Source File Names::
11885 Each project has exactly one object directory and one or more source
11886 directories. The source directories must contain at least one source file,
11887 unless the project file explicitly specifies that no source files are present
11888 (@pxref{Source File Names}).
11890 @node Object Directory
11891 @subsection Object Directory
11894 The object directory for a project is the directory containing the compiler's
11895 output (such as @file{ALI} files and object files) for the project's immediate
11898 The object directory is given by the value of the attribute @code{Object_Dir}
11899 in the project file.
11901 @smallexample @c projectfile
11902 for Object_Dir use "objects";
11906 The attribute @var{Object_Dir} has a string value, the path name of the object
11907 directory. The path name may be absolute or relative to the directory of the
11908 project file. This directory must already exist, and be readable and writable.
11910 By default, when the attribute @code{Object_Dir} is not given an explicit value
11911 or when its value is the empty string, the object directory is the same as the
11912 directory containing the project file.
11914 @node Exec Directory
11915 @subsection Exec Directory
11918 The exec directory for a project is the directory containing the executables
11919 for the project's main subprograms.
11921 The exec directory is given by the value of the attribute @code{Exec_Dir}
11922 in the project file.
11924 @smallexample @c projectfile
11925 for Exec_Dir use "executables";
11929 The attribute @var{Exec_Dir} has a string value, the path name of the exec
11930 directory. The path name may be absolute or relative to the directory of the
11931 project file. This directory must already exist, and be writable.
11933 By default, when the attribute @code{Exec_Dir} is not given an explicit value
11934 or when its value is the empty string, the exec directory is the same as the
11935 object directory of the project file.
11937 @node Source Directories
11938 @subsection Source Directories
11941 The source directories of a project are specified by the project file
11942 attribute @code{Source_Dirs}.
11944 This attribute's value is a string list. If the attribute is not given an
11945 explicit value, then there is only one source directory, the one where the
11946 project file resides.
11948 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
11951 @smallexample @c projectfile
11952 for Source_Dirs use ();
11956 indicates that the project contains no source files.
11958 Otherwise, each string in the string list designates one or more
11959 source directories.
11961 @smallexample @c projectfile
11962 for Source_Dirs use ("sources", "test/drivers");
11966 If a string in the list ends with @code{"/**"}, then the directory whose path
11967 name precedes the two asterisks, as well as all its subdirectories
11968 (recursively), are source directories.
11970 @smallexample @c projectfile
11971 for Source_Dirs use ("/system/sources/**");
11975 Here the directory @code{/system/sources} and all of its subdirectories
11976 (recursively) are source directories.
11978 To specify that the source directories are the directory of the project file
11979 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
11980 @smallexample @c projectfile
11981 for Source_Dirs use ("./**");
11985 Each of the source directories must exist and be readable.
11987 @node Source File Names
11988 @subsection Source File Names
11991 In a project that contains source files, their names may be specified by the
11992 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
11993 (a string). Source file names never include any directory information.
11995 If the attribute @code{Source_Files} is given an explicit value, then each
11996 element of the list is a source file name.
11998 @smallexample @c projectfile
11999 for Source_Files use ("main.adb");
12000 for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
12004 If the attribute @code{Source_Files} is not given an explicit value,
12005 but the attribute @code{Source_List_File} is given a string value,
12006 then the source file names are contained in the text file whose path name
12007 (absolute or relative to the directory of the project file) is the
12008 value of the attribute @code{Source_List_File}.
12010 Each line in the file that is not empty or is not a comment
12011 contains a source file name.
12013 @smallexample @c projectfile
12014 for Source_List_File use "source_list.txt";
12018 By default, if neither the attribute @code{Source_Files} nor the attribute
12019 @code{Source_List_File} is given an explicit value, then each file in the
12020 source directories that conforms to the project's naming scheme
12021 (@pxref{Naming Schemes}) is an immediate source of the project.
12023 A warning is issued if both attributes @code{Source_Files} and
12024 @code{Source_List_File} are given explicit values. In this case, the attribute
12025 @code{Source_Files} prevails.
12027 Each source file name must be the name of one existing source file
12028 in one of the source directories.
12030 A @code{Source_Files} attribute whose value is an empty list
12031 indicates that there are no source files in the project.
12033 If the order of the source directories is known statically, that is if
12034 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
12035 be several files with the same source file name. In this case, only the file
12036 in the first directory is considered as an immediate source of the project
12037 file. If the order of the source directories is not known statically, it is
12038 an error to have several files with the same source file name.
12040 Projects can be specified to have no Ada source
12041 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
12042 list, or the @code{"Ada"} may be absent from @code{Languages}:
12044 @smallexample @c projectfile
12045 for Source_Dirs use ();
12046 for Source_Files use ();
12047 for Languages use ("C", "C++");
12051 Otherwise, a project must contain at least one immediate source.
12053 Projects with no source files are useful as template packages
12054 (@pxref{Packages in Project Files}) for other projects; in particular to
12055 define a package @code{Naming} (@pxref{Naming Schemes}).
12057 @c ****************************
12058 @c * Importing Projects *
12059 @c ****************************
12061 @node Importing Projects
12062 @section Importing Projects
12063 @cindex @code{ADA_PROJECT_PATH}
12066 An immediate source of a project P may depend on source files that
12067 are neither immediate sources of P nor in the predefined library.
12068 To get this effect, P must @emph{import} the projects that contain the needed
12071 @smallexample @c projectfile
12073 with "project1", "utilities.gpr";
12074 with "/namings/apex.gpr";
12081 As can be seen in this example, the syntax for importing projects is similar
12082 to the syntax for importing compilation units in Ada. However, project files
12083 use literal strings instead of names, and the @code{with} clause identifies
12084 project files rather than packages.
12086 Each literal string is the file name or path name (absolute or relative) of a
12087 project file. If a string corresponds to a file name, with no path or a
12088 relative path, then its location is determined by the @emph{project path}. The
12089 latter can be queried using @code{gnatls -v}. It contains:
12093 In first position, the directory containing the current project file.
12095 In last position, the default project directory. This default project directory
12096 is part of the GNAT installation and is the standard place to install project
12097 files giving access to standard support libraries.
12099 @ref{Installing a library}
12103 In between, all the directories referenced in the
12104 ^environment variable^logical name^ @env{ADA_PROJECT_PATH} if it exists.
12108 If a relative pathname is used, as in
12110 @smallexample @c projectfile
12115 then the full path for the project is constructed by concatenating this
12116 relative path to those in the project path, in order, until a matching file is
12117 found. Any symbolic link will be fully resolved in the directory of the
12118 importing project file before the imported project file is examined.
12120 If the @code{with}'ed project file name does not have an extension,
12121 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
12122 then the file name as specified in the @code{with} clause (no extension) will
12123 be used. In the above example, if a file @code{project1.gpr} is found, then it
12124 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
12125 then it will be used; if neither file exists, this is an error.
12127 A warning is issued if the name of the project file does not match the
12128 name of the project; this check is case insensitive.
12130 Any source file that is an immediate source of the imported project can be
12131 used by the immediate sources of the importing project, transitively. Thus
12132 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
12133 sources of @code{A} may depend on the immediate sources of @code{C}, even if
12134 @code{A} does not import @code{C} explicitly. However, this is not recommended,
12135 because if and when @code{B} ceases to import @code{C}, some sources in
12136 @code{A} will no longer compile.
12138 A side effect of this capability is that normally cyclic dependencies are not
12139 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
12140 is not allowed to import @code{A}. However, there are cases when cyclic
12141 dependencies would be beneficial. For these cases, another form of import
12142 between projects exists, the @code{limited with}: a project @code{A} that
12143 imports a project @code{B} with a straigh @code{with} may also be imported,
12144 directly or indirectly, by @code{B} on the condition that imports from @code{B}
12145 to @code{A} include at least one @code{limited with}.
12147 @smallexample @c 0projectfile
12153 limited with "../a/a.gpr";
12161 limited with "../a/a.gpr";
12167 In the above legal example, there are two project cycles:
12170 @item A -> C -> D -> A
12174 In each of these cycle there is one @code{limited with}: import of @code{A}
12175 from @code{B} and import of @code{A} from @code{D}.
12177 The difference between straight @code{with} and @code{limited with} is that
12178 the name of a project imported with a @code{limited with} cannot be used in the
12179 project that imports it. In particular, its packages cannot be renamed and
12180 its variables cannot be referred to.
12182 An exception to the above rules for @code{limited with} is that for the main
12183 project specified to @command{gnatmake} or to the @command{GNAT} driver a
12184 @code{limited with} is equivalent to a straight @code{with}. For example,
12185 in the example above, projects @code{B} and @code{D} could not be main
12186 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
12187 each have a @code{limited with} that is the only one in a cycle of importing
12190 @c *********************
12191 @c * Project Extension *
12192 @c *********************
12194 @node Project Extension
12195 @section Project Extension
12198 During development of a large system, it is sometimes necessary to use
12199 modified versions of some of the source files, without changing the original
12200 sources. This can be achieved through the @emph{project extension} facility.
12202 @smallexample @c projectfile
12203 project Modified_Utilities extends "/baseline/utilities.gpr" is ...
12207 A project extension declaration introduces an extending project
12208 (the @emph{child}) and a project being extended (the @emph{parent}).
12210 By default, a child project inherits all the sources of its parent.
12211 However, inherited sources can be overridden: a unit in a parent is hidden
12212 by a unit of the same name in the child.
12214 Inherited sources are considered to be sources (but not immediate sources)
12215 of the child project; see @ref{Project File Syntax}.
12217 An inherited source file retains any switches specified in the parent project.
12219 For example if the project @code{Utilities} contains the specification and the
12220 body of an Ada package @code{Util_IO}, then the project
12221 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
12222 The original body of @code{Util_IO} will not be considered in program builds.
12223 However, the package specification will still be found in the project
12226 A child project can have only one parent but it may import any number of other
12229 A project is not allowed to import directly or indirectly at the same time a
12230 child project and any of its ancestors.
12232 @c *******************************
12233 @c * Project Hierarchy Extension *
12234 @c *******************************
12236 @node Project Hierarchy Extension
12237 @section Project Hierarchy Extension
12240 When extending a large system spanning multiple projects, it is often
12241 inconvenient to extend every project in the hierarchy that is impacted by a
12242 small change introduced. In such cases, it is possible to create a virtual
12243 extension of entire hierarchy using @code{extends all} relationship.
12245 When the project is extended using @code{extends all} inheritance, all projects
12246 that are imported by it, both directly and indirectly, are considered virtually
12247 extended. That is, the Project Manager creates "virtual projects"
12248 that extend every project in the hierarchy; all these virtual projects have
12249 no sources of their own and have as object directory the object directory of
12250 the root of "extending all" project.
12252 It is possible to explicitly extend one or more projects in the hierarchy
12253 in order to modify the sources. These extending projects must be imported by
12254 the "extending all" project, which will replace the corresponding virtual
12255 projects with the explicit ones.
12257 When building such a project hierarchy extension, the Project Manager will
12258 ensure that both modified sources and sources in virtual extending projects
12259 that depend on them, are recompiled.
12261 By means of example, consider the following hierarchy of projects.
12265 project A, containing package P1
12267 project B importing A and containing package P2 which depends on P1
12269 project C importing B and containing package P3 which depends on P2
12273 We want to modify packages P1 and P3.
12275 This project hierarchy will need to be extended as follows:
12279 Create project A1 that extends A, placing modified P1 there:
12281 @smallexample @c 0projectfile
12282 project A1 extends "(...)/A" is
12287 Create project C1 that "extends all" C and imports A1, placing modified
12290 @smallexample @c 0projectfile
12292 project C1 extends all "(...)/C" is
12297 When you build project C1, your entire modified project space will be
12298 recompiled, including the virtual project B1 that has been impacted by the
12299 "extending all" inheritance of project C.
12301 Note that if a Library Project in the hierarchy is virtually extended,
12302 the virtual project that extends the Library Project is not a Library Project.
12304 @c ****************************************
12305 @c * External References in Project Files *
12306 @c ****************************************
12308 @node External References in Project Files
12309 @section External References in Project Files
12312 A project file may contain references to external variables; such references
12313 are called @emph{external references}.
12315 An external variable is either defined as part of the environment (an
12316 environment variable in Unix, for example) or else specified on the command
12317 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
12318 If both, then the command line value is used.
12320 The value of an external reference is obtained by means of the built-in
12321 function @code{external}, which returns a string value.
12322 This function has two forms:
12324 @item @code{external (external_variable_name)}
12325 @item @code{external (external_variable_name, default_value)}
12329 Each parameter must be a string literal. For example:
12331 @smallexample @c projectfile
12333 external ("OS", "GNU/Linux")
12337 In the form with one parameter, the function returns the value of
12338 the external variable given as parameter. If this name is not present in the
12339 environment, the function returns an empty string.
12341 In the form with two string parameters, the second argument is
12342 the value returned when the variable given as the first argument is not
12343 present in the environment. In the example above, if @code{"OS"} is not
12344 the name of ^an environment variable^a logical name^ and is not passed on
12345 the command line, then the returned value is @code{"GNU/Linux"}.
12347 An external reference may be part of a string expression or of a string
12348 list expression, and can therefore appear in a variable declaration or
12349 an attribute declaration.
12351 @smallexample @c projectfile
12353 type Mode_Type is ("Debug", "Release");
12354 Mode : Mode_Type := external ("MODE");
12361 @c *****************************
12362 @c * Packages in Project Files *
12363 @c *****************************
12365 @node Packages in Project Files
12366 @section Packages in Project Files
12369 A @emph{package} defines the settings for project-aware tools within a
12371 For each such tool one can declare a package; the names for these
12372 packages are preset (@pxref{Packages}).
12373 A package may contain variable declarations, attribute declarations, and case
12376 @smallexample @c projectfile
12379 package Builder is -- used by gnatmake
12380 for ^Default_Switches^Default_Switches^ ("Ada")
12389 The syntax of package declarations mimics that of package in Ada.
12391 Most of the packages have an attribute
12392 @code{^Default_Switches^Default_Switches^}.
12393 This attribute is an associative array, and its value is a string list.
12394 The index of the associative array is the name of a programming language (case
12395 insensitive). This attribute indicates the ^switch^switch^
12396 or ^switches^switches^ to be used
12397 with the corresponding tool.
12399 Some packages also have another attribute, @code{^Switches^Switches^},
12400 an associative array whose value is a string list.
12401 The index is the name of a source file.
12402 This attribute indicates the ^switch^switch^
12403 or ^switches^switches^ to be used by the corresponding
12404 tool when dealing with this specific file.
12406 Further information on these ^switch^switch^-related attributes is found in
12407 @ref{^Switches^Switches^ and Project Files}.
12409 A package may be declared as a @emph{renaming} of another package; e.g., from
12410 the project file for an imported project.
12412 @smallexample @c projectfile
12414 with "/global/apex.gpr";
12416 package Naming renames Apex.Naming;
12423 Packages that are renamed in other project files often come from project files
12424 that have no sources: they are just used as templates. Any modification in the
12425 template will be reflected automatically in all the project files that rename
12426 a package from the template.
12428 In addition to the tool-oriented packages, you can also declare a package
12429 named @code{Naming} to establish specialized source file naming conventions
12430 (@pxref{Naming Schemes}).
12432 @c ************************************
12433 @c * Variables from Imported Projects *
12434 @c ************************************
12436 @node Variables from Imported Projects
12437 @section Variables from Imported Projects
12440 An attribute or variable defined in an imported or parent project can
12441 be used in expressions in the importing / extending project.
12442 Such an attribute or variable is denoted by an expanded name whose prefix
12443 is either the name of the project or the expanded name of a package within
12446 @smallexample @c projectfile
12449 project Main extends "base" is
12450 Var1 := Imported.Var;
12451 Var2 := Base.Var & ".new";
12456 for ^Default_Switches^Default_Switches^ ("Ada")
12457 use Imported.Builder.Ada_^Switches^Switches^ &
12458 "^-gnatg^-gnatg^" &
12464 package Compiler is
12465 for ^Default_Switches^Default_Switches^ ("Ada")
12466 use Base.Compiler.Ada_^Switches^Switches^;
12477 The value of @code{Var1} is a copy of the variable @code{Var} defined
12478 in the project file @file{"imported.gpr"}
12480 the value of @code{Var2} is a copy of the value of variable @code{Var}
12481 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
12483 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12484 @code{Builder} is a string list that includes in its value a copy of the value
12485 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
12486 in project file @file{imported.gpr} plus two new elements:
12487 @option{"^-gnatg^-gnatg^"}
12488 and @option{"^-v^-v^"};
12490 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12491 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
12492 defined in the @code{Compiler} package in project file @file{base.gpr},
12493 the project being extended.
12496 @c ******************
12497 @c * Naming Schemes *
12498 @c ******************
12500 @node Naming Schemes
12501 @section Naming Schemes
12504 Sometimes an Ada software system is ported from a foreign compilation
12505 environment to GNAT, and the file names do not use the default GNAT
12506 conventions. Instead of changing all the file names (which for a variety
12507 of reasons might not be possible), you can define the relevant file
12508 naming scheme in the @code{Naming} package in your project file.
12511 Note that the use of pragmas described in
12512 @ref{Alternative File Naming Schemes} by mean of a configuration
12513 pragmas file is not supported when using project files. You must use
12514 the features described in this paragraph. You can however use specify
12515 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
12518 For example, the following
12519 package models the Apex file naming rules:
12521 @smallexample @c projectfile
12524 for Casing use "lowercase";
12525 for Dot_Replacement use ".";
12526 for Spec_Suffix ("Ada") use ".1.ada";
12527 for Body_Suffix ("Ada") use ".2.ada";
12534 For example, the following package models the DEC Ada file naming rules:
12536 @smallexample @c projectfile
12539 for Casing use "lowercase";
12540 for Dot_Replacement use "__";
12541 for Spec_Suffix ("Ada") use "_.^ada^ada^";
12542 for Body_Suffix ("Ada") use ".^ada^ada^";
12548 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
12549 names in lower case)
12553 You can define the following attributes in package @code{Naming}:
12558 This must be a string with one of the three values @code{"lowercase"},
12559 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
12562 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
12564 @item @var{Dot_Replacement}
12565 This must be a string whose value satisfies the following conditions:
12568 @item It must not be empty
12569 @item It cannot start or end with an alphanumeric character
12570 @item It cannot be a single underscore
12571 @item It cannot start with an underscore followed by an alphanumeric
12572 @item It cannot contain a dot @code{'.'} except if the entire string
12577 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
12579 @item @var{Spec_Suffix}
12580 This is an associative array (indexed by the programming language name, case
12581 insensitive) whose value is a string that must satisfy the following
12585 @item It must not be empty
12586 @item It must include at least one dot
12589 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
12590 @code{"^.ads^.ADS^"}.
12592 @item @var{Body_Suffix}
12593 This is an associative array (indexed by the programming language name, case
12594 insensitive) whose value is a string that must satisfy the following
12598 @item It must not be empty
12599 @item It must include at least one dot
12600 @item It cannot end with the same string as @code{Spec_Suffix ("Ada")}
12603 If @code{Body_Suffix ("Ada")} is not specified, then the default is
12604 @code{"^.adb^.ADB^"}.
12606 @item @var{Separate_Suffix}
12607 This must be a string whose value satisfies the same conditions as
12608 @code{Body_Suffix}.
12611 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
12612 value as @code{Body_Suffix ("Ada")}.
12616 You can use the associative array attribute @code{Spec} to define
12617 the source file name for an individual Ada compilation unit's spec. The array
12618 index must be a string literal that identifies the Ada unit (case insensitive).
12619 The value of this attribute must be a string that identifies the file that
12620 contains this unit's spec (case sensitive or insensitive depending on the
12623 @smallexample @c projectfile
12624 for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
12629 You can use the associative array attribute @code{Body} to
12630 define the source file name for an individual Ada compilation unit's body
12631 (possibly a subunit). The array index must be a string literal that identifies
12632 the Ada unit (case insensitive). The value of this attribute must be a string
12633 that identifies the file that contains this unit's body or subunit (case
12634 sensitive or insensitive depending on the operating system).
12636 @smallexample @c projectfile
12637 for Body ("MyPack.MyChild") use "mypack.mychild.body";
12641 @c ********************
12642 @c * Library Projects *
12643 @c ********************
12645 @node Library Projects
12646 @section Library Projects
12649 @emph{Library projects} are projects whose object code is placed in a library.
12650 (Note that this facility is not yet supported on all platforms)
12652 To create a library project, you need to define in its project file
12653 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
12654 Additionally, you may define the library-related attributes
12655 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
12656 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
12658 The @code{Library_Name} attribute has a string value. There is no restriction
12659 on the name of a library. It is the responsibility of the developer to
12660 choose a name that will be accepted by the platform. It is recommended to
12661 choose names that could be Ada identifiers; such names are almost guaranteed
12662 to be acceptable on all platforms.
12664 The @code{Library_Dir} attribute has a string value that designates the path
12665 (absolute or relative) of the directory where the library will reside.
12666 It must designate an existing directory, and this directory must be
12667 different from the project's object directory. It also needs to be writable.
12668 The directory should only be used for one library; the reason is that all
12669 files contained in this directory may be deleted by the Project Manager.
12671 If both @code{Library_Name} and @code{Library_Dir} are specified and
12672 are legal, then the project file defines a library project. The optional
12673 library-related attributes are checked only for such project files.
12675 The @code{Library_Kind} attribute has a string value that must be one of the
12676 following (case insensitive): @code{"static"}, @code{"dynamic"} or
12677 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
12678 attribute is not specified, the library is a static library, that is
12679 an archive of object files that can be potentially linked into an
12680 static executable. Otherwise, the library may be dynamic or
12681 relocatable, that is a library that is loaded only at the start of execution.
12683 If you need to build both a static and a dynamic library, you should use two
12684 different object directories, since in some cases some extra code needs to
12685 be generated for the latter. For such cases, it is recommended to either use
12686 two different project files, or a single one which uses external variables
12687 to indicate what kind of library should be build.
12689 The @code{Library_Version} attribute has a string value whose interpretation
12690 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
12691 used only for dynamic/relocatable libraries as the internal name of the
12692 library (the @code{"soname"}). If the library file name (built from the
12693 @code{Library_Name}) is different from the @code{Library_Version}, then the
12694 library file will be a symbolic link to the actual file whose name will be
12695 @code{Library_Version}.
12699 @smallexample @c projectfile
12705 for Library_Dir use "lib_dir";
12706 for Library_Name use "dummy";
12707 for Library_Kind use "relocatable";
12708 for Library_Version use "libdummy.so." & Version;
12715 Directory @file{lib_dir} will contain the internal library file whose name
12716 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
12717 @file{libdummy.so.1}.
12719 When @command{gnatmake} detects that a project file
12720 is a library project file, it will check all immediate sources of the project
12721 and rebuild the library if any of the sources have been recompiled.
12723 Standard project files can import library project files. In such cases,
12724 the libraries will only be rebuild if some of its sources are recompiled
12725 because they are in the closure of some other source in an importing project.
12726 Sources of the library project files that are not in such a closure will
12727 not be checked, unless the full library is checked, because one of its sources
12728 needs to be recompiled.
12730 For instance, assume the project file @code{A} imports the library project file
12731 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
12732 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
12733 @file{l2.ads}, @file{l2.adb}.
12735 If @file{l1.adb} has been modified, then the library associated with @code{L}
12736 will be rebuild when compiling all the immediate sources of @code{A} only
12737 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
12740 To be sure that all the sources in the library associated with @code{L} are
12741 up to date, and that all the sources of project @code{A} are also up to date,
12742 the following two commands needs to be used:
12749 When a library is built or rebuilt, an attempt is made first to delete all
12750 files in the library directory.
12751 All @file{ALI} files will also be copied from the object directory to the
12752 library directory. To build executables, @command{gnatmake} will use the
12753 library rather than the individual object files.
12756 It is also possible to create library project files for third-party libraries
12757 that are precompiled and cannot be compiled locally thanks to the
12758 @code{externally_built} attribute. (See @ref{Installing a library}).
12761 @c *******************************
12762 @c * Stand-alone Library Projects *
12763 @c *******************************
12765 @node Stand-alone Library Projects
12766 @section Stand-alone Library Projects
12769 A Stand-alone Library is a library that contains the necessary code to
12770 elaborate the Ada units that are included in the library. A Stand-alone
12771 Library is suitable to be used in an executable when the main is not
12772 in Ada. However, Stand-alone Libraries may also be used with an Ada main
12775 A Stand-alone Library Project is a Library Project where the library is
12776 a Stand-alone Library.
12778 To be a Stand-alone Library Project, in addition to the two attributes
12779 that make a project a Library Project (@code{Library_Name} and
12780 @code{Library_Dir}, see @ref{Library Projects}), the attribute
12781 @code{Library_Interface} must be defined.
12783 @smallexample @c projectfile
12785 for Library_Dir use "lib_dir";
12786 for Library_Name use "dummy";
12787 for Library_Interface use ("int1", "int1.child");
12791 Attribute @code{Library_Interface} has a non empty string list value,
12792 each string in the list designating a unit contained in an immediate source
12793 of the project file.
12795 When a Stand-alone Library is built, first the binder is invoked to build
12796 a package whose name depends on the library name
12797 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
12798 This binder-generated package includes initialization and
12799 finalization procedures whose
12800 names depend on the library name (dummyinit and dummyfinal in the example
12801 above). The object corresponding to this package is included in the library.
12803 A dynamic or relocatable Stand-alone Library is automatically initialized
12804 if automatic initialization of Stand-alone Libraries is supported on the
12805 platform and if attribute @code{Library_Auto_Init} is not specified or
12806 is specified with the value "true". A static Stand-alone Library is never
12807 automatically initialized.
12809 Single string attribute @code{Library_Auto_Init} may be specified with only
12810 two possible values: "false" or "true" (case-insensitive). Specifying
12811 "false" for attribute @code{Library_Auto_Init} will prevent automatic
12812 initialization of dynamic or relocatable libraries.
12814 When a non automatically initialized Stand-alone Library is used
12815 in an executable, its initialization procedure must be called before
12816 any service of the library is used.
12817 When the main subprogram is in Ada, it may mean that the initialization
12818 procedure has to be called during elaboration of another package.
12820 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
12821 (those that are listed in attribute @code{Library_Interface}) are copied to
12822 the Library Directory. As a consequence, only the Interface Units may be
12823 imported from Ada units outside of the library. If other units are imported,
12824 the binding phase will fail.
12826 When a Stand-Alone Library is bound, the switches that are specified in
12827 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
12828 used in the call to @command{gnatbind}.
12830 The string list attribute @code{Library_Options} may be used to specified
12831 additional switches to the call to @command{gcc} to link the library.
12833 The attribute @code{Library_Src_Dir}, may be specified for a
12834 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
12835 single string value. Its value must be the path (absolute or relative to the
12836 project directory) of an existing directory. This directory cannot be the
12837 object directory or one of the source directories, but it can be the same as
12838 the library directory. The sources of the Interface
12839 Units of the library, necessary to an Ada client of the library, will be
12840 copied to the designated directory, called Interface Copy directory.
12841 These sources includes the specs of the Interface Units, but they may also
12842 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
12843 are used, or when there is a generic units in the spec. Before the sources
12844 are copied to the Interface Copy directory, an attempt is made to delete all
12845 files in the Interface Copy directory.
12847 @c *************************************
12848 @c * Switches Related to Project Files *
12849 @c *************************************
12850 @node Switches Related to Project Files
12851 @section Switches Related to Project Files
12854 The following switches are used by GNAT tools that support project files:
12858 @item ^-P^/PROJECT_FILE=^@var{project}
12859 @cindex @option{^-P^/PROJECT_FILE^} (any tool supporting project files)
12860 Indicates the name of a project file. This project file will be parsed with
12861 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12862 if any, and using the external references indicated
12863 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12865 There may zero, one or more spaces between @option{-P} and @var{project}.
12869 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12872 Since the Project Manager parses the project file only after all the switches
12873 on the command line are checked, the order of the switches
12874 @option{^-P^/PROJECT_FILE^},
12875 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12876 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12878 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12879 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any tool supporting project files)
12880 Indicates that external variable @var{name} has the value @var{value}.
12881 The Project Manager will use this value for occurrences of
12882 @code{external(name)} when parsing the project file.
12886 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12887 put between quotes.
12895 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12896 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12897 @var{name}, only the last one is used.
12900 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12901 takes precedence over the value of the same name in the environment.
12903 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12904 @cindex @code{^-vP^/MESSAGES_PROJECT_FILE^} (any tool supporting project files)
12905 @c Previous line uses code vs option command, to stay less than 80 chars
12906 Indicates the verbosity of the parsing of GNAT project files.
12909 @option{-vP0} means Default;
12910 @option{-vP1} means Medium;
12911 @option{-vP2} means High.
12915 There are three possible options for this qualifier: DEFAULT, MEDIUM and
12920 The default is ^Default^DEFAULT^: no output for syntactically correct
12923 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12924 only the last one is used.
12928 @c **********************************
12929 @c * Tools Supporting Project Files *
12930 @c **********************************
12932 @node Tools Supporting Project Files
12933 @section Tools Supporting Project Files
12936 * gnatmake and Project Files::
12937 * The GNAT Driver and Project Files::
12939 * Glide and Project Files::
12943 @node gnatmake and Project Files
12944 @subsection gnatmake and Project Files
12947 This section covers several topics related to @command{gnatmake} and
12948 project files: defining ^switches^switches^ for @command{gnatmake}
12949 and for the tools that it invokes; specifying configuration pragmas;
12950 the use of the @code{Main} attribute; building and rebuilding library project
12954 * ^Switches^Switches^ and Project Files::
12955 * Specifying Configuration Pragmas::
12956 * Project Files and Main Subprograms::
12957 * Library Project Files::
12960 @node ^Switches^Switches^ and Project Files
12961 @subsubsection ^Switches^Switches^ and Project Files
12964 It is not currently possible to specify VMS style qualifiers in the project
12965 files; only Unix style ^switches^switches^ may be specified.
12969 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12970 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
12971 attribute, a @code{^Switches^Switches^} attribute, or both;
12972 as their names imply, these ^switch^switch^-related
12973 attributes affect the ^switches^switches^ that are used for each of these GNAT
12975 @command{gnatmake} is invoked. As will be explained below, these
12976 component-specific ^switches^switches^ precede
12977 the ^switches^switches^ provided on the @command{gnatmake} command line.
12979 The @code{^Default_Switches^Default_Switches^} attribute is an associative
12980 array indexed by language name (case insensitive) whose value is a string list.
12983 @smallexample @c projectfile
12985 package Compiler is
12986 for ^Default_Switches^Default_Switches^ ("Ada")
12987 use ("^-gnaty^-gnaty^",
12994 The @code{^Switches^Switches^} attribute is also an associative array,
12995 indexed by a file name (which may or may not be case sensitive, depending
12996 on the operating system) whose value is a string list. For example:
12998 @smallexample @c projectfile
13001 for ^Switches^Switches^ ("main1.adb")
13003 for ^Switches^Switches^ ("main2.adb")
13010 For the @code{Builder} package, the file names must designate source files
13011 for main subprograms. For the @code{Binder} and @code{Linker} packages, the
13012 file names must designate @file{ALI} or source files for main subprograms.
13013 In each case just the file name without an explicit extension is acceptable.
13015 For each tool used in a program build (@command{gnatmake}, the compiler, the
13016 binder, and the linker), the corresponding package @dfn{contributes} a set of
13017 ^switches^switches^ for each file on which the tool is invoked, based on the
13018 ^switch^switch^-related attributes defined in the package.
13019 In particular, the ^switches^switches^
13020 that each of these packages contributes for a given file @var{f} comprise:
13024 the value of attribute @code{^Switches^Switches^ (@var{f})},
13025 if it is specified in the package for the given file,
13027 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
13028 if it is specified in the package.
13032 If neither of these attributes is defined in the package, then the package does
13033 not contribute any ^switches^switches^ for the given file.
13035 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
13036 two sets, in the following order: those contributed for the file
13037 by the @code{Builder} package;
13038 and the switches passed on the command line.
13040 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
13041 the ^switches^switches^ passed to the tool comprise three sets,
13042 in the following order:
13046 the applicable ^switches^switches^ contributed for the file
13047 by the @code{Builder} package in the project file supplied on the command line;
13050 those contributed for the file by the package (in the relevant project file --
13051 see below) corresponding to the tool; and
13054 the applicable switches passed on the command line.
13058 The term @emph{applicable ^switches^switches^} reflects the fact that
13059 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
13060 tools, depending on the individual ^switch^switch^.
13062 @command{gnatmake} may invoke the compiler on source files from different
13063 projects. The Project Manager will use the appropriate project file to
13064 determine the @code{Compiler} package for each source file being compiled.
13065 Likewise for the @code{Binder} and @code{Linker} packages.
13067 As an example, consider the following package in a project file:
13069 @smallexample @c projectfile
13072 package Compiler is
13073 for ^Default_Switches^Default_Switches^ ("Ada")
13075 for ^Switches^Switches^ ("a.adb")
13077 for ^Switches^Switches^ ("b.adb")
13079 "^-gnaty^-gnaty^");
13086 If @command{gnatmake} is invoked with this project file, and it needs to
13087 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
13088 @file{a.adb} will be compiled with the ^switch^switch^
13089 @option{^-O1^-O1^},
13090 @file{b.adb} with ^switches^switches^
13092 and @option{^-gnaty^-gnaty^},
13093 and @file{c.adb} with @option{^-g^-g^}.
13095 The following example illustrates the ordering of the ^switches^switches^
13096 contributed by different packages:
13098 @smallexample @c projectfile
13102 for ^Switches^Switches^ ("main.adb")
13110 package Compiler is
13111 for ^Switches^Switches^ ("main.adb")
13119 If you issue the command:
13122 gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
13126 then the compiler will be invoked on @file{main.adb} with the following
13127 sequence of ^switches^switches^
13130 ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
13133 with the last @option{^-O^-O^}
13134 ^switch^switch^ having precedence over the earlier ones;
13135 several other ^switches^switches^
13136 (such as @option{^-c^-c^}) are added implicitly.
13138 The ^switches^switches^
13140 and @option{^-O1^-O1^} are contributed by package
13141 @code{Builder}, @option{^-O2^-O2^} is contributed
13142 by the package @code{Compiler}
13143 and @option{^-O0^-O0^} comes from the command line.
13145 The @option{^-g^-g^}
13146 ^switch^switch^ will also be passed in the invocation of
13147 @command{Gnatlink.}
13149 A final example illustrates switch contributions from packages in different
13152 @smallexample @c projectfile
13155 for Source_Files use ("pack.ads", "pack.adb");
13156 package Compiler is
13157 for ^Default_Switches^Default_Switches^ ("Ada")
13158 use ("^-gnata^-gnata^");
13166 for Source_Files use ("foo_main.adb", "bar_main.adb");
13168 for ^Switches^Switches^ ("foo_main.adb")
13176 -- Ada source file:
13178 procedure Foo_Main is
13186 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
13190 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
13191 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
13192 @option{^-gnato^-gnato^} (passed on the command line).
13193 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
13194 are @option{^-g^-g^} from @code{Proj4.Builder},
13195 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
13196 and @option{^-gnato^-gnato^} from the command line.
13199 When using @command{gnatmake} with project files, some ^switches^switches^ or
13200 arguments may be expressed as relative paths. As the working directory where
13201 compilation occurs may change, these relative paths are converted to absolute
13202 paths. For the ^switches^switches^ found in a project file, the relative paths
13203 are relative to the project file directory, for the switches on the command
13204 line, they are relative to the directory where @command{gnatmake} is invoked.
13205 The ^switches^switches^ for which this occurs are:
13211 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
13213 ^-o^-o^, object files specified in package @code{Linker} or after
13214 -largs on the command line). The exception to this rule is the ^switch^switch^
13215 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
13217 @node Specifying Configuration Pragmas
13218 @subsubsection Specifying Configuration Pragmas
13220 When using @command{gnatmake} with project files, if there exists a file
13221 @file{gnat.adc} that contains configuration pragmas, this file will be
13224 Configuration pragmas can be defined by means of the following attributes in
13225 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
13226 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
13228 Both these attributes are single string attributes. Their values is the path
13229 name of a file containing configuration pragmas. If a path name is relative,
13230 then it is relative to the project directory of the project file where the
13231 attribute is defined.
13233 When compiling a source, the configuration pragmas used are, in order,
13234 those listed in the file designated by attribute
13235 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
13236 project file, if it is specified, and those listed in the file designated by
13237 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
13238 the project file of the source, if it exists.
13240 @node Project Files and Main Subprograms
13241 @subsubsection Project Files and Main Subprograms
13244 When using a project file, you can invoke @command{gnatmake}
13245 with one or several main subprograms, by specifying their source files on the
13249 gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
13253 Each of these needs to be a source file of the same project, except
13254 when the switch ^-u^/UNIQUE^ is used.
13257 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
13258 same project, one of the project in the tree rooted at the project specified
13259 on the command line. The package @code{Builder} of this common project, the
13260 "main project" is the one that is considered by @command{gnatmake}.
13263 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
13264 imported directly or indirectly by the project specified on the command line.
13265 Note that if such a source file is not part of the project specified on the
13266 command line, the ^switches^switches^ found in package @code{Builder} of the
13267 project specified on the command line, if any, that are transmitted
13268 to the compiler will still be used, not those found in the project file of
13272 When using a project file, you can also invoke @command{gnatmake} without
13273 explicitly specifying any main, and the effect depends on whether you have
13274 defined the @code{Main} attribute. This attribute has a string list value,
13275 where each element in the list is the name of a source file (the file
13276 extension is optional) that contains a unit that can be a main subprogram.
13278 If the @code{Main} attribute is defined in a project file as a non-empty
13279 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
13280 line, then invoking @command{gnatmake} with this project file but without any
13281 main on the command line is equivalent to invoking @command{gnatmake} with all
13282 the file names in the @code{Main} attribute on the command line.
13285 @smallexample @c projectfile
13288 for Main use ("main1", "main2", "main3");
13294 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
13296 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
13298 When the project attribute @code{Main} is not specified, or is specified
13299 as an empty string list, or when the switch @option{-u} is used on the command
13300 line, then invoking @command{gnatmake} with no main on the command line will
13301 result in all immediate sources of the project file being checked, and
13302 potentially recompiled. Depending on the presence of the switch @option{-u},
13303 sources from other project files on which the immediate sources of the main
13304 project file depend are also checked and potentially recompiled. In other
13305 words, the @option{-u} switch is applied to all of the immediate sources of the
13308 When no main is specified on the command line and attribute @code{Main} exists
13309 and includes several mains, or when several mains are specified on the
13310 command line, the default ^switches^switches^ in package @code{Builder} will
13311 be used for all mains, even if there are specific ^switches^switches^
13312 specified for one or several mains.
13314 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
13315 the specific ^switches^switches^ for each main, if they are specified.
13317 @node Library Project Files
13318 @subsubsection Library Project Files
13321 When @command{gnatmake} is invoked with a main project file that is a library
13322 project file, it is not allowed to specify one or more mains on the command
13326 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
13327 ^-l^/ACTION=LINK^ have special meanings.
13330 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
13331 to @command{gnatmake} that @command{gnatbind} should be invoked for the
13334 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13335 to @command{gnatmake} that the binder generated file should be compiled
13336 (in the case of a stand-alone library) and that the library should be built.
13340 @node The GNAT Driver and Project Files
13341 @subsection The GNAT Driver and Project Files
13344 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13346 @command{^gnatbind^gnatbind^},
13347 @command{^gnatfind^gnatfind^},
13348 @command{^gnatlink^gnatlink^},
13349 @command{^gnatls^gnatls^},
13350 @command{^gnatelim^gnatelim^},
13351 @command{^gnatpp^gnatpp^},
13352 @command{^gnatmetric^gnatmetric^},
13353 @command{^gnatstub^gnatstub^},
13354 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
13355 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13356 They must be invoked through the @command{gnat} driver.
13358 The @command{gnat} driver is a front-end that accepts a number of commands and
13359 call the corresponding tool. It has been designed initially for VMS to convert
13360 VMS style qualifiers to Unix style switches, but it is now available to all
13361 the GNAT supported platforms.
13363 On non VMS platforms, the @command{gnat} driver accepts the following commands
13364 (case insensitive):
13368 BIND to invoke @command{^gnatbind^gnatbind^}
13370 CHOP to invoke @command{^gnatchop^gnatchop^}
13372 CLEAN to invoke @command{^gnatclean^gnatclean^}
13374 COMP or COMPILE to invoke the compiler
13376 ELIM to invoke @command{^gnatelim^gnatelim^}
13378 FIND to invoke @command{^gnatfind^gnatfind^}
13380 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
13382 LINK to invoke @command{^gnatlink^gnatlink^}
13384 LS or LIST to invoke @command{^gnatls^gnatls^}
13386 MAKE to invoke @command{^gnatmake^gnatmake^}
13388 NAME to invoke @command{^gnatname^gnatname^}
13390 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
13392 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
13394 METRIC to invoke @command{^gnatmetric^gnatmetric^}
13396 STUB to invoke @command{^gnatstub^gnatstub^}
13398 XREF to invoke @command{^gnatxref^gnatxref^}
13402 (note that the compiler is invoked using the command
13403 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
13406 On non VMS platforms, between @command{gnat} and the command, two
13407 special switches may be used:
13411 @command{-v} to display the invocation of the tool.
13413 @command{-dn} to prevent the @command{gnat} driver from removing
13414 the temporary files it has created. These temporary files are
13415 configuration files and temporary file list files.
13419 The command may be followed by switches and arguments for the invoked
13423 gnat bind -C main.ali
13429 Switches may also be put in text files, one switch per line, and the text
13430 files may be specified with their path name preceded by '@@'.
13433 gnat bind @@args.txt main.ali
13437 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
13438 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
13439 (@option{^-P^/PROJECT_FILE^},
13440 @option{^-X^/EXTERNAL_REFERENCE^} and
13441 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
13442 the switches of the invoking tool.
13445 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
13446 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
13447 the immediate sources of the specified project file.
13450 When GNAT METRIC is used with a project file, but with no source
13451 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
13452 with all the immediate sources of the specified project file and with
13453 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
13457 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
13458 a project file, no source is specified on the command line and
13459 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
13460 the underlying tool (^gnatpp^gnatpp^ or
13461 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
13462 not only for the immediate sources of the main project.
13464 (-U stands for Universal or Union of the project files of the project tree)
13468 For each of the following commands, there is optionally a corresponding
13469 package in the main project.
13473 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
13476 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
13479 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
13482 package @code{Eliminate} for command ELIM (invoking
13483 @code{^gnatelim^gnatelim^})
13486 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
13489 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
13492 package @code{Metrics} for command METRIC
13493 (invoking @code{^gnatmetric^gnatmetric^})
13496 package @code{Pretty_Printer} for command PP or PRETTY
13497 (invoking @code{^gnatpp^gnatpp^})
13500 package @code{Gnatstub} for command STUB
13501 (invoking @code{^gnatstub^gnatstub^})
13504 package @code{Cross_Reference} for command XREF (invoking
13505 @code{^gnatxref^gnatxref^})
13510 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
13511 a simple variable with a string list value. It contains ^switches^switches^
13512 for the invocation of @code{^gnatls^gnatls^}.
13514 @smallexample @c projectfile
13518 for ^Switches^Switches^
13527 All other packages have two attribute @code{^Switches^Switches^} and
13528 @code{^Default_Switches^Default_Switches^}.
13531 @code{^Switches^Switches^} is an associated array attribute, indexed by the
13532 source file name, that has a string list value: the ^switches^switches^ to be
13533 used when the tool corresponding to the package is invoked for the specific
13537 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
13538 indexed by the programming language that has a string list value.
13539 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
13540 ^switches^switches^ for the invocation of the tool corresponding
13541 to the package, except if a specific @code{^Switches^Switches^} attribute
13542 is specified for the source file.
13544 @smallexample @c projectfile
13548 for Source_Dirs use ("./**");
13551 for ^Switches^Switches^ use
13558 package Compiler is
13559 for ^Default_Switches^Default_Switches^ ("Ada")
13560 use ("^-gnatv^-gnatv^",
13561 "^-gnatwa^-gnatwa^");
13567 for ^Default_Switches^Default_Switches^ ("Ada")
13575 for ^Default_Switches^Default_Switches^ ("Ada")
13577 for ^Switches^Switches^ ("main.adb")
13586 for ^Default_Switches^Default_Switches^ ("Ada")
13593 package Cross_Reference is
13594 for ^Default_Switches^Default_Switches^ ("Ada")
13599 end Cross_Reference;
13605 With the above project file, commands such as
13608 ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13609 ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13610 ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13611 ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13612 ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13616 will set up the environment properly and invoke the tool with the switches
13617 found in the package corresponding to the tool:
13618 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13619 except @code{^Switches^Switches^ ("main.adb")}
13620 for @code{^gnatlink^gnatlink^}.
13623 @node Glide and Project Files
13624 @subsection Glide and Project Files
13627 Glide will automatically recognize the @file{.gpr} extension for
13628 project files, and will
13629 convert them to its own internal format automatically. However, it
13630 doesn't provide a syntax-oriented editor for modifying these
13632 The project file will be loaded as text when you select the menu item
13633 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
13634 You can edit this text and save the @file{gpr} file;
13635 when you next select this project file in Glide it
13636 will be automatically reloaded.
13639 @c **********************
13640 @node An Extended Example
13641 @section An Extended Example
13644 Suppose that we have two programs, @var{prog1} and @var{prog2},
13645 whose sources are in corresponding directories. We would like
13646 to build them with a single @command{gnatmake} command, and we want to place
13647 their object files into @file{build} subdirectories of the source directories.
13648 Furthermore, we want to have to have two separate subdirectories
13649 in @file{build} -- @file{release} and @file{debug} -- which will contain
13650 the object files compiled with different set of compilation flags.
13652 In other words, we have the following structure:
13669 Here are the project files that we must place in a directory @file{main}
13670 to maintain this structure:
13674 @item We create a @code{Common} project with a package @code{Compiler} that
13675 specifies the compilation ^switches^switches^:
13680 @b{project} Common @b{is}
13682 @b{for} Source_Dirs @b{use} (); -- No source files
13686 @b{type} Build_Type @b{is} ("release", "debug");
13687 Build : Build_Type := External ("BUILD", "debug");
13690 @b{package} Compiler @b{is}
13691 @b{case} Build @b{is}
13692 @b{when} "release" =>
13693 @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13694 @b{use} ("^-O2^-O2^");
13695 @b{when} "debug" =>
13696 @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13697 @b{use} ("^-g^-g^");
13705 @item We create separate projects for the two programs:
13712 @b{project} Prog1 @b{is}
13714 @b{for} Source_Dirs @b{use} ("prog1");
13715 @b{for} Object_Dir @b{use} "prog1/build/" & Common.Build;
13717 @b{package} Compiler @b{renames} Common.Compiler;
13728 @b{project} Prog2 @b{is}
13730 @b{for} Source_Dirs @b{use} ("prog2");
13731 @b{for} Object_Dir @b{use} "prog2/build/" & Common.Build;
13733 @b{package} Compiler @b{renames} Common.Compiler;
13739 @item We create a wrapping project @code{Main}:
13748 @b{project} Main @b{is}
13750 @b{package} Compiler @b{renames} Common.Compiler;
13756 @item Finally we need to create a dummy procedure that @code{with}s (either
13757 explicitly or implicitly) all the sources of our two programs.
13762 Now we can build the programs using the command
13765 gnatmake ^-P^/PROJECT_FILE=^main dummy
13769 for the Debug mode, or
13773 gnatmake -Pmain -XBUILD=release
13779 GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
13784 for the Release mode.
13786 @c ********************************
13787 @c * Project File Complete Syntax *
13788 @c ********************************
13790 @node Project File Complete Syntax
13791 @section Project File Complete Syntax
13795 context_clause project_declaration
13801 @b{with} path_name @{ , path_name @} ;
13806 project_declaration ::=
13807 simple_project_declaration | project_extension
13809 simple_project_declaration ::=
13810 @b{project} <project_>simple_name @b{is}
13811 @{declarative_item@}
13812 @b{end} <project_>simple_name;
13814 project_extension ::=
13815 @b{project} <project_>simple_name @b{extends} path_name @b{is}
13816 @{declarative_item@}
13817 @b{end} <project_>simple_name;
13819 declarative_item ::=
13820 package_declaration |
13821 typed_string_declaration |
13822 other_declarative_item
13824 package_declaration ::=
13825 package_specification | package_renaming
13827 package_specification ::=
13828 @b{package} package_identifier @b{is}
13829 @{simple_declarative_item@}
13830 @b{end} package_identifier ;
13832 package_identifier ::=
13833 @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
13834 @code{Linker} | @code{Finder} | @code{Cross_Reference} |
13835 @code{^gnatls^gnatls^} | @code{IDE} | @code{Pretty_Printer}
13837 package_renaming ::==
13838 @b{package} package_identifier @b{renames}
13839 <project_>simple_name.package_identifier ;
13841 typed_string_declaration ::=
13842 @b{type} <typed_string_>_simple_name @b{is}
13843 ( string_literal @{, string_literal@} );
13845 other_declarative_item ::=
13846 attribute_declaration |
13847 typed_variable_declaration |
13848 variable_declaration |
13851 attribute_declaration ::=
13852 full_associative_array_declaration |
13853 @b{for} attribute_designator @b{use} expression ;
13855 full_associative_array_declaration ::=
13856 @b{for} <associative_array_attribute_>simple_name @b{use}
13857 <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
13859 attribute_designator ::=
13860 <simple_attribute_>simple_name |
13861 <associative_array_attribute_>simple_name ( string_literal )
13863 typed_variable_declaration ::=
13864 <typed_variable_>simple_name : <typed_string_>name := string_expression ;
13866 variable_declaration ::=
13867 <variable_>simple_name := expression;
13877 attribute_reference
13883 ( <string_>expression @{ , <string_>expression @} )
13886 @b{external} ( string_literal [, string_literal] )
13888 attribute_reference ::=
13889 attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
13891 attribute_prefix ::=
13893 <project_>simple_name | package_identifier |
13894 <project_>simple_name . package_identifier
13896 case_construction ::=
13897 @b{case} <typed_variable_>name @b{is}
13902 @b{when} discrete_choice_list =>
13903 @{case_construction | attribute_declaration@}
13905 discrete_choice_list ::=
13906 string_literal @{| string_literal@} |
13910 simple_name @{. simple_name@}
13913 identifier (same as Ada)
13917 @node The Cross-Referencing Tools gnatxref and gnatfind
13918 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13923 The compiler generates cross-referencing information (unless
13924 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13925 This information indicates where in the source each entity is declared and
13926 referenced. Note that entities in package Standard are not included, but
13927 entities in all other predefined units are included in the output.
13929 Before using any of these two tools, you need to compile successfully your
13930 application, so that GNAT gets a chance to generate the cross-referencing
13933 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13934 information to provide the user with the capability to easily locate the
13935 declaration and references to an entity. These tools are quite similar,
13936 the difference being that @code{gnatfind} is intended for locating
13937 definitions and/or references to a specified entity or entities, whereas
13938 @code{gnatxref} is oriented to generating a full report of all
13941 To use these tools, you must not compile your application using the
13942 @option{-gnatx} switch on the @command{gnatmake} command line
13943 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
13944 information will not be generated.
13947 * gnatxref Switches::
13948 * gnatfind Switches::
13949 * Project Files for gnatxref and gnatfind::
13950 * Regular Expressions in gnatfind and gnatxref::
13951 * Examples of gnatxref Usage::
13952 * Examples of gnatfind Usage::
13955 @node gnatxref Switches
13956 @section @code{gnatxref} Switches
13959 The command invocation for @code{gnatxref} is:
13961 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
13968 @item sourcefile1, sourcefile2
13969 identifies the source files for which a report is to be generated. The
13970 ``with''ed units will be processed too. You must provide at least one file.
13972 These file names are considered to be regular expressions, so for instance
13973 specifying @file{source*.adb} is the same as giving every file in the current
13974 directory whose name starts with @file{source} and whose extension is
13977 You shouldn't specify any directory name, just base names. @command{gnatxref}
13978 and @command{gnatfind} will be able to locate these files by themselves using
13979 the source path. If you specify directories, no result is produced.
13984 The switches can be :
13987 @item ^-a^/ALL_FILES^
13988 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
13989 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13990 the read-only files found in the library search path. Otherwise, these files
13991 will be ignored. This option can be used to protect Gnat sources or your own
13992 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13993 much faster, and their output much smaller. Read-only here refers to access
13994 or permissions status in the file system for the current user.
13997 @cindex @option{-aIDIR} (@command{gnatxref})
13998 When looking for source files also look in directory DIR. The order in which
13999 source file search is undertaken is the same as for @command{gnatmake}.
14002 @cindex @option{-aODIR} (@command{gnatxref})
14003 When searching for library and object files, look in directory
14004 DIR. The order in which library files are searched is the same as for
14005 @command{gnatmake}.
14008 @cindex @option{-nostdinc} (@command{gnatxref})
14009 Do not look for sources in the system default directory.
14012 @cindex @option{-nostdlib} (@command{gnatxref})
14013 Do not look for library files in the system default directory.
14015 @item --RTS=@var{rts-path}
14016 @cindex @option{--RTS} (@command{gnatxref})
14017 Specifies the default location of the runtime library. Same meaning as the
14018 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14020 @item ^-d^/DERIVED_TYPES^
14021 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
14022 If this switch is set @code{gnatxref} will output the parent type
14023 reference for each matching derived types.
14025 @item ^-f^/FULL_PATHNAME^
14026 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
14027 If this switch is set, the output file names will be preceded by their
14028 directory (if the file was found in the search path). If this switch is
14029 not set, the directory will not be printed.
14031 @item ^-g^/IGNORE_LOCALS^
14032 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
14033 If this switch is set, information is output only for library-level
14034 entities, ignoring local entities. The use of this switch may accelerate
14035 @code{gnatfind} and @code{gnatxref}.
14038 @cindex @option{-IDIR} (@command{gnatxref})
14039 Equivalent to @samp{-aODIR -aIDIR}.
14042 @cindex @option{-pFILE} (@command{gnatxref})
14043 Specify a project file to use @xref{Project Files}. These project files are
14044 the @file{.adp} files used by Glide. If you need to use the @file{.gpr}
14045 project files, you should use gnatxref through the GNAT driver
14046 (@command{gnat xref -Pproject}).
14048 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14049 project file in the current directory.
14051 If a project file is either specified or found by the tools, then the content
14052 of the source directory and object directory lines are added as if they
14053 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
14054 and @samp{^-aO^OBJECT_SEARCH^}.
14056 Output only unused symbols. This may be really useful if you give your
14057 main compilation unit on the command line, as @code{gnatxref} will then
14058 display every unused entity and 'with'ed package.
14062 Instead of producing the default output, @code{gnatxref} will generate a
14063 @file{tags} file that can be used by vi. For examples how to use this
14064 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
14065 to the standard output, thus you will have to redirect it to a file.
14071 All these switches may be in any order on the command line, and may even
14072 appear after the file names. They need not be separated by spaces, thus
14073 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14074 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14076 @node gnatfind Switches
14077 @section @code{gnatfind} Switches
14080 The command line for @code{gnatfind} is:
14083 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
14092 An entity will be output only if it matches the regular expression found
14093 in @samp{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
14095 Omitting the pattern is equivalent to specifying @samp{*}, which
14096 will match any entity. Note that if you do not provide a pattern, you
14097 have to provide both a sourcefile and a line.
14099 Entity names are given in Latin-1, with uppercase/lowercase equivalence
14100 for matching purposes. At the current time there is no support for
14101 8-bit codes other than Latin-1, or for wide characters in identifiers.
14104 @code{gnatfind} will look for references, bodies or declarations
14105 of symbols referenced in @file{sourcefile}, at line @samp{line}
14106 and column @samp{column}. See @ref{Examples of gnatfind Usage}
14107 for syntax examples.
14110 is a decimal integer identifying the line number containing
14111 the reference to the entity (or entities) to be located.
14114 is a decimal integer identifying the exact location on the
14115 line of the first character of the identifier for the
14116 entity reference. Columns are numbered from 1.
14118 @item file1 file2 ...
14119 The search will be restricted to these source files. If none are given, then
14120 the search will be done for every library file in the search path.
14121 These file must appear only after the pattern or sourcefile.
14123 These file names are considered to be regular expressions, so for instance
14124 specifying 'source*.adb' is the same as giving every file in the current
14125 directory whose name starts with 'source' and whose extension is 'adb'.
14127 The location of the spec of the entity will always be displayed, even if it
14128 isn't in one of file1, file2,... The occurrences of the entity in the
14129 separate units of the ones given on the command line will also be displayed.
14131 Note that if you specify at least one file in this part, @code{gnatfind} may
14132 sometimes not be able to find the body of the subprograms...
14137 At least one of 'sourcefile' or 'pattern' has to be present on
14140 The following switches are available:
14144 @item ^-a^/ALL_FILES^
14145 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
14146 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
14147 the read-only files found in the library search path. Otherwise, these files
14148 will be ignored. This option can be used to protect Gnat sources or your own
14149 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
14150 much faster, and their output much smaller. Read-only here refers to access
14151 or permission status in the file system for the current user.
14154 @cindex @option{-aIDIR} (@command{gnatfind})
14155 When looking for source files also look in directory DIR. The order in which
14156 source file search is undertaken is the same as for @command{gnatmake}.
14159 @cindex @option{-aODIR} (@command{gnatfind})
14160 When searching for library and object files, look in directory
14161 DIR. The order in which library files are searched is the same as for
14162 @command{gnatmake}.
14165 @cindex @option{-nostdinc} (@command{gnatfind})
14166 Do not look for sources in the system default directory.
14169 @cindex @option{-nostdlib} (@command{gnatfind})
14170 Do not look for library files in the system default directory.
14172 @item --RTS=@var{rts-path}
14173 @cindex @option{--RTS} (@command{gnatfind})
14174 Specifies the default location of the runtime library. Same meaning as the
14175 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14177 @item ^-d^/DERIVED_TYPE_INFORMATION^
14178 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
14179 If this switch is set, then @code{gnatfind} will output the parent type
14180 reference for each matching derived types.
14182 @item ^-e^/EXPRESSIONS^
14183 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
14184 By default, @code{gnatfind} accept the simple regular expression set for
14185 @samp{pattern}. If this switch is set, then the pattern will be
14186 considered as full Unix-style regular expression.
14188 @item ^-f^/FULL_PATHNAME^
14189 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
14190 If this switch is set, the output file names will be preceded by their
14191 directory (if the file was found in the search path). If this switch is
14192 not set, the directory will not be printed.
14194 @item ^-g^/IGNORE_LOCALS^
14195 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
14196 If this switch is set, information is output only for library-level
14197 entities, ignoring local entities. The use of this switch may accelerate
14198 @code{gnatfind} and @code{gnatxref}.
14201 @cindex @option{-IDIR} (@command{gnatfind})
14202 Equivalent to @samp{-aODIR -aIDIR}.
14205 @cindex @option{-pFILE} (@command{gnatfind})
14206 Specify a project file (@pxref{Project Files}) to use.
14207 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14208 project file in the current directory.
14210 If a project file is either specified or found by the tools, then the content
14211 of the source directory and object directory lines are added as if they
14212 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
14213 @samp{^-aO^/OBJECT_SEARCH^}.
14215 @item ^-r^/REFERENCES^
14216 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
14217 By default, @code{gnatfind} will output only the information about the
14218 declaration, body or type completion of the entities. If this switch is
14219 set, the @code{gnatfind} will locate every reference to the entities in
14220 the files specified on the command line (or in every file in the search
14221 path if no file is given on the command line).
14223 @item ^-s^/PRINT_LINES^
14224 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
14225 If this switch is set, then @code{gnatfind} will output the content
14226 of the Ada source file lines were the entity was found.
14228 @item ^-t^/TYPE_HIERARCHY^
14229 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
14230 If this switch is set, then @code{gnatfind} will output the type hierarchy for
14231 the specified type. It act like -d option but recursively from parent
14232 type to parent type. When this switch is set it is not possible to
14233 specify more than one file.
14238 All these switches may be in any order on the command line, and may even
14239 appear after the file names. They need not be separated by spaces, thus
14240 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14241 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14243 As stated previously, gnatfind will search in every directory in the
14244 search path. You can force it to look only in the current directory if
14245 you specify @code{*} at the end of the command line.
14247 @node Project Files for gnatxref and gnatfind
14248 @section Project Files for @command{gnatxref} and @command{gnatfind}
14251 Project files allow a programmer to specify how to compile its
14252 application, where to find sources, etc. These files are used
14254 primarily by the Glide Ada mode, but they can also be used
14257 @code{gnatxref} and @code{gnatfind}.
14259 A project file name must end with @file{.gpr}. If a single one is
14260 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
14261 extract the information from it. If multiple project files are found, none of
14262 them is read, and you have to use the @samp{-p} switch to specify the one
14265 The following lines can be included, even though most of them have default
14266 values which can be used in most cases.
14267 The lines can be entered in any order in the file.
14268 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
14269 each line. If you have multiple instances, only the last one is taken into
14274 [default: @code{"^./^[]^"}]
14275 specifies a directory where to look for source files. Multiple @code{src_dir}
14276 lines can be specified and they will be searched in the order they
14280 [default: @code{"^./^[]^"}]
14281 specifies a directory where to look for object and library files. Multiple
14282 @code{obj_dir} lines can be specified, and they will be searched in the order
14285 @item comp_opt=SWITCHES
14286 [default: @code{""}]
14287 creates a variable which can be referred to subsequently by using
14288 the @code{$@{comp_opt@}} notation. This is intended to store the default
14289 switches given to @command{gnatmake} and @command{gcc}.
14291 @item bind_opt=SWITCHES
14292 [default: @code{""}]
14293 creates a variable which can be referred to subsequently by using
14294 the @samp{$@{bind_opt@}} notation. This is intended to store the default
14295 switches given to @command{gnatbind}.
14297 @item link_opt=SWITCHES
14298 [default: @code{""}]
14299 creates a variable which can be referred to subsequently by using
14300 the @samp{$@{link_opt@}} notation. This is intended to store the default
14301 switches given to @command{gnatlink}.
14303 @item main=EXECUTABLE
14304 [default: @code{""}]
14305 specifies the name of the executable for the application. This variable can
14306 be referred to in the following lines by using the @samp{$@{main@}} notation.
14309 @item comp_cmd=COMMAND
14310 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
14313 @item comp_cmd=COMMAND
14314 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
14316 specifies the command used to compile a single file in the application.
14319 @item make_cmd=COMMAND
14320 [default: @code{"GNAT MAKE $@{main@}
14321 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
14322 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
14323 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
14326 @item make_cmd=COMMAND
14327 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
14328 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
14329 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
14331 specifies the command used to recompile the whole application.
14333 @item run_cmd=COMMAND
14334 [default: @code{"$@{main@}"}]
14335 specifies the command used to run the application.
14337 @item debug_cmd=COMMAND
14338 [default: @code{"gdb $@{main@}"}]
14339 specifies the command used to debug the application
14344 @command{gnatxref} and @command{gnatfind} only take into account the
14345 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
14347 @node Regular Expressions in gnatfind and gnatxref
14348 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
14351 As specified in the section about @command{gnatfind}, the pattern can be a
14352 regular expression. Actually, there are to set of regular expressions
14353 which are recognized by the program :
14356 @item globbing patterns
14357 These are the most usual regular expression. They are the same that you
14358 generally used in a Unix shell command line, or in a DOS session.
14360 Here is a more formal grammar :
14367 term ::= elmt -- matches elmt
14368 term ::= elmt elmt -- concatenation (elmt then elmt)
14369 term ::= * -- any string of 0 or more characters
14370 term ::= ? -- matches any character
14371 term ::= [char @{char@}] -- matches any character listed
14372 term ::= [char - char] -- matches any character in range
14376 @item full regular expression
14377 The second set of regular expressions is much more powerful. This is the
14378 type of regular expressions recognized by utilities such a @file{grep}.
14380 The following is the form of a regular expression, expressed in Ada
14381 reference manual style BNF is as follows
14388 regexp ::= term @{| term@} -- alternation (term or term ...)
14390 term ::= item @{item@} -- concatenation (item then item)
14392 item ::= elmt -- match elmt
14393 item ::= elmt * -- zero or more elmt's
14394 item ::= elmt + -- one or more elmt's
14395 item ::= elmt ? -- matches elmt or nothing
14398 elmt ::= nschar -- matches given character
14399 elmt ::= [nschar @{nschar@}] -- matches any character listed
14400 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
14401 elmt ::= [char - char] -- matches chars in given range
14402 elmt ::= \ char -- matches given character
14403 elmt ::= . -- matches any single character
14404 elmt ::= ( regexp ) -- parens used for grouping
14406 char ::= any character, including special characters
14407 nschar ::= any character except ()[].*+?^^^
14411 Following are a few examples :
14415 will match any of the two strings 'abcde' and 'fghi'.
14418 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
14421 will match any string which has only lowercase characters in it (and at
14422 least one character
14427 @node Examples of gnatxref Usage
14428 @section Examples of @code{gnatxref} Usage
14430 @subsection General Usage
14433 For the following examples, we will consider the following units :
14435 @smallexample @c ada
14441 3: procedure Foo (B : in Integer);
14448 1: package body Main is
14449 2: procedure Foo (B : in Integer) is
14460 2: procedure Print (B : Integer);
14469 The first thing to do is to recompile your application (for instance, in
14470 that case just by doing a @samp{gnatmake main}, so that GNAT generates
14471 the cross-referencing information.
14472 You can then issue any of the following commands:
14474 @item gnatxref main.adb
14475 @code{gnatxref} generates cross-reference information for main.adb
14476 and every unit 'with'ed by main.adb.
14478 The output would be:
14486 Decl: main.ads 3:20
14487 Body: main.adb 2:20
14488 Ref: main.adb 4:13 5:13 6:19
14491 Ref: main.adb 6:8 7:8
14501 Decl: main.ads 3:15
14502 Body: main.adb 2:15
14505 Body: main.adb 1:14
14508 Ref: main.adb 6:12 7:12
14512 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
14513 its body is in main.adb, line 1, column 14 and is not referenced any where.
14515 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
14516 it referenced in main.adb, line 6 column 12 and line 7 column 12.
14518 @item gnatxref package1.adb package2.ads
14519 @code{gnatxref} will generates cross-reference information for
14520 package1.adb, package2.ads and any other package 'with'ed by any
14526 @subsection Using gnatxref with vi
14528 @code{gnatxref} can generate a tags file output, which can be used
14529 directly from @file{vi}. Note that the standard version of @file{vi}
14530 will not work properly with overloaded symbols. Consider using another
14531 free implementation of @file{vi}, such as @file{vim}.
14534 $ gnatxref -v gnatfind.adb > tags
14538 will generate the tags file for @code{gnatfind} itself (if the sources
14539 are in the search path!).
14541 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
14542 (replacing @i{entity} by whatever you are looking for), and vi will
14543 display a new file with the corresponding declaration of entity.
14546 @node Examples of gnatfind Usage
14547 @section Examples of @code{gnatfind} Usage
14551 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
14552 Find declarations for all entities xyz referenced at least once in
14553 main.adb. The references are search in every library file in the search
14556 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
14559 The output will look like:
14561 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14562 ^directory/^[directory]^main.adb:24:10: xyz <= body
14563 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14567 that is to say, one of the entities xyz found in main.adb is declared at
14568 line 12 of main.ads (and its body is in main.adb), and another one is
14569 declared at line 45 of foo.ads
14571 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
14572 This is the same command as the previous one, instead @code{gnatfind} will
14573 display the content of the Ada source file lines.
14575 The output will look like:
14578 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14580 ^directory/^[directory]^main.adb:24:10: xyz <= body
14582 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14587 This can make it easier to find exactly the location your are looking
14590 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14591 Find references to all entities containing an x that are
14592 referenced on line 123 of main.ads.
14593 The references will be searched only in main.ads and foo.adb.
14595 @item gnatfind main.ads:123
14596 Find declarations and bodies for all entities that are referenced on
14597 line 123 of main.ads.
14599 This is the same as @code{gnatfind "*":main.adb:123}.
14601 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
14602 Find the declaration for the entity referenced at column 45 in
14603 line 123 of file main.adb in directory mydir. Note that it
14604 is usual to omit the identifier name when the column is given,
14605 since the column position identifies a unique reference.
14607 The column has to be the beginning of the identifier, and should not
14608 point to any character in the middle of the identifier.
14612 @c *********************************
14613 @node The GNAT Pretty-Printer gnatpp
14614 @chapter The GNAT Pretty-Printer @command{gnatpp}
14616 @cindex Pretty-Printer
14619 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
14620 for source reformatting / pretty-printing.
14621 It takes an Ada source file as input and generates a reformatted
14623 You can specify various style directives via switches; e.g.,
14624 identifier case conventions, rules of indentation, and comment layout.
14626 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
14627 tree for the input source and thus requires the input to be syntactically and
14628 semantically legal.
14629 If this condition is not met, @command{gnatpp} will terminate with an
14630 error message; no output file will be generated.
14632 If the compilation unit
14633 contained in the input source depends semantically upon units located
14634 outside the current directory, you have to provide the source search path
14635 when invoking @command{gnatpp}, if these units are contained in files with
14636 names that do not follow the GNAT file naming rules, you have to provide
14637 the configuration file describing the corresponding naming scheme;
14638 see the description of the @command{gnatpp}
14639 switches below. Another possibility is to use a project file and to
14640 call @command{gnatpp} through the @command{gnat} driver
14642 The @command{gnatpp} command has the form
14645 $ gnatpp [@var{switches}] @var{filename}
14652 @var{switches} is an optional sequence of switches defining such properties as
14653 the formatting rules, the source search path, and the destination for the
14657 @var{filename} is the name (including the extension) of the source file to
14658 reformat; ``wildcards'' or several file names on the same gnatpp command are
14659 allowed. The file name may contain path information; it does not have to
14660 follow the GNAT file naming rules
14664 * Switches for gnatpp::
14665 * Formatting Rules::
14668 @node Switches for gnatpp
14669 @section Switches for @command{gnatpp}
14672 The following subsections describe the various switches accepted by
14673 @command{gnatpp}, organized by category.
14676 You specify a switch by supplying a name and generally also a value.
14677 In many cases the values for a switch with a given name are incompatible with
14679 (for example the switch that controls the casing of a reserved word may have
14680 exactly one value: upper case, lower case, or
14681 mixed case) and thus exactly one such switch can be in effect for an
14682 invocation of @command{gnatpp}.
14683 If more than one is supplied, the last one is used.
14684 However, some values for the same switch are mutually compatible.
14685 You may supply several such switches to @command{gnatpp}, but then
14686 each must be specified in full, with both the name and the value.
14687 Abbreviated forms (the name appearing once, followed by each value) are
14689 For example, to set
14690 the alignment of the assignment delimiter both in declarations and in
14691 assignment statements, you must write @option{-A2A3}
14692 (or @option{-A2 -A3}), but not @option{-A23}.
14696 In many cases the set of options for a given qualifier are incompatible with
14697 each other (for example the qualifier that controls the casing of a reserved
14698 word may have exactly one option, which specifies either upper case, lower
14699 case, or mixed case), and thus exactly one such option can be in effect for
14700 an invocation of @command{gnatpp}.
14701 If more than one is supplied, the last one is used.
14702 However, some qualifiers have options that are mutually compatible,
14703 and then you may then supply several such options when invoking
14707 In most cases, it is obvious whether or not the
14708 ^values for a switch with a given name^options for a given qualifier^
14709 are compatible with each other.
14710 When the semantics might not be evident, the summaries below explicitly
14711 indicate the effect.
14714 * Alignment Control::
14716 * Construct Layout Control::
14717 * General Text Layout Control::
14718 * Other Formatting Options::
14719 * Setting the Source Search Path::
14720 * Output File Control::
14721 * Other gnatpp Switches::
14724 @node Alignment Control
14725 @subsection Alignment Control
14726 @cindex Alignment control in @command{gnatpp}
14729 Programs can be easier to read if certain constructs are vertically aligned.
14730 By default all alignments are set ON.
14731 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
14732 OFF, and then use one or more of the other
14733 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
14734 to activate alignment for specific constructs.
14737 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
14741 Set all alignments to ON
14744 @item ^-A0^/ALIGN=OFF^
14745 Set all alignments to OFF
14747 @item ^-A1^/ALIGN=COLONS^
14748 Align @code{:} in declarations
14750 @item ^-A2^/ALIGN=DECLARATIONS^
14751 Align @code{:=} in initializations in declarations
14753 @item ^-A3^/ALIGN=STATEMENTS^
14754 Align @code{:=} in assignment statements
14756 @item ^-A4^/ALIGN=ARROWS^
14757 Align @code{=>} in associations
14759 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
14760 Align @code{at} keywords in the component clauses in record
14761 representation clauses
14765 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
14768 @node Casing Control
14769 @subsection Casing Control
14770 @cindex Casing control in @command{gnatpp}
14773 @command{gnatpp} allows you to specify the casing for reserved words,
14774 pragma names, attribute designators and identifiers.
14775 For identifiers you may define a
14776 general rule for name casing but also override this rule
14777 via a set of dictionary files.
14779 Three types of casing are supported: lower case, upper case, and mixed case.
14780 Lower and upper case are self-explanatory (but since some letters in
14781 Latin1 and other GNAT-supported character sets
14782 exist only in lower-case form, an upper case conversion will have no
14784 ``Mixed case'' means that the first letter, and also each letter immediately
14785 following an underscore, are converted to their uppercase forms;
14786 all the other letters are converted to their lowercase forms.
14789 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
14790 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
14791 Attribute designators are lower case
14793 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
14794 Attribute designators are upper case
14796 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
14797 Attribute designators are mixed case (this is the default)
14799 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
14800 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
14801 Keywords (technically, these are known in Ada as @emph{reserved words}) are
14802 lower case (this is the default)
14804 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
14805 Keywords are upper case
14807 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
14808 @item ^-nD^/NAME_CASING=AS_DECLARED^
14809 Name casing for defining occurrences are as they appear in the source file
14810 (this is the default)
14812 @item ^-nU^/NAME_CASING=UPPER_CASE^
14813 Names are in upper case
14815 @item ^-nL^/NAME_CASING=LOWER_CASE^
14816 Names are in lower case
14818 @item ^-nM^/NAME_CASING=MIXED_CASE^
14819 Names are in mixed case
14821 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
14822 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
14823 Pragma names are lower case
14825 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
14826 Pragma names are upper case
14828 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
14829 Pragma names are mixed case (this is the default)
14831 @item ^-D@var{file}^/DICTIONARY=@var{file}^
14832 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
14833 Use @var{file} as a @emph{dictionary file} that defines
14834 the casing for a set of specified names,
14835 thereby overriding the effect on these names by
14836 any explicit or implicit
14837 ^-n^/NAME_CASING^ switch.
14838 To supply more than one dictionary file,
14839 use ^several @option{-D} switches^a list of files as options^.
14842 @option{gnatpp} implicitly uses a @emph{default dictionary file}
14843 to define the casing for the Ada predefined names and
14844 the names declared in the GNAT libraries.
14846 @item ^-D-^/SPECIFIC_CASING^
14847 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
14848 Do not use the default dictionary file;
14849 instead, use the casing
14850 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
14855 The structure of a dictionary file, and details on the conventions
14856 used in the default dictionary file, are defined in @ref{Name Casing}.
14858 The @option{^-D-^/SPECIFIC_CASING^} and
14859 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
14862 @node Construct Layout Control
14863 @subsection Construct Layout Control
14864 @cindex Layout control in @command{gnatpp}
14867 This group of @command{gnatpp} switches controls the layout of comments and
14868 complex syntactic constructs. See @ref{Formatting Comments} for details
14872 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
14873 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
14874 All the comments remain unchanged
14876 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
14877 GNAT-style comment line indentation (this is the default).
14879 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
14880 Reference-manual comment line indentation.
14882 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
14883 GNAT-style comment beginning
14885 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14886 Reformat comment blocks
14888 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
14889 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
14890 GNAT-style layout (this is the default)
14892 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
14895 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
14898 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
14900 All the VT characters are removed from the comment text. All the HT characters
14901 are expanded with the sequences of space characters to get to the next tab
14904 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
14905 @item ^--no-separate-is^/NO_SEPARATE_IS^
14906 Do not place the keyword @code{is} on a separate line in a subprogram body in
14907 case if the specification occupies more then one line.
14913 The @option{-c1} and @option{-c2} switches are incompatible.
14914 The @option{-c3} and @option{-c4} switches are compatible with each other and
14915 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
14916 the other comment formatting switches.
14918 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
14923 For the @option{/COMMENTS_LAYOUT} qualifier:
14926 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
14928 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
14929 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
14933 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
14934 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
14937 @node General Text Layout Control
14938 @subsection General Text Layout Control
14941 These switches allow control over line length and indentation.
14944 @item ^-M@i{nnn}^/LINE_LENGTH_MAX=@i{nnn}^
14945 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14946 Maximum line length, @i{nnn} from 32 ..256, the default value is 79
14948 @item ^-i@i{nnn}^/INDENTATION_LEVEL=@i{nnn}^
14949 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14950 Indentation level, @i{nnn} from 1 .. 9, the default value is 3
14952 @item ^-cl@i{nnn}^/CONTINUATION_INDENT=@i{nnn}^
14953 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
14954 Indentation level for continuation lines (relative to the line being
14955 continued), @i{nnn} from 1 .. 9.
14957 value is one less then the (normal) indentation level, unless the
14958 indentation is set to 1 (in which case the default value for continuation
14959 line indentation is also 1)
14962 @node Other Formatting Options
14963 @subsection Other Formatting Options
14966 These switches control the inclusion of missing end/exit labels, and
14967 the indentation level in @b{case} statements.
14970 @item ^-e^/NO_MISSED_LABELS^
14971 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
14972 Do not insert missing end/exit labels. An end label is the name of
14973 a construct that may optionally be repeated at the end of the
14974 construct's declaration;
14975 e.g., the names of packages, subprograms, and tasks.
14976 An exit label is the name of a loop that may appear as target
14977 of an exit statement within the loop.
14978 By default, @command{gnatpp} inserts these end/exit labels when
14979 they are absent from the original source. This option suppresses such
14980 insertion, so that the formatted source reflects the original.
14982 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
14983 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
14984 Insert a Form Feed character after a pragma Page.
14986 @item ^-T@i{nnn}^/MAX_INDENT=@i{nnn}^
14987 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
14988 Do not use an additional indentation level for @b{case} alternatives
14989 and variants if there are @i{nnn} or more (the default
14991 If @i{nnn} is 0, an additional indentation level is
14992 used for @b{case} alternatives and variants regardless of their number.
14995 @node Setting the Source Search Path
14996 @subsection Setting the Source Search Path
14999 To define the search path for the input source file, @command{gnatpp}
15000 uses the same switches as the GNAT compiler, with the same effects.
15003 @item ^-I^/SEARCH=^@var{dir}
15004 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
15005 The same as the corresponding gcc switch
15007 @item ^-I-^/NOCURRENT_DIRECTORY^
15008 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
15009 The same as the corresponding gcc switch
15011 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
15012 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
15013 The same as the corresponding gcc switch
15015 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
15016 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
15017 The same as the corresponding gcc switch
15021 @node Output File Control
15022 @subsection Output File Control
15025 By default the output is sent to the file whose name is obtained by appending
15026 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
15027 (if the file with this name already exists, it is unconditionally overwritten).
15028 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
15029 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
15031 The output may be redirected by the following switches:
15034 @item ^-pipe^/STANDARD_OUTPUT^
15035 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
15036 Send the output to @code{Standard_Output}
15038 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
15039 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
15040 Write the output into @var{output_file}.
15041 If @var{output_file} already exists, @command{gnatpp} terminates without
15042 reading or processing the input file.
15044 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
15045 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
15046 Write the output into @var{output_file}, overwriting the existing file
15047 (if one is present).
15049 @item ^-r^/REPLACE^
15050 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
15051 Replace the input source file with the reformatted output, and copy the
15052 original input source into the file whose name is obtained by appending the
15053 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
15054 If a file with this name already exists, @command{gnatpp} terminates without
15055 reading or processing the input file.
15057 @item ^-rf^/OVERRIDING_REPLACE^
15058 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
15059 Like @option{^-r^/REPLACE^} except that if the file with the specified name
15060 already exists, it is overwritten.
15062 @item ^-rnb^/NO_BACKUP^
15063 @cindex @option{^-rnb^/NO_BACKUP^} (@code{gnatpp})
15064 Replace the input source file with the reformatted output without
15065 creating any backup copy of the input source.
15067 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
15068 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
15069 Specifies the format of the reformatted output file. The @var{xxx}
15070 ^string specified with the switch^option^ may be either
15072 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
15073 @item ``@option{^crlf^CRLF^}''
15074 the same as @option{^crlf^CRLF^}
15075 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
15076 @item ``@option{^lf^LF^}''
15077 the same as @option{^unix^UNIX^}
15083 Options @option{^-pipe^/STANDARD_OUTPUT^},
15084 @option{^-o^/OUTPUT^} and
15085 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
15086 contains only one file to reformat.
15088 @option{^--eol^/END_OF_LINE^}
15089 can not be used together
15090 with @option{^-pipe^/STANDARD_OUTPUT^} option.
15092 @node Other gnatpp Switches
15093 @subsection Other @code{gnatpp} Switches
15096 The additional @command{gnatpp} switches are defined in this subsection.
15099 @item ^-files @var{filename}^/FILES=@var{output_file}^
15100 @cindex @option{^-files^/FILES^} (@code{gnatpp})
15101 Take the argument source files from the specified file. This file should be an
15102 ordinary textual file containing file names separated by spaces or
15103 line breaks. You can use this switch more then once in the same call to
15104 @command{gnatpp}. You also can combine this switch with explicit list of
15107 @item ^-v^/VERBOSE^
15108 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
15110 @command{gnatpp} generates version information and then
15111 a trace of the actions it takes to produce or obtain the ASIS tree.
15113 @item ^-w^/WARNINGS^
15114 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
15116 @command{gnatpp} generates a warning whenever it can not provide
15117 a required layout in the result source.
15120 @node Formatting Rules
15121 @section Formatting Rules
15124 The following subsections show how @command{gnatpp} treats ``white space'',
15125 comments, program layout, and name casing.
15126 They provide the detailed descriptions of the switches shown above.
15129 * White Space and Empty Lines::
15130 * Formatting Comments::
15131 * Construct Layout::
15135 @node White Space and Empty Lines
15136 @subsection White Space and Empty Lines
15139 @command{gnatpp} does not have an option to control space characters.
15140 It will add or remove spaces according to the style illustrated by the
15141 examples in the @cite{Ada Reference Manual}.
15143 The only format effectors
15144 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
15145 that will appear in the output file are platform-specific line breaks,
15146 and also format effectors within (but not at the end of) comments.
15147 In particular, each horizontal tab character that is not inside
15148 a comment will be treated as a space and thus will appear in the
15149 output file as zero or more spaces depending on
15150 the reformatting of the line in which it appears.
15151 The only exception is a Form Feed character, which is inserted after a
15152 pragma @code{Page} when @option{-ff} is set.
15154 The output file will contain no lines with trailing ``white space'' (spaces,
15157 Empty lines in the original source are preserved
15158 only if they separate declarations or statements.
15159 In such contexts, a
15160 sequence of two or more empty lines is replaced by exactly one empty line.
15161 Note that a blank line will be removed if it separates two ``comment blocks''
15162 (a comment block is a sequence of whole-line comments).
15163 In order to preserve a visual separation between comment blocks, use an
15164 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
15165 Likewise, if for some reason you wish to have a sequence of empty lines,
15166 use a sequence of empty comments instead.
15168 @node Formatting Comments
15169 @subsection Formatting Comments
15172 Comments in Ada code are of two kinds:
15175 a @emph{whole-line comment}, which appears by itself (possibly preceded by
15176 ``white space'') on a line
15179 an @emph{end-of-line comment}, which follows some other Ada lexical element
15184 The indentation of a whole-line comment is that of either
15185 the preceding or following line in
15186 the formatted source, depending on switch settings as will be described below.
15188 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
15189 between the end of the preceding Ada lexical element and the beginning
15190 of the comment as appear in the original source,
15191 unless either the comment has to be split to
15192 satisfy the line length limitation, or else the next line contains a
15193 whole line comment that is considered a continuation of this end-of-line
15194 comment (because it starts at the same position).
15196 cases, the start of the end-of-line comment is moved right to the nearest
15197 multiple of the indentation level.
15198 This may result in a ``line overflow'' (the right-shifted comment extending
15199 beyond the maximum line length), in which case the comment is split as
15202 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
15203 (GNAT-style comment line indentation)
15204 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
15205 (reference-manual comment line indentation).
15206 With reference-manual style, a whole-line comment is indented as if it
15207 were a declaration or statement at the same place
15208 (i.e., according to the indentation of the preceding line(s)).
15209 With GNAT style, a whole-line comment that is immediately followed by an
15210 @b{if} or @b{case} statement alternative, a record variant, or the reserved
15211 word @b{begin}, is indented based on the construct that follows it.
15214 @smallexample @c ada
15226 Reference-manual indentation produces:
15228 @smallexample @c ada
15240 while GNAT-style indentation produces:
15242 @smallexample @c ada
15254 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
15255 (GNAT style comment beginning) has the following
15260 For each whole-line comment that does not end with two hyphens,
15261 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
15262 to ensure that there are at least two spaces between these hyphens and the
15263 first non-blank character of the comment.
15267 For an end-of-line comment, if in the original source the next line is a
15268 whole-line comment that starts at the same position
15269 as the end-of-line comment,
15270 then the whole-line comment (and all whole-line comments
15271 that follow it and that start at the same position)
15272 will start at this position in the output file.
15275 That is, if in the original source we have:
15277 @smallexample @c ada
15280 A := B + C; -- B must be in the range Low1..High1
15281 -- C must be in the range Low2..High2
15282 --B+C will be in the range Low1+Low2..High1+High2
15288 Then in the formatted source we get
15290 @smallexample @c ada
15293 A := B + C; -- B must be in the range Low1..High1
15294 -- C must be in the range Low2..High2
15295 -- B+C will be in the range Low1+Low2..High1+High2
15301 A comment that exceeds the line length limit will be split.
15303 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
15304 the line belongs to a reformattable block, splitting the line generates a
15305 @command{gnatpp} warning.
15306 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
15307 comments may be reformatted in typical
15308 word processor style (that is, moving words between lines and putting as
15309 many words in a line as possible).
15311 @node Construct Layout
15312 @subsection Construct Layout
15315 In several cases the suggested layout in the Ada Reference Manual includes
15316 an extra level of indentation that many programmers prefer to avoid. The
15317 affected cases include:
15321 @item Record type declaration (RM 3.8)
15323 @item Record representation clause (RM 13.5.1)
15325 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
15327 @item Block statement in case if a block has a statement identifier (RM 5.6)
15331 In compact mode (when GNAT style layout or compact layout is set),
15332 the pretty printer uses one level of indentation instead
15333 of two. This is achieved in the record definition and record representation
15334 clause cases by putting the @code{record} keyword on the same line as the
15335 start of the declaration or representation clause, and in the block and loop
15336 case by putting the block or loop header on the same line as the statement
15340 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
15341 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
15342 layout on the one hand, and uncompact layout
15343 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
15344 can be illustrated by the following examples:
15348 @multitable @columnfractions .5 .5
15349 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
15352 @smallexample @c ada
15359 @smallexample @c ada
15368 @smallexample @c ada
15370 a at 0 range 0 .. 31;
15371 b at 4 range 0 .. 31;
15375 @smallexample @c ada
15378 a at 0 range 0 .. 31;
15379 b at 4 range 0 .. 31;
15384 @smallexample @c ada
15392 @smallexample @c ada
15402 @smallexample @c ada
15403 Clear : for J in 1 .. 10 loop
15408 @smallexample @c ada
15410 for J in 1 .. 10 loop
15421 GNAT style, compact layout Uncompact layout
15423 type q is record type q is
15424 a : integer; record
15425 b : integer; a : integer;
15426 end record; b : integer;
15429 for q use record for q use
15430 a at 0 range 0 .. 31; record
15431 b at 4 range 0 .. 31; a at 0 range 0 .. 31;
15432 end record; b at 4 range 0 .. 31;
15435 Block : declare Block :
15436 A : Integer := 3; declare
15437 begin A : Integer := 3;
15439 end Block; Proc (A, A);
15442 Clear : for J in 1 .. 10 loop Clear :
15443 A (J) := 0; for J in 1 .. 10 loop
15444 end loop Clear; A (J) := 0;
15451 A further difference between GNAT style layout and compact layout is that
15452 GNAT style layout inserts empty lines as separation for
15453 compound statements, return statements and bodies.
15456 @subsection Name Casing
15459 @command{gnatpp} always converts the usage occurrence of a (simple) name to
15460 the same casing as the corresponding defining identifier.
15462 You control the casing for defining occurrences via the
15463 @option{^-n^/NAME_CASING^} switch.
15465 With @option{-nD} (``as declared'', which is the default),
15468 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
15470 defining occurrences appear exactly as in the source file
15471 where they are declared.
15472 The other ^values for this switch^options for this qualifier^ ---
15473 @option{^-nU^UPPER_CASE^},
15474 @option{^-nL^LOWER_CASE^},
15475 @option{^-nM^MIXED_CASE^} ---
15477 ^upper, lower, or mixed case, respectively^the corresponding casing^.
15478 If @command{gnatpp} changes the casing of a defining
15479 occurrence, it analogously changes the casing of all the
15480 usage occurrences of this name.
15482 If the defining occurrence of a name is not in the source compilation unit
15483 currently being processed by @command{gnatpp}, the casing of each reference to
15484 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
15485 switch (subject to the dictionary file mechanism described below).
15486 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
15488 casing for the defining occurrence of the name.
15490 Some names may need to be spelled with casing conventions that are not
15491 covered by the upper-, lower-, and mixed-case transformations.
15492 You can arrange correct casing by placing such names in a
15493 @emph{dictionary file},
15494 and then supplying a @option{^-D^/DICTIONARY^} switch.
15495 The casing of names from dictionary files overrides
15496 any @option{^-n^/NAME_CASING^} switch.
15498 To handle the casing of Ada predefined names and the names from GNAT libraries,
15499 @command{gnatpp} assumes a default dictionary file.
15500 The name of each predefined entity is spelled with the same casing as is used
15501 for the entity in the @cite{Ada Reference Manual}.
15502 The name of each entity in the GNAT libraries is spelled with the same casing
15503 as is used in the declaration of that entity.
15505 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
15506 default dictionary file.
15507 Instead, the casing for predefined and GNAT-defined names will be established
15508 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
15509 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
15510 will appear as just shown,
15511 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
15512 To ensure that even such names are rendered in uppercase,
15513 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
15514 (or else, less conveniently, place these names in upper case in a dictionary
15517 A dictionary file is
15518 a plain text file; each line in this file can be either a blank line
15519 (containing only space characters and ASCII.HT characters), an Ada comment
15520 line, or the specification of exactly one @emph{casing schema}.
15522 A casing schema is a string that has the following syntax:
15526 @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
15528 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
15533 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
15534 @var{identifier} lexical element and the @var{letter_or_digit} category.)
15536 The casing schema string can be followed by white space and/or an Ada-style
15537 comment; any amount of white space is allowed before the string.
15539 If a dictionary file is passed as
15541 the value of a @option{-D@var{file}} switch
15544 an option to the @option{/DICTIONARY} qualifier
15547 simple name and every identifier, @command{gnatpp} checks if the dictionary
15548 defines the casing for the name or for some of its parts (the term ``subword''
15549 is used below to denote the part of a name which is delimited by ``_'' or by
15550 the beginning or end of the word and which does not contain any ``_'' inside):
15554 if the whole name is in the dictionary, @command{gnatpp} uses for this name
15555 the casing defined by the dictionary; no subwords are checked for this word
15558 for every subword @command{gnatpp} checks if the dictionary contains the
15559 corresponding string of the form @code{*@var{simple_identifier}*},
15560 and if it does, the casing of this @var{simple_identifier} is used
15564 if the whole name does not contain any ``_'' inside, and if for this name
15565 the dictionary contains two entries - one of the form @var{identifier},
15566 and another - of the form *@var{simple_identifier}*, then the first one
15567 is applied to define the casing of this name
15570 if more than one dictionary file is passed as @command{gnatpp} switches, each
15571 dictionary adds new casing exceptions and overrides all the existing casing
15572 exceptions set by the previous dictionaries
15575 when @command{gnatpp} checks if the word or subword is in the dictionary,
15576 this check is not case sensitive
15580 For example, suppose we have the following source to reformat:
15582 @smallexample @c ada
15585 name1 : integer := 1;
15586 name4_name3_name2 : integer := 2;
15587 name2_name3_name4 : Boolean;
15590 name2_name3_name4 := name4_name3_name2 > name1;
15596 And suppose we have two dictionaries:
15613 If @command{gnatpp} is called with the following switches:
15617 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
15620 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
15625 then we will get the following name casing in the @command{gnatpp} output:
15627 @smallexample @c ada
15630 NAME1 : Integer := 1;
15631 Name4_NAME3_Name2 : Integer := 2;
15632 Name2_NAME3_Name4 : Boolean;
15635 Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
15640 @c *********************************
15641 @node The GNAT Metric Tool gnatmetric
15642 @chapter The GNAT Metric Tool @command{gnatmetric}
15644 @cindex Metric tool
15647 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
15648 for computing various program metrics.
15649 It takes an Ada source file as input and generates a file containing the
15650 metrics data as output. Various switches control which
15651 metrics are computed and output.
15653 @command{gnatmetric} generates and uses the ASIS
15654 tree for the input source and thus requires the input to be syntactically and
15655 semantically legal.
15656 If this condition is not met, @command{gnatmetric} will generate
15657 an error message; no metric information for this file will be
15658 computed and reported.
15660 If the compilation unit contained in the input source depends semantically
15661 upon units in files located outside the current directory, you have to provide
15662 the source search path when invoking @command{gnatmetric}.
15663 If it depends semantically upon units that are contained
15664 in files with names that do not follow the GNAT file naming rules, you have to
15665 provide the configuration file describing the corresponding naming scheme (see
15666 the description of the @command{gnatmetric} switches below.)
15667 Alternatively, you may use a project file and invoke @command{gnatmetric}
15668 through the @command{gnat} driver.
15671 The @command{gnatmetric} command has the form
15674 $ gnatmetric [@i{switches}] @{@i{filename}@} [@i{-cargs gcc_switches}]
15681 @i{switches} specify the metrics to compute and define the destination for
15685 Each @i{filename} is the name (including the extension) of a source
15686 file to process. ``Wildcards'' are allowed, and
15687 the file name may contain path information.
15688 If no @i{filename} is supplied, then the @i{switches} list must contain
15690 @option{-files} switch (@pxref{Other gnatmetric Switches}).
15691 Including both a @option{-files} switch and one or more
15692 @i{filename} arguments is permitted.
15695 @i{-cargs gcc_switches} is a list of switches for
15696 @command{gcc}. They will be passed on to all compiler invocations made by
15697 @command{gnatmetric} to generate the ASIS trees. Here you can provide
15698 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
15699 and use the @option{-gnatec} switch to set the configuration file.
15703 * Switches for gnatmetric::
15706 @node Switches for gnatmetric
15707 @section Switches for @command{gnatmetric}
15710 The following subsections describe the various switches accepted by
15711 @command{gnatmetric}, organized by category.
15714 * Output Files Control::
15715 * Disable Metrics For Local Units::
15716 * Line Metrics Control::
15717 * Syntax Metrics Control::
15718 * Complexity Metrics Control::
15719 * Other gnatmetric Switches::
15722 @node Output Files Control
15723 @subsection Output File Control
15724 @cindex Output file control in @command{gnatmetric}
15727 @command{gnatmetric} has two output formats. It can generate a
15728 textual (human-readable) form, and also XML. By default only textual
15729 output is generated.
15731 When generating the output in textual form, @command{gnatmetric} creates
15732 for each Ada source file a corresponding text file
15733 containing the computed metrics. By default, this file
15734 is placed in the same directory as where the source file is located, and
15735 its name is obtained
15736 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
15739 All the output information generated in XML format is placed in a single
15740 file. By default this file is placed in the current directory and has the
15741 name ^@file{metrix.xml}^@file{METRIX$XML}^.
15743 Some of the computed metrics are summed over the units passed to
15744 @command{gnatmetric}; for example, the total number of lines of code.
15745 By default this information is sent to @file{stdout}, but a file
15746 can be specified with the @option{-og} switch.
15748 The following switches control the @command{gnatmetric} output:
15751 @cindex @option{^-x^/XML^} (@command{gnatmetric})
15753 Generate the XML output
15755 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
15756 @item ^-nt^/NO_TEXT^
15757 Do not generate the output in text form (implies @option{^-x^/XML^})
15759 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
15760 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
15761 Put textual files with detailed metrics into @var{output_dir}
15763 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
15764 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
15765 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
15766 in the name of the output file.
15768 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
15769 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
15770 Put global metrics into @var{file_name}
15772 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
15773 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
15774 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
15776 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
15777 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
15778 Use ``short'' source file names in the output. (The @command{gnatmetric}
15779 output includes the name(s) of the Ada source file(s) from which the metrics
15780 are computed. By default each name includes the absolute path. The
15781 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
15782 to exclude all directory information from the file names that are output.)
15786 @node Disable Metrics For Local Units
15787 @subsection Disable Metrics For Local Units
15788 @cindex Disable Metrics For Local Units in @command{gnatmetric}
15791 @command{gnatmetric} relies on the GNAT compilation model @minus{}
15793 unit per one source file. It computes line metrics for the whole source
15794 file, and it also computes syntax
15795 and complexity metrics for the file's outermost unit.
15797 By default, @command{gnatmetric} will also compute all metrics for certain
15798 kinds of locally declared program units:
15802 subprogram (and generic subprogram) bodies;
15805 package (and generic package) specifications and bodies;
15808 task object and type specifications and bodies;
15811 protected object and type specifications and bodies.
15815 These kinds of entities will be referred to as
15816 @emph{eligible local program units}, or simply @emph{eligible local units},
15817 @cindex Eligible local unit (for @command{gnatmetric})
15818 in the discussion below.
15820 Note that a subprogram declaration, generic instantiation,
15821 or renaming declaration only receives metrics
15822 computation when it appear as the outermost entity
15825 Suppression of metrics computation for eligible local units can be
15826 obtained via the following switch:
15829 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
15830 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
15831 Do not compute detailed metrics for eligible local program units
15835 @node Line Metrics Control
15836 @subsection Line Metrics Control
15837 @cindex Line metrics control in @command{gnatmetric}
15840 For any (legal) source file, and for each of its
15841 eligible local program units, @command{gnatmetric} computes the following
15846 the total number of lines;
15849 the total number of code lines (i.e., non-blank lines that are not comments)
15852 the number of comment lines
15855 the number of code lines containing end-of-line comments;
15858 the number of empty lines and lines containing only space characters and/or
15859 format effectors (blank lines)
15863 If @command{gnatmetric} is invoked on more than one source file, it sums the
15864 values of the line metrics for all the files being processed and then
15865 generates the cumulative results.
15867 By default, all the line metrics are computed and reported. You can use the
15868 following switches to select the specific line metrics to be computed and
15869 reported (if any of these parameters is set, only explicitly specified line
15870 metrics are computed).
15873 @cindex @option{^-la^/LINES_ALL^} (@command{gnatmetric})
15874 @item ^-la^/LINES_ALL^
15875 The number of all lines
15877 @cindex @option{^-lcode^/CODE_LINES^} (@command{gnatmetric})
15878 @item ^-lcode^/CODE_LINES^
15879 The number of code lines
15881 @cindex @option{^-lcomm^/COMENT_LINES^} (@command{gnatmetric})
15882 @item ^-lcomm^/COMENT_LINES^
15883 The number of comment lines
15885 @cindex @option{^-leol^/MIXED_CODE_COMMENTS^} (@command{gnatmetric})
15886 @item ^-leol^/MIXED_CODE_COMMENTS^
15887 The number of code lines containing
15888 end-of-line comments
15890 @cindex @option{^-lb^/BLANK_LINES^} (@command{gnatmetric})
15891 @item ^-lb^/BLANK_LINES^
15892 The number of blank lines
15897 @node Syntax Metrics Control
15898 @subsection Syntax Metrics Control
15899 @cindex Syntax metrics control in @command{gnatmetric}
15902 @command{gnatmetric} computes various syntactic metrics for the
15903 outermost unit and for each eligible local unit:
15906 @item LSLOC (``Logical Source Lines Of Code'')
15907 The total number of declarations and the total number of statements
15909 @item Maximal static nesting level of inner program units
15911 @cite{Ada 95 Language Reference Manual}, 10.1(1), ``A program unit is either a
15912 package, a task unit, a protected unit, a
15913 protected entry, a generic unit, or an explicitly declared subprogram other
15914 than an enumeration literal.''
15916 @item Maximal nesting level of composite syntactic constructs
15917 This corresponds to the notion of the
15918 maximum nesting level in the GNAT built-in style checks
15919 (@pxref{Style Checking})
15923 For the outermost unit in the file, @command{gnatmetric} additionally computes
15924 the following metrics:
15927 @item Public subprograms
15928 This metric is computed for package specifications. It is the
15929 number of subprograms and generic subprograms declared in the visible
15930 part (including in nested packages, protected objects, and
15933 @item All subprograms
15934 This metric is computed for bodies and subunits. The
15935 metric is equal to a total number of subprogram bodies in the compilation
15937 Neither generic instantiations nor renamings-as-a-body nor body stubs
15938 are counted. Any subprogram body is counted, independently of its nesting
15939 level and enclosing constructs. Generic bodies and bodies of protected
15940 subprograms are counted in the same way as ``usual'' subprogram bodies.
15943 This metric is computed for package specifications and
15944 generic package declarations. It is the total number of types
15945 that can be referenced from outside this compilation unit, plus the
15946 number of types from all the visible parts of all the visible generic packages.
15947 Generic formal types are not counted. Only types, not subtypes,
15951 Along with the total number of public types, the following
15952 types are counted and reported separately:
15959 Root tagged types (abstract, non-abstract, private, non-private). Type
15960 extensions are @emph{not} counted
15963 Private types (including private extensions)
15974 This metric is computed for any compilation unit. It is equal to the total
15975 number of the declarations of different types given in the compilation unit.
15976 The private and the corresponding full type declaration are counted as one
15977 type declaration. Incomplete type declarations and generic formal types
15979 No distinction is made among different kinds of types (abstract,
15980 private etc.); the total number of types is computed and reported.
15985 By default, all the syntax metrics are computed and reported. You can use the
15986 following switches to select specific syntax metrics;
15987 if any of these is set, only the explicitly specified metrics are computed.
15990 @cindex @option{^-ed^/DECLARATION_TOTAL^} (@command{gnatmetric})
15991 @item ^-ed^/DECLARATION_TOTAL^
15992 The total number of declarations
15994 @cindex @option{^-es^/STATEMENT_TOTAL^} (@command{gnatmetric})
15995 @item ^-es^/STATEMENT_TOTAL^
15996 The total number of statements
15998 @cindex @option{^-eps^/^} (@command{gnatmetric})
15999 @item ^-eps^/INT_SUBPROGRAMS^
16000 The number of public subprograms in a compilation unit
16002 @cindex @option{^-eas^/SUBPROGRAMS_ALL^} (@command{gnatmetric})
16003 @item ^-eas^/SUBPROGRAMS_ALL^
16004 The number of all the subprograms in a compilation unit
16006 @cindex @option{^-ept^/INT_TYPES^} (@command{gnatmetric})
16007 @item ^-ept^/INT_TYPES^
16008 The number of public types in a compilation unit
16010 @cindex @option{^-eat^/TYPES_ALL^} (@command{gnatmetric})
16011 @item ^-eat^/TYPES_ALL^
16012 The number of all the types in a compilation unit
16014 @cindex @option{^-enu^/PROGRAM_NESTING_MAX^} (@command{gnatmetric})
16015 @item ^-enu^/PROGRAM_NESTING_MAX^
16016 The maximal program unit nesting level
16018 @cindex @option{^-ec^/CONSTRUCT_NESTING_MAX^} (@command{gnatmetric})
16019 @item ^-ec^/CONSTRUCT_NESTING_MAX^
16020 The maximal construct nesting level
16024 @node Complexity Metrics Control
16025 @subsection Complexity Metrics Control
16026 @cindex Complexity metrics control in @command{gnatmetric}
16029 For a program unit that is an executable body (a subprogram body (including
16030 generic bodies), task body, entry body or a package body containing
16031 its own statement sequence ) @command{gnatmetric} computes the following
16032 complexity metrics:
16036 McCabe cyclomatic complexity;
16039 McCabe essential complexity;
16042 maximal loop nesting level
16047 The McCabe complexity metrics are defined
16048 in @url{www.mccabe.com/pdf/nist235r.pdf}
16050 According to McCabe, both control statements and short-circuit control forms
16051 should be taken into account when computing cyclomatic complexity. For each
16052 body, we compute three metric values:
16056 the complexity introduced by control
16057 statements only, without taking into account short-circuit forms,
16060 the complexity introduced by short-circuit control forms only, and
16064 cyclomatic complexity, which is the sum of these two values.
16068 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
16069 the code in the exception handlers and in all the nested program units.
16071 By default, all the complexity metrics are computed and reported.
16072 For more finely-grained control you can use
16073 the following switches:
16076 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
16078 @item ^-nocc^/SUPPRESS=CYCLOMATIC_COMPLEXITY^
16079 Do not compute the McCabe Cyclomatic Complexity
16081 @item ^-noec^/SUPPRESS=ESSENTIAL_COMPLEXITY^
16082 Do not compute the Essential Complexity
16084 @item ^-nonl^/SUPPRESS=MAXIMAL_LOOP_NESTING^
16085 Do not compute maximal loop nesting level
16087 @item ^-ne^/SUPPRESS=EXITS_AS_GOTOS^
16088 Do not consider @code{exit} statements as @code{goto}s when
16089 computing Essential Complexity
16093 @node Other gnatmetric Switches
16094 @subsection Other @code{gnatmetric} Switches
16097 Additional @command{gnatmetric} switches are as follows:
16100 @item ^-files @var{filename}^/FILES=@var{filename}^
16101 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
16102 Take the argument source files from the specified file. This file should be an
16103 ordinary textual file containing file names separated by spaces or
16104 line breaks. You can use this switch more then once in the same call to
16105 @command{gnatmetric}. You also can combine this switch with
16106 an explicit list of files.
16108 @item ^-v^/VERBOSE^
16109 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
16111 @command{gnatmetric} generates version information and then
16112 a trace of sources being processed.
16114 @item ^-dv^/DEBUG_OUTPUT^
16115 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
16117 @command{gnatmetric} generates various messages useful to understand what
16118 happens during the metrics computation
16121 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
16125 @c ***********************************
16126 @node File Name Krunching Using gnatkr
16127 @chapter File Name Krunching Using @code{gnatkr}
16131 This chapter discusses the method used by the compiler to shorten
16132 the default file names chosen for Ada units so that they do not
16133 exceed the maximum length permitted. It also describes the
16134 @code{gnatkr} utility that can be used to determine the result of
16135 applying this shortening.
16139 * Krunching Method::
16140 * Examples of gnatkr Usage::
16144 @section About @code{gnatkr}
16147 The default file naming rule in GNAT
16148 is that the file name must be derived from
16149 the unit name. The exact default rule is as follows:
16152 Take the unit name and replace all dots by hyphens.
16154 If such a replacement occurs in the
16155 second character position of a name, and the first character is
16156 ^a, g, s, or i^A, G, S, or I^ then replace the dot by the character
16157 ^~ (tilde)^$ (dollar sign)^
16158 instead of a minus.
16160 The reason for this exception is to avoid clashes
16161 with the standard names for children of System, Ada, Interfaces,
16162 and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^
16165 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
16166 switch of the compiler activates a ``krunching''
16167 circuit that limits file names to nn characters (where nn is a decimal
16168 integer). For example, using OpenVMS,
16169 where the maximum file name length is
16170 39, the value of nn is usually set to 39, but if you want to generate
16171 a set of files that would be usable if ported to a system with some
16172 different maximum file length, then a different value can be specified.
16173 The default value of 39 for OpenVMS need not be specified.
16175 The @code{gnatkr} utility can be used to determine the krunched name for
16176 a given file, when krunched to a specified maximum length.
16179 @section Using @code{gnatkr}
16182 The @code{gnatkr} command has the form
16186 $ gnatkr @var{name} [@var{length}]
16192 $ gnatkr @var{name} /COUNT=nn
16197 @var{name} is the uncrunched file name, derived from the name of the unit
16198 in the standard manner described in the previous section (i.e. in particular
16199 all dots are replaced by hyphens). The file name may or may not have an
16200 extension (defined as a suffix of the form period followed by arbitrary
16201 characters other than period). If an extension is present then it will
16202 be preserved in the output. For example, when krunching @file{hellofile.ads}
16203 to eight characters, the result will be hellofil.ads.
16205 Note: for compatibility with previous versions of @code{gnatkr} dots may
16206 appear in the name instead of hyphens, but the last dot will always be
16207 taken as the start of an extension. So if @code{gnatkr} is given an argument
16208 such as @file{Hello.World.adb} it will be treated exactly as if the first
16209 period had been a hyphen, and for example krunching to eight characters
16210 gives the result @file{hellworl.adb}.
16212 Note that the result is always all lower case (except on OpenVMS where it is
16213 all upper case). Characters of the other case are folded as required.
16215 @var{length} represents the length of the krunched name. The default
16216 when no argument is given is ^8^39^ characters. A length of zero stands for
16217 unlimited, in other words do not chop except for system files where the
16218 implied crunching length is always eight characters.
16221 The output is the krunched name. The output has an extension only if the
16222 original argument was a file name with an extension.
16224 @node Krunching Method
16225 @section Krunching Method
16228 The initial file name is determined by the name of the unit that the file
16229 contains. The name is formed by taking the full expanded name of the
16230 unit and replacing the separating dots with hyphens and
16231 using ^lowercase^uppercase^
16232 for all letters, except that a hyphen in the second character position is
16233 replaced by a ^tilde^dollar sign^ if the first character is
16234 ^a, i, g, or s^A, I, G, or S^.
16235 The extension is @code{.ads} for a
16236 specification and @code{.adb} for a body.
16237 Krunching does not affect the extension, but the file name is shortened to
16238 the specified length by following these rules:
16242 The name is divided into segments separated by hyphens, tildes or
16243 underscores and all hyphens, tildes, and underscores are
16244 eliminated. If this leaves the name short enough, we are done.
16247 If the name is too long, the longest segment is located (left-most
16248 if there are two of equal length), and shortened by dropping
16249 its last character. This is repeated until the name is short enough.
16251 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16252 to fit the name into 8 characters as required by some operating systems.
16255 our-strings-wide_fixed 22
16256 our strings wide fixed 19
16257 our string wide fixed 18
16258 our strin wide fixed 17
16259 our stri wide fixed 16
16260 our stri wide fixe 15
16261 our str wide fixe 14
16262 our str wid fixe 13
16268 Final file name: oustwifi.adb
16272 The file names for all predefined units are always krunched to eight
16273 characters. The krunching of these predefined units uses the following
16274 special prefix replacements:
16278 replaced by @file{^a^A^-}
16281 replaced by @file{^g^G^-}
16284 replaced by @file{^i^I^-}
16287 replaced by @file{^s^S^-}
16290 These system files have a hyphen in the second character position. That
16291 is why normal user files replace such a character with a
16292 ^tilde^dollar sign^, to
16293 avoid confusion with system file names.
16295 As an example of this special rule, consider
16296 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16299 ada-strings-wide_fixed 22
16300 a- strings wide fixed 18
16301 a- string wide fixed 17
16302 a- strin wide fixed 16
16303 a- stri wide fixed 15
16304 a- stri wide fixe 14
16305 a- str wide fixe 13
16311 Final file name: a-stwifi.adb
16315 Of course no file shortening algorithm can guarantee uniqueness over all
16316 possible unit names, and if file name krunching is used then it is your
16317 responsibility to ensure that no name clashes occur. The utility
16318 program @code{gnatkr} is supplied for conveniently determining the
16319 krunched name of a file.
16321 @node Examples of gnatkr Usage
16322 @section Examples of @code{gnatkr} Usage
16329 $ gnatkr very_long_unit_name.ads --> velounna.ads
16330 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
16331 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16332 $ gnatkr grandparent-parent-child --> grparchi
16334 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16335 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16338 @node Preprocessing Using gnatprep
16339 @chapter Preprocessing Using @code{gnatprep}
16343 The @code{gnatprep} utility provides
16344 a simple preprocessing capability for Ada programs.
16345 It is designed for use with GNAT, but is not dependent on any special
16350 * Switches for gnatprep::
16351 * Form of Definitions File::
16352 * Form of Input Text for gnatprep::
16355 @node Using gnatprep
16356 @section Using @code{gnatprep}
16359 To call @code{gnatprep} use
16362 $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile]
16369 is the full name of the input file, which is an Ada source
16370 file containing preprocessor directives.
16373 is the full name of the output file, which is an Ada source
16374 in standard Ada form. When used with GNAT, this file name will
16375 normally have an ads or adb suffix.
16378 is the full name of a text file containing definitions of
16379 symbols to be referenced by the preprocessor. This argument is
16380 optional, and can be replaced by the use of the @option{-D} switch.
16383 is an optional sequence of switches as described in the next section.
16386 @node Switches for gnatprep
16387 @section Switches for @code{gnatprep}
16392 @item ^-b^/BLANK_LINES^
16393 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
16394 Causes both preprocessor lines and the lines deleted by
16395 preprocessing to be replaced by blank lines in the output source file,
16396 preserving line numbers in the output file.
16398 @item ^-c^/COMMENTS^
16399 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
16400 Causes both preprocessor lines and the lines deleted
16401 by preprocessing to be retained in the output source as comments marked
16402 with the special string @code{"--! "}. This option will result in line numbers
16403 being preserved in the output file.
16405 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
16406 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
16407 Defines a new symbol, associated with value. If no value is given on the
16408 command line, then symbol is considered to be @code{True}. This switch
16409 can be used in place of a definition file.
16413 @cindex @option{/REMOVE} (@command{gnatprep})
16414 This is the default setting which causes lines deleted by preprocessing
16415 to be entirely removed from the output file.
16418 @item ^-r^/REFERENCE^
16419 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
16420 Causes a @code{Source_Reference} pragma to be generated that
16421 references the original input file, so that error messages will use
16422 the file name of this original file. The use of this switch implies
16423 that preprocessor lines are not to be removed from the file, so its
16424 use will force @option{^-b^/BLANK_LINES^} mode if
16425 @option{^-c^/COMMENTS^}
16426 has not been specified explicitly.
16428 Note that if the file to be preprocessed contains multiple units, then
16429 it will be necessary to @code{gnatchop} the output file from
16430 @code{gnatprep}. If a @code{Source_Reference} pragma is present
16431 in the preprocessed file, it will be respected by
16432 @code{gnatchop ^-r^/REFERENCE^}
16433 so that the final chopped files will correctly refer to the original
16434 input source file for @code{gnatprep}.
16436 @item ^-s^/SYMBOLS^
16437 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
16438 Causes a sorted list of symbol names and values to be
16439 listed on the standard output file.
16441 @item ^-u^/UNDEFINED^
16442 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
16443 Causes undefined symbols to be treated as having the value FALSE in the context
16444 of a preprocessor test. In the absence of this option, an undefined symbol in
16445 a @code{#if} or @code{#elsif} test will be treated as an error.
16451 Note: if neither @option{-b} nor @option{-c} is present,
16452 then preprocessor lines and
16453 deleted lines are completely removed from the output, unless -r is
16454 specified, in which case -b is assumed.
16457 @node Form of Definitions File
16458 @section Form of Definitions File
16461 The definitions file contains lines of the form
16468 where symbol is an identifier, following normal Ada (case-insensitive)
16469 rules for its syntax, and value is one of the following:
16473 Empty, corresponding to a null substitution
16475 A string literal using normal Ada syntax
16477 Any sequence of characters from the set
16478 (letters, digits, period, underline).
16482 Comment lines may also appear in the definitions file, starting with
16483 the usual @code{--},
16484 and comments may be added to the definitions lines.
16486 @node Form of Input Text for gnatprep
16487 @section Form of Input Text for @code{gnatprep}
16490 The input text may contain preprocessor conditional inclusion lines,
16491 as well as general symbol substitution sequences.
16493 The preprocessor conditional inclusion commands have the form
16498 #if @i{expression} [then]
16500 #elsif @i{expression} [then]
16502 #elsif @i{expression} [then]
16513 In this example, @i{expression} is defined by the following grammar:
16515 @i{expression} ::= <symbol>
16516 @i{expression} ::= <symbol> = "<value>"
16517 @i{expression} ::= <symbol> = <symbol>
16518 @i{expression} ::= <symbol> 'Defined
16519 @i{expression} ::= not @i{expression}
16520 @i{expression} ::= @i{expression} and @i{expression}
16521 @i{expression} ::= @i{expression} or @i{expression}
16522 @i{expression} ::= @i{expression} and then @i{expression}
16523 @i{expression} ::= @i{expression} or else @i{expression}
16524 @i{expression} ::= ( @i{expression} )
16528 For the first test (@i{expression} ::= <symbol>) the symbol must have
16529 either the value true or false, that is to say the right-hand of the
16530 symbol definition must be one of the (case-insensitive) literals
16531 @code{True} or @code{False}. If the value is true, then the
16532 corresponding lines are included, and if the value is false, they are
16535 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
16536 the symbol has been defined in the definition file or by a @option{-D}
16537 switch on the command line. Otherwise, the test is false.
16539 The equality tests are case insensitive, as are all the preprocessor lines.
16541 If the symbol referenced is not defined in the symbol definitions file,
16542 then the effect depends on whether or not switch @option{-u}
16543 is specified. If so, then the symbol is treated as if it had the value
16544 false and the test fails. If this switch is not specified, then
16545 it is an error to reference an undefined symbol. It is also an error to
16546 reference a symbol that is defined with a value other than @code{True}
16549 The use of the @code{not} operator inverts the sense of this logical test, so
16550 that the lines are included only if the symbol is not defined.
16551 The @code{then} keyword is optional as shown
16553 The @code{#} must be the first non-blank character on a line, but
16554 otherwise the format is free form. Spaces or tabs may appear between
16555 the @code{#} and the keyword. The keywords and the symbols are case
16556 insensitive as in normal Ada code. Comments may be used on a
16557 preprocessor line, but other than that, no other tokens may appear on a
16558 preprocessor line. Any number of @code{elsif} clauses can be present,
16559 including none at all. The @code{else} is optional, as in Ada.
16561 The @code{#} marking the start of a preprocessor line must be the first
16562 non-blank character on the line, i.e. it must be preceded only by
16563 spaces or horizontal tabs.
16565 Symbol substitution outside of preprocessor lines is obtained by using
16573 anywhere within a source line, except in a comment or within a
16574 string literal. The identifier
16575 following the @code{$} must match one of the symbols defined in the symbol
16576 definition file, and the result is to substitute the value of the
16577 symbol in place of @code{$symbol} in the output file.
16579 Note that although the substitution of strings within a string literal
16580 is not possible, it is possible to have a symbol whose defined value is
16581 a string literal. So instead of setting XYZ to @code{hello} and writing:
16584 Header : String := "$XYZ";
16588 you should set XYZ to @code{"hello"} and write:
16591 Header : String := $XYZ;
16595 and then the substitution will occur as desired.
16598 @node The GNAT Run-Time Library Builder gnatlbr
16599 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
16601 @cindex Library builder
16604 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
16605 supplied configuration pragmas.
16608 * Running gnatlbr::
16609 * Switches for gnatlbr::
16610 * Examples of gnatlbr Usage::
16613 @node Running gnatlbr
16614 @section Running @code{gnatlbr}
16617 The @code{gnatlbr} command has the form
16620 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
16623 @node Switches for gnatlbr
16624 @section Switches for @code{gnatlbr}
16627 @code{gnatlbr} recognizes the following switches:
16631 @item /CREATE=directory
16632 @cindex @code{/CREATE} (@code{gnatlbr})
16633 Create the new run-time library in the specified directory.
16635 @item /SET=directory
16636 @cindex @code{/SET} (@code{gnatlbr})
16637 Make the library in the specified directory the current run-time
16640 @item /DELETE=directory
16641 @cindex @code{/DELETE} (@code{gnatlbr})
16642 Delete the run-time library in the specified directory.
16645 @cindex @code{/CONFIG} (@code{gnatlbr})
16647 Use the configuration pragmas in the specified file when building
16651 Use the configuration pragmas in the specified file when compiling.
16655 @node Examples of gnatlbr Usage
16656 @section Example of @code{gnatlbr} Usage
16659 Contents of VAXFLOAT.ADC:
16660 pragma Float_Representation (VAX_Float);
16662 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
16664 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
16669 @node The GNAT Library Browser gnatls
16670 @chapter The GNAT Library Browser @code{gnatls}
16672 @cindex Library browser
16675 @code{gnatls} is a tool that outputs information about compiled
16676 units. It gives the relationship between objects, unit names and source
16677 files. It can also be used to check the source dependencies of a unit
16678 as well as various characteristics.
16682 * Switches for gnatls::
16683 * Examples of gnatls Usage::
16686 @node Running gnatls
16687 @section Running @code{gnatls}
16690 The @code{gnatls} command has the form
16693 $ gnatls switches @var{object_or_ali_file}
16697 The main argument is the list of object or @file{ali} files
16698 (@pxref{The Ada Library Information Files})
16699 for which information is requested.
16701 In normal mode, without additional option, @code{gnatls} produces a
16702 four-column listing. Each line represents information for a specific
16703 object. The first column gives the full path of the object, the second
16704 column gives the name of the principal unit in this object, the third
16705 column gives the status of the source and the fourth column gives the
16706 full path of the source representing this unit.
16707 Here is a simple example of use:
16711 ^./^[]^demo1.o demo1 DIF demo1.adb
16712 ^./^[]^demo2.o demo2 OK demo2.adb
16713 ^./^[]^hello.o h1 OK hello.adb
16714 ^./^[]^instr-child.o instr.child MOK instr-child.adb
16715 ^./^[]^instr.o instr OK instr.adb
16716 ^./^[]^tef.o tef DIF tef.adb
16717 ^./^[]^text_io_example.o text_io_example OK text_io_example.adb
16718 ^./^[]^tgef.o tgef DIF tgef.adb
16722 The first line can be interpreted as follows: the main unit which is
16724 object file @file{demo1.o} is demo1, whose main source is in
16725 @file{demo1.adb}. Furthermore, the version of the source used for the
16726 compilation of demo1 has been modified (DIF). Each source file has a status
16727 qualifier which can be:
16730 @item OK (unchanged)
16731 The version of the source file used for the compilation of the
16732 specified unit corresponds exactly to the actual source file.
16734 @item MOK (slightly modified)
16735 The version of the source file used for the compilation of the
16736 specified unit differs from the actual source file but not enough to
16737 require recompilation. If you use gnatmake with the qualifier
16738 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
16739 MOK will not be recompiled.
16741 @item DIF (modified)
16742 No version of the source found on the path corresponds to the source
16743 used to build this object.
16745 @item ??? (file not found)
16746 No source file was found for this unit.
16748 @item HID (hidden, unchanged version not first on PATH)
16749 The version of the source that corresponds exactly to the source used
16750 for compilation has been found on the path but it is hidden by another
16751 version of the same source that has been modified.
16755 @node Switches for gnatls
16756 @section Switches for @code{gnatls}
16759 @code{gnatls} recognizes the following switches:
16763 @item ^-a^/ALL_UNITS^
16764 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
16765 Consider all units, including those of the predefined Ada library.
16766 Especially useful with @option{^-d^/DEPENDENCIES^}.
16768 @item ^-d^/DEPENDENCIES^
16769 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
16770 List sources from which specified units depend on.
16772 @item ^-h^/OUTPUT=OPTIONS^
16773 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
16774 Output the list of options.
16776 @item ^-o^/OUTPUT=OBJECTS^
16777 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
16778 Only output information about object files.
16780 @item ^-s^/OUTPUT=SOURCES^
16781 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
16782 Only output information about source files.
16784 @item ^-u^/OUTPUT=UNITS^
16785 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
16786 Only output information about compilation units.
16788 @item ^-files^/FILES^=@var{file}
16789 @cindex @option{^-files^/FILES^} (@code{gnatls})
16790 Take as arguments the files listed in text file @var{file}.
16791 Text file @var{file} may contain empty lines that are ignored.
16792 Each non empty line should contain the name of an existing file.
16793 Several such switches may be specified simultaneously.
16795 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16796 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
16797 @itemx ^-I^/SEARCH=^@var{dir}
16798 @itemx ^-I-^/NOCURRENT_DIRECTORY^
16800 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
16801 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
16802 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
16803 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
16804 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
16805 flags (@pxref{Switches for gnatmake}).
16807 @item --RTS=@var{rts-path}
16808 @cindex @option{--RTS} (@code{gnatls})
16809 Specifies the default location of the runtime library. Same meaning as the
16810 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
16812 @item ^-v^/OUTPUT=VERBOSE^
16813 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
16814 Verbose mode. Output the complete source, object and project paths. Do not use
16815 the default column layout but instead use long format giving as much as
16816 information possible on each requested units, including special
16817 characteristics such as:
16820 @item Preelaborable
16821 The unit is preelaborable in the Ada 95 sense.
16824 No elaboration code has been produced by the compiler for this unit.
16827 The unit is pure in the Ada 95 sense.
16829 @item Elaborate_Body
16830 The unit contains a pragma Elaborate_Body.
16833 The unit contains a pragma Remote_Types.
16835 @item Shared_Passive
16836 The unit contains a pragma Shared_Passive.
16839 This unit is part of the predefined environment and cannot be modified
16842 @item Remote_Call_Interface
16843 The unit contains a pragma Remote_Call_Interface.
16849 @node Examples of gnatls Usage
16850 @section Example of @code{gnatls} Usage
16854 Example of using the verbose switch. Note how the source and
16855 object paths are affected by the -I switch.
16858 $ gnatls -v -I.. demo1.o
16860 GNATLS 5.03w (20041123-34)
16861 Copyright 1997-2004 Free Software Foundation, Inc.
16863 Source Search Path:
16864 <Current_Directory>
16866 /home/comar/local/adainclude/
16868 Object Search Path:
16869 <Current_Directory>
16871 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
16873 Project Search Path:
16874 <Current_Directory>
16875 /home/comar/local/lib/gnat/
16880 Kind => subprogram body
16881 Flags => No_Elab_Code
16882 Source => demo1.adb modified
16886 The following is an example of use of the dependency list.
16887 Note the use of the -s switch
16888 which gives a straight list of source files. This can be useful for
16889 building specialized scripts.
16892 $ gnatls -d demo2.o
16893 ./demo2.o demo2 OK demo2.adb
16899 $ gnatls -d -s -a demo1.o
16901 /home/comar/local/adainclude/ada.ads
16902 /home/comar/local/adainclude/a-finali.ads
16903 /home/comar/local/adainclude/a-filico.ads
16904 /home/comar/local/adainclude/a-stream.ads
16905 /home/comar/local/adainclude/a-tags.ads
16908 /home/comar/local/adainclude/gnat.ads
16909 /home/comar/local/adainclude/g-io.ads
16911 /home/comar/local/adainclude/system.ads
16912 /home/comar/local/adainclude/s-exctab.ads
16913 /home/comar/local/adainclude/s-finimp.ads
16914 /home/comar/local/adainclude/s-finroo.ads
16915 /home/comar/local/adainclude/s-secsta.ads
16916 /home/comar/local/adainclude/s-stalib.ads
16917 /home/comar/local/adainclude/s-stoele.ads
16918 /home/comar/local/adainclude/s-stratt.ads
16919 /home/comar/local/adainclude/s-tasoli.ads
16920 /home/comar/local/adainclude/s-unstyp.ads
16921 /home/comar/local/adainclude/unchconv.ads
16927 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
16929 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
16930 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
16931 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
16932 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
16933 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
16937 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
16938 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
16940 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
16941 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
16942 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
16943 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
16944 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
16945 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
16946 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
16947 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
16948 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
16949 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
16950 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
16954 @node Cleaning Up Using gnatclean
16955 @chapter Cleaning Up Using @code{gnatclean}
16957 @cindex Cleaning tool
16960 @code{gnatclean} is a tool that allows the deletion of files produced by the
16961 compiler, binder and linker, including ALI files, object files, tree files,
16962 expanded source files, library files, interface copy source files, binder
16963 generated files and executable files.
16966 * Running gnatclean::
16967 * Switches for gnatclean::
16968 @c * Examples of gnatclean Usage::
16971 @node Running gnatclean
16972 @section Running @code{gnatclean}
16975 The @code{gnatclean} command has the form:
16978 $ gnatclean switches @var{names}
16982 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
16983 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
16984 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
16987 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
16988 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
16989 the linker. In informative-only mode, specified by switch
16990 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
16991 normal mode is listed, but no file is actually deleted.
16993 @node Switches for gnatclean
16994 @section Switches for @code{gnatclean}
16997 @code{gnatclean} recognizes the following switches:
17001 @item ^-c^/COMPILER_FILES_ONLY^
17002 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
17003 Only attempt to delete the files produced by the compiler, not those produced
17004 by the binder or the linker. The files that are not to be deleted are library
17005 files, interface copy files, binder generated files and executable files.
17007 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
17008 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
17009 Indicate that ALI and object files should normally be found in directory
17012 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
17013 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
17014 When using project files, if some errors or warnings are detected during
17015 parsing and verbose mode is not in effect (no use of switch
17016 ^-v^/VERBOSE^), then error lines start with the full path name of the project
17017 file, rather than its simple file name.
17020 @cindex @option{^-h^/HELP^} (@code{gnatclean})
17021 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
17023 @item ^-n^/NODELETE^
17024 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
17025 Informative-only mode. Do not delete any files. Output the list of the files
17026 that would have been deleted if this switch was not specified.
17028 @item ^-P^/PROJECT_FILE=^@var{project}
17029 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
17030 Use project file @var{project}. Only one such switch can be used.
17031 When cleaning a project file, the files produced by the compilation of the
17032 immediate sources or inherited sources of the project files are to be
17033 deleted. This is not depending on the presence or not of executable names
17034 on the command line.
17037 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
17038 Quiet output. If there are no error, do not ouuput anything, except in
17039 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
17040 (switch ^-n^/NODELETE^).
17042 @item ^-r^/RECURSIVE^
17043 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
17044 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
17045 clean all imported and extended project files, recursively. If this switch
17046 is not specified, only the files related to the main project file are to be
17047 deleted. This switch has no effect if no project file is specified.
17049 @item ^-v^/VERBOSE^
17050 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
17053 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
17054 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
17055 Indicates the verbosity of the parsing of GNAT project files.
17056 @xref{Switches Related to Project Files}.
17058 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
17059 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
17060 Indicates that external variable @var{name} has the value @var{value}.
17061 The Project Manager will use this value for occurrences of
17062 @code{external(name)} when parsing the project file.
17063 @xref{Switches Related to Project Files}.
17065 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17066 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
17067 When searching for ALI and object files, look in directory
17070 @item ^-I^/SEARCH=^@var{dir}
17071 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
17072 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
17074 @item ^-I-^/NOCURRENT_DIRECTORY^
17075 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
17076 @cindex Source files, suppressing search
17077 Do not look for ALI or object files in the directory
17078 where @code{gnatclean} was invoked.
17082 @c @node Examples of gnatclean Usage
17083 @c @section Examples of @code{gnatclean} Usage
17086 @node GNAT and Libraries
17087 @chapter GNAT and Libraries
17088 @cindex Library, building, installing, using
17091 This chapter describes how to build and use libraries with GNAT, and also shows
17092 how to recompile the GNAT run-time library. You should be familiar with the
17093 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
17097 * Introduction to Libraries in GNAT::
17098 * General Ada Libraries::
17099 * Stand-alone Ada Libraries::
17100 * Rebuilding the GNAT Run-Time Library::
17103 @node Introduction to Libraries in GNAT
17104 @section Introduction to Libraries in GNAT
17107 A library is, conceptually, a collection of objects which does not have its
17108 own main thread of execution, but rather provides certain services to the
17109 applications that use it. A library can be either statically linked with the
17110 application, in which case its code is directly included in the application,
17111 or, on platforms that support it, be dynamically linked, in which case
17112 its code is shared by all applications making use of this library.
17114 GNAT supports both types of libraries.
17115 In the static case, the compiled code can be provided in different ways. The
17116 simplest approach is to provide directly the set of objects resulting from
17117 compilation of the library source files. Alternatively, you can group the
17118 objects into an archive using whatever commands are provided by the operating
17119 system. For the latter case, the objects are grouped into a shared library.
17121 In the GNAT environment, a library has three types of components:
17127 @xref{The Ada Library Information Files}.
17129 Object files, an archive or a shared library.
17133 A GNAT library may expose all its source files, which is useful for
17134 documentation purposes. Alternatively, it may expose only the units needed by
17135 an external user to make use of the library. That is to say, the specs
17136 reflecting the library services along with all the units needed to compile
17137 those specs, which can include generic bodies or any body implementing an
17138 inlined routine. In the case of @emph{stand-alone libraries} those exposed
17139 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
17141 All compilation units comprising an application, including those in a library,
17142 need to be elaborated in an order partially defined by Ada's semantics. GNAT
17143 computes the elaboration order from the @file{ALI} files and this is why they
17144 constitute a mandatory part of GNAT libraries. Except in the case of
17145 @emph{stand-alone libraries}, where a specific library elaboration routine is
17146 produced independently of the application(s) using the library.
17148 @node General Ada Libraries
17149 @section General Ada Libraries
17152 * Building a library::
17153 * Installing a library::
17154 * Using a library::
17157 @node Building a library
17158 @subsection Building a library
17161 The easiest way to build a library is to use the Project Manager,
17162 which supports a special type of project called a @emph{Library Project}
17163 (@pxref{Library Projects}).
17165 A project is considered a library project, when two project-level attributes
17166 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
17167 control different aspects of library configuration, additional optional
17168 project-level attributes can be specified:
17171 This attribute controls whether the library is to be static or dynamic
17173 @item Library_Version
17174 This attribute specifies the library version; this value is used
17175 during dynamic linking of shared libraries to determine if the currently
17176 installed versions of the binaries are compatible.
17178 @item Library_Options
17180 These attributes specify additional low-level options to be used during
17181 library generation, and redefine the actual application used to generate
17186 The GNAT Project Manager takes full care of the library maintenance task,
17187 including recompilation of the source files for which objects do not exist
17188 or are not up to date, assembly of the library archive, and installation of
17189 the library (i.e., copying associated source, object and @file{ALI} files
17190 to the specified location).
17192 Here is a simple library project file:
17193 @smallexample @c ada
17195 for Source_Dirs use ("src1", "src2");
17196 for Object_Dir use "obj";
17197 for Library_Name use "mylib";
17198 for Library_Dir use "lib";
17199 for Library_Kind use "dynamic";
17204 and the compilation command to build and install the library:
17206 @smallexample @c ada
17207 $ gnatmake -Pmy_lib
17211 It is not entirely trivial to perform manually all the steps required to
17212 produce a library. We recommend that you use the GNAT Project Manager
17213 for this task. In special cases where this is not desired, the necessary
17214 steps are discussed below.
17216 There are various possibilities for compiling the units that make up the
17217 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
17218 with a conventional script. For simple libraries, it is also possible to create
17219 a dummy main program which depends upon all the packages that comprise the
17220 interface of the library. This dummy main program can then be given to
17221 @command{gnatmake}, which will ensure that all necessary objects are built.
17223 After this task is accomplished, you should follow the standard procedure
17224 of the underlying operating system to produce the static or shared library.
17226 Here is an example of such a dummy program:
17227 @smallexample @c ada
17229 with My_Lib.Service1;
17230 with My_Lib.Service2;
17231 with My_Lib.Service3;
17232 procedure My_Lib_Dummy is
17240 Here are the generic commands that will build an archive or a shared library.
17243 # compiling the library
17244 $ gnatmake -c my_lib_dummy.adb
17246 # we don't need the dummy object itself
17247 $ rm my_lib_dummy.o my_lib_dummy.ali
17249 # create an archive with the remaining objects
17250 $ ar rc libmy_lib.a *.o
17251 # some systems may require "ranlib" to be run as well
17253 # or create a shared library
17254 $ gcc -shared -o libmy_lib.so *.o
17255 # some systems may require the code to have been compiled with -fPIC
17257 # remove the object files that are now in the library
17260 # Make the ALI files read-only so that gnatmake will not try to
17261 # regenerate the objects that are in the library
17266 Please note that the library must have a name of the form @file{libxxx.a} or
17267 @file{libxxx.so} (or @file{libxxx.dll} on Windows) in order to be accessed by
17268 the directive @option{-lxxx} at link time.
17270 @node Installing a library
17271 @subsection Installing a library
17272 @cindex @code{ADA_PROJECT_PATH}
17275 If you use project files, library installation is part of the library build
17276 process. Thus no further action is needed in order to make use of the
17277 libraries that are built as part of the general application build. A usable
17278 version of the library is installed in the directory specified by the
17279 @code{Library_Dir} attribute of the library project file.
17281 You may want to install a library in a context different from where the library
17282 is built. This situation arises with third party suppliers, who may want
17283 to distribute a library in binary form where the user is not expected to be
17284 able to recompile the library. The simplest option in this case is to provide
17285 a project file slightly different from the one used to build the library, by
17286 using the @code{externally_built} attribute. For instance, the project
17287 file used to build the library in the previous section can be changed into the
17288 following one when the library is installed:
17290 @smallexample @c projectfile
17292 for Source_Dirs use ("src1", "src2");
17293 for Library_Name use "mylib";
17294 for Library_Dir use "lib";
17295 for Library_Kind use "dynamic";
17296 for Externally_Built use "true";
17301 This project file assumes that the directories @file{src1},
17302 @file{src2}, and @file{lib} exist in
17303 the directory containing the project file. The @code{externally_built}
17304 attribute makes it clear to the GNAT builder that it should not attempt to
17305 recompile any of the units from this library. It allows the library provider to
17306 restrict the source set to the minimum necessary for clients to make use of the
17307 library as described in the first section of this chapter. It is the
17308 responsibility of the library provider to install the necessary sources, ALI
17309 files and libraries in the directories mentioned in the project file. For
17310 convenience, the user's library project file should be installed in a location
17311 that will be searched automatically by the GNAT
17312 builder. These are the directories referenced in the @code{ADA_PROJECT_PATH}
17313 environment variable (@pxref{Importing Projects}), and also the default GNAT
17314 library location that can be queried with @command{gnatls -v} and is usually of
17315 the form $gnat_install_root/lib/gnat.
17317 When project files are not an option, it is also possible, but not recommended,
17318 to install the library so that the sources needed to use the library are on the
17319 Ada source path and the ALI files & libraries be on the Ada Object path (see
17320 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
17321 administrator can place general-purpose libraries in the default compiler
17322 paths, by specifying the libraries' location in the configuration files
17323 @file{ada_source_path} and @file{ada_object_path}. These configuration files
17324 must be located in the GNAT installation tree at the same place as the gcc spec
17325 file. The location of the gcc spec file can be determined as follows:
17331 The configuration files mentioned above have a simple format: each line
17332 must contain one unique directory name.
17333 Those names are added to the corresponding path
17334 in their order of appearance in the file. The names can be either absolute
17335 or relative; in the latter case, they are relative to where theses files
17338 The files @file{ada_source_path} and @file{ada_object_path} might not be
17340 GNAT installation, in which case, GNAT will look for its run-time library in
17341 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17342 objects and @file{ALI} files). When the files exist, the compiler does not
17343 look in @file{adainclude} and @file{adalib}, and thus the
17344 @file{ada_source_path} file
17345 must contain the location for the GNAT run-time sources (which can simply
17346 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17347 contain the location for the GNAT run-time objects (which can simply
17350 You can also specify a new default path to the run-time library at compilation
17351 time with the switch @option{--RTS=rts-path}. You can thus choose / change
17352 the run-time library you want your program to be compiled with. This switch is
17353 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17354 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17356 It is possible to install a library before or after the standard GNAT
17357 library, by reordering the lines in the configuration files. In general, a
17358 library must be installed before the GNAT library if it redefines
17361 @node Using a library
17362 @subsection Using a library
17364 @noindent Once again, the project facility greatly simplifies the use of
17365 libraries. In this context, using a library is just a matter of adding a
17366 @code{with} clause in the user project. For instance, to make use of the
17367 library @code{My_Lib} shown in examples in earlier sections, you can
17370 @smallexample @c projectfile
17377 Even if you have a third-party, non-Ada library, you can still use GNAT's
17378 Project Manager facility to provide a wrapper for it. For example, the
17379 following project, when @code{with}ed by your main project, will link with the
17380 third-party library @file{liba.a}:
17382 @smallexample @c projectfile
17385 for Externally_Built use "true";
17386 for Library_Dir use "lib";
17387 for Library_Name use "a";
17388 for Library_Kind use "static";
17392 This is an alternative to the use of @code{pragma Linker_Options}. It is
17393 especially interesting in the context of systems with several interdependant
17394 static libraries where finding a proper linker order is not easy and best be
17395 left to the tools having visibility over project dependancy information.
17398 In order to use an Ada library manually, you need to make sure that this
17399 library is on both your source and object path
17400 (see @ref{Search Paths and the Run-Time Library (RTL)}
17401 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17402 in an archive or a shared library, you need to specify the desired
17403 library at link time.
17405 For example, you can use the library @file{mylib} installed in
17406 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17409 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17414 This can be expressed more simply:
17419 when the following conditions are met:
17422 @file{/dir/my_lib_src} has been added by the user to the environment
17423 variable @code{ADA_INCLUDE_PATH}, or by the administrator to the file
17424 @file{ada_source_path}
17426 @file{/dir/my_lib_obj} has been added by the user to the environment
17427 variable @code{ADA_OBJECTS_PATH}, or by the administrator to the file
17428 @file{ada_object_path}
17430 a pragma @code{Linker_Options} has been added to one of the sources.
17433 @smallexample @c ada
17434 pragma Linker_Options ("-lmy_lib");
17438 @node Stand-alone Ada Libraries
17439 @section Stand-alone Ada Libraries
17440 @cindex Stand-alone library, building, using
17443 * Introduction to Stand-alone Libraries::
17444 * Building a Stand-alone Library::
17445 * Creating a Stand-alone Library to be used in a non-Ada context::
17446 * Restrictions in Stand-alone Libraries::
17449 @node Introduction to Stand-alone Libraries
17450 @subsection Introduction to Stand-alone Libraries
17453 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
17455 elaborate the Ada units that are included in the library. In contrast with
17456 an ordinary library, which consists of all sources, objects and @file{ALI}
17458 library, a SAL may specify a restricted subset of compilation units
17459 to serve as a library interface. In this case, the fully
17460 self-sufficient set of files will normally consist of an objects
17461 archive, the sources of interface units' specs, and the @file{ALI}
17462 files of interface units.
17463 If an interface spec contains a generic unit or an inlined subprogram,
17465 source must also be provided; if the units that must be provided in the source
17466 form depend on other units, the source and @file{ALI} files of those must
17469 The main purpose of a SAL is to minimize the recompilation overhead of client
17470 applications when a new version of the library is installed. Specifically,
17471 if the interface sources have not changed, client applications do not need to
17472 be recompiled. If, furthermore, a SAL is provided in the shared form and its
17473 version, controlled by @code{Library_Version} attribute, is not changed,
17474 then the clients do not need to be relinked.
17476 SALs also allow the library providers to minimize the amount of library source
17477 text exposed to the clients. Such ``information hiding'' might be useful or
17478 necessary for various reasons.
17480 Stand-alone libraries are also well suited to be used in an executable whose
17481 main routine is not written in Ada.
17483 @node Building a Stand-alone Library
17484 @subsection Building a Stand-alone Library
17487 GNAT's Project facility provides a simple way of building and installing
17488 stand-alone libraries; see @ref{Stand-alone Library Projects}.
17489 To be a Stand-alone Library Project, in addition to the two attributes
17490 that make a project a Library Project (@code{Library_Name} and
17491 @code{Library_Dir}; see @ref{Library Projects}), the attribute
17492 @code{Library_Interface} must be defined. For example:
17494 @smallexample @c projectfile
17496 for Library_Dir use "lib_dir";
17497 for Library_Name use "dummy";
17498 for Library_Interface use ("int1", "int1.child");
17503 Attribute @code{Library_Interface} has a non-empty string list value,
17504 each string in the list designating a unit contained in an immediate source
17505 of the project file.
17507 When a Stand-alone Library is built, first the binder is invoked to build
17508 a package whose name depends on the library name
17509 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
17510 This binder-generated package includes initialization and
17511 finalization procedures whose
17512 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
17514 above). The object corresponding to this package is included in the library.
17516 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
17517 calling of these procedures if a static SAL is built, or if a shared SAL
17519 with the project-level attribute @code{Library_Auto_Init} set to
17522 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
17523 (those that are listed in attribute @code{Library_Interface}) are copied to
17524 the Library Directory. As a consequence, only the Interface Units may be
17525 imported from Ada units outside of the library. If other units are imported,
17526 the binding phase will fail.
17528 The attribute @code{Library_Src_Dir} may be specified for a
17529 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
17530 single string value. Its value must be the path (absolute or relative to the
17531 project directory) of an existing directory. This directory cannot be the
17532 object directory or one of the source directories, but it can be the same as
17533 the library directory. The sources of the Interface
17534 Units of the library that are needed by an Ada client of the library will be
17535 copied to the designated directory, called the Interface Copy directory.
17536 These sources include the specs of the Interface Units, but they may also
17537 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
17538 are used, or when there is a generic unit in the spec. Before the sources
17539 are copied to the Interface Copy directory, an attempt is made to delete all
17540 files in the Interface Copy directory.
17542 Building stand-alone libraries by hand is somewhat tedious, but for those
17543 occasions when it is necessary here are the steps that you need to perform:
17546 Compile all library sources.
17549 Invoke the binder with the switch @option{-n} (No Ada main program),
17550 with all the @file{ALI} files of the interfaces, and
17551 with the switch @option{-L} to give specific names to the @code{init}
17552 and @code{final} procedures. For example:
17554 gnatbind -n int1.ali int2.ali -Lsal1
17558 Compile the binder generated file:
17564 Link the dynamic library with all the necessary object files,
17565 indicating to the linker the names of the @code{init} (and possibly
17566 @code{final}) procedures for automatic initialization (and finalization).
17567 The built library should be placed in a directory different from
17568 the object directory.
17571 Copy the @code{ALI} files of the interface to the library directory,
17572 add in this copy an indication that it is an interface to a SAL
17573 (i.e. add a word @option{SL} on the line in the @file{ALI} file that starts
17574 with letter ``P'') and make the modified copy of the @file{ALI} file
17579 Using SALs is not different from using other libraries
17580 (see @ref{Using a library}).
17582 @node Creating a Stand-alone Library to be used in a non-Ada context
17583 @subsection Creating a Stand-alone Library to be used in a non-Ada context
17586 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
17589 The only extra step required is to ensure that library interface subprograms
17590 are compatible with the main program, by means of @code{pragma Export}
17591 or @code{pragma Convention}.
17593 Here is an example of simple library interface for use with C main program:
17595 @smallexample @c ada
17596 package Interface is
17598 procedure Do_Something;
17599 pragma Export (C, Do_Something, "do_something");
17601 procedure Do_Something_Else;
17602 pragma Export (C, Do_Something_Else, "do_something_else");
17608 On the foreign language side, you must provide a ``foreign'' view of the
17609 library interface; remember that it should contain elaboration routines in
17610 addition to interface subprograms.
17612 The example below shows the content of @code{mylib_interface.h} (note
17613 that there is no rule for the naming of this file, any name can be used)
17615 /* the library elaboration procedure */
17616 extern void mylibinit (void);
17618 /* the library finalization procedure */
17619 extern void mylibfinal (void);
17621 /* the interface exported by the library */
17622 extern void do_something (void);
17623 extern void do_something_else (void);
17627 Libraries built as explained above can be used from any program, provided
17628 that the elaboration procedures (named @code{mylibinit} in the previous
17629 example) are called before the library services are used. Any number of
17630 libraries can be used simultaneously, as long as the elaboration
17631 procedure of each library is called.
17633 Below is an example of a C program that uses the @code{mylib} library.
17636 #include "mylib_interface.h"
17641 /* First, elaborate the library before using it */
17644 /* Main program, using the library exported entities */
17646 do_something_else ();
17648 /* Library finalization at the end of the program */
17655 Note that invoking any library finalization procedure generated by
17656 @code{gnatbind} shuts down the Ada run-time environment.
17658 finalization of all Ada libraries must be performed at the end of the program.
17659 No call to these libraries or to the Ada run-time library should be made
17660 after the finalization phase.
17662 @node Restrictions in Stand-alone Libraries
17663 @subsection Restrictions in Stand-alone Libraries
17666 The pragmas listed below should be used with caution inside libraries,
17667 as they can create incompatibilities with other Ada libraries:
17669 @item pragma @code{Locking_Policy}
17670 @item pragma @code{Queuing_Policy}
17671 @item pragma @code{Task_Dispatching_Policy}
17672 @item pragma @code{Unreserve_All_Interrupts}
17676 When using a library that contains such pragmas, the user must make sure
17677 that all libraries use the same pragmas with the same values. Otherwise,
17678 @code{Program_Error} will
17679 be raised during the elaboration of the conflicting
17680 libraries. The usage of these pragmas and its consequences for the user
17681 should therefore be well documented.
17683 Similarly, the traceback in the exception occurrence mechanism should be
17684 enabled or disabled in a consistent manner across all libraries.
17685 Otherwise, Program_Error will be raised during the elaboration of the
17686 conflicting libraries.
17688 If the @code{Version} or @code{Body_Version}
17689 attributes are used inside a library, then you need to
17690 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
17691 libraries, so that version identifiers can be properly computed.
17692 In practice these attributes are rarely used, so this is unlikely
17693 to be a consideration.
17695 @node Rebuilding the GNAT Run-Time Library
17696 @section Rebuilding the GNAT Run-Time Library
17697 @cindex GNAT Run-Time Library, rebuilding
17700 It may be useful to recompile the GNAT library in various contexts, the
17701 most important one being the use of partition-wide configuration pragmas
17702 such as @code{Normalize_Scalars}. A special Makefile called
17703 @code{Makefile.adalib} is provided to that effect and can be found in
17704 the directory containing the GNAT library. The location of this
17705 directory depends on the way the GNAT environment has been installed and can
17706 be determined by means of the command:
17713 The last entry in the object search path usually contains the
17714 gnat library. This Makefile contains its own documentation and in
17715 particular the set of instructions needed to rebuild a new library and
17718 @node Using the GNU make Utility
17719 @chapter Using the GNU @code{make} Utility
17723 This chapter offers some examples of makefiles that solve specific
17724 problems. It does not explain how to write a makefile (see the GNU make
17725 documentation), nor does it try to replace the @command{gnatmake} utility
17726 (@pxref{The GNAT Make Program gnatmake}).
17728 All the examples in this section are specific to the GNU version of
17729 make. Although @code{make} is a standard utility, and the basic language
17730 is the same, these examples use some advanced features found only in
17734 * Using gnatmake in a Makefile::
17735 * Automatically Creating a List of Directories::
17736 * Generating the Command Line Switches::
17737 * Overcoming Command Line Length Limits::
17740 @node Using gnatmake in a Makefile
17741 @section Using gnatmake in a Makefile
17746 Complex project organizations can be handled in a very powerful way by
17747 using GNU make combined with gnatmake. For instance, here is a Makefile
17748 which allows you to build each subsystem of a big project into a separate
17749 shared library. Such a makefile allows you to significantly reduce the link
17750 time of very big applications while maintaining full coherence at
17751 each step of the build process.
17753 The list of dependencies are handled automatically by
17754 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
17755 the appropriate directories.
17757 Note that you should also read the example on how to automatically
17758 create the list of directories
17759 (@pxref{Automatically Creating a List of Directories})
17760 which might help you in case your project has a lot of subdirectories.
17765 @font@heightrm=cmr8
17768 ## This Makefile is intended to be used with the following directory
17770 ## - The sources are split into a series of csc (computer software components)
17771 ## Each of these csc is put in its own directory.
17772 ## Their name are referenced by the directory names.
17773 ## They will be compiled into shared library (although this would also work
17774 ## with static libraries
17775 ## - The main program (and possibly other packages that do not belong to any
17776 ## csc is put in the top level directory (where the Makefile is).
17777 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
17778 ## \_ second_csc (sources) __ lib (will contain the library)
17780 ## Although this Makefile is build for shared library, it is easy to modify
17781 ## to build partial link objects instead (modify the lines with -shared and
17784 ## With this makefile, you can change any file in the system or add any new
17785 ## file, and everything will be recompiled correctly (only the relevant shared
17786 ## objects will be recompiled, and the main program will be re-linked).
17788 # The list of computer software component for your project. This might be
17789 # generated automatically.
17792 # Name of the main program (no extension)
17795 # If we need to build objects with -fPIC, uncomment the following line
17798 # The following variable should give the directory containing libgnat.so
17799 # You can get this directory through 'gnatls -v'. This is usually the last
17800 # directory in the Object_Path.
17803 # The directories for the libraries
17804 # (This macro expands the list of CSC to the list of shared libraries, you
17805 # could simply use the expanded form :
17806 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17807 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17809 $@{MAIN@}: objects $@{LIB_DIR@}
17810 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17811 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17814 # recompile the sources
17815 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17817 # Note: In a future version of GNAT, the following commands will be simplified
17818 # by a new tool, gnatmlib
17820 mkdir -p $@{dir $@@ @}
17821 cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17822 cd $@{dir $@@ @}; cp -f ../*.ali .
17824 # The dependencies for the modules
17825 # Note that we have to force the expansion of *.o, since in some cases
17826 # make won't be able to do it itself.
17827 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17828 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17829 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17831 # Make sure all of the shared libraries are in the path before starting the
17834 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17837 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17838 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17839 $@{RM@} $@{CSC_LIST:%=%/*.o@}
17840 $@{RM@} *.o *.ali $@{MAIN@}
17843 @node Automatically Creating a List of Directories
17844 @section Automatically Creating a List of Directories
17847 In most makefiles, you will have to specify a list of directories, and
17848 store it in a variable. For small projects, it is often easier to
17849 specify each of them by hand, since you then have full control over what
17850 is the proper order for these directories, which ones should be
17853 However, in larger projects, which might involve hundreds of
17854 subdirectories, it might be more convenient to generate this list
17857 The example below presents two methods. The first one, although less
17858 general, gives you more control over the list. It involves wildcard
17859 characters, that are automatically expanded by @code{make}. Its
17860 shortcoming is that you need to explicitly specify some of the
17861 organization of your project, such as for instance the directory tree
17862 depth, whether some directories are found in a separate tree,...
17864 The second method is the most general one. It requires an external
17865 program, called @code{find}, which is standard on all Unix systems. All
17866 the directories found under a given root directory will be added to the
17872 @font@heightrm=cmr8
17875 # The examples below are based on the following directory hierarchy:
17876 # All the directories can contain any number of files
17877 # ROOT_DIRECTORY -> a -> aa -> aaa
17880 # -> b -> ba -> baa
17883 # This Makefile creates a variable called DIRS, that can be reused any time
17884 # you need this list (see the other examples in this section)
17886 # The root of your project's directory hierarchy
17890 # First method: specify explicitly the list of directories
17891 # This allows you to specify any subset of all the directories you need.
17894 DIRS := a/aa/ a/ab/ b/ba/
17897 # Second method: use wildcards
17898 # Note that the argument(s) to wildcard below should end with a '/'.
17899 # Since wildcards also return file names, we have to filter them out
17900 # to avoid duplicate directory names.
17901 # We thus use make's @code{dir} and @code{sort} functions.
17902 # It sets DIRs to the following value (note that the directories aaa and baa
17903 # are not given, unless you change the arguments to wildcard).
17904 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17907 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17908 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17911 # Third method: use an external program
17912 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17913 # This is the most complete command: it sets DIRs to the following value:
17914 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17917 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17921 @node Generating the Command Line Switches
17922 @section Generating the Command Line Switches
17925 Once you have created the list of directories as explained in the
17926 previous section (@pxref{Automatically Creating a List of Directories}),
17927 you can easily generate the command line arguments to pass to gnatmake.
17929 For the sake of completeness, this example assumes that the source path
17930 is not the same as the object path, and that you have two separate lists
17934 # see "Automatically creating a list of directories" to create
17939 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17940 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17943 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17946 @node Overcoming Command Line Length Limits
17947 @section Overcoming Command Line Length Limits
17950 One problem that might be encountered on big projects is that many
17951 operating systems limit the length of the command line. It is thus hard to give
17952 gnatmake the list of source and object directories.
17954 This example shows how you can set up environment variables, which will
17955 make @command{gnatmake} behave exactly as if the directories had been
17956 specified on the command line, but have a much higher length limit (or
17957 even none on most systems).
17959 It assumes that you have created a list of directories in your Makefile,
17960 using one of the methods presented in
17961 @ref{Automatically Creating a List of Directories}.
17962 For the sake of completeness, we assume that the object
17963 path (where the ALI files are found) is different from the sources patch.
17965 Note a small trick in the Makefile below: for efficiency reasons, we
17966 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17967 expanded immediately by @code{make}. This way we overcome the standard
17968 make behavior which is to expand the variables only when they are
17971 On Windows, if you are using the standard Windows command shell, you must
17972 replace colons with semicolons in the assignments to these variables.
17977 @font@heightrm=cmr8
17980 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
17981 # This is the same thing as putting the -I arguments on the command line.
17982 # (the equivalent of using -aI on the command line would be to define
17983 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
17984 # You can of course have different values for these variables.
17986 # Note also that we need to keep the previous values of these variables, since
17987 # they might have been set before running 'make' to specify where the GNAT
17988 # library is installed.
17990 # see "Automatically creating a list of directories" to create these
17996 space:=$@{empty@} $@{empty@}
17997 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17998 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17999 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
18000 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
18001 export ADA_INCLUDE_PATH
18002 export ADA_OBJECT_PATH
18009 @node Memory Management Issues
18010 @chapter Memory Management Issues
18013 This chapter describes some useful memory pools provided in the GNAT library
18014 and in particular the GNAT Debug Pool facility, which can be used to detect
18015 incorrect uses of access values (including ``dangling references'').
18017 It also describes the @command{gnatmem} tool, which can be used to track down
18022 * Some Useful Memory Pools::
18023 * The GNAT Debug Pool Facility::
18025 * The gnatmem Tool::
18029 @node Some Useful Memory Pools
18030 @section Some Useful Memory Pools
18031 @findex Memory Pool
18032 @cindex storage, pool
18035 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
18036 storage pool. Allocations use the standard system call @code{malloc} while
18037 deallocations use the standard system call @code{free}. No reclamation is
18038 performed when the pool goes out of scope. For performance reasons, the
18039 standard default Ada allocators/deallocators do not use any explicit storage
18040 pools but if they did, they could use this storage pool without any change in
18041 behavior. That is why this storage pool is used when the user
18042 manages to make the default implicit allocator explicit as in this example:
18043 @smallexample @c ada
18044 type T1 is access Something;
18045 -- no Storage pool is defined for T2
18046 type T2 is access Something_Else;
18047 for T2'Storage_Pool use T1'Storage_Pool;
18048 -- the above is equivalent to
18049 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
18053 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
18054 pool. The allocation strategy is similar to @code{Pool_Local}'s
18055 except that the all
18056 storage allocated with this pool is reclaimed when the pool object goes out of
18057 scope. This pool provides a explicit mechanism similar to the implicit one
18058 provided by several Ada 83 compilers for allocations performed through a local
18059 access type and whose purpose was to reclaim memory when exiting the
18060 scope of a given local access. As an example, the following program does not
18061 leak memory even though it does not perform explicit deallocation:
18063 @smallexample @c ada
18064 with System.Pool_Local;
18065 procedure Pooloc1 is
18066 procedure Internal is
18067 type A is access Integer;
18068 X : System.Pool_Local.Unbounded_Reclaim_Pool;
18069 for A'Storage_Pool use X;
18072 for I in 1 .. 50 loop
18077 for I in 1 .. 100 loop
18084 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
18085 @code{Storage_Size} is specified for an access type.
18086 The whole storage for the pool is
18087 allocated at once, usually on the stack at the point where the access type is
18088 elaborated. It is automatically reclaimed when exiting the scope where the
18089 access type is defined. This package is not intended to be used directly by the
18090 user and it is implicitly used for each such declaration:
18092 @smallexample @c ada
18093 type T1 is access Something;
18094 for T1'Storage_Size use 10_000;
18098 @node The GNAT Debug Pool Facility
18099 @section The GNAT Debug Pool Facility
18101 @cindex storage, pool, memory corruption
18104 The use of unchecked deallocation and unchecked conversion can easily
18105 lead to incorrect memory references. The problems generated by such
18106 references are usually difficult to tackle because the symptoms can be
18107 very remote from the origin of the problem. In such cases, it is
18108 very helpful to detect the problem as early as possible. This is the
18109 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
18111 In order to use the GNAT specific debugging pool, the user must
18112 associate a debug pool object with each of the access types that may be
18113 related to suspected memory problems. See Ada Reference Manual 13.11.
18114 @smallexample @c ada
18115 type Ptr is access Some_Type;
18116 Pool : GNAT.Debug_Pools.Debug_Pool;
18117 for Ptr'Storage_Pool use Pool;
18121 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
18122 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
18123 allow the user to redefine allocation and deallocation strategies. They
18124 also provide a checkpoint for each dereference, through the use of
18125 the primitive operation @code{Dereference} which is implicitly called at
18126 each dereference of an access value.
18128 Once an access type has been associated with a debug pool, operations on
18129 values of the type may raise four distinct exceptions,
18130 which correspond to four potential kinds of memory corruption:
18133 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
18135 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
18137 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
18139 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
18143 For types associated with a Debug_Pool, dynamic allocation is performed using
18144 the standard GNAT allocation routine. References to all allocated chunks of
18145 memory are kept in an internal dictionary. Several deallocation strategies are
18146 provided, whereupon the user can choose to release the memory to the system,
18147 keep it allocated for further invalid access checks, or fill it with an easily
18148 recognizable pattern for debug sessions. The memory pattern is the old IBM
18149 hexadecimal convention: @code{16#DEADBEEF#}.
18151 See the documentation in the file g-debpoo.ads for more information on the
18152 various strategies.
18154 Upon each dereference, a check is made that the access value denotes a
18155 properly allocated memory location. Here is a complete example of use of
18156 @code{Debug_Pools}, that includes typical instances of memory corruption:
18157 @smallexample @c ada
18161 with Gnat.Io; use Gnat.Io;
18162 with Unchecked_Deallocation;
18163 with Unchecked_Conversion;
18164 with GNAT.Debug_Pools;
18165 with System.Storage_Elements;
18166 with Ada.Exceptions; use Ada.Exceptions;
18167 procedure Debug_Pool_Test is
18169 type T is access Integer;
18170 type U is access all T;
18172 P : GNAT.Debug_Pools.Debug_Pool;
18173 for T'Storage_Pool use P;
18175 procedure Free is new Unchecked_Deallocation (Integer, T);
18176 function UC is new Unchecked_Conversion (U, T);
18179 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
18189 Put_Line (Integer'Image(B.all));
18191 when E : others => Put_Line ("raised: " & Exception_Name (E));
18196 when E : others => Put_Line ("raised: " & Exception_Name (E));
18200 Put_Line (Integer'Image(B.all));
18202 when E : others => Put_Line ("raised: " & Exception_Name (E));
18207 when E : others => Put_Line ("raised: " & Exception_Name (E));
18210 end Debug_Pool_Test;
18214 The debug pool mechanism provides the following precise diagnostics on the
18215 execution of this erroneous program:
18218 Total allocated bytes : 0
18219 Total deallocated bytes : 0
18220 Current Water Mark: 0
18224 Total allocated bytes : 8
18225 Total deallocated bytes : 0
18226 Current Water Mark: 8
18229 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18230 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18231 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18232 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18234 Total allocated bytes : 8
18235 Total deallocated bytes : 4
18236 Current Water Mark: 4
18241 @node The gnatmem Tool
18242 @section The @command{gnatmem} Tool
18246 The @code{gnatmem} utility monitors dynamic allocation and
18247 deallocation activity in a program, and displays information about
18248 incorrect deallocations and possible sources of memory leaks.
18249 It provides three type of information:
18252 General information concerning memory management, such as the total
18253 number of allocations and deallocations, the amount of allocated
18254 memory and the high water mark, i.e. the largest amount of allocated
18255 memory in the course of program execution.
18258 Backtraces for all incorrect deallocations, that is to say deallocations
18259 which do not correspond to a valid allocation.
18262 Information on each allocation that is potentially the origin of a memory
18267 * Running gnatmem::
18268 * Switches for gnatmem::
18269 * Example of gnatmem Usage::
18272 @node Running gnatmem
18273 @subsection Running @code{gnatmem}
18276 @code{gnatmem} makes use of the output created by the special version of
18277 allocation and deallocation routines that record call information. This
18278 allows to obtain accurate dynamic memory usage history at a minimal cost to
18279 the execution speed. Note however, that @code{gnatmem} is not supported on
18280 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux x86,
18281 32-bit Solaris (sparc and x86) and Windows NT/2000/XP (x86).
18284 The @code{gnatmem} command has the form
18287 $ gnatmem [switches] user_program
18291 The program must have been linked with the instrumented version of the
18292 allocation and deallocation routines. This is done by linking with the
18293 @file{libgmem.a} library. For correct symbolic backtrace information,
18294 the user program should be compiled with debugging options
18295 @ref{Switches for gcc}. For example to build @file{my_program}:
18298 $ gnatmake -g my_program -largs -lgmem
18302 When running @file{my_program} the file @file{gmem.out} is produced. This file
18303 contains information about all allocations and deallocations done by the
18304 program. It is produced by the instrumented allocations and
18305 deallocations routines and will be used by @code{gnatmem}.
18308 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18309 examine. If the location of @file{gmem.out} file was not explicitly supplied by
18310 @code{-i} switch, gnatmem will assume that this file can be found in the
18311 current directory. For example, after you have executed @file{my_program},
18312 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18315 $ gnatmem my_program
18319 This will produce the output with the following format:
18321 *************** debut cc
18323 $ gnatmem my_program
18327 Total number of allocations : 45
18328 Total number of deallocations : 6
18329 Final Water Mark (non freed mem) : 11.29 Kilobytes
18330 High Water Mark : 11.40 Kilobytes
18335 Allocation Root # 2
18336 -------------------
18337 Number of non freed allocations : 11
18338 Final Water Mark (non freed mem) : 1.16 Kilobytes
18339 High Water Mark : 1.27 Kilobytes
18341 my_program.adb:23 my_program.alloc
18347 The first block of output gives general information. In this case, the
18348 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18349 Unchecked_Deallocation routine occurred.
18352 Subsequent paragraphs display information on all allocation roots.
18353 An allocation root is a specific point in the execution of the program
18354 that generates some dynamic allocation, such as a ``@code{@b{new}}''
18355 construct. This root is represented by an execution backtrace (or subprogram
18356 call stack). By default the backtrace depth for allocations roots is 1, so
18357 that a root corresponds exactly to a source location. The backtrace can
18358 be made deeper, to make the root more specific.
18360 @node Switches for gnatmem
18361 @subsection Switches for @code{gnatmem}
18364 @code{gnatmem} recognizes the following switches:
18369 @cindex @option{-q} (@code{gnatmem})
18370 Quiet. Gives the minimum output needed to identify the origin of the
18371 memory leaks. Omits statistical information.
18374 @cindex @var{N} (@code{gnatmem})
18375 N is an integer literal (usually between 1 and 10) which controls the
18376 depth of the backtraces defining allocation root. The default value for
18377 N is 1. The deeper the backtrace, the more precise the localization of
18378 the root. Note that the total number of roots can depend on this
18379 parameter. This parameter must be specified @emph{before} the name of the
18380 executable to be analyzed, to avoid ambiguity.
18383 @cindex @option{-b} (@code{gnatmem})
18384 This switch has the same effect as just depth parameter.
18386 @item -i @var{file}
18387 @cindex @option{-i} (@code{gnatmem})
18388 Do the @code{gnatmem} processing starting from @file{file}, rather than
18389 @file{gmem.out} in the current directory.
18392 @cindex @option{-m} (@code{gnatmem})
18393 This switch causes @code{gnatmem} to mask the allocation roots that have less
18394 than n leaks. The default value is 1. Specifying the value of 0 will allow to
18395 examine even the roots that didn't result in leaks.
18398 @cindex @option{-s} (@code{gnatmem})
18399 This switch causes @code{gnatmem} to sort the allocation roots according to the
18400 specified order of sort criteria, each identified by a single letter. The
18401 currently supported criteria are @code{n, h, w} standing respectively for
18402 number of unfreed allocations, high watermark, and final watermark
18403 corresponding to a specific root. The default order is @code{nwh}.
18407 @node Example of gnatmem Usage
18408 @subsection Example of @code{gnatmem} Usage
18411 The following example shows the use of @code{gnatmem}
18412 on a simple memory-leaking program.
18413 Suppose that we have the following Ada program:
18415 @smallexample @c ada
18418 with Unchecked_Deallocation;
18419 procedure Test_Gm is
18421 type T is array (1..1000) of Integer;
18422 type Ptr is access T;
18423 procedure Free is new Unchecked_Deallocation (T, Ptr);
18426 procedure My_Alloc is
18431 procedure My_DeAlloc is
18439 for I in 1 .. 5 loop
18440 for J in I .. 5 loop
18451 The program needs to be compiled with debugging option and linked with
18452 @code{gmem} library:
18455 $ gnatmake -g test_gm -largs -lgmem
18459 Then we execute the program as usual:
18466 Then @code{gnatmem} is invoked simply with
18472 which produces the following output (result may vary on different platforms):
18477 Total number of allocations : 18
18478 Total number of deallocations : 5
18479 Final Water Mark (non freed mem) : 53.00 Kilobytes
18480 High Water Mark : 56.90 Kilobytes
18482 Allocation Root # 1
18483 -------------------
18484 Number of non freed allocations : 11
18485 Final Water Mark (non freed mem) : 42.97 Kilobytes
18486 High Water Mark : 46.88 Kilobytes
18488 test_gm.adb:11 test_gm.my_alloc
18490 Allocation Root # 2
18491 -------------------
18492 Number of non freed allocations : 1
18493 Final Water Mark (non freed mem) : 10.02 Kilobytes
18494 High Water Mark : 10.02 Kilobytes
18496 s-secsta.adb:81 system.secondary_stack.ss_init
18498 Allocation Root # 3
18499 -------------------
18500 Number of non freed allocations : 1
18501 Final Water Mark (non freed mem) : 12 Bytes
18502 High Water Mark : 12 Bytes
18504 s-secsta.adb:181 system.secondary_stack.ss_init
18508 Note that the GNAT run time contains itself a certain number of
18509 allocations that have no corresponding deallocation,
18510 as shown here for root #2 and root
18511 #3. This is a normal behavior when the number of non freed allocations
18512 is one, it allocates dynamic data structures that the run time needs for
18513 the complete lifetime of the program. Note also that there is only one
18514 allocation root in the user program with a single line back trace:
18515 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
18516 program shows that 'My_Alloc' is called at 2 different points in the
18517 source (line 21 and line 24). If those two allocation roots need to be
18518 distinguished, the backtrace depth parameter can be used:
18521 $ gnatmem 3 test_gm
18525 which will give the following output:
18530 Total number of allocations : 18
18531 Total number of deallocations : 5
18532 Final Water Mark (non freed mem) : 53.00 Kilobytes
18533 High Water Mark : 56.90 Kilobytes
18535 Allocation Root # 1
18536 -------------------
18537 Number of non freed allocations : 10
18538 Final Water Mark (non freed mem) : 39.06 Kilobytes
18539 High Water Mark : 42.97 Kilobytes
18541 test_gm.adb:11 test_gm.my_alloc
18542 test_gm.adb:24 test_gm
18543 b_test_gm.c:52 main
18545 Allocation Root # 2
18546 -------------------
18547 Number of non freed allocations : 1
18548 Final Water Mark (non freed mem) : 10.02 Kilobytes
18549 High Water Mark : 10.02 Kilobytes
18551 s-secsta.adb:81 system.secondary_stack.ss_init
18552 s-secsta.adb:283 <system__secondary_stack___elabb>
18553 b_test_gm.c:33 adainit
18555 Allocation Root # 3
18556 -------------------
18557 Number of non freed allocations : 1
18558 Final Water Mark (non freed mem) : 3.91 Kilobytes
18559 High Water Mark : 3.91 Kilobytes
18561 test_gm.adb:11 test_gm.my_alloc
18562 test_gm.adb:21 test_gm
18563 b_test_gm.c:52 main
18565 Allocation Root # 4
18566 -------------------
18567 Number of non freed allocations : 1
18568 Final Water Mark (non freed mem) : 12 Bytes
18569 High Water Mark : 12 Bytes
18571 s-secsta.adb:181 system.secondary_stack.ss_init
18572 s-secsta.adb:283 <system__secondary_stack___elabb>
18573 b_test_gm.c:33 adainit
18577 The allocation root #1 of the first example has been split in 2 roots #1
18578 and #3 thanks to the more precise associated backtrace.
18582 @node Creating Sample Bodies Using gnatstub
18583 @chapter Creating Sample Bodies Using @command{gnatstub}
18587 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
18588 for library unit declarations.
18590 To create a body stub, @command{gnatstub} has to compile the library
18591 unit declaration. Therefore, bodies can be created only for legal
18592 library units. Moreover, if a library unit depends semantically upon
18593 units located outside the current directory, you have to provide
18594 the source search path when calling @command{gnatstub}, see the description
18595 of @command{gnatstub} switches below.
18598 * Running gnatstub::
18599 * Switches for gnatstub::
18602 @node Running gnatstub
18603 @section Running @command{gnatstub}
18606 @command{gnatstub} has the command-line interface of the form
18609 $ gnatstub [switches] filename [directory]
18616 is the name of the source file that contains a library unit declaration
18617 for which a body must be created. The file name may contain the path
18619 The file name does not have to follow the GNAT file name conventions. If the
18621 does not follow GNAT file naming conventions, the name of the body file must
18623 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
18624 If the file name follows the GNAT file naming
18625 conventions and the name of the body file is not provided,
18628 of the body file from the argument file name by replacing the @file{.ads}
18630 with the @file{.adb} suffix.
18633 indicates the directory in which the body stub is to be placed (the default
18638 is an optional sequence of switches as described in the next section
18641 @node Switches for gnatstub
18642 @section Switches for @command{gnatstub}
18648 @cindex @option{^-f^/FULL^} (@command{gnatstub})
18649 If the destination directory already contains a file with the name of the
18651 for the argument spec file, replace it with the generated body stub.
18653 @item ^-hs^/HEADER=SPEC^
18654 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
18655 Put the comment header (i.e., all the comments preceding the
18656 compilation unit) from the source of the library unit declaration
18657 into the body stub.
18659 @item ^-hg^/HEADER=GENERAL^
18660 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
18661 Put a sample comment header into the body stub.
18665 @cindex @option{-IDIR} (@command{gnatstub})
18667 @cindex @option{-I-} (@command{gnatstub})
18670 @item /NOCURRENT_DIRECTORY
18671 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
18673 ^These switches have ^This switch has^ the same meaning as in calls to
18675 ^They define ^It defines ^ the source search path in the call to
18676 @command{gcc} issued
18677 by @command{gnatstub} to compile an argument source file.
18679 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
18680 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
18681 This switch has the same meaning as in calls to @command{gcc}.
18682 It defines the additional configuration file to be passed to the call to
18683 @command{gcc} issued
18684 by @command{gnatstub} to compile an argument source file.
18686 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
18687 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
18688 (@var{n} is a non-negative integer). Set the maximum line length in the
18689 body stub to @var{n}; the default is 79. The maximum value that can be
18690 specified is 32767. Note that in the special case of configuration
18691 pragma files, the maximum is always 32767 regardless of whether or
18692 not this switch appears.
18694 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
18695 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
18696 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
18697 the generated body sample to @var{n}.
18698 The default indentation is 3.
18700 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
18701 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
18702 Order local bodies alphabetically. (By default local bodies are ordered
18703 in the same way as the corresponding local specs in the argument spec file.)
18705 @item ^-i^/INDENTATION=^@var{n}
18706 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
18707 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
18709 @item ^-k^/TREE_FILE=SAVE^
18710 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
18711 Do not remove the tree file (i.e., the snapshot of the compiler internal
18712 structures used by @command{gnatstub}) after creating the body stub.
18714 @item ^-l^/LINE_LENGTH=^@var{n}
18715 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
18716 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
18718 @item ^-o^/BODY=^@var{body-name}
18719 @cindex @option{^-o^/BODY^} (@command{gnatstub})
18720 Body file name. This should be set if the argument file name does not
18722 the GNAT file naming
18723 conventions. If this switch is omitted the default name for the body will be
18725 from the argument file name according to the GNAT file naming conventions.
18728 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
18729 Quiet mode: do not generate a confirmation when a body is
18730 successfully created, and do not generate a message when a body is not
18734 @item ^-r^/TREE_FILE=REUSE^
18735 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
18736 Reuse the tree file (if it exists) instead of creating it. Instead of
18737 creating the tree file for the library unit declaration, @command{gnatstub}
18738 tries to find it in the current directory and use it for creating
18739 a body. If the tree file is not found, no body is created. This option
18740 also implies @option{^-k^/SAVE^}, whether or not
18741 the latter is set explicitly.
18743 @item ^-t^/TREE_FILE=OVERWRITE^
18744 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
18745 Overwrite the existing tree file. If the current directory already
18746 contains the file which, according to the GNAT file naming rules should
18747 be considered as a tree file for the argument source file,
18749 will refuse to create the tree file needed to create a sample body
18750 unless this option is set.
18752 @item ^-v^/VERBOSE^
18753 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
18754 Verbose mode: generate version information.
18758 @node Other Utility Programs
18759 @chapter Other Utility Programs
18762 This chapter discusses some other utility programs available in the Ada
18766 * Using Other Utility Programs with GNAT::
18767 * The External Symbol Naming Scheme of GNAT::
18769 * Ada Mode for Glide::
18771 * Converting Ada Files to html with gnathtml::
18772 * Installing gnathtml::
18779 @node Using Other Utility Programs with GNAT
18780 @section Using Other Utility Programs with GNAT
18783 The object files generated by GNAT are in standard system format and in
18784 particular the debugging information uses this format. This means
18785 programs generated by GNAT can be used with existing utilities that
18786 depend on these formats.
18789 In general, any utility program that works with C will also often work with
18790 Ada programs generated by GNAT. This includes software utilities such as
18791 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
18795 @node The External Symbol Naming Scheme of GNAT
18796 @section The External Symbol Naming Scheme of GNAT
18799 In order to interpret the output from GNAT, when using tools that are
18800 originally intended for use with other languages, it is useful to
18801 understand the conventions used to generate link names from the Ada
18804 All link names are in all lowercase letters. With the exception of library
18805 procedure names, the mechanism used is simply to use the full expanded
18806 Ada name with dots replaced by double underscores. For example, suppose
18807 we have the following package spec:
18809 @smallexample @c ada
18820 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
18821 the corresponding link name is @code{qrs__mn}.
18823 Of course if a @code{pragma Export} is used this may be overridden:
18825 @smallexample @c ada
18830 pragma Export (Var1, C, External_Name => "var1_name");
18832 pragma Export (Var2, C, Link_Name => "var2_link_name");
18839 In this case, the link name for @var{Var1} is whatever link name the
18840 C compiler would assign for the C function @var{var1_name}. This typically
18841 would be either @var{var1_name} or @var{_var1_name}, depending on operating
18842 system conventions, but other possibilities exist. The link name for
18843 @var{Var2} is @var{var2_link_name}, and this is not operating system
18847 One exception occurs for library level procedures. A potential ambiguity
18848 arises between the required name @code{_main} for the C main program,
18849 and the name we would otherwise assign to an Ada library level procedure
18850 called @code{Main} (which might well not be the main program).
18852 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
18853 names. So if we have a library level procedure such as
18855 @smallexample @c ada
18858 procedure Hello (S : String);
18864 the external name of this procedure will be @var{_ada_hello}.
18867 @node Ada Mode for Glide
18868 @section Ada Mode for @code{Glide}
18869 @cindex Ada mode (for Glide)
18872 The Glide mode for programming in Ada (both Ada83 and Ada95) helps the
18873 user to understand and navigate existing code, and facilitates writing
18874 new code. It furthermore provides some utility functions for easier
18875 integration of standard Emacs features when programming in Ada.
18877 Its general features include:
18881 An Integrated Development Environment with functionality such as the
18886 ``Project files'' for configuration-specific aspects
18887 (e.g. directories and compilation options)
18890 Compiling and stepping through error messages.
18893 Running and debugging an applications within Glide.
18900 User configurability
18903 Some of the specific Ada mode features are:
18907 Functions for easy and quick stepping through Ada code
18910 Getting cross reference information for identifiers (e.g., finding a
18911 defining occurrence)
18914 Displaying an index menu of types and subprograms, allowing
18915 direct selection for browsing
18918 Automatic color highlighting of the various Ada entities
18921 Glide directly supports writing Ada code, via several facilities:
18925 Switching between spec and body files with possible
18926 autogeneration of body files
18929 Automatic formating of subprogram parameter lists
18932 Automatic indentation according to Ada syntax
18935 Automatic completion of identifiers
18938 Automatic (and configurable) casing of identifiers, keywords, and attributes
18941 Insertion of syntactic templates
18944 Block commenting / uncommenting
18948 For more information, please refer to the online documentation
18949 available in the @code{Glide} @result{} @code{Help} menu.
18952 @node Converting Ada Files to html with gnathtml
18953 @section Converting Ada Files to HTML with @code{gnathtml}
18956 This @code{Perl} script allows Ada source files to be browsed using
18957 standard Web browsers. For installation procedure, see the section
18958 @xref{Installing gnathtml}.
18960 Ada reserved keywords are highlighted in a bold font and Ada comments in
18961 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
18962 switch to suppress the generation of cross-referencing information, user
18963 defined variables and types will appear in a different color; you will
18964 be able to click on any identifier and go to its declaration.
18966 The command line is as follow:
18968 $ perl gnathtml.pl [switches] ada-files
18972 You can pass it as many Ada files as you want. @code{gnathtml} will generate
18973 an html file for every ada file, and a global file called @file{index.htm}.
18974 This file is an index of every identifier defined in the files.
18976 The available switches are the following ones :
18980 @cindex @option{-83} (@code{gnathtml})
18981 Only the subset on the Ada 83 keywords will be highlighted, not the full
18982 Ada 95 keywords set.
18984 @item -cc @var{color}
18985 @cindex @option{-cc} (@code{gnathtml})
18986 This option allows you to change the color used for comments. The default
18987 value is green. The color argument can be any name accepted by html.
18990 @cindex @option{-d} (@code{gnathtml})
18991 If the ada files depend on some other files (using for instance the
18992 @code{with} command, the latter will also be converted to html.
18993 Only the files in the user project will be converted to html, not the files
18994 in the run-time library itself.
18997 @cindex @option{-D} (@code{gnathtml})
18998 This command is the same as @option{-d} above, but @command{gnathtml} will
18999 also look for files in the run-time library, and generate html files for them.
19001 @item -ext @var{extension}
19002 @cindex @option{-ext} (@code{gnathtml})
19003 This option allows you to change the extension of the generated HTML files.
19004 If you do not specify an extension, it will default to @file{htm}.
19007 @cindex @option{-f} (@code{gnathtml})
19008 By default, gnathtml will generate html links only for global entities
19009 ('with'ed units, global variables and types,...). If you specify the
19010 @option{-f} on the command line, then links will be generated for local
19013 @item -l @var{number}
19014 @cindex @option{-l} (@code{gnathtml})
19015 If this switch is provided and @var{number} is not 0, then @code{gnathtml}
19016 will number the html files every @var{number} line.
19019 @cindex @option{-I} (@code{gnathtml})
19020 Specify a directory to search for library files (@file{.ALI} files) and
19021 source files. You can provide several -I switches on the command line,
19022 and the directories will be parsed in the order of the command line.
19025 @cindex @option{-o} (@code{gnathtml})
19026 Specify the output directory for html files. By default, gnathtml will
19027 saved the generated html files in a subdirectory named @file{html/}.
19029 @item -p @var{file}
19030 @cindex @option{-p} (@code{gnathtml})
19031 If you are using Emacs and the most recent Emacs Ada mode, which provides
19032 a full Integrated Development Environment for compiling, checking,
19033 running and debugging applications, you may use @file{.gpr} files
19034 to give the directories where Emacs can find sources and object files.
19036 Using this switch, you can tell gnathtml to use these files. This allows
19037 you to get an html version of your application, even if it is spread
19038 over multiple directories.
19040 @item -sc @var{color}
19041 @cindex @option{-sc} (@code{gnathtml})
19042 This option allows you to change the color used for symbol definitions.
19043 The default value is red. The color argument can be any name accepted by html.
19045 @item -t @var{file}
19046 @cindex @option{-t} (@code{gnathtml})
19047 This switch provides the name of a file. This file contains a list of
19048 file names to be converted, and the effect is exactly as though they had
19049 appeared explicitly on the command line. This
19050 is the recommended way to work around the command line length limit on some
19055 @node Installing gnathtml
19056 @section Installing @code{gnathtml}
19059 @code{Perl} needs to be installed on your machine to run this script.
19060 @code{Perl} is freely available for almost every architecture and
19061 Operating System via the Internet.
19063 On Unix systems, you may want to modify the first line of the script
19064 @code{gnathtml}, to explicitly tell the Operating system where Perl
19065 is. The syntax of this line is :
19067 #!full_path_name_to_perl
19071 Alternatively, you may run the script using the following command line:
19074 $ perl gnathtml.pl [switches] files
19083 The GNAT distribution provides an Ada 95 template for the Digital Language
19084 Sensitive Editor (LSE), a component of DECset. In order to
19085 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
19092 GNAT supports The Digital Performance Coverage Analyzer (PCA), a component
19093 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
19094 the collection phase with the /DEBUG qualifier.
19097 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
19098 $ DEFINE LIB$DEBUG PCA$COLLECTOR
19099 $ RUN/DEBUG <PROGRAM_NAME>
19104 @node Running and Debugging Ada Programs
19105 @chapter Running and Debugging Ada Programs
19109 This chapter discusses how to debug Ada programs.
19111 It applies to the Alpha OpenVMS platform;
19112 the debugger for Integrity OpenVMS is scheduled for a subsequent release.
19115 An incorrect Ada program may be handled in three ways by the GNAT compiler:
19119 The illegality may be a violation of the static semantics of Ada. In
19120 that case GNAT diagnoses the constructs in the program that are illegal.
19121 It is then a straightforward matter for the user to modify those parts of
19125 The illegality may be a violation of the dynamic semantics of Ada. In
19126 that case the program compiles and executes, but may generate incorrect
19127 results, or may terminate abnormally with some exception.
19130 When presented with a program that contains convoluted errors, GNAT
19131 itself may terminate abnormally without providing full diagnostics on
19132 the incorrect user program.
19136 * The GNAT Debugger GDB::
19138 * Introduction to GDB Commands::
19139 * Using Ada Expressions::
19140 * Calling User-Defined Subprograms::
19141 * Using the Next Command in a Function::
19144 * Debugging Generic Units::
19145 * GNAT Abnormal Termination or Failure to Terminate::
19146 * Naming Conventions for GNAT Source Files::
19147 * Getting Internal Debugging Information::
19148 * Stack Traceback::
19154 @node The GNAT Debugger GDB
19155 @section The GNAT Debugger GDB
19158 @code{GDB} is a general purpose, platform-independent debugger that
19159 can be used to debug mixed-language programs compiled with @command{gcc},
19160 and in particular is capable of debugging Ada programs compiled with
19161 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
19162 complex Ada data structures.
19164 The manual @cite{Debugging with GDB}
19166 , located in the GNU:[DOCS] directory,
19168 contains full details on the usage of @code{GDB}, including a section on
19169 its usage on programs. This manual should be consulted for full
19170 details. The section that follows is a brief introduction to the
19171 philosophy and use of @code{GDB}.
19173 When GNAT programs are compiled, the compiler optionally writes debugging
19174 information into the generated object file, including information on
19175 line numbers, and on declared types and variables. This information is
19176 separate from the generated code. It makes the object files considerably
19177 larger, but it does not add to the size of the actual executable that
19178 will be loaded into memory, and has no impact on run-time performance. The
19179 generation of debug information is triggered by the use of the
19180 ^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out
19181 the compilations. It is important to emphasize that the use of these
19182 options does not change the generated code.
19184 The debugging information is written in standard system formats that
19185 are used by many tools, including debuggers and profilers. The format
19186 of the information is typically designed to describe C types and
19187 semantics, but GNAT implements a translation scheme which allows full
19188 details about Ada types and variables to be encoded into these
19189 standard C formats. Details of this encoding scheme may be found in
19190 the file exp_dbug.ads in the GNAT source distribution. However, the
19191 details of this encoding are, in general, of no interest to a user,
19192 since @code{GDB} automatically performs the necessary decoding.
19194 When a program is bound and linked, the debugging information is
19195 collected from the object files, and stored in the executable image of
19196 the program. Again, this process significantly increases the size of
19197 the generated executable file, but it does not increase the size of
19198 the executable program itself. Furthermore, if this program is run in
19199 the normal manner, it runs exactly as if the debug information were
19200 not present, and takes no more actual memory.
19202 However, if the program is run under control of @code{GDB}, the
19203 debugger is activated. The image of the program is loaded, at which
19204 point it is ready to run. If a run command is given, then the program
19205 will run exactly as it would have if @code{GDB} were not present. This
19206 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
19207 entirely non-intrusive until a breakpoint is encountered. If no
19208 breakpoint is ever hit, the program will run exactly as it would if no
19209 debugger were present. When a breakpoint is hit, @code{GDB} accesses
19210 the debugging information and can respond to user commands to inspect
19211 variables, and more generally to report on the state of execution.
19215 @section Running GDB
19218 The debugger can be launched directly and simply from @code{glide} or
19219 through its graphical interface: @code{gvd}. It can also be used
19220 directly in text mode. Here is described the basic use of @code{GDB}
19221 in text mode. All the commands described below can be used in the
19222 @code{gvd} console window even though there is usually other more
19223 graphical ways to achieve the same goals.
19227 The command to run the graphical interface of the debugger is
19234 The command to run @code{GDB} in text mode is
19237 $ ^gdb program^$ GDB PROGRAM^
19241 where @code{^program^PROGRAM^} is the name of the executable file. This
19242 activates the debugger and results in a prompt for debugger commands.
19243 The simplest command is simply @code{run}, which causes the program to run
19244 exactly as if the debugger were not present. The following section
19245 describes some of the additional commands that can be given to @code{GDB}.
19247 @c *******************************
19248 @node Introduction to GDB Commands
19249 @section Introduction to GDB Commands
19252 @code{GDB} contains a large repertoire of commands. The manual
19253 @cite{Debugging with GDB}
19255 , located in the GNU:[DOCS] directory,
19257 includes extensive documentation on the use
19258 of these commands, together with examples of their use. Furthermore,
19259 the command @var{help} invoked from within @code{GDB} activates a simple help
19260 facility which summarizes the available commands and their options.
19261 In this section we summarize a few of the most commonly
19262 used commands to give an idea of what @code{GDB} is about. You should create
19263 a simple program with debugging information and experiment with the use of
19264 these @code{GDB} commands on the program as you read through the
19268 @item set args @var{arguments}
19269 The @var{arguments} list above is a list of arguments to be passed to
19270 the program on a subsequent run command, just as though the arguments
19271 had been entered on a normal invocation of the program. The @code{set args}
19272 command is not needed if the program does not require arguments.
19275 The @code{run} command causes execution of the program to start from
19276 the beginning. If the program is already running, that is to say if
19277 you are currently positioned at a breakpoint, then a prompt will ask
19278 for confirmation that you want to abandon the current execution and
19281 @item breakpoint @var{location}
19282 The breakpoint command sets a breakpoint, that is to say a point at which
19283 execution will halt and @code{GDB} will await further
19284 commands. @var{location} is
19285 either a line number within a file, given in the format @code{file:linenumber},
19286 or it is the name of a subprogram. If you request that a breakpoint be set on
19287 a subprogram that is overloaded, a prompt will ask you to specify on which of
19288 those subprograms you want to breakpoint. You can also
19289 specify that all of them should be breakpointed. If the program is run
19290 and execution encounters the breakpoint, then the program
19291 stops and @code{GDB} signals that the breakpoint was encountered by
19292 printing the line of code before which the program is halted.
19294 @item breakpoint exception @var{name}
19295 A special form of the breakpoint command which breakpoints whenever
19296 exception @var{name} is raised.
19297 If @var{name} is omitted,
19298 then a breakpoint will occur when any exception is raised.
19300 @item print @var{expression}
19301 This will print the value of the given expression. Most simple
19302 Ada expression formats are properly handled by @code{GDB}, so the expression
19303 can contain function calls, variables, operators, and attribute references.
19306 Continues execution following a breakpoint, until the next breakpoint or the
19307 termination of the program.
19310 Executes a single line after a breakpoint. If the next statement
19311 is a subprogram call, execution continues into (the first statement of)
19312 the called subprogram.
19315 Executes a single line. If this line is a subprogram call, executes and
19316 returns from the call.
19319 Lists a few lines around the current source location. In practice, it
19320 is usually more convenient to have a separate edit window open with the
19321 relevant source file displayed. Successive applications of this command
19322 print subsequent lines. The command can be given an argument which is a
19323 line number, in which case it displays a few lines around the specified one.
19326 Displays a backtrace of the call chain. This command is typically
19327 used after a breakpoint has occurred, to examine the sequence of calls that
19328 leads to the current breakpoint. The display includes one line for each
19329 activation record (frame) corresponding to an active subprogram.
19332 At a breakpoint, @code{GDB} can display the values of variables local
19333 to the current frame. The command @code{up} can be used to
19334 examine the contents of other active frames, by moving the focus up
19335 the stack, that is to say from callee to caller, one frame at a time.
19338 Moves the focus of @code{GDB} down from the frame currently being
19339 examined to the frame of its callee (the reverse of the previous command),
19341 @item frame @var{n}
19342 Inspect the frame with the given number. The value 0 denotes the frame
19343 of the current breakpoint, that is to say the top of the call stack.
19347 The above list is a very short introduction to the commands that
19348 @code{GDB} provides. Important additional capabilities, including conditional
19349 breakpoints, the ability to execute command sequences on a breakpoint,
19350 the ability to debug at the machine instruction level and many other
19351 features are described in detail in @cite{Debugging with GDB}.
19352 Note that most commands can be abbreviated
19353 (for example, c for continue, bt for backtrace).
19355 @node Using Ada Expressions
19356 @section Using Ada Expressions
19357 @cindex Ada expressions
19360 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
19361 extensions. The philosophy behind the design of this subset is
19365 That @code{GDB} should provide basic literals and access to operations for
19366 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19367 leaving more sophisticated computations to subprograms written into the
19368 program (which therefore may be called from @code{GDB}).
19371 That type safety and strict adherence to Ada language restrictions
19372 are not particularly important to the @code{GDB} user.
19375 That brevity is important to the @code{GDB} user.
19378 Thus, for brevity, the debugger acts as if there were
19379 implicit @code{with} and @code{use} clauses in effect for all user-written
19380 packages, thus making it unnecessary to fully qualify most names with
19381 their packages, regardless of context. Where this causes ambiguity,
19382 @code{GDB} asks the user's intent.
19384 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
19386 @node Calling User-Defined Subprograms
19387 @section Calling User-Defined Subprograms
19390 An important capability of @code{GDB} is the ability to call user-defined
19391 subprograms while debugging. This is achieved simply by entering
19392 a subprogram call statement in the form:
19395 call subprogram-name (parameters)
19399 The keyword @code{call} can be omitted in the normal case where the
19400 @code{subprogram-name} does not coincide with any of the predefined
19401 @code{GDB} commands.
19403 The effect is to invoke the given subprogram, passing it the
19404 list of parameters that is supplied. The parameters can be expressions and
19405 can include variables from the program being debugged. The
19406 subprogram must be defined
19407 at the library level within your program, and @code{GDB} will call the
19408 subprogram within the environment of your program execution (which
19409 means that the subprogram is free to access or even modify variables
19410 within your program).
19412 The most important use of this facility is in allowing the inclusion of
19413 debugging routines that are tailored to particular data structures
19414 in your program. Such debugging routines can be written to provide a suitably
19415 high-level description of an abstract type, rather than a low-level dump
19416 of its physical layout. After all, the standard
19417 @code{GDB print} command only knows the physical layout of your
19418 types, not their abstract meaning. Debugging routines can provide information
19419 at the desired semantic level and are thus enormously useful.
19421 For example, when debugging GNAT itself, it is crucial to have access to
19422 the contents of the tree nodes used to represent the program internally.
19423 But tree nodes are represented simply by an integer value (which in turn
19424 is an index into a table of nodes).
19425 Using the @code{print} command on a tree node would simply print this integer
19426 value, which is not very useful. But the PN routine (defined in file
19427 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19428 a useful high level representation of the tree node, which includes the
19429 syntactic category of the node, its position in the source, the integers
19430 that denote descendant nodes and parent node, as well as varied
19431 semantic information. To study this example in more detail, you might want to
19432 look at the body of the PN procedure in the stated file.
19434 @node Using the Next Command in a Function
19435 @section Using the Next Command in a Function
19438 When you use the @code{next} command in a function, the current source
19439 location will advance to the next statement as usual. A special case
19440 arises in the case of a @code{return} statement.
19442 Part of the code for a return statement is the ``epilog'' of the function.
19443 This is the code that returns to the caller. There is only one copy of
19444 this epilog code, and it is typically associated with the last return
19445 statement in the function if there is more than one return. In some
19446 implementations, this epilog is associated with the first statement
19449 The result is that if you use the @code{next} command from a return
19450 statement that is not the last return statement of the function you
19451 may see a strange apparent jump to the last return statement or to
19452 the start of the function. You should simply ignore this odd jump.
19453 The value returned is always that from the first return statement
19454 that was stepped through.
19456 @node Ada Exceptions
19457 @section Breaking on Ada Exceptions
19461 You can set breakpoints that trip when your program raises
19462 selected exceptions.
19465 @item break exception
19466 Set a breakpoint that trips whenever (any task in the) program raises
19469 @item break exception @var{name}
19470 Set a breakpoint that trips whenever (any task in the) program raises
19471 the exception @var{name}.
19473 @item break exception unhandled
19474 Set a breakpoint that trips whenever (any task in the) program raises an
19475 exception for which there is no handler.
19477 @item info exceptions
19478 @itemx info exceptions @var{regexp}
19479 The @code{info exceptions} command permits the user to examine all defined
19480 exceptions within Ada programs. With a regular expression, @var{regexp}, as
19481 argument, prints out only those exceptions whose name matches @var{regexp}.
19489 @code{GDB} allows the following task-related commands:
19493 This command shows a list of current Ada tasks, as in the following example:
19500 ID TID P-ID Thread Pri State Name
19501 1 8088000 0 807e000 15 Child Activation Wait main_task
19502 2 80a4000 1 80ae000 15 Accept/Select Wait b
19503 3 809a800 1 80a4800 15 Child Activation Wait a
19504 * 4 80ae800 3 80b8000 15 Running c
19508 In this listing, the asterisk before the first task indicates it to be the
19509 currently running task. The first column lists the task ID that is used
19510 to refer to tasks in the following commands.
19512 @item break @var{linespec} task @var{taskid}
19513 @itemx break @var{linespec} task @var{taskid} if @dots{}
19514 @cindex Breakpoints and tasks
19515 These commands are like the @code{break @dots{} thread @dots{}}.
19516 @var{linespec} specifies source lines.
19518 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
19519 to specify that you only want @code{GDB} to stop the program when a
19520 particular Ada task reaches this breakpoint. @var{taskid} is one of the
19521 numeric task identifiers assigned by @code{GDB}, shown in the first
19522 column of the @samp{info tasks} display.
19524 If you do not specify @samp{task @var{taskid}} when you set a
19525 breakpoint, the breakpoint applies to @emph{all} tasks of your
19528 You can use the @code{task} qualifier on conditional breakpoints as
19529 well; in this case, place @samp{task @var{taskid}} before the
19530 breakpoint condition (before the @code{if}).
19532 @item task @var{taskno}
19533 @cindex Task switching
19535 This command allows to switch to the task referred by @var{taskno}. In
19536 particular, This allows to browse the backtrace of the specified
19537 task. It is advised to switch back to the original task before
19538 continuing execution otherwise the scheduling of the program may be
19543 For more detailed information on the tasking support,
19544 see @cite{Debugging with GDB}.
19546 @node Debugging Generic Units
19547 @section Debugging Generic Units
19548 @cindex Debugging Generic Units
19552 GNAT always uses code expansion for generic instantiation. This means that
19553 each time an instantiation occurs, a complete copy of the original code is
19554 made, with appropriate substitutions of formals by actuals.
19556 It is not possible to refer to the original generic entities in
19557 @code{GDB}, but it is always possible to debug a particular instance of
19558 a generic, by using the appropriate expanded names. For example, if we have
19560 @smallexample @c ada
19565 generic package k is
19566 procedure kp (v1 : in out integer);
19570 procedure kp (v1 : in out integer) is
19576 package k1 is new k;
19577 package k2 is new k;
19579 var : integer := 1;
19592 Then to break on a call to procedure kp in the k2 instance, simply
19596 (gdb) break g.k2.kp
19600 When the breakpoint occurs, you can step through the code of the
19601 instance in the normal manner and examine the values of local variables, as for
19604 @node GNAT Abnormal Termination or Failure to Terminate
19605 @section GNAT Abnormal Termination or Failure to Terminate
19606 @cindex GNAT Abnormal Termination or Failure to Terminate
19609 When presented with programs that contain serious errors in syntax
19611 GNAT may on rare occasions experience problems in operation, such
19613 segmentation fault or illegal memory access, raising an internal
19614 exception, terminating abnormally, or failing to terminate at all.
19615 In such cases, you can activate
19616 various features of GNAT that can help you pinpoint the construct in your
19617 program that is the likely source of the problem.
19619 The following strategies are presented in increasing order of
19620 difficulty, corresponding to your experience in using GNAT and your
19621 familiarity with compiler internals.
19625 Run @command{gcc} with the @option{-gnatf}. This first
19626 switch causes all errors on a given line to be reported. In its absence,
19627 only the first error on a line is displayed.
19629 The @option{-gnatdO} switch causes errors to be displayed as soon as they
19630 are encountered, rather than after compilation is terminated. If GNAT
19631 terminates prematurely or goes into an infinite loop, the last error
19632 message displayed may help to pinpoint the culprit.
19635 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
19636 mode, @command{gcc} produces ongoing information about the progress of the
19637 compilation and provides the name of each procedure as code is
19638 generated. This switch allows you to find which Ada procedure was being
19639 compiled when it encountered a code generation problem.
19642 @cindex @option{-gnatdc} switch
19643 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
19644 switch that does for the front-end what @option{^-v^VERBOSE^} does
19645 for the back end. The system prints the name of each unit,
19646 either a compilation unit or nested unit, as it is being analyzed.
19648 Finally, you can start
19649 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19650 front-end of GNAT, and can be run independently (normally it is just
19651 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
19652 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
19653 @code{where} command is the first line of attack; the variable
19654 @code{lineno} (seen by @code{print lineno}), used by the second phase of
19655 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
19656 which the execution stopped, and @code{input_file name} indicates the name of
19660 @node Naming Conventions for GNAT Source Files
19661 @section Naming Conventions for GNAT Source Files
19664 In order to examine the workings of the GNAT system, the following
19665 brief description of its organization may be helpful:
19669 Files with prefix @file{^sc^SC^} contain the lexical scanner.
19672 All files prefixed with @file{^par^PAR^} are components of the parser. The
19673 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
19674 parsing of select statements can be found in @file{par-ch9.adb}.
19677 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
19678 numbers correspond to chapters of the Ada standard. For example, all
19679 issues involving context clauses can be found in @file{sem_ch10.adb}. In
19680 addition, some features of the language require sufficient special processing
19681 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19682 dynamic dispatching, etc.
19685 All files prefixed with @file{^exp^EXP^} perform normalization and
19686 expansion of the intermediate representation (abstract syntax tree, or AST).
19687 these files use the same numbering scheme as the parser and semantics files.
19688 For example, the construction of record initialization procedures is done in
19689 @file{exp_ch3.adb}.
19692 The files prefixed with @file{^bind^BIND^} implement the binder, which
19693 verifies the consistency of the compilation, determines an order of
19694 elaboration, and generates the bind file.
19697 The files @file{atree.ads} and @file{atree.adb} detail the low-level
19698 data structures used by the front-end.
19701 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
19702 the abstract syntax tree as produced by the parser.
19705 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
19706 all entities, computed during semantic analysis.
19709 Library management issues are dealt with in files with prefix
19715 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
19716 defined in Annex A.
19721 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
19722 defined in Annex B.
19726 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
19727 both language-defined children and GNAT run-time routines.
19731 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
19732 general-purpose packages, fully documented in their specifications. All
19733 the other @file{.c} files are modifications of common @command{gcc} files.
19736 @node Getting Internal Debugging Information
19737 @section Getting Internal Debugging Information
19740 Most compilers have internal debugging switches and modes. GNAT
19741 does also, except GNAT internal debugging switches and modes are not
19742 secret. A summary and full description of all the compiler and binder
19743 debug flags are in the file @file{debug.adb}. You must obtain the
19744 sources of the compiler to see the full detailed effects of these flags.
19746 The switches that print the source of the program (reconstructed from
19747 the internal tree) are of general interest for user programs, as are the
19749 the full internal tree, and the entity table (the symbol table
19750 information). The reconstructed source provides a readable version of the
19751 program after the front-end has completed analysis and expansion,
19752 and is useful when studying the performance of specific constructs.
19753 For example, constraint checks are indicated, complex aggregates
19754 are replaced with loops and assignments, and tasking primitives
19755 are replaced with run-time calls.
19757 @node Stack Traceback
19758 @section Stack Traceback
19760 @cindex stack traceback
19761 @cindex stack unwinding
19764 Traceback is a mechanism to display the sequence of subprogram calls that
19765 leads to a specified execution point in a program. Often (but not always)
19766 the execution point is an instruction at which an exception has been raised.
19767 This mechanism is also known as @i{stack unwinding} because it obtains
19768 its information by scanning the run-time stack and recovering the activation
19769 records of all active subprograms. Stack unwinding is one of the most
19770 important tools for program debugging.
19772 The first entry stored in traceback corresponds to the deepest calling level,
19773 that is to say the subprogram currently executing the instruction
19774 from which we want to obtain the traceback.
19776 Note that there is no runtime performance penalty when stack traceback
19777 is enabled, and no exception is raised during program execution.
19780 * Non-Symbolic Traceback::
19781 * Symbolic Traceback::
19784 @node Non-Symbolic Traceback
19785 @subsection Non-Symbolic Traceback
19786 @cindex traceback, non-symbolic
19789 Note: this feature is not supported on all platforms. See
19790 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
19794 * Tracebacks From an Unhandled Exception::
19795 * Tracebacks From Exception Occurrences (non-symbolic)::
19796 * Tracebacks From Anywhere in a Program (non-symbolic)::
19799 @node Tracebacks From an Unhandled Exception
19800 @subsubsection Tracebacks From an Unhandled Exception
19803 A runtime non-symbolic traceback is a list of addresses of call instructions.
19804 To enable this feature you must use the @option{-E}
19805 @code{gnatbind}'s option. With this option a stack traceback is stored as part
19806 of exception information. You can retrieve this information using the
19807 @code{addr2line} tool.
19809 Here is a simple example:
19811 @smallexample @c ada
19817 raise Constraint_Error;
19832 $ gnatmake stb -bargs -E
19835 Execution terminated by unhandled exception
19836 Exception name: CONSTRAINT_ERROR
19838 Call stack traceback locations:
19839 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19843 As we see the traceback lists a sequence of addresses for the unhandled
19844 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19845 guess that this exception come from procedure P1. To translate these
19846 addresses into the source lines where the calls appear, the
19847 @code{addr2line} tool, described below, is invaluable. The use of this tool
19848 requires the program to be compiled with debug information.
19851 $ gnatmake -g stb -bargs -E
19854 Execution terminated by unhandled exception
19855 Exception name: CONSTRAINT_ERROR
19857 Call stack traceback locations:
19858 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19860 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19861 0x4011f1 0x77e892a4
19863 00401373 at d:/stb/stb.adb:5
19864 0040138B at d:/stb/stb.adb:10
19865 0040139C at d:/stb/stb.adb:14
19866 00401335 at d:/stb/b~stb.adb:104
19867 004011C4 at /build/.../crt1.c:200
19868 004011F1 at /build/.../crt1.c:222
19869 77E892A4 in ?? at ??:0
19873 The @code{addr2line} tool has several other useful options:
19877 to get the function name corresponding to any location
19879 @item --demangle=gnat
19880 to use the gnat decoding mode for the function names. Note that
19881 for binutils version 2.9.x the option is simply @option{--demangle}.
19885 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
19886 0x40139c 0x401335 0x4011c4 0x4011f1
19888 00401373 in stb.p1 at d:/stb/stb.adb:5
19889 0040138B in stb.p2 at d:/stb/stb.adb:10
19890 0040139C in stb at d:/stb/stb.adb:14
19891 00401335 in main at d:/stb/b~stb.adb:104
19892 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
19893 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
19897 From this traceback we can see that the exception was raised in
19898 @file{stb.adb} at line 5, which was reached from a procedure call in
19899 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
19900 which contains the call to the main program.
19901 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
19902 and the output will vary from platform to platform.
19904 It is also possible to use @code{GDB} with these traceback addresses to debug
19905 the program. For example, we can break at a given code location, as reported
19906 in the stack traceback:
19912 Furthermore, this feature is not implemented inside Windows DLL. Only
19913 the non-symbolic traceback is reported in this case.
19916 (gdb) break *0x401373
19917 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19921 It is important to note that the stack traceback addresses
19922 do not change when debug information is included. This is particularly useful
19923 because it makes it possible to release software without debug information (to
19924 minimize object size), get a field report that includes a stack traceback
19925 whenever an internal bug occurs, and then be able to retrieve the sequence
19926 of calls with the same program compiled with debug information.
19928 @node Tracebacks From Exception Occurrences (non-symbolic)
19929 @subsubsection Tracebacks From Exception Occurrences
19932 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
19933 The stack traceback is attached to the exception information string, and can
19934 be retrieved in an exception handler within the Ada program, by means of the
19935 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19937 @smallexample @c ada
19939 with Ada.Exceptions;
19944 use Ada.Exceptions;
19952 Text_IO.Put_Line (Exception_Information (E));
19966 This program will output:
19971 Exception name: CONSTRAINT_ERROR
19972 Message: stb.adb:12
19973 Call stack traceback locations:
19974 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19977 @node Tracebacks From Anywhere in a Program (non-symbolic)
19978 @subsubsection Tracebacks From Anywhere in a Program
19981 It is also possible to retrieve a stack traceback from anywhere in a
19982 program. For this you need to
19983 use the @code{GNAT.Traceback} API. This package includes a procedure called
19984 @code{Call_Chain} that computes a complete stack traceback, as well as useful
19985 display procedures described below. It is not necessary to use the
19986 @option{-E gnatbind} option in this case, because the stack traceback mechanism
19987 is invoked explicitly.
19990 In the following example we compute a traceback at a specific location in
19991 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
19992 convert addresses to strings:
19994 @smallexample @c ada
19996 with GNAT.Traceback;
19997 with GNAT.Debug_Utilities;
20003 use GNAT.Traceback;
20006 TB : Tracebacks_Array (1 .. 10);
20007 -- We are asking for a maximum of 10 stack frames.
20009 -- Len will receive the actual number of stack frames returned.
20011 Call_Chain (TB, Len);
20013 Text_IO.Put ("In STB.P1 : ");
20015 for K in 1 .. Len loop
20016 Text_IO.Put (Debug_Utilities.Image (TB (K)));
20037 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
20038 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
20042 You can then get further information by invoking the @code{addr2line}
20043 tool as described earlier (note that the hexadecimal addresses
20044 need to be specified in C format, with a leading ``0x'').
20046 @node Symbolic Traceback
20047 @subsection Symbolic Traceback
20048 @cindex traceback, symbolic
20051 A symbolic traceback is a stack traceback in which procedure names are
20052 associated with each code location.
20055 Note that this feature is not supported on all platforms. See
20056 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
20057 list of currently supported platforms.
20060 Note that the symbolic traceback requires that the program be compiled
20061 with debug information. If it is not compiled with debug information
20062 only the non-symbolic information will be valid.
20065 * Tracebacks From Exception Occurrences (symbolic)::
20066 * Tracebacks From Anywhere in a Program (symbolic)::
20069 @node Tracebacks From Exception Occurrences (symbolic)
20070 @subsubsection Tracebacks From Exception Occurrences
20072 @smallexample @c ada
20074 with GNAT.Traceback.Symbolic;
20080 raise Constraint_Error;
20097 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
20102 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
20105 0040149F in stb.p1 at stb.adb:8
20106 004014B7 in stb.p2 at stb.adb:13
20107 004014CF in stb.p3 at stb.adb:18
20108 004015DD in ada.stb at stb.adb:22
20109 00401461 in main at b~stb.adb:168
20110 004011C4 in __mingw_CRTStartup at crt1.c:200
20111 004011F1 in mainCRTStartup at crt1.c:222
20112 77E892A4 in ?? at ??:0
20116 In the above example the ``.\'' syntax in the @command{gnatmake} command
20117 is currently required by @command{addr2line} for files that are in
20118 the current working directory.
20119 Moreover, the exact sequence of linker options may vary from platform
20121 The above @option{-largs} section is for Windows platforms. By contrast,
20122 under Unix there is no need for the @option{-largs} section.
20123 Differences across platforms are due to details of linker implementation.
20125 @node Tracebacks From Anywhere in a Program (symbolic)
20126 @subsubsection Tracebacks From Anywhere in a Program
20129 It is possible to get a symbolic stack traceback
20130 from anywhere in a program, just as for non-symbolic tracebacks.
20131 The first step is to obtain a non-symbolic
20132 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
20133 information. Here is an example:
20135 @smallexample @c ada
20137 with GNAT.Traceback;
20138 with GNAT.Traceback.Symbolic;
20143 use GNAT.Traceback;
20144 use GNAT.Traceback.Symbolic;
20147 TB : Tracebacks_Array (1 .. 10);
20148 -- We are asking for a maximum of 10 stack frames.
20150 -- Len will receive the actual number of stack frames returned.
20152 Call_Chain (TB, Len);
20153 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20167 @node Compatibility with DEC Ada
20168 @chapter Compatibility with DEC Ada
20169 @cindex Compatibility
20172 This section of the manual compares DEC Ada for OpenVMS Alpha and GNAT
20173 OpenVMS Alpha. GNAT achieves a high level of compatibility
20174 with DEC Ada, and it should generally be straightforward to port code
20175 from the DEC Ada environment to GNAT. However, there are a few language
20176 and implementation differences of which the user must be aware. These
20177 differences are discussed in this section. In
20178 addition, the operating environment and command structure for the
20179 compiler are different, and these differences are also discussed.
20181 Note that this discussion addresses specifically the implementation
20182 of Ada 83 for DIGITAL OpenVMS Alpha Systems. In cases where the implementation
20183 of DEC Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
20184 GNAT always follows the Alpha implementation.
20187 * Ada 95 Compatibility::
20188 * Differences in the Definition of Package System::
20189 * Language-Related Features::
20190 * The Package STANDARD::
20191 * The Package SYSTEM::
20192 * Tasking and Task-Related Features::
20193 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
20194 * Pragmas and Pragma-Related Features::
20195 * Library of Predefined Units::
20197 * Main Program Definition::
20198 * Implementation-Defined Attributes::
20199 * Compiler and Run-Time Interfacing::
20200 * Program Compilation and Library Management::
20202 * Implementation Limits::
20206 @node Ada 95 Compatibility
20207 @section Ada 95 Compatibility
20210 GNAT is an Ada 95 compiler, and DEC Ada is an Ada 83
20211 compiler. Ada 95 is almost completely upwards compatible
20212 with Ada 83, and therefore Ada 83 programs will compile
20213 and run under GNAT with
20214 no changes or only minor changes. The Ada 95 Reference
20215 Manual (ANSI/ISO/IEC-8652:1995) provides details on specific
20218 GNAT provides the switch /83 on the GNAT COMPILE command,
20219 as well as the pragma ADA_83, to force the compiler to
20220 operate in Ada 83 mode. This mode does not guarantee complete
20221 conformance to Ada 83, but in practice is sufficient to
20222 eliminate most sources of incompatibilities.
20223 In particular, it eliminates the recognition of the
20224 additional Ada 95 keywords, so that their use as identifiers
20225 in Ada83 program is legal, and handles the cases of packages
20226 with optional bodies, and generics that instantiate unconstrained
20227 types without the use of @code{(<>)}.
20229 @node Differences in the Definition of Package System
20230 @section Differences in the Definition of Package System
20233 Both the Ada 95 and Ada 83 reference manuals permit a compiler to add
20234 implementation-dependent declarations to package System. In normal mode,
20235 GNAT does not take advantage of this permission, and the version of System
20236 provided by GNAT exactly matches that in the Ada 95 Reference Manual.
20238 However, DEC Ada adds an extensive set of declarations to package System,
20239 as fully documented in the DEC Ada manuals. To minimize changes required
20240 for programs that make use of these extensions, GNAT provides the pragma
20241 Extend_System for extending the definition of package System. By using:
20243 @smallexample @c ada
20246 pragma Extend_System (Aux_DEC);
20252 The set of definitions in System is extended to include those in package
20253 @code{System.Aux_DEC}.
20254 These definitions are incorporated directly into package
20255 System, as though they had been declared there in the first place. For a
20256 list of the declarations added, see the specification of this package,
20257 which can be found in the file @code{s-auxdec.ads} in the GNAT library.
20258 The pragma Extend_System is a configuration pragma, which means that
20259 it can be placed in the file @file{gnat.adc}, so that it will automatically
20260 apply to all subsequent compilations. See the section on Configuration
20261 Pragmas for further details.
20263 An alternative approach that avoids the use of the non-standard
20264 Extend_System pragma is to add a context clause to the unit that
20265 references these facilities:
20267 @smallexample @c ada
20270 with System.Aux_DEC;
20271 use System.Aux_DEC;
20277 The effect is not quite semantically identical to incorporating
20278 the declarations directly into package @code{System},
20279 but most programs will not notice a difference
20280 unless they use prefix notation (e.g. @code{System.Integer_8})
20282 entities directly in package @code{System}.
20283 For units containing such references,
20284 the prefixes must either be removed, or the pragma @code{Extend_System}
20287 @node Language-Related Features
20288 @section Language-Related Features
20291 The following sections highlight differences in types,
20292 representations of types, operations, alignment, and
20296 * Integer Types and Representations::
20297 * Floating-Point Types and Representations::
20298 * Pragmas Float_Representation and Long_Float::
20299 * Fixed-Point Types and Representations::
20300 * Record and Array Component Alignment::
20301 * Address Clauses::
20302 * Other Representation Clauses::
20305 @node Integer Types and Representations
20306 @subsection Integer Types and Representations
20309 The set of predefined integer types is identical in DEC Ada and GNAT.
20310 Furthermore the representation of these integer types is also identical,
20311 including the capability of size clauses forcing biased representation.
20314 DEC Ada for OpenVMS Alpha systems has defined the
20315 following additional integer types in package System:
20336 When using GNAT, the first four of these types may be obtained from the
20337 standard Ada 95 package @code{Interfaces}.
20338 Alternatively, by use of the pragma
20339 @code{Extend_System}, identical
20340 declarations can be referenced directly in package @code{System}.
20341 On both GNAT and DEC Ada, the maximum integer size is 64 bits.
20343 @node Floating-Point Types and Representations
20344 @subsection Floating-Point Types and Representations
20345 @cindex Floating-Point types
20348 The set of predefined floating-point types is identical in DEC Ada and GNAT.
20349 Furthermore the representation of these floating-point
20350 types is also identical. One important difference is that the default
20351 representation for DEC Ada is VAX_Float, but the default representation
20354 Specific types may be declared to be VAX_Float or IEEE, using the pragma
20355 @code{Float_Representation} as described in the DEC Ada documentation.
20356 For example, the declarations:
20358 @smallexample @c ada
20361 type F_Float is digits 6;
20362 pragma Float_Representation (VAX_Float, F_Float);
20368 declare a type F_Float that will be represented in VAX_Float format.
20369 This set of declarations actually appears in System.Aux_DEC, which provides
20370 the full set of additional floating-point declarations provided in
20371 the DEC Ada version of package
20372 System. This and similar declarations may be accessed in a user program
20373 by using pragma @code{Extend_System}. The use of this
20374 pragma, and the related pragma @code{Long_Float} is described in further
20375 detail in the following section.
20377 @node Pragmas Float_Representation and Long_Float
20378 @subsection Pragmas Float_Representation and Long_Float
20381 DEC Ada provides the pragma @code{Float_Representation}, which
20382 acts as a program library switch to allow control over
20383 the internal representation chosen for the predefined
20384 floating-point types declared in the package @code{Standard}.
20385 The format of this pragma is as follows:
20390 @b{pragma} @code{Float_Representation}(VAX_Float | IEEE_Float);
20396 This pragma controls the representation of floating-point
20401 @code{VAX_Float} specifies that floating-point
20402 types are represented by default with the VAX hardware types
20403 F-floating, D-floating, G-floating. Note that the H-floating
20404 type is available only on DIGITAL Vax systems, and is not available
20405 in either DEC Ada or GNAT for Alpha systems.
20408 @code{IEEE_Float} specifies that floating-point
20409 types are represented by default with the IEEE single and
20410 double floating-point types.
20414 GNAT provides an identical implementation of the pragma
20415 @code{Float_Representation}, except that it functions as a
20416 configuration pragma, as defined by Ada 95. Note that the
20417 notion of configuration pragma corresponds closely to the
20418 DEC Ada notion of a program library switch.
20420 When no pragma is used in GNAT, the default is IEEE_Float, which is different
20421 from DEC Ada 83, where the default is VAX_Float. In addition, the
20422 predefined libraries in GNAT are built using IEEE_Float, so it is not
20423 advisable to change the format of numbers passed to standard library
20424 routines, and if necessary explicit type conversions may be needed.
20426 The use of IEEE_Float is recommended in GNAT since it is more efficient,
20427 and (given that it conforms to an international standard) potentially more
20428 portable. The situation in which VAX_Float may be useful is in interfacing
20429 to existing code and data that expects the use of VAX_Float. There are
20430 two possibilities here. If the requirement for the use of VAX_Float is
20431 localized, then the best approach is to use the predefined VAX_Float
20432 types in package @code{System}, as extended by
20433 @code{Extend_System}. For example, use @code{System.F_Float}
20434 to specify the 32-bit @code{F-Float} format.
20436 Alternatively, if an entire program depends heavily on the use of
20437 the @code{VAX_Float} and in particular assumes that the types in
20438 package @code{Standard} are in @code{Vax_Float} format, then it
20439 may be desirable to reconfigure GNAT to assume Vax_Float by default.
20440 This is done by using the GNAT LIBRARY command to rebuild the library, and
20441 then using the general form of the @code{Float_Representation}
20442 pragma to ensure that this default format is used throughout.
20443 The form of the GNAT LIBRARY command is:
20446 GNAT LIBRARY /CONFIG=@i{file} /CREATE=@i{directory}
20450 where @i{file} contains the new configuration pragmas
20451 and @i{directory} is the directory to be created to contain
20455 On OpenVMS systems, DEC Ada provides the pragma @code{Long_Float}
20456 to allow control over the internal representation chosen
20457 for the predefined type @code{Long_Float} and for floating-point
20458 type declarations with digits specified in the range 7 .. 15.
20459 The format of this pragma is as follows:
20461 @smallexample @c ada
20463 pragma Long_Float (D_FLOAT | G_FLOAT);
20467 @node Fixed-Point Types and Representations
20468 @subsection Fixed-Point Types and Representations
20471 On DEC Ada for OpenVMS Alpha systems, rounding is
20472 away from zero for both positive and negative numbers.
20473 Therefore, +0.5 rounds to 1 and -0.5 rounds to -1.
20475 On GNAT for OpenVMS Alpha, the results of operations
20476 on fixed-point types are in accordance with the Ada 95
20477 rules. In particular, results of operations on decimal
20478 fixed-point types are truncated.
20480 @node Record and Array Component Alignment
20481 @subsection Record and Array Component Alignment
20484 On DEC Ada for OpenVMS Alpha, all non composite components
20485 are aligned on natural boundaries. For example, 1-byte
20486 components are aligned on byte boundaries, 2-byte
20487 components on 2-byte boundaries, 4-byte components on 4-byte
20488 byte boundaries, and so on. The OpenVMS Alpha hardware
20489 runs more efficiently with naturally aligned data.
20491 ON GNAT for OpenVMS Alpha, alignment rules are compatible
20492 with DEC Ada for OpenVMS Alpha.
20494 @node Address Clauses
20495 @subsection Address Clauses
20498 In DEC Ada and GNAT, address clauses are supported for
20499 objects and imported subprograms.
20500 The predefined type @code{System.Address} is a private type
20501 in both compilers, with the same representation (it is simply
20502 a machine pointer). Addition, subtraction, and comparison
20503 operations are available in the standard Ada 95 package
20504 @code{System.Storage_Elements}, or in package @code{System}
20505 if it is extended to include @code{System.Aux_DEC} using a
20506 pragma @code{Extend_System} as previously described.
20508 Note that code that with's both this extended package @code{System}
20509 and the package @code{System.Storage_Elements} should not @code{use}
20510 both packages, or ambiguities will result. In general it is better
20511 not to mix these two sets of facilities. The Ada 95 package was
20512 designed specifically to provide the kind of features that DEC Ada
20513 adds directly to package @code{System}.
20515 GNAT is compatible with DEC Ada in its handling of address
20516 clauses, except for some limitations in
20517 the form of address clauses for composite objects with
20518 initialization. Such address clauses are easily replaced
20519 by the use of an explicitly-defined constant as described
20520 in the Ada 95 Reference Manual (13.1(22)). For example, the sequence
20523 @smallexample @c ada
20525 X, Y : Integer := Init_Func;
20526 Q : String (X .. Y) := "abc";
20528 for Q'Address use Compute_Address;
20533 will be rejected by GNAT, since the address cannot be computed at the time
20534 that Q is declared. To achieve the intended effect, write instead:
20536 @smallexample @c ada
20539 X, Y : Integer := Init_Func;
20540 Q_Address : constant Address := Compute_Address;
20541 Q : String (X .. Y) := "abc";
20543 for Q'Address use Q_Address;
20549 which will be accepted by GNAT (and other Ada 95 compilers), and is also
20550 backwards compatible with Ada 83. A fuller description of the restrictions
20551 on address specifications is found in the GNAT Reference Manual.
20553 @node Other Representation Clauses
20554 @subsection Other Representation Clauses
20557 GNAT supports in a compatible manner all the representation
20558 clauses supported by DEC Ada. In addition, it
20559 supports representation clause forms that are new in Ada 95
20560 including COMPONENT_SIZE and SIZE clauses for objects.
20562 @node The Package STANDARD
20563 @section The Package STANDARD
20566 The package STANDARD, as implemented by DEC Ada, is fully
20567 described in the Reference Manual for the Ada Programming
20568 Language (ANSI/MIL-STD-1815A-1983) and in the DEC Ada
20569 Language Reference Manual. As implemented by GNAT, the
20570 package STANDARD is described in the Ada 95 Reference
20573 In addition, DEC Ada supports the Latin-1 character set in
20574 the type CHARACTER. GNAT supports the Latin-1 character set
20575 in the type CHARACTER and also Unicode (ISO 10646 BMP) in
20576 the type WIDE_CHARACTER.
20578 The floating-point types supported by GNAT are those
20579 supported by DEC Ada, but defaults are different, and are controlled by
20580 pragmas. See @ref{Floating-Point Types and Representations} for details.
20582 @node The Package SYSTEM
20583 @section The Package SYSTEM
20586 DEC Ada provides a system-specific version of the package
20587 SYSTEM for each platform on which the language ships.
20588 For the complete specification of the package SYSTEM, see
20589 Appendix F of the DEC Ada Language Reference Manual.
20591 On DEC Ada, the package SYSTEM includes the following conversion functions:
20593 @item TO_ADDRESS(INTEGER)
20595 @item TO_ADDRESS(UNSIGNED_LONGWORD)
20597 @item TO_ADDRESS(universal_integer)
20599 @item TO_INTEGER(ADDRESS)
20601 @item TO_UNSIGNED_LONGWORD(ADDRESS)
20603 @item Function IMPORT_VALUE return UNSIGNED_LONGWORD and the
20604 functions IMPORT_ADDRESS and IMPORT_LARGEST_VALUE
20608 By default, GNAT supplies a version of SYSTEM that matches
20609 the definition given in the Ada 95 Reference Manual.
20611 is a subset of the DIGITAL system definitions, which is as
20612 close as possible to the original definitions. The only difference
20613 is that the definition of SYSTEM_NAME is different:
20615 @smallexample @c ada
20618 type Name is (SYSTEM_NAME_GNAT);
20619 System_Name : constant Name := SYSTEM_NAME_GNAT;
20625 Also, GNAT adds the new Ada 95 declarations for
20626 BIT_ORDER and DEFAULT_BIT_ORDER.
20628 However, the use of the following pragma causes GNAT
20629 to extend the definition of package SYSTEM so that it
20630 encompasses the full set of DIGITAL-specific extensions,
20631 including the functions listed above:
20633 @smallexample @c ada
20635 pragma Extend_System (Aux_DEC);
20640 The pragma Extend_System is a configuration pragma that
20641 is most conveniently placed in the @file{gnat.adc} file. See the
20642 GNAT Reference Manual for further details.
20644 DEC Ada does not allow the recompilation of the package
20645 SYSTEM. Instead DEC Ada provides several pragmas (SYSTEM_
20646 NAME, STORAGE_UNIT, and MEMORY_SIZE) to modify values in
20647 the package SYSTEM. On OpenVMS Alpha systems, the pragma
20648 SYSTEM_NAME takes the enumeration literal OPENVMS_AXP as
20649 its single argument.
20651 GNAT does permit the recompilation of package SYSTEM using
20652 a special switch (@option{-gnatg}) and this switch can be used if
20653 it is necessary to modify the definitions in SYSTEM. GNAT does
20654 not permit the specification of SYSTEM_NAME, STORAGE_UNIT
20655 or MEMORY_SIZE by any other means.
20657 On GNAT systems, the pragma SYSTEM_NAME takes the
20658 enumeration literal SYSTEM_NAME_GNAT.
20660 The definitions provided by the use of
20662 @smallexample @c ada
20663 pragma Extend_System (AUX_Dec);
20667 are virtually identical to those provided by the DEC Ada 83 package
20668 System. One important difference is that the name of the TO_ADDRESS
20669 function for type UNSIGNED_LONGWORD is changed to TO_ADDRESS_LONG.
20670 See the GNAT Reference manual for a discussion of why this change was
20674 The version of TO_ADDRESS taking a universal integer argument is in fact
20675 an extension to Ada 83 not strictly compatible with the reference manual.
20676 In GNAT, we are constrained to be exactly compatible with the standard,
20677 and this means we cannot provide this capability. In DEC Ada 83, the
20678 point of this definition is to deal with a call like:
20680 @smallexample @c ada
20681 TO_ADDRESS (16#12777#);
20685 Normally, according to the Ada 83 standard, one would expect this to be
20686 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
20687 of TO_ADDRESS. However, in DEC Ada 83, there is no ambiguity, since the
20688 definition using universal_integer takes precedence.
20690 In GNAT, since the version with universal_integer cannot be supplied, it is
20691 not possible to be 100% compatible. Since there are many programs using
20692 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
20693 to change the name of the function in the UNSIGNED_LONGWORD case, so the
20694 declarations provided in the GNAT version of AUX_Dec are:
20696 @smallexample @c ada
20697 function To_Address (X : Integer) return Address;
20698 pragma Pure_Function (To_Address);
20700 function To_Address_Long (X : Unsigned_Longword) return Address;
20701 pragma Pure_Function (To_Address_Long);
20705 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
20706 change the name to TO_ADDRESS_LONG.
20708 @node Tasking and Task-Related Features
20709 @section Tasking and Task-Related Features
20712 The concepts relevant to a comparison of tasking on GNAT
20713 and on DEC Ada for OpenVMS Alpha systems are discussed in
20714 the following sections.
20716 For detailed information on concepts related to tasking in
20717 DEC Ada, see the DEC Ada Language Reference Manual and the
20718 relevant run-time reference manual.
20720 @node Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
20721 @section Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
20724 On OpenVMS Alpha systems, each Ada task (except a passive
20725 task) is implemented as a single stream of execution
20726 that is created and managed by the kernel. On these
20727 systems, DEC Ada tasking support is based on DECthreads,
20728 an implementation of the POSIX standard for threads.
20730 Although tasks are implemented as threads, all tasks in
20731 an Ada program are part of the same process. As a result,
20732 resources such as open files and virtual memory can be
20733 shared easily among tasks. Having all tasks in one process
20734 allows better integration with the programming environment
20735 (the shell and the debugger, for example).
20737 Also, on OpenVMS Alpha systems, DEC Ada tasks and foreign
20738 code that calls DECthreads routines can be used together.
20739 The interaction between Ada tasks and DECthreads routines
20740 can have some benefits. For example when on OpenVMS Alpha,
20741 DEC Ada can call C code that is already threaded.
20742 GNAT on OpenVMS Alpha uses the facilities of DECthreads,
20743 and Ada tasks are mapped to threads.
20746 * Assigning Task IDs::
20747 * Task IDs and Delays::
20748 * Task-Related Pragmas::
20749 * Scheduling and Task Priority::
20751 * External Interrupts::
20754 @node Assigning Task IDs
20755 @subsection Assigning Task IDs
20758 The DEC Ada Run-Time Library always assigns %TASK 1 to
20759 the environment task that executes the main program. On
20760 OpenVMS Alpha systems, %TASK 0 is often used for tasks
20761 that have been created but are not yet activated.
20763 On OpenVMS Alpha systems, task IDs are assigned at
20764 activation. On GNAT systems, task IDs are also assigned at
20765 task creation but do not have the same form or values as
20766 task ID values in DEC Ada. There is no null task, and the
20767 environment task does not have a specific task ID value.
20769 @node Task IDs and Delays
20770 @subsection Task IDs and Delays
20773 On OpenVMS Alpha systems, tasking delays are implemented
20774 using Timer System Services. The Task ID is used for the
20775 identification of the timer request (the REQIDT parameter).
20776 If Timers are used in the application take care not to use
20777 0 for the identification, because cancelling such a timer
20778 will cancel all timers and may lead to unpredictable results.
20780 @node Task-Related Pragmas
20781 @subsection Task-Related Pragmas
20784 Ada supplies the pragma TASK_STORAGE, which allows
20785 specification of the size of the guard area for a task
20786 stack. (The guard area forms an area of memory that has no
20787 read or write access and thus helps in the detection of
20788 stack overflow.) On OpenVMS Alpha systems, if the pragma
20789 TASK_STORAGE specifies a value of zero, a minimal guard
20790 area is created. In the absence of a pragma TASK_STORAGE, a default guard
20793 GNAT supplies the following task-related pragmas:
20798 This pragma appears within a task definition and
20799 applies to the task in which it appears. The argument
20800 must be of type SYSTEM.TASK_INFO.TASK_INFO_TYPE.
20804 GNAT implements pragma TASK_STORAGE in the same way as
20806 Both DEC Ada and GNAT supply the pragmas PASSIVE,
20807 SUPPRESS, and VOLATILE.
20809 @node Scheduling and Task Priority
20810 @subsection Scheduling and Task Priority
20813 DEC Ada implements the Ada language requirement that
20814 when two tasks are eligible for execution and they have
20815 different priorities, the lower priority task does not
20816 execute while the higher priority task is waiting. The DEC
20817 Ada Run-Time Library keeps a task running until either the
20818 task is suspended or a higher priority task becomes ready.
20820 On OpenVMS Alpha systems, the default strategy is round-
20821 robin with preemption. Tasks of equal priority take turns
20822 at the processor. A task is run for a certain period of
20823 time and then placed at the rear of the ready queue for
20824 its priority level.
20826 DEC Ada provides the implementation-defined pragma TIME_SLICE,
20827 which can be used to enable or disable round-robin
20828 scheduling of tasks with the same priority.
20829 See the relevant DEC Ada run-time reference manual for
20830 information on using the pragmas to control DEC Ada task
20833 GNAT follows the scheduling rules of Annex D (real-time
20834 Annex) of the Ada 95 Reference Manual. In general, this
20835 scheduling strategy is fully compatible with DEC Ada
20836 although it provides some additional constraints (as
20837 fully documented in Annex D).
20838 GNAT implements time slicing control in a manner compatible with
20839 DEC Ada 83, by means of the pragma Time_Slice, whose semantics are identical
20840 to the DEC Ada 83 pragma of the same name.
20841 Note that it is not possible to mix GNAT tasking and
20842 DEC Ada 83 tasking in the same program, since the two run times are
20845 @node The Task Stack
20846 @subsection The Task Stack
20849 In DEC Ada, a task stack is allocated each time a
20850 non passive task is activated. As soon as the task is
20851 terminated, the storage for the task stack is deallocated.
20852 If you specify a size of zero (bytes) with T'STORAGE_SIZE,
20853 a default stack size is used. Also, regardless of the size
20854 specified, some additional space is allocated for task
20855 management purposes. On OpenVMS Alpha systems, at least
20856 one page is allocated.
20858 GNAT handles task stacks in a similar manner. According to
20859 the Ada 95 rules, it provides the pragma STORAGE_SIZE as
20860 an alternative method for controlling the task stack size.
20861 The specification of the attribute T'STORAGE_SIZE is also
20862 supported in a manner compatible with DEC Ada.
20864 @node External Interrupts
20865 @subsection External Interrupts
20868 On DEC Ada, external interrupts can be associated with task entries.
20869 GNAT is compatible with DEC Ada in its handling of external interrupts.
20871 @node Pragmas and Pragma-Related Features
20872 @section Pragmas and Pragma-Related Features
20875 Both DEC Ada and GNAT supply all language-defined pragmas
20876 as specified by the Ada 83 standard. GNAT also supplies all
20877 language-defined pragmas specified in the Ada 95 Reference Manual.
20878 In addition, GNAT implements the implementation-defined pragmas
20884 @item COMMON_OBJECT
20886 @item COMPONENT_ALIGNMENT
20888 @item EXPORT_EXCEPTION
20890 @item EXPORT_FUNCTION
20892 @item EXPORT_OBJECT
20894 @item EXPORT_PROCEDURE
20896 @item EXPORT_VALUED_PROCEDURE
20898 @item FLOAT_REPRESENTATION
20902 @item IMPORT_EXCEPTION
20904 @item IMPORT_FUNCTION
20906 @item IMPORT_OBJECT
20908 @item IMPORT_PROCEDURE
20910 @item IMPORT_VALUED_PROCEDURE
20912 @item INLINE_GENERIC
20914 @item INTERFACE_NAME
20924 @item SHARE_GENERIC
20936 These pragmas are all fully implemented, with the exception of @code{Title},
20937 @code{Passive}, and @code{Share_Generic}, which are
20938 recognized, but which have no
20939 effect in GNAT. The effect of @code{Passive} may be obtained by the
20940 use of protected objects in Ada 95. In GNAT, all generics are inlined.
20942 Unlike DEC Ada, the GNAT 'EXPORT_@i{subprogram}' pragmas require
20943 a separate subprogram specification which must appear before the
20946 GNAT also supplies a number of implementation-defined pragmas as follows:
20948 @item C_PASS_BY_COPY
20950 @item EXTEND_SYSTEM
20952 @item SOURCE_FILE_NAME
20972 @item CPP_CONSTRUCTOR
20974 @item CPP_DESTRUCTOR
20984 @item LINKER_SECTION
20986 @item MACHINE_ATTRIBUTE
20990 @item PURE_FUNCTION
20992 @item SOURCE_REFERENCE
20996 @item UNCHECKED_UNION
20998 @item UNIMPLEMENTED_UNIT
21000 @item UNIVERSAL_DATA
21002 @item WEAK_EXTERNAL
21006 For full details on these GNAT implementation-defined pragmas, see
21007 the GNAT Reference Manual.
21010 * Restrictions on the Pragma INLINE::
21011 * Restrictions on the Pragma INTERFACE::
21012 * Restrictions on the Pragma SYSTEM_NAME::
21015 @node Restrictions on the Pragma INLINE
21016 @subsection Restrictions on the Pragma INLINE
21019 DEC Ada applies the following restrictions to the pragma INLINE:
21021 @item Parameters cannot be a task type.
21023 @item Function results cannot be task types, unconstrained
21024 array types, or unconstrained types with discriminants.
21026 @item Bodies cannot declare the following:
21028 @item Subprogram body or stub (imported subprogram is allowed)
21032 @item Generic declarations
21034 @item Instantiations
21038 @item Access types (types derived from access types allowed)
21040 @item Array or record types
21042 @item Dependent tasks
21044 @item Direct recursive calls of subprogram or containing
21045 subprogram, directly or via a renaming
21051 In GNAT, the only restriction on pragma INLINE is that the
21052 body must occur before the call if both are in the same
21053 unit, and the size must be appropriately small. There are
21054 no other specific restrictions which cause subprograms to
21055 be incapable of being inlined.
21057 @node Restrictions on the Pragma INTERFACE
21058 @subsection Restrictions on the Pragma INTERFACE
21061 The following lists and describes the restrictions on the
21062 pragma INTERFACE on DEC Ada and GNAT:
21064 @item Languages accepted: Ada, Bliss, C, Fortran, Default.
21065 Default is the default on OpenVMS Alpha systems.
21067 @item Parameter passing: Language specifies default
21068 mechanisms but can be overridden with an EXPORT pragma.
21071 @item Ada: Use internal Ada rules.
21073 @item Bliss, C: Parameters must be mode @code{in}; cannot be
21074 record or task type. Result cannot be a string, an
21075 array, or a record.
21077 @item Fortran: Parameters cannot be a task. Result cannot
21078 be a string, an array, or a record.
21083 GNAT is entirely upwards compatible with DEC Ada, and in addition allows
21084 record parameters for all languages.
21086 @node Restrictions on the Pragma SYSTEM_NAME
21087 @subsection Restrictions on the Pragma SYSTEM_NAME
21090 For DEC Ada for OpenVMS Alpha, the enumeration literal
21091 for the type NAME is OPENVMS_AXP. In GNAT, the enumeration
21092 literal for the type NAME is SYSTEM_NAME_GNAT.
21094 @node Library of Predefined Units
21095 @section Library of Predefined Units
21098 A library of predefined units is provided as part of the
21099 DEC Ada and GNAT implementations. DEC Ada does not provide
21100 the package MACHINE_CODE but instead recommends importing
21103 The GNAT versions of the DEC Ada Run-Time Library (ADA$PREDEFINED:)
21104 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
21105 version. During GNAT installation, the DEC Ada Predefined
21106 Library units are copied into the GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
21107 (aka DECLIB) directory and patched to remove Ada 95 incompatibilities
21108 and to make them interoperable with GNAT, @pxref{Changes to DECLIB}
21111 The GNAT RTL is contained in
21112 the GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB] (aka ADALIB) directory and
21113 the default search path is set up to find DECLIB units in preference
21114 to ADALIB units with the same name (TEXT_IO, SEQUENTIAL_IO, and DIRECT_IO,
21117 However, it is possible to change the default so that the
21118 reverse is true, or even to mix them using child package
21119 notation. The DEC Ada 83 units are available as DEC.xxx where xxx
21120 is the package name, and the Ada units are available in the
21121 standard manner defined for Ada 95, that is to say as Ada.xxx. To
21122 change the default, set ADA_INCLUDE_PATH and ADA_OBJECTS_PATH
21123 appropriately. For example, to change the default to use the Ada95
21127 $ DEFINE ADA_INCLUDE_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADAINCLUDE],-
21128 GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
21129 $ DEFINE ADA_OBJECTS_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB],-
21130 GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
21134 * Changes to DECLIB::
21137 @node Changes to DECLIB
21138 @subsection Changes to DECLIB
21141 The changes made to the DEC Ada predefined library for GNAT and Ada 95
21142 compatibility are minor and include the following:
21145 @item Adjusting the location of pragmas and record representation
21146 clauses to obey Ada 95 rules
21148 @item Adding the proper notation to generic formal parameters
21149 that take unconstrained types in instantiation
21151 @item Adding pragma ELABORATE_BODY to package specifications
21152 that have package bodies not otherwise allowed
21154 @item Occurrences of the identifier @code{"PROTECTED"} are renamed to
21156 Currently these are found only in the STARLET package spec.
21160 None of the above changes is visible to users.
21166 On OpenVMS Alpha, DEC Ada provides the following strongly-typed bindings:
21169 @item Command Language Interpreter (CLI interface)
21171 @item DECtalk Run-Time Library (DTK interface)
21173 @item Librarian utility routines (LBR interface)
21175 @item General Purpose Run-Time Library (LIB interface)
21177 @item Math Run-Time Library (MTH interface)
21179 @item National Character Set Run-Time Library (NCS interface)
21181 @item Compiled Code Support Run-Time Library (OTS interface)
21183 @item Parallel Processing Run-Time Library (PPL interface)
21185 @item Screen Management Run-Time Library (SMG interface)
21187 @item Sort Run-Time Library (SOR interface)
21189 @item String Run-Time Library (STR interface)
21191 @item STARLET System Library
21194 @item X Window System Version 11R4 and 11R5 (X, XLIB interface)
21196 @item X Windows Toolkit (XT interface)
21198 @item X/Motif Version 1.1.3 and 1.2 (XM interface)
21202 GNAT provides implementations of these DEC bindings in the DECLIB directory.
21204 The X/Motif bindings used to build DECLIB are whatever versions are in the
21205 DEC Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
21206 The build script will
21207 automatically add a pragma Linker_Options to packages @code{Xm}, @code{Xt},
21209 causing the default X/Motif sharable image libraries to be linked in. This
21210 is done via options files named @file{xm.opt}, @file{xt.opt}, and
21211 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
21213 It may be necessary to edit these options files to update or correct the
21214 library names if, for example, the newer X/Motif bindings from
21215 @file{ADA$EXAMPLES}
21216 had been (previous to installing GNAT) copied and renamed to supersede the
21217 default @file{ADA$PREDEFINED} versions.
21220 * Shared Libraries and Options Files::
21221 * Interfaces to C::
21224 @node Shared Libraries and Options Files
21225 @subsection Shared Libraries and Options Files
21228 When using the DEC Ada
21229 predefined X and Motif bindings, the linking with their sharable images is
21230 done automatically by @command{GNAT LINK}.
21231 When using other X and Motif bindings, you need
21232 to add the corresponding sharable images to the command line for
21233 @code{GNAT LINK}. When linking with shared libraries, or with
21234 @file{.OPT} files, you must
21235 also add them to the command line for @command{GNAT LINK}.
21237 A shared library to be used with GNAT is built in the same way as other
21238 libraries under VMS. The VMS Link command can be used in standard fashion.
21240 @node Interfaces to C
21241 @subsection Interfaces to C
21245 provides the following Ada types and operations:
21248 @item C types package (C_TYPES)
21250 @item C strings (C_TYPES.NULL_TERMINATED)
21252 @item Other_types (SHORT_INT)
21256 Interfacing to C with GNAT, one can use the above approach
21257 described for DEC Ada or the facilities of Annex B of
21258 the Ada 95 Reference Manual (packages INTERFACES.C,
21259 INTERFACES.C.STRINGS and INTERFACES.C.POINTERS). For more
21260 information, see the section ``Interfacing to C'' in the
21261 @cite{GNAT Reference Manual}.
21263 The @option{-gnatF} qualifier forces default and explicit
21264 @code{External_Name} parameters in pragmas Import and Export
21265 to be uppercased for compatibility with the default behavior
21266 of Compaq C. The qualifier has no effect on @code{Link_Name} parameters.
21268 @node Main Program Definition
21269 @section Main Program Definition
21272 The following section discusses differences in the
21273 definition of main programs on DEC Ada and GNAT.
21274 On DEC Ada, main programs are defined to meet the
21275 following conditions:
21277 @item Procedure with no formal parameters (returns 0 upon
21280 @item Procedure with no formal parameters (returns 42 when
21281 unhandled exceptions are raised)
21283 @item Function with no formal parameters whose returned value
21284 is of a discrete type
21286 @item Procedure with one OUT formal of a discrete type for
21287 which a specification of pragma EXPORT_VALUED_PROCEDURE is given.
21292 When declared with the pragma EXPORT_VALUED_PROCEDURE,
21293 a main function or main procedure returns a discrete
21294 value whose size is less than 64 bits (32 on VAX systems),
21295 the value is zero- or sign-extended as appropriate.
21296 On GNAT, main programs are defined as follows:
21298 @item Must be a non-generic, parameter-less subprogram that
21299 is either a procedure or function returning an Ada
21300 STANDARD.INTEGER (the predefined type)
21302 @item Cannot be a generic subprogram or an instantiation of a
21306 @node Implementation-Defined Attributes
21307 @section Implementation-Defined Attributes
21310 GNAT provides all DEC Ada implementation-defined
21313 @node Compiler and Run-Time Interfacing
21314 @section Compiler and Run-Time Interfacing
21317 DEC Ada provides the following ways to pass options to the linker
21320 @item /WAIT and /SUBMIT qualifiers
21322 @item /COMMAND qualifier
21324 @item /[NO]MAP qualifier
21326 @item /OUTPUT=file-spec
21328 @item /[NO]DEBUG and /[NO]TRACEBACK qualifiers
21332 To pass options to the linker, GNAT provides the following
21336 @item @option{/EXECUTABLE=exec-name}
21338 @item @option{/VERBOSE qualifier}
21340 @item @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK} qualifiers
21344 For more information on these switches, see
21345 @ref{Switches for gnatlink}.
21346 In DEC Ada, the command-line switch @option{/OPTIMIZE} is available
21347 to control optimization. DEC Ada also supplies the
21350 @item @code{OPTIMIZE}
21352 @item @code{INLINE}
21354 @item @code{INLINE_GENERIC}
21356 @item @code{SUPPRESS_ALL}
21358 @item @code{PASSIVE}
21362 In GNAT, optimization is controlled strictly by command
21363 line parameters, as described in the corresponding section of this guide.
21364 The DIGITAL pragmas for control of optimization are
21365 recognized but ignored.
21367 Note that in GNAT, the default is optimization off, whereas in DEC Ada 83,
21368 the default is that optimization is turned on.
21370 @node Program Compilation and Library Management
21371 @section Program Compilation and Library Management
21374 DEC Ada and GNAT provide a comparable set of commands to
21375 build programs. DEC Ada also provides a program library,
21376 which is a concept that does not exist on GNAT. Instead,
21377 GNAT provides directories of sources that are compiled as
21380 The following table summarizes
21381 the DEC Ada commands and provides
21382 equivalent GNAT commands. In this table, some GNAT
21383 equivalents reflect the fact that GNAT does not use the
21384 concept of a program library. Instead, it uses a model
21385 in which collections of source and object files are used
21386 in a manner consistent with other languages like C and
21387 Fortran. Therefore, standard system file commands are used
21388 to manipulate these elements. Those GNAT commands are marked with
21390 Note that, unlike DEC Ada, none of the GNAT commands accepts wild cards.
21393 @multitable @columnfractions .35 .65
21395 @item @emph{DEC Ada Command}
21396 @tab @emph{GNAT Equivalent / Description}
21398 @item @command{ADA}
21399 @tab @command{GNAT COMPILE}@*
21400 Invokes the compiler to compile one or more Ada source files.
21402 @item @command{ACS ATTACH}@*
21403 @tab [No equivalent]@*
21404 Switches control of terminal from current process running the program
21407 @item @command{ACS CHECK}
21408 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
21409 Forms the execution closure of one
21410 or more compiled units and checks completeness and currency.
21412 @item @command{ACS COMPILE}
21413 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21414 Forms the execution closure of one or
21415 more specified units, checks completeness and currency,
21416 identifies units that have revised source files, compiles same,
21417 and recompiles units that are or will become obsolete.
21418 Also completes incomplete generic instantiations.
21420 @item @command{ACS COPY FOREIGN}
21422 Copies a foreign object file into the program library as a
21425 @item @command{ACS COPY UNIT}
21427 Copies a compiled unit from one program library to another.
21429 @item @command{ACS CREATE LIBRARY}
21430 @tab Create /directory (*)@*
21431 Creates a program library.
21433 @item @command{ACS CREATE SUBLIBRARY}
21434 @tab Create /directory (*)@*
21435 Creates a program sublibrary.
21437 @item @command{ACS DELETE LIBRARY}
21439 Deletes a program library and its contents.
21441 @item @command{ACS DELETE SUBLIBRARY}
21443 Deletes a program sublibrary and its contents.
21445 @item @command{ACS DELETE UNIT}
21446 @tab Delete file (*)@*
21447 On OpenVMS systems, deletes one or more compiled units from
21448 the current program library.
21450 @item @command{ACS DIRECTORY}
21451 @tab Directory (*)@*
21452 On OpenVMS systems, lists units contained in the current
21455 @item @command{ACS ENTER FOREIGN}
21457 Allows the import of a foreign body as an Ada library
21458 specification and enters a reference to a pointer.
21460 @item @command{ACS ENTER UNIT}
21462 Enters a reference (pointer) from the current program library to
21463 a unit compiled into another program library.
21465 @item @command{ACS EXIT}
21466 @tab [No equivalent]@*
21467 Exits from the program library manager.
21469 @item @command{ACS EXPORT}
21471 Creates an object file that contains system-specific object code
21472 for one or more units. With GNAT, object files can simply be copied
21473 into the desired directory.
21475 @item @command{ACS EXTRACT SOURCE}
21477 Allows access to the copied source file for each Ada compilation unit
21479 @item @command{ACS HELP}
21480 @tab @command{HELP GNAT}@*
21481 Provides online help.
21483 @item @command{ACS LINK}
21484 @tab @command{GNAT LINK}@*
21485 Links an object file containing Ada units into an executable file.
21487 @item @command{ACS LOAD}
21489 Loads (partially compiles) Ada units into the program library.
21490 Allows loading a program from a collection of files into a library
21491 without knowing the relationship among units.
21493 @item @command{ACS MERGE}
21495 Merges into the current program library, one or more units from
21496 another library where they were modified.
21498 @item @command{ACS RECOMPILE}
21499 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21500 Recompiles from external or copied source files any obsolete
21501 unit in the closure. Also, completes any incomplete generic
21504 @item @command{ACS REENTER}
21505 @tab @command{GNAT MAKE}@*
21506 Reenters current references to units compiled after last entered
21507 with the @command{ACS ENTER UNIT} command.
21509 @item @command{ACS SET LIBRARY}
21510 @tab Set default (*)@*
21511 Defines a program library to be the compilation context as well
21512 as the target library for compiler output and commands in general.
21514 @item @command{ACS SET PRAGMA}
21515 @tab Edit @file{gnat.adc} (*)@*
21516 Redefines specified values of the library characteristics
21517 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
21518 and @code{Float_Representation}.
21520 @item @command{ACS SET SOURCE}
21521 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
21522 Defines the source file search list for the @command{ACS COMPILE} command.
21524 @item @command{ACS SHOW LIBRARY}
21525 @tab Directory (*)@*
21526 Lists information about one or more program libraries.
21528 @item @command{ACS SHOW PROGRAM}
21529 @tab [No equivalent]@*
21530 Lists information about the execution closure of one or
21531 more units in the program library.
21533 @item @command{ACS SHOW SOURCE}
21534 @tab Show logical @code{ADA_INCLUDE_PATH}@*
21535 Shows the source file search used when compiling units.
21537 @item @command{ACS SHOW VERSION}
21538 @tab Compile with @option{VERBOSE} option
21539 Displays the version number of the compiler and program library
21542 @item @command{ACS SPAWN}
21543 @tab [No equivalent]@*
21544 Creates a subprocess of the current process (same as @command{DCL SPAWN}
21547 @item @command{ACS VERIFY}
21548 @tab [No equivalent]@*
21549 Performs a series of consistency checks on a program library to
21550 determine whether the library structure and library files are in
21557 @section Input-Output
21560 On OpenVMS Alpha systems, DEC Ada uses OpenVMS Record
21561 Management Services (RMS) to perform operations on
21565 DEC Ada and GNAT predefine an identical set of input-
21566 output packages. To make the use of the
21567 generic TEXT_IO operations more convenient, DEC Ada
21568 provides predefined library packages that instantiate the
21569 integer and floating-point operations for the predefined
21570 integer and floating-point types as shown in the following table.
21572 @multitable @columnfractions .45 .55
21573 @item @emph{Package Name} @tab Instantiation
21575 @item @code{INTEGER_TEXT_IO}
21576 @tab @code{INTEGER_IO(INTEGER)}
21578 @item @code{SHORT_INTEGER_TEXT_IO}
21579 @tab @code{INTEGER_IO(SHORT_INTEGER)}
21581 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
21582 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
21584 @item @code{FLOAT_TEXT_IO}
21585 @tab @code{FLOAT_IO(FLOAT)}
21587 @item @code{LONG_FLOAT_TEXT_IO}
21588 @tab @code{FLOAT_IO(LONG_FLOAT)}
21592 The DEC Ada predefined packages and their operations
21593 are implemented using OpenVMS Alpha files and input-
21594 output facilities. DEC Ada supports asynchronous input-
21595 output on OpenVMS Alpha. Familiarity with the following is
21598 @item RMS file organizations and access methods
21600 @item OpenVMS file specifications and directories
21602 @item OpenVMS File Definition Language (FDL)
21606 GNAT provides I/O facilities that are completely
21607 compatible with DEC Ada. The distribution includes the
21608 standard DEC Ada versions of all I/O packages, operating
21609 in a manner compatible with DEC Ada. In particular, the
21610 following packages are by default the DEC Ada (Ada 83)
21611 versions of these packages rather than the renamings
21612 suggested in annex J of the Ada 95 Reference Manual:
21614 @item @code{TEXT_IO}
21616 @item @code{SEQUENTIAL_IO}
21618 @item @code{DIRECT_IO}
21622 The use of the standard Ada 95 syntax for child packages (for
21623 example, @code{ADA.TEXT_IO}) retrieves the Ada 95 versions of these
21624 packages, as defined in the Ada 95 Reference Manual.
21625 GNAT provides DIGITAL-compatible predefined instantiations
21626 of the @code{TEXT_IO} packages, and also
21627 provides the standard predefined instantiations required
21628 by the Ada 95 Reference Manual.
21630 For further information on how GNAT interfaces to the file
21631 system or how I/O is implemented in programs written in
21632 mixed languages, see the chapter ``Implementation of the
21633 Standard I/O'' in the @cite{GNAT Reference Manual}.
21634 This chapter covers the following:
21636 @item Standard I/O packages
21638 @item @code{FORM} strings
21640 @item @code{ADA.DIRECT_IO}
21642 @item @code{ADA.SEQUENTIAL_IO}
21644 @item @code{ADA.TEXT_IO}
21646 @item Stream pointer positioning
21648 @item Reading and writing non-regular files
21650 @item @code{GET_IMMEDIATE}
21652 @item Treating @code{TEXT_IO} files as streams
21659 @node Implementation Limits
21660 @section Implementation Limits
21663 The following table lists implementation limits for DEC Ada
21665 @multitable @columnfractions .60 .20 .20
21667 @item @emph{Compilation Parameter}
21668 @tab @emph{DEC Ada}
21672 @item In a subprogram or entry declaration, maximum number of
21673 formal parameters that are of an unconstrained record type
21678 @item Maximum identifier length (number of characters)
21683 @item Maximum number of characters in a source line
21688 @item Maximum collection size (number of bytes)
21693 @item Maximum number of discriminants for a record type
21698 @item Maximum number of formal parameters in an entry or
21699 subprogram declaration
21704 @item Maximum number of dimensions in an array type
21709 @item Maximum number of library units and subunits in a compilation.
21714 @item Maximum number of library units and subunits in an execution.
21719 @item Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
21720 or @code{PSECT_OBJECT}
21725 @item Maximum number of enumeration literals in an enumeration type
21731 @item Maximum number of lines in a source file
21736 @item Maximum number of bits in any object
21741 @item Maximum size of the static portion of a stack frame (approximate)
21751 @c **************************************
21752 @node Platform-Specific Information for the Run-Time Libraries
21753 @appendix Platform-Specific Information for the Run-Time Libraries
21754 @cindex Tasking and threads libraries
21755 @cindex Threads libraries and tasking
21756 @cindex Run-time libraries (platform-specific information)
21759 The GNAT run-time implementation may vary with respect to both the
21760 underlying threads library and the exception handling scheme.
21761 For threads support, one or more of the following are supplied:
21763 @item @b{native threads library}, a binding to the thread package from
21764 the underlying operating system
21766 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
21767 POSIX thread package
21771 For exception handling, either or both of two models are supplied:
21773 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
21774 Most programs should experience a substantial speed improvement by
21775 being compiled with a ZCX run-time.
21776 This is especially true for
21777 tasking applications or applications with many exception handlers.}
21778 @cindex Zero-Cost Exceptions
21779 @cindex ZCX (Zero-Cost Exceptions)
21780 which uses binder-generated tables that
21781 are interrogated at run time to locate a handler
21783 @item @b{setjmp / longjmp} (``SJLJ''),
21784 @cindex setjmp/longjmp Exception Model
21785 @cindex SJLJ (setjmp/longjmp Exception Model)
21786 which uses dynamically-set data to establish
21787 the set of handlers
21791 This appendix summarizes which combinations of threads and exception support
21792 are supplied on various GNAT platforms.
21793 It then shows how to select a particular library either
21794 permanently or temporarily,
21795 explains the properties of (and tradeoffs among) the various threads
21796 libraries, and provides some additional
21797 information about several specific platforms.
21800 * Summary of Run-Time Configurations::
21801 * Specifying a Run-Time Library::
21802 * Choosing the Scheduling Policy::
21803 * Solaris-Specific Considerations::
21804 * IRIX-Specific Considerations::
21805 * Linux-Specific Considerations::
21806 * AIX-Specific Considerations::
21809 @node Summary of Run-Time Configurations
21810 @section Summary of Run-Time Configurations
21812 @multitable @columnfractions .30 .70
21813 @item @b{alpha-openvms}
21814 @item @code{@ @ }@i{rts-native (default)}
21815 @item @code{@ @ @ @ }Tasking @tab native VMS threads
21816 @item @code{@ @ @ @ }Exceptions @tab ZCX
21819 @item @code{@ @ }@i{rts-native (default)}
21820 @item @code{@ @ @ @ }Tasking @tab native HP threads library
21821 @item @code{@ @ @ @ }Exceptions @tab ZCX
21823 @item @code{@ @ }@i{rts-sjlj}
21824 @item @code{@ @ @ @ }Tasking @tab native HP threads library
21825 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21827 @item @b{sparc-solaris} @tab
21828 @item @code{@ @ }@i{rts-native (default)}
21829 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
21830 @item @code{@ @ @ @ }Exceptions @tab ZCX
21832 @item @code{@ @ }@i{rts-m64}
21833 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
21834 @item @code{@ @ @ @ }Exceptions @tab ZCX
21835 @item @code{@ @ @ @ }Constraints @tab Use only when compiling in 64-bit mode;
21836 @item @tab Use only on Solaris 8 or later.
21837 @item @tab @xref{Building and Debugging 64-bit Applications}, for details.
21839 @item @code{@ @ }@i{rts-pthread}
21840 @item @code{@ @ @ @ }Tasking @tab pthreads library
21841 @item @code{@ @ @ @ }Exceptions @tab ZCX
21843 @item @code{@ @ }@i{rts-sjlj}
21844 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
21845 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21847 @item @b{x86-linux}
21848 @item @code{@ @ }@i{rts-native (default)}
21849 @item @code{@ @ @ @ }Tasking @tab pthread library
21850 @item @code{@ @ @ @ }Exceptions @tab ZCX
21852 @item @code{@ @ }@i{rts-sjlj}
21853 @item @code{@ @ @ @ }Tasking @tab pthread library
21854 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21856 @item @b{x86-windows}
21857 @item @code{@ @ }@i{rts-native (default)}
21858 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
21859 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21863 @node Specifying a Run-Time Library
21864 @section Specifying a Run-Time Library
21867 The @file{adainclude} subdirectory containing the sources of the GNAT
21868 run-time library, and the @file{adalib} subdirectory containing the
21869 @file{ALI} files and the static and/or shared GNAT library, are located
21870 in the gcc target-dependent area:
21873 target=$prefix/lib/gcc-lib/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
21877 As indicated above, on some platforms several run-time libraries are supplied.
21878 These libraries are installed in the target dependent area and
21879 contain a complete source and binary subdirectory. The detailed description
21880 below explains the differences between the different libraries in terms of
21881 their thread support.
21883 The default run-time library (when GNAT is installed) is @emph{rts-native}.
21884 This default run time is selected by the means of soft links.
21885 For example on x86-linux:
21891 +--- adainclude----------+
21893 +--- adalib-----------+ |
21895 +--- rts-native | |
21897 | +--- adainclude <---+
21899 | +--- adalib <----+
21910 If the @i{rts-sjlj} library is to be selected on a permanent basis,
21911 these soft links can be modified with the following commands:
21915 $ rm -f adainclude adalib
21916 $ ln -s rts-sjlj/adainclude adainclude
21917 $ ln -s rts-sjlj/adalib adalib
21921 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
21922 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
21923 @file{$target/ada_object_path}.
21925 Selecting another run-time library temporarily can be
21926 achieved by the regular mechanism for GNAT object or source path selection:
21930 Set the environment variables:
21933 $ ADA_INCLUDE_PATH=$target/rts-sjlj/adainclude:$ADA_INCLUDE_PATH
21934 $ ADA_OBJECTS_PATH=$target/rts-sjlj/adalib:$ADA_OBJECTS_PATH
21935 $ export ADA_INCLUDE_PATH ADA_OBJECTS_PATH
21939 Use @option{-aI$target/rts-sjlj/adainclude}
21940 and @option{-aO$target/rts-sjlj/adalib}
21941 on the @command{gnatmake} command line
21944 Use the switch @option{--RTS}; e.g., @option{--RTS=sjlj}
21945 @cindex @option{--RTS} option
21948 @node Choosing the Scheduling Policy
21949 @section Choosing the Scheduling Policy
21952 When using a POSIX threads implementation, you have a choice of several
21953 scheduling policies: @code{SCHED_FIFO},
21954 @cindex @code{SCHED_FIFO} scheduling policy
21956 @cindex @code{SCHED_RR} scheduling policy
21957 and @code{SCHED_OTHER}.
21958 @cindex @code{SCHED_OTHER} scheduling policy
21959 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
21960 or @code{SCHED_RR} requires special (e.g., root) privileges.
21962 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
21964 @cindex @code{SCHED_FIFO} scheduling policy
21965 you can use one of the following:
21969 @code{pragma Time_Slice (0.0)}
21970 @cindex pragma Time_Slice
21972 the corresponding binder option @option{-T0}
21973 @cindex @option{-T0} option
21975 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21976 @cindex pragma Task_Dispatching_Policy
21980 To specify @code{SCHED_RR},
21981 @cindex @code{SCHED_RR} scheduling policy
21982 you should use @code{pragma Time_Slice} with a
21983 value greater than @code{0.0}, or else use the corresponding @option{-T}
21986 @node Solaris-Specific Considerations
21987 @section Solaris-Specific Considerations
21988 @cindex Solaris Sparc threads libraries
21991 This section addresses some topics related to the various threads libraries
21992 on Sparc Solaris and then provides some information on building and
21993 debugging 64-bit applications.
21996 * Solaris Threads Issues::
21997 * Building and Debugging 64-bit Applications::
22000 @node Solaris Threads Issues
22001 @subsection Solaris Threads Issues
22004 GNAT under Solaris comes with an alternate tasking run-time library
22005 based on POSIX threads --- @emph{rts-pthread}.
22006 @cindex rts-pthread threads library
22007 This run-time library has the advantage of being mostly shared across all
22008 POSIX-compliant thread implementations, and it also provides under
22009 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
22010 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
22011 and @code{PTHREAD_PRIO_PROTECT}
22012 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
22013 semantics that can be selected using the predefined pragma
22014 @code{Locking_Policy}
22015 @cindex pragma Locking_Policy (under rts-pthread)
22017 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
22018 @cindex @code{Inheritance_Locking} (under rts-pthread)
22019 @cindex @code{Ceiling_Locking} (under rts-pthread)
22021 As explained above, the native run-time library is based on the Solaris thread
22022 library (@code{libthread}) and is the default library.
22024 When the Solaris threads library is used (this is the default), programs
22025 compiled with GNAT can automatically take advantage of
22026 and can thus execute on multiple processors.
22027 The user can alternatively specify a processor on which the program should run
22028 to emulate a single-processor system. The multiprocessor / uniprocessor choice
22030 setting the environment variable @code{GNAT_PROCESSOR}
22031 @cindex @code{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
22032 to one of the following:
22036 Use the default configuration (run the program on all
22037 available processors) - this is the same as having
22038 @code{GNAT_PROCESSOR} unset
22041 Let the run-time implementation choose one processor and run the program on
22044 @item 0 .. Last_Proc
22045 Run the program on the specified processor.
22046 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
22047 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
22050 @node Building and Debugging 64-bit Applications
22051 @subsection Building and Debugging 64-bit Applications
22054 In a 64-bit application, all the sources involved must be compiled with the
22055 @option{-m64} command-line option, and a specific GNAT library (compiled with
22056 this option) is required.
22057 The easiest way to build a 64bit application is to add
22058 @option{-m64 --RTS=m64} to the @command{gnatmake} flags.
22060 To debug these applications, a special version of gdb called @command{gdb64}
22063 To summarize, building and debugging a ``Hello World'' program in 64-bit mode
22067 $ gnatmake -m64 -g --RTS=m64 hello.adb
22071 In addition, the following capabilities are not supported when using the
22072 @option{-m64} option:
22075 @item -fstack-check does not work together with -m64.
22076 Any application combining these options crashes at startup time.
22078 @item Call-chain backtrace computation does not work with -m64.
22079 Thus the gnatbind switch -E is not supported.
22082 @node IRIX-Specific Considerations
22083 @section IRIX-Specific Considerations
22084 @cindex IRIX thread library
22087 On SGI IRIX, the thread library depends on which compiler is used.
22088 The @emph{o32 ABI} compiler comes with a run-time library based on the
22089 user-level @code{athread}
22090 library. Thus kernel-level capabilities such as nonblocking system
22091 calls or time slicing can only be achieved reliably by specifying different
22092 @code{sprocs} via the pragma @code{Task_Info}
22093 @cindex pragma Task_Info (and IRIX threads)
22095 @code{System.Task_Info} package.
22096 @cindex @code{System.Task_Info} package (and IRIX threads)
22097 See the @cite{GNAT Reference Manual} for further information.
22099 The @emph{n32 ABI} compiler comes with a run-time library based on the
22100 kernel POSIX threads and thus does not have the limitations mentioned above.
22102 @node Linux-Specific Considerations
22103 @section Linux-Specific Considerations
22104 @cindex Linux threads libraries
22107 The default thread library under GNU/Linux has the following disadvantages
22108 compared to other native thread libraries:
22111 @item The size of the task's stack is limited to 2 megabytes.
22112 @item The signal model is not POSIX compliant, which means that to send a
22113 signal to the process, you need to send the signal to all threads,
22114 e.g. by using @code{killpg()}.
22117 @node AIX-Specific Considerations
22118 @section AIX-Specific Considerations
22119 @cindex AIX resolver library
22122 On AIX, the resolver library initializes some internal structure on
22123 the first call to @code{get*by*} functions, which are used to implement
22124 @code{GNAT.Sockets.Get_Host_By_Name} and
22125 @code{GNAT.Sockets.Get_Host_By_Addrss}.
22126 If such initialization occurs within an Ada task, and the stack size for
22127 the task is the default size, a stack overflow may occur.
22129 To avoid this overflow, the user should either ensure that the first call
22130 to @code{GNAT.Sockets.Get_Host_By_Name} or
22131 @code{GNAT.Sockets.Get_Host_By_Addrss}
22132 occurs in the environment task, or use @code{pragma Storage_Size} to
22133 specify a sufficiently large size for the stack of the task that contains
22136 @c *******************************
22137 @node Example of Binder Output File
22138 @appendix Example of Binder Output File
22141 This Appendix displays the source code for @command{gnatbind}'s output
22142 file generated for a simple ``Hello World'' program.
22143 Comments have been added for clarification purposes.
22145 @smallexample @c adanocomment
22149 -- The package is called Ada_Main unless this name is actually used
22150 -- as a unit name in the partition, in which case some other unique
22154 package ada_main is
22156 Elab_Final_Code : Integer;
22157 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
22159 -- The main program saves the parameters (argument count,
22160 -- argument values, environment pointer) in global variables
22161 -- for later access by other units including
22162 -- Ada.Command_Line.
22164 gnat_argc : Integer;
22165 gnat_argv : System.Address;
22166 gnat_envp : System.Address;
22168 -- The actual variables are stored in a library routine. This
22169 -- is useful for some shared library situations, where there
22170 -- are problems if variables are not in the library.
22172 pragma Import (C, gnat_argc);
22173 pragma Import (C, gnat_argv);
22174 pragma Import (C, gnat_envp);
22176 -- The exit status is similarly an external location
22178 gnat_exit_status : Integer;
22179 pragma Import (C, gnat_exit_status);
22181 GNAT_Version : constant String :=
22182 "GNAT Version: 3.15w (20010315)";
22183 pragma Export (C, GNAT_Version, "__gnat_version");
22185 -- This is the generated adafinal routine that performs
22186 -- finalization at the end of execution. In the case where
22187 -- Ada is the main program, this main program makes a call
22188 -- to adafinal at program termination.
22190 procedure adafinal;
22191 pragma Export (C, adafinal, "adafinal");
22193 -- This is the generated adainit routine that performs
22194 -- initialization at the start of execution. In the case
22195 -- where Ada is the main program, this main program makes
22196 -- a call to adainit at program startup.
22199 pragma Export (C, adainit, "adainit");
22201 -- This routine is called at the start of execution. It is
22202 -- a dummy routine that is used by the debugger to breakpoint
22203 -- at the start of execution.
22205 procedure Break_Start;
22206 pragma Import (C, Break_Start, "__gnat_break_start");
22208 -- This is the actual generated main program (it would be
22209 -- suppressed if the no main program switch were used). As
22210 -- required by standard system conventions, this program has
22211 -- the external name main.
22215 argv : System.Address;
22216 envp : System.Address)
22218 pragma Export (C, main, "main");
22220 -- The following set of constants give the version
22221 -- identification values for every unit in the bound
22222 -- partition. This identification is computed from all
22223 -- dependent semantic units, and corresponds to the
22224 -- string that would be returned by use of the
22225 -- Body_Version or Version attributes.
22227 type Version_32 is mod 2 ** 32;
22228 u00001 : constant Version_32 := 16#7880BEB3#;
22229 u00002 : constant Version_32 := 16#0D24CBD0#;
22230 u00003 : constant Version_32 := 16#3283DBEB#;
22231 u00004 : constant Version_32 := 16#2359F9ED#;
22232 u00005 : constant Version_32 := 16#664FB847#;
22233 u00006 : constant Version_32 := 16#68E803DF#;
22234 u00007 : constant Version_32 := 16#5572E604#;
22235 u00008 : constant Version_32 := 16#46B173D8#;
22236 u00009 : constant Version_32 := 16#156A40CF#;
22237 u00010 : constant Version_32 := 16#033DABE0#;
22238 u00011 : constant Version_32 := 16#6AB38FEA#;
22239 u00012 : constant Version_32 := 16#22B6217D#;
22240 u00013 : constant Version_32 := 16#68A22947#;
22241 u00014 : constant Version_32 := 16#18CC4A56#;
22242 u00015 : constant Version_32 := 16#08258E1B#;
22243 u00016 : constant Version_32 := 16#367D5222#;
22244 u00017 : constant Version_32 := 16#20C9ECA4#;
22245 u00018 : constant Version_32 := 16#50D32CB6#;
22246 u00019 : constant Version_32 := 16#39A8BB77#;
22247 u00020 : constant Version_32 := 16#5CF8FA2B#;
22248 u00021 : constant Version_32 := 16#2F1EB794#;
22249 u00022 : constant Version_32 := 16#31AB6444#;
22250 u00023 : constant Version_32 := 16#1574B6E9#;
22251 u00024 : constant Version_32 := 16#5109C189#;
22252 u00025 : constant Version_32 := 16#56D770CD#;
22253 u00026 : constant Version_32 := 16#02F9DE3D#;
22254 u00027 : constant Version_32 := 16#08AB6B2C#;
22255 u00028 : constant Version_32 := 16#3FA37670#;
22256 u00029 : constant Version_32 := 16#476457A0#;
22257 u00030 : constant Version_32 := 16#731E1B6E#;
22258 u00031 : constant Version_32 := 16#23C2E789#;
22259 u00032 : constant Version_32 := 16#0F1BD6A1#;
22260 u00033 : constant Version_32 := 16#7C25DE96#;
22261 u00034 : constant Version_32 := 16#39ADFFA2#;
22262 u00035 : constant Version_32 := 16#571DE3E7#;
22263 u00036 : constant Version_32 := 16#5EB646AB#;
22264 u00037 : constant Version_32 := 16#4249379B#;
22265 u00038 : constant Version_32 := 16#0357E00A#;
22266 u00039 : constant Version_32 := 16#3784FB72#;
22267 u00040 : constant Version_32 := 16#2E723019#;
22268 u00041 : constant Version_32 := 16#623358EA#;
22269 u00042 : constant Version_32 := 16#107F9465#;
22270 u00043 : constant Version_32 := 16#6843F68A#;
22271 u00044 : constant Version_32 := 16#63305874#;
22272 u00045 : constant Version_32 := 16#31E56CE1#;
22273 u00046 : constant Version_32 := 16#02917970#;
22274 u00047 : constant Version_32 := 16#6CCBA70E#;
22275 u00048 : constant Version_32 := 16#41CD4204#;
22276 u00049 : constant Version_32 := 16#572E3F58#;
22277 u00050 : constant Version_32 := 16#20729FF5#;
22278 u00051 : constant Version_32 := 16#1D4F93E8#;
22279 u00052 : constant Version_32 := 16#30B2EC3D#;
22280 u00053 : constant Version_32 := 16#34054F96#;
22281 u00054 : constant Version_32 := 16#5A199860#;
22282 u00055 : constant Version_32 := 16#0E7F912B#;
22283 u00056 : constant Version_32 := 16#5760634A#;
22284 u00057 : constant Version_32 := 16#5D851835#;
22286 -- The following Export pragmas export the version numbers
22287 -- with symbolic names ending in B (for body) or S
22288 -- (for spec) so that they can be located in a link. The
22289 -- information provided here is sufficient to track down
22290 -- the exact versions of units used in a given build.
22292 pragma Export (C, u00001, "helloB");
22293 pragma Export (C, u00002, "system__standard_libraryB");
22294 pragma Export (C, u00003, "system__standard_libraryS");
22295 pragma Export (C, u00004, "adaS");
22296 pragma Export (C, u00005, "ada__text_ioB");
22297 pragma Export (C, u00006, "ada__text_ioS");
22298 pragma Export (C, u00007, "ada__exceptionsB");
22299 pragma Export (C, u00008, "ada__exceptionsS");
22300 pragma Export (C, u00009, "gnatS");
22301 pragma Export (C, u00010, "gnat__heap_sort_aB");
22302 pragma Export (C, u00011, "gnat__heap_sort_aS");
22303 pragma Export (C, u00012, "systemS");
22304 pragma Export (C, u00013, "system__exception_tableB");
22305 pragma Export (C, u00014, "system__exception_tableS");
22306 pragma Export (C, u00015, "gnat__htableB");
22307 pragma Export (C, u00016, "gnat__htableS");
22308 pragma Export (C, u00017, "system__exceptionsS");
22309 pragma Export (C, u00018, "system__machine_state_operationsB");
22310 pragma Export (C, u00019, "system__machine_state_operationsS");
22311 pragma Export (C, u00020, "system__machine_codeS");
22312 pragma Export (C, u00021, "system__storage_elementsB");
22313 pragma Export (C, u00022, "system__storage_elementsS");
22314 pragma Export (C, u00023, "system__secondary_stackB");
22315 pragma Export (C, u00024, "system__secondary_stackS");
22316 pragma Export (C, u00025, "system__parametersB");
22317 pragma Export (C, u00026, "system__parametersS");
22318 pragma Export (C, u00027, "system__soft_linksB");
22319 pragma Export (C, u00028, "system__soft_linksS");
22320 pragma Export (C, u00029, "system__stack_checkingB");
22321 pragma Export (C, u00030, "system__stack_checkingS");
22322 pragma Export (C, u00031, "system__tracebackB");
22323 pragma Export (C, u00032, "system__tracebackS");
22324 pragma Export (C, u00033, "ada__streamsS");
22325 pragma Export (C, u00034, "ada__tagsB");
22326 pragma Export (C, u00035, "ada__tagsS");
22327 pragma Export (C, u00036, "system__string_opsB");
22328 pragma Export (C, u00037, "system__string_opsS");
22329 pragma Export (C, u00038, "interfacesS");
22330 pragma Export (C, u00039, "interfaces__c_streamsB");
22331 pragma Export (C, u00040, "interfaces__c_streamsS");
22332 pragma Export (C, u00041, "system__file_ioB");
22333 pragma Export (C, u00042, "system__file_ioS");
22334 pragma Export (C, u00043, "ada__finalizationB");
22335 pragma Export (C, u00044, "ada__finalizationS");
22336 pragma Export (C, u00045, "system__finalization_rootB");
22337 pragma Export (C, u00046, "system__finalization_rootS");
22338 pragma Export (C, u00047, "system__finalization_implementationB");
22339 pragma Export (C, u00048, "system__finalization_implementationS");
22340 pragma Export (C, u00049, "system__string_ops_concat_3B");
22341 pragma Export (C, u00050, "system__string_ops_concat_3S");
22342 pragma Export (C, u00051, "system__stream_attributesB");
22343 pragma Export (C, u00052, "system__stream_attributesS");
22344 pragma Export (C, u00053, "ada__io_exceptionsS");
22345 pragma Export (C, u00054, "system__unsigned_typesS");
22346 pragma Export (C, u00055, "system__file_control_blockS");
22347 pragma Export (C, u00056, "ada__finalization__list_controllerB");
22348 pragma Export (C, u00057, "ada__finalization__list_controllerS");
22350 -- BEGIN ELABORATION ORDER
22353 -- gnat.heap_sort_a (spec)
22354 -- gnat.heap_sort_a (body)
22355 -- gnat.htable (spec)
22356 -- gnat.htable (body)
22357 -- interfaces (spec)
22359 -- system.machine_code (spec)
22360 -- system.parameters (spec)
22361 -- system.parameters (body)
22362 -- interfaces.c_streams (spec)
22363 -- interfaces.c_streams (body)
22364 -- system.standard_library (spec)
22365 -- ada.exceptions (spec)
22366 -- system.exception_table (spec)
22367 -- system.exception_table (body)
22368 -- ada.io_exceptions (spec)
22369 -- system.exceptions (spec)
22370 -- system.storage_elements (spec)
22371 -- system.storage_elements (body)
22372 -- system.machine_state_operations (spec)
22373 -- system.machine_state_operations (body)
22374 -- system.secondary_stack (spec)
22375 -- system.stack_checking (spec)
22376 -- system.soft_links (spec)
22377 -- system.soft_links (body)
22378 -- system.stack_checking (body)
22379 -- system.secondary_stack (body)
22380 -- system.standard_library (body)
22381 -- system.string_ops (spec)
22382 -- system.string_ops (body)
22385 -- ada.streams (spec)
22386 -- system.finalization_root (spec)
22387 -- system.finalization_root (body)
22388 -- system.string_ops_concat_3 (spec)
22389 -- system.string_ops_concat_3 (body)
22390 -- system.traceback (spec)
22391 -- system.traceback (body)
22392 -- ada.exceptions (body)
22393 -- system.unsigned_types (spec)
22394 -- system.stream_attributes (spec)
22395 -- system.stream_attributes (body)
22396 -- system.finalization_implementation (spec)
22397 -- system.finalization_implementation (body)
22398 -- ada.finalization (spec)
22399 -- ada.finalization (body)
22400 -- ada.finalization.list_controller (spec)
22401 -- ada.finalization.list_controller (body)
22402 -- system.file_control_block (spec)
22403 -- system.file_io (spec)
22404 -- system.file_io (body)
22405 -- ada.text_io (spec)
22406 -- ada.text_io (body)
22408 -- END ELABORATION ORDER
22412 -- The following source file name pragmas allow the generated file
22413 -- names to be unique for different main programs. They are needed
22414 -- since the package name will always be Ada_Main.
22416 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
22417 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
22419 -- Generated package body for Ada_Main starts here
22421 package body ada_main is
22423 -- The actual finalization is performed by calling the
22424 -- library routine in System.Standard_Library.Adafinal
22426 procedure Do_Finalize;
22427 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
22434 procedure adainit is
22436 -- These booleans are set to True once the associated unit has
22437 -- been elaborated. It is also used to avoid elaborating the
22438 -- same unit twice.
22441 pragma Import (Ada, E040, "interfaces__c_streams_E");
22444 pragma Import (Ada, E008, "ada__exceptions_E");
22447 pragma Import (Ada, E014, "system__exception_table_E");
22450 pragma Import (Ada, E053, "ada__io_exceptions_E");
22453 pragma Import (Ada, E017, "system__exceptions_E");
22456 pragma Import (Ada, E024, "system__secondary_stack_E");
22459 pragma Import (Ada, E030, "system__stack_checking_E");
22462 pragma Import (Ada, E028, "system__soft_links_E");
22465 pragma Import (Ada, E035, "ada__tags_E");
22468 pragma Import (Ada, E033, "ada__streams_E");
22471 pragma Import (Ada, E046, "system__finalization_root_E");
22474 pragma Import (Ada, E048, "system__finalization_implementation_E");
22477 pragma Import (Ada, E044, "ada__finalization_E");
22480 pragma Import (Ada, E057, "ada__finalization__list_controller_E");
22483 pragma Import (Ada, E055, "system__file_control_block_E");
22486 pragma Import (Ada, E042, "system__file_io_E");
22489 pragma Import (Ada, E006, "ada__text_io_E");
22491 -- Set_Globals is a library routine that stores away the
22492 -- value of the indicated set of global values in global
22493 -- variables within the library.
22495 procedure Set_Globals
22496 (Main_Priority : Integer;
22497 Time_Slice_Value : Integer;
22498 WC_Encoding : Character;
22499 Locking_Policy : Character;
22500 Queuing_Policy : Character;
22501 Task_Dispatching_Policy : Character;
22502 Adafinal : System.Address;
22503 Unreserve_All_Interrupts : Integer;
22504 Exception_Tracebacks : Integer);
22505 @findex __gnat_set_globals
22506 pragma Import (C, Set_Globals, "__gnat_set_globals");
22508 -- SDP_Table_Build is a library routine used to build the
22509 -- exception tables. See unit Ada.Exceptions in files
22510 -- a-except.ads/adb for full details of how zero cost
22511 -- exception handling works. This procedure, the call to
22512 -- it, and the two following tables are all omitted if the
22513 -- build is in longjmp/setjump exception mode.
22515 @findex SDP_Table_Build
22516 @findex Zero Cost Exceptions
22517 procedure SDP_Table_Build
22518 (SDP_Addresses : System.Address;
22519 SDP_Count : Natural;
22520 Elab_Addresses : System.Address;
22521 Elab_Addr_Count : Natural);
22522 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22524 -- Table of Unit_Exception_Table addresses. Used for zero
22525 -- cost exception handling to build the top level table.
22527 ST : aliased constant array (1 .. 23) of System.Address := (
22529 Ada.Text_Io'UET_Address,
22530 Ada.Exceptions'UET_Address,
22531 Gnat.Heap_Sort_A'UET_Address,
22532 System.Exception_Table'UET_Address,
22533 System.Machine_State_Operations'UET_Address,
22534 System.Secondary_Stack'UET_Address,
22535 System.Parameters'UET_Address,
22536 System.Soft_Links'UET_Address,
22537 System.Stack_Checking'UET_Address,
22538 System.Traceback'UET_Address,
22539 Ada.Streams'UET_Address,
22540 Ada.Tags'UET_Address,
22541 System.String_Ops'UET_Address,
22542 Interfaces.C_Streams'UET_Address,
22543 System.File_Io'UET_Address,
22544 Ada.Finalization'UET_Address,
22545 System.Finalization_Root'UET_Address,
22546 System.Finalization_Implementation'UET_Address,
22547 System.String_Ops_Concat_3'UET_Address,
22548 System.Stream_Attributes'UET_Address,
22549 System.File_Control_Block'UET_Address,
22550 Ada.Finalization.List_Controller'UET_Address);
22552 -- Table of addresses of elaboration routines. Used for
22553 -- zero cost exception handling to make sure these
22554 -- addresses are included in the top level procedure
22557 EA : aliased constant array (1 .. 23) of System.Address := (
22558 adainit'Code_Address,
22559 Do_Finalize'Code_Address,
22560 Ada.Exceptions'Elab_Spec'Address,
22561 System.Exceptions'Elab_Spec'Address,
22562 Interfaces.C_Streams'Elab_Spec'Address,
22563 System.Exception_Table'Elab_Body'Address,
22564 Ada.Io_Exceptions'Elab_Spec'Address,
22565 System.Stack_Checking'Elab_Spec'Address,
22566 System.Soft_Links'Elab_Body'Address,
22567 System.Secondary_Stack'Elab_Body'Address,
22568 Ada.Tags'Elab_Spec'Address,
22569 Ada.Tags'Elab_Body'Address,
22570 Ada.Streams'Elab_Spec'Address,
22571 System.Finalization_Root'Elab_Spec'Address,
22572 Ada.Exceptions'Elab_Body'Address,
22573 System.Finalization_Implementation'Elab_Spec'Address,
22574 System.Finalization_Implementation'Elab_Body'Address,
22575 Ada.Finalization'Elab_Spec'Address,
22576 Ada.Finalization.List_Controller'Elab_Spec'Address,
22577 System.File_Control_Block'Elab_Spec'Address,
22578 System.File_Io'Elab_Body'Address,
22579 Ada.Text_Io'Elab_Spec'Address,
22580 Ada.Text_Io'Elab_Body'Address);
22582 -- Start of processing for adainit
22586 -- Call SDP_Table_Build to build the top level procedure
22587 -- table for zero cost exception handling (omitted in
22588 -- longjmp/setjump mode).
22590 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
22592 -- Call Set_Globals to record various information for
22593 -- this partition. The values are derived by the binder
22594 -- from information stored in the ali files by the compiler.
22596 @findex __gnat_set_globals
22598 (Main_Priority => -1,
22599 -- Priority of main program, -1 if no pragma Priority used
22601 Time_Slice_Value => -1,
22602 -- Time slice from Time_Slice pragma, -1 if none used
22604 WC_Encoding => 'b',
22605 -- Wide_Character encoding used, default is brackets
22607 Locking_Policy => ' ',
22608 -- Locking_Policy used, default of space means not
22609 -- specified, otherwise it is the first character of
22610 -- the policy name.
22612 Queuing_Policy => ' ',
22613 -- Queuing_Policy used, default of space means not
22614 -- specified, otherwise it is the first character of
22615 -- the policy name.
22617 Task_Dispatching_Policy => ' ',
22618 -- Task_Dispatching_Policy used, default of space means
22619 -- not specified, otherwise first character of the
22622 Adafinal => System.Null_Address,
22623 -- Address of Adafinal routine, not used anymore
22625 Unreserve_All_Interrupts => 0,
22626 -- Set true if pragma Unreserve_All_Interrupts was used
22628 Exception_Tracebacks => 0);
22629 -- Indicates if exception tracebacks are enabled
22631 Elab_Final_Code := 1;
22633 -- Now we have the elaboration calls for all units in the partition.
22634 -- The Elab_Spec and Elab_Body attributes generate references to the
22635 -- implicit elaboration procedures generated by the compiler for
22636 -- each unit that requires elaboration.
22639 Interfaces.C_Streams'Elab_Spec;
22643 Ada.Exceptions'Elab_Spec;
22646 System.Exception_Table'Elab_Body;
22650 Ada.Io_Exceptions'Elab_Spec;
22654 System.Exceptions'Elab_Spec;
22658 System.Stack_Checking'Elab_Spec;
22661 System.Soft_Links'Elab_Body;
22666 System.Secondary_Stack'Elab_Body;
22670 Ada.Tags'Elab_Spec;
22673 Ada.Tags'Elab_Body;
22677 Ada.Streams'Elab_Spec;
22681 System.Finalization_Root'Elab_Spec;
22685 Ada.Exceptions'Elab_Body;
22689 System.Finalization_Implementation'Elab_Spec;
22692 System.Finalization_Implementation'Elab_Body;
22696 Ada.Finalization'Elab_Spec;
22700 Ada.Finalization.List_Controller'Elab_Spec;
22704 System.File_Control_Block'Elab_Spec;
22708 System.File_Io'Elab_Body;
22712 Ada.Text_Io'Elab_Spec;
22715 Ada.Text_Io'Elab_Body;
22719 Elab_Final_Code := 0;
22727 procedure adafinal is
22736 -- main is actually a function, as in the ANSI C standard,
22737 -- defined to return the exit status. The three parameters
22738 -- are the argument count, argument values and environment
22741 @findex Main Program
22744 argv : System.Address;
22745 envp : System.Address)
22748 -- The initialize routine performs low level system
22749 -- initialization using a standard library routine which
22750 -- sets up signal handling and performs any other
22751 -- required setup. The routine can be found in file
22754 @findex __gnat_initialize
22755 procedure initialize;
22756 pragma Import (C, initialize, "__gnat_initialize");
22758 -- The finalize routine performs low level system
22759 -- finalization using a standard library routine. The
22760 -- routine is found in file a-final.c and in the standard
22761 -- distribution is a dummy routine that does nothing, so
22762 -- really this is a hook for special user finalization.
22764 @findex __gnat_finalize
22765 procedure finalize;
22766 pragma Import (C, finalize, "__gnat_finalize");
22768 -- We get to the main program of the partition by using
22769 -- pragma Import because if we try to with the unit and
22770 -- call it Ada style, then not only do we waste time
22771 -- recompiling it, but also, we don't really know the right
22772 -- switches (e.g. identifier character set) to be used
22775 procedure Ada_Main_Program;
22776 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
22778 -- Start of processing for main
22781 -- Save global variables
22787 -- Call low level system initialization
22791 -- Call our generated Ada initialization routine
22795 -- This is the point at which we want the debugger to get
22800 -- Now we call the main program of the partition
22804 -- Perform Ada finalization
22808 -- Perform low level system finalization
22812 -- Return the proper exit status
22813 return (gnat_exit_status);
22816 -- This section is entirely comments, so it has no effect on the
22817 -- compilation of the Ada_Main package. It provides the list of
22818 -- object files and linker options, as well as some standard
22819 -- libraries needed for the link. The gnatlink utility parses
22820 -- this b~hello.adb file to read these comment lines to generate
22821 -- the appropriate command line arguments for the call to the
22822 -- system linker. The BEGIN/END lines are used for sentinels for
22823 -- this parsing operation.
22825 -- The exact file names will of course depend on the environment,
22826 -- host/target and location of files on the host system.
22828 @findex Object file list
22829 -- BEGIN Object file/option list
22832 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
22833 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22834 -- END Object file/option list
22840 The Ada code in the above example is exactly what is generated by the
22841 binder. We have added comments to more clearly indicate the function
22842 of each part of the generated @code{Ada_Main} package.
22844 The code is standard Ada in all respects, and can be processed by any
22845 tools that handle Ada. In particular, it is possible to use the debugger
22846 in Ada mode to debug the generated @code{Ada_Main} package. For example,
22847 suppose that for reasons that you do not understand, your program is crashing
22848 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
22849 you can place a breakpoint on the call:
22851 @smallexample @c ada
22852 Ada.Text_Io'Elab_Body;
22856 and trace the elaboration routine for this package to find out where
22857 the problem might be (more usually of course you would be debugging
22858 elaboration code in your own application).
22860 @node Elaboration Order Handling in GNAT
22861 @appendix Elaboration Order Handling in GNAT
22862 @cindex Order of elaboration
22863 @cindex Elaboration control
22866 * Elaboration Code in Ada 95::
22867 * Checking the Elaboration Order in Ada 95::
22868 * Controlling the Elaboration Order in Ada 95::
22869 * Controlling Elaboration in GNAT - Internal Calls::
22870 * Controlling Elaboration in GNAT - External Calls::
22871 * Default Behavior in GNAT - Ensuring Safety::
22872 * Treatment of Pragma Elaborate::
22873 * Elaboration Issues for Library Tasks::
22874 * Mixing Elaboration Models::
22875 * What to Do If the Default Elaboration Behavior Fails::
22876 * Elaboration for Access-to-Subprogram Values::
22877 * Summary of Procedures for Elaboration Control::
22878 * Other Elaboration Order Considerations::
22882 This chapter describes the handling of elaboration code in Ada 95 and
22883 in GNAT, and discusses how the order of elaboration of program units can
22884 be controlled in GNAT, either automatically or with explicit programming
22887 @node Elaboration Code in Ada 95
22888 @section Elaboration Code in Ada 95
22891 Ada 95 provides rather general mechanisms for executing code at elaboration
22892 time, that is to say before the main program starts executing. Such code arises
22896 @item Initializers for variables.
22897 Variables declared at the library level, in package specs or bodies, can
22898 require initialization that is performed at elaboration time, as in:
22899 @smallexample @c ada
22901 Sqrt_Half : Float := Sqrt (0.5);
22905 @item Package initialization code
22906 Code in a @code{BEGIN-END} section at the outer level of a package body is
22907 executed as part of the package body elaboration code.
22909 @item Library level task allocators
22910 Tasks that are declared using task allocators at the library level
22911 start executing immediately and hence can execute at elaboration time.
22915 Subprogram calls are possible in any of these contexts, which means that
22916 any arbitrary part of the program may be executed as part of the elaboration
22917 code. It is even possible to write a program which does all its work at
22918 elaboration time, with a null main program, although stylistically this
22919 would usually be considered an inappropriate way to structure
22922 An important concern arises in the context of elaboration code:
22923 we have to be sure that it is executed in an appropriate order. What we
22924 have is a series of elaboration code sections, potentially one section
22925 for each unit in the program. It is important that these execute
22926 in the correct order. Correctness here means that, taking the above
22927 example of the declaration of @code{Sqrt_Half},
22928 if some other piece of
22929 elaboration code references @code{Sqrt_Half},
22930 then it must run after the
22931 section of elaboration code that contains the declaration of
22934 There would never be any order of elaboration problem if we made a rule
22935 that whenever you @code{with} a unit, you must elaborate both the spec and body
22936 of that unit before elaborating the unit doing the @code{with}'ing:
22938 @smallexample @c ada
22942 package Unit_2 is ...
22948 would require that both the body and spec of @code{Unit_1} be elaborated
22949 before the spec of @code{Unit_2}. However, a rule like that would be far too
22950 restrictive. In particular, it would make it impossible to have routines
22951 in separate packages that were mutually recursive.
22953 You might think that a clever enough compiler could look at the actual
22954 elaboration code and determine an appropriate correct order of elaboration,
22955 but in the general case, this is not possible. Consider the following
22958 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
22960 the variable @code{Sqrt_1}, which is declared in the elaboration code
22961 of the body of @code{Unit_1}:
22963 @smallexample @c ada
22965 Sqrt_1 : Float := Sqrt (0.1);
22970 The elaboration code of the body of @code{Unit_1} also contains:
22972 @smallexample @c ada
22975 if expression_1 = 1 then
22976 Q := Unit_2.Func_2;
22983 @code{Unit_2} is exactly parallel,
22984 it has a procedure @code{Func_2} that references
22985 the variable @code{Sqrt_2}, which is declared in the elaboration code of
22986 the body @code{Unit_2}:
22988 @smallexample @c ada
22990 Sqrt_2 : Float := Sqrt (0.1);
22995 The elaboration code of the body of @code{Unit_2} also contains:
22997 @smallexample @c ada
23000 if expression_2 = 2 then
23001 Q := Unit_1.Func_1;
23008 Now the question is, which of the following orders of elaboration is
23033 If you carefully analyze the flow here, you will see that you cannot tell
23034 at compile time the answer to this question.
23035 If @code{expression_1} is not equal to 1,
23036 and @code{expression_2} is not equal to 2,
23037 then either order is acceptable, because neither of the function calls is
23038 executed. If both tests evaluate to true, then neither order is acceptable
23039 and in fact there is no correct order.
23041 If one of the two expressions is true, and the other is false, then one
23042 of the above orders is correct, and the other is incorrect. For example,
23043 if @code{expression_1} = 1 and @code{expression_2} /= 2,
23044 then the call to @code{Func_2}
23045 will occur, but not the call to @code{Func_1.}
23046 This means that it is essential
23047 to elaborate the body of @code{Unit_1} before
23048 the body of @code{Unit_2}, so the first
23049 order of elaboration is correct and the second is wrong.
23051 By making @code{expression_1} and @code{expression_2}
23052 depend on input data, or perhaps
23053 the time of day, we can make it impossible for the compiler or binder
23054 to figure out which of these expressions will be true, and hence it
23055 is impossible to guarantee a safe order of elaboration at run time.
23057 @node Checking the Elaboration Order in Ada 95
23058 @section Checking the Elaboration Order in Ada 95
23061 In some languages that involve the same kind of elaboration problems,
23062 e.g. Java and C++, the programmer is expected to worry about these
23063 ordering problems himself, and it is common to
23064 write a program in which an incorrect elaboration order gives
23065 surprising results, because it references variables before they
23067 Ada 95 is designed to be a safe language, and a programmer-beware approach is
23068 clearly not sufficient. Consequently, the language provides three lines
23072 @item Standard rules
23073 Some standard rules restrict the possible choice of elaboration
23074 order. In particular, if you @code{with} a unit, then its spec is always
23075 elaborated before the unit doing the @code{with}. Similarly, a parent
23076 spec is always elaborated before the child spec, and finally
23077 a spec is always elaborated before its corresponding body.
23079 @item Dynamic elaboration checks
23080 @cindex Elaboration checks
23081 @cindex Checks, elaboration
23082 Dynamic checks are made at run time, so that if some entity is accessed
23083 before it is elaborated (typically by means of a subprogram call)
23084 then the exception (@code{Program_Error}) is raised.
23086 @item Elaboration control
23087 Facilities are provided for the programmer to specify the desired order
23091 Let's look at these facilities in more detail. First, the rules for
23092 dynamic checking. One possible rule would be simply to say that the
23093 exception is raised if you access a variable which has not yet been
23094 elaborated. The trouble with this approach is that it could require
23095 expensive checks on every variable reference. Instead Ada 95 has two
23096 rules which are a little more restrictive, but easier to check, and
23100 @item Restrictions on calls
23101 A subprogram can only be called at elaboration time if its body
23102 has been elaborated. The rules for elaboration given above guarantee
23103 that the spec of the subprogram has been elaborated before the
23104 call, but not the body. If this rule is violated, then the
23105 exception @code{Program_Error} is raised.
23107 @item Restrictions on instantiations
23108 A generic unit can only be instantiated if the body of the generic
23109 unit has been elaborated. Again, the rules for elaboration given above
23110 guarantee that the spec of the generic unit has been elaborated
23111 before the instantiation, but not the body. If this rule is
23112 violated, then the exception @code{Program_Error} is raised.
23116 The idea is that if the body has been elaborated, then any variables
23117 it references must have been elaborated; by checking for the body being
23118 elaborated we guarantee that none of its references causes any
23119 trouble. As we noted above, this is a little too restrictive, because a
23120 subprogram that has no non-local references in its body may in fact be safe
23121 to call. However, it really would be unsafe to rely on this, because
23122 it would mean that the caller was aware of details of the implementation
23123 in the body. This goes against the basic tenets of Ada.
23125 A plausible implementation can be described as follows.
23126 A Boolean variable is associated with each subprogram
23127 and each generic unit. This variable is initialized to False, and is set to
23128 True at the point body is elaborated. Every call or instantiation checks the
23129 variable, and raises @code{Program_Error} if the variable is False.
23131 Note that one might think that it would be good enough to have one Boolean
23132 variable for each package, but that would not deal with cases of trying
23133 to call a body in the same package as the call
23134 that has not been elaborated yet.
23135 Of course a compiler may be able to do enough analysis to optimize away
23136 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
23137 does such optimizations, but still the easiest conceptual model is to
23138 think of there being one variable per subprogram.
23140 @node Controlling the Elaboration Order in Ada 95
23141 @section Controlling the Elaboration Order in Ada 95
23144 In the previous section we discussed the rules in Ada 95 which ensure
23145 that @code{Program_Error} is raised if an incorrect elaboration order is
23146 chosen. This prevents erroneous executions, but we need mechanisms to
23147 specify a correct execution and avoid the exception altogether.
23148 To achieve this, Ada 95 provides a number of features for controlling
23149 the order of elaboration. We discuss these features in this section.
23151 First, there are several ways of indicating to the compiler that a given
23152 unit has no elaboration problems:
23155 @item packages that do not require a body
23156 In Ada 95, a library package that does not require a body does not permit
23157 a body. This means that if we have a such a package, as in:
23159 @smallexample @c ada
23162 package Definitions is
23164 type m is new integer;
23166 type a is array (1 .. 10) of m;
23167 type b is array (1 .. 20) of m;
23175 A package that @code{with}'s @code{Definitions} may safely instantiate
23176 @code{Definitions.Subp} because the compiler can determine that there
23177 definitely is no package body to worry about in this case
23180 @cindex pragma Pure
23182 Places sufficient restrictions on a unit to guarantee that
23183 no call to any subprogram in the unit can result in an
23184 elaboration problem. This means that the compiler does not need
23185 to worry about the point of elaboration of such units, and in
23186 particular, does not need to check any calls to any subprograms
23189 @item pragma Preelaborate
23190 @findex Preelaborate
23191 @cindex pragma Preelaborate
23192 This pragma places slightly less stringent restrictions on a unit than
23194 but these restrictions are still sufficient to ensure that there
23195 are no elaboration problems with any calls to the unit.
23197 @item pragma Elaborate_Body
23198 @findex Elaborate_Body
23199 @cindex pragma Elaborate_Body
23200 This pragma requires that the body of a unit be elaborated immediately
23201 after its spec. Suppose a unit @code{A} has such a pragma,
23202 and unit @code{B} does
23203 a @code{with} of unit @code{A}. Recall that the standard rules require
23204 the spec of unit @code{A}
23205 to be elaborated before the @code{with}'ing unit; given the pragma in
23206 @code{A}, we also know that the body of @code{A}
23207 will be elaborated before @code{B}, so
23208 that calls to @code{A} are safe and do not need a check.
23213 unlike pragma @code{Pure} and pragma @code{Preelaborate},
23215 @code{Elaborate_Body} does not guarantee that the program is
23216 free of elaboration problems, because it may not be possible
23217 to satisfy the requested elaboration order.
23218 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
23220 marks @code{Unit_1} as @code{Elaborate_Body},
23221 and not @code{Unit_2,} then the order of
23222 elaboration will be:
23234 Now that means that the call to @code{Func_1} in @code{Unit_2}
23235 need not be checked,
23236 it must be safe. But the call to @code{Func_2} in
23237 @code{Unit_1} may still fail if
23238 @code{Expression_1} is equal to 1,
23239 and the programmer must still take
23240 responsibility for this not being the case.
23242 If all units carry a pragma @code{Elaborate_Body}, then all problems are
23243 eliminated, except for calls entirely within a body, which are
23244 in any case fully under programmer control. However, using the pragma
23245 everywhere is not always possible.
23246 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
23247 we marked both of them as having pragma @code{Elaborate_Body}, then
23248 clearly there would be no possible elaboration order.
23250 The above pragmas allow a server to guarantee safe use by clients, and
23251 clearly this is the preferable approach. Consequently a good rule in
23252 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
23253 and if this is not possible,
23254 mark them as @code{Elaborate_Body} if possible.
23255 As we have seen, there are situations where neither of these
23256 three pragmas can be used.
23257 So we also provide methods for clients to control the
23258 order of elaboration of the servers on which they depend:
23261 @item pragma Elaborate (unit)
23263 @cindex pragma Elaborate
23264 This pragma is placed in the context clause, after a @code{with} clause,
23265 and it requires that the body of the named unit be elaborated before
23266 the unit in which the pragma occurs. The idea is to use this pragma
23267 if the current unit calls at elaboration time, directly or indirectly,
23268 some subprogram in the named unit.
23270 @item pragma Elaborate_All (unit)
23271 @findex Elaborate_All
23272 @cindex pragma Elaborate_All
23273 This is a stronger version of the Elaborate pragma. Consider the
23277 Unit A @code{with}'s unit B and calls B.Func in elab code
23278 Unit B @code{with}'s unit C, and B.Func calls C.Func
23282 Now if we put a pragma @code{Elaborate (B)}
23283 in unit @code{A}, this ensures that the
23284 body of @code{B} is elaborated before the call, but not the
23285 body of @code{C}, so
23286 the call to @code{C.Func} could still cause @code{Program_Error} to
23289 The effect of a pragma @code{Elaborate_All} is stronger, it requires
23290 not only that the body of the named unit be elaborated before the
23291 unit doing the @code{with}, but also the bodies of all units that the
23292 named unit uses, following @code{with} links transitively. For example,
23293 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
23295 not only that the body of @code{B} be elaborated before @code{A},
23297 body of @code{C}, because @code{B} @code{with}'s @code{C}.
23301 We are now in a position to give a usage rule in Ada 95 for avoiding
23302 elaboration problems, at least if dynamic dispatching and access to
23303 subprogram values are not used. We will handle these cases separately
23306 The rule is simple. If a unit has elaboration code that can directly or
23307 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
23308 a generic unit in a @code{with}'ed unit,
23309 then if the @code{with}'ed unit does not have
23310 pragma @code{Pure} or @code{Preelaborate}, then the client should have
23311 a pragma @code{Elaborate_All}
23312 for the @code{with}'ed unit. By following this rule a client is
23313 assured that calls can be made without risk of an exception.
23314 If this rule is not followed, then a program may be in one of four
23318 @item No order exists
23319 No order of elaboration exists which follows the rules, taking into
23320 account any @code{Elaborate}, @code{Elaborate_All},
23321 or @code{Elaborate_Body} pragmas. In
23322 this case, an Ada 95 compiler must diagnose the situation at bind
23323 time, and refuse to build an executable program.
23325 @item One or more orders exist, all incorrect
23326 One or more acceptable elaboration orders exists, and all of them
23327 generate an elaboration order problem. In this case, the binder
23328 can build an executable program, but @code{Program_Error} will be raised
23329 when the program is run.
23331 @item Several orders exist, some right, some incorrect
23332 One or more acceptable elaboration orders exists, and some of them
23333 work, and some do not. The programmer has not controlled
23334 the order of elaboration, so the binder may or may not pick one of
23335 the correct orders, and the program may or may not raise an
23336 exception when it is run. This is the worst case, because it means
23337 that the program may fail when moved to another compiler, or even
23338 another version of the same compiler.
23340 @item One or more orders exists, all correct
23341 One ore more acceptable elaboration orders exist, and all of them
23342 work. In this case the program runs successfully. This state of
23343 affairs can be guaranteed by following the rule we gave above, but
23344 may be true even if the rule is not followed.
23348 Note that one additional advantage of following our Elaborate_All rule
23349 is that the program continues to stay in the ideal (all orders OK) state
23350 even if maintenance
23351 changes some bodies of some subprograms. Conversely, if a program that does
23352 not follow this rule happens to be safe at some point, this state of affairs
23353 may deteriorate silently as a result of maintenance changes.
23355 You may have noticed that the above discussion did not mention
23356 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
23357 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
23358 code in the body makes calls to some other unit, so it is still necessary
23359 to use @code{Elaborate_All} on such units.
23361 @node Controlling Elaboration in GNAT - Internal Calls
23362 @section Controlling Elaboration in GNAT - Internal Calls
23365 In the case of internal calls, i.e. calls within a single package, the
23366 programmer has full control over the order of elaboration, and it is up
23367 to the programmer to elaborate declarations in an appropriate order. For
23370 @smallexample @c ada
23373 function One return Float;
23377 function One return Float is
23386 will obviously raise @code{Program_Error} at run time, because function
23387 One will be called before its body is elaborated. In this case GNAT will
23388 generate a warning that the call will raise @code{Program_Error}:
23394 2. function One return Float;
23396 4. Q : Float := One;
23398 >>> warning: cannot call "One" before body is elaborated
23399 >>> warning: Program_Error will be raised at run time
23402 6. function One return Float is
23415 Note that in this particular case, it is likely that the call is safe, because
23416 the function @code{One} does not access any global variables.
23417 Nevertheless in Ada 95, we do not want the validity of the check to depend on
23418 the contents of the body (think about the separate compilation case), so this
23419 is still wrong, as we discussed in the previous sections.
23421 The error is easily corrected by rearranging the declarations so that the
23422 body of One appears before the declaration containing the call
23423 (note that in Ada 95,
23424 declarations can appear in any order, so there is no restriction that
23425 would prevent this reordering, and if we write:
23427 @smallexample @c ada
23430 function One return Float;
23432 function One return Float is
23443 then all is well, no warning is generated, and no
23444 @code{Program_Error} exception
23446 Things are more complicated when a chain of subprograms is executed:
23448 @smallexample @c ada
23451 function A return Integer;
23452 function B return Integer;
23453 function C return Integer;
23455 function B return Integer is begin return A; end;
23456 function C return Integer is begin return B; end;
23460 function A return Integer is begin return 1; end;
23466 Now the call to @code{C}
23467 at elaboration time in the declaration of @code{X} is correct, because
23468 the body of @code{C} is already elaborated,
23469 and the call to @code{B} within the body of
23470 @code{C} is correct, but the call
23471 to @code{A} within the body of @code{B} is incorrect, because the body
23472 of @code{A} has not been elaborated, so @code{Program_Error}
23473 will be raised on the call to @code{A}.
23474 In this case GNAT will generate a
23475 warning that @code{Program_Error} may be
23476 raised at the point of the call. Let's look at the warning:
23482 2. function A return Integer;
23483 3. function B return Integer;
23484 4. function C return Integer;
23486 6. function B return Integer is begin return A; end;
23488 >>> warning: call to "A" before body is elaborated may
23489 raise Program_Error
23490 >>> warning: "B" called at line 7
23491 >>> warning: "C" called at line 9
23493 7. function C return Integer is begin return B; end;
23495 9. X : Integer := C;
23497 11. function A return Integer is begin return 1; end;
23507 Note that the message here says ``may raise'', instead of the direct case,
23508 where the message says ``will be raised''. That's because whether
23510 actually called depends in general on run-time flow of control.
23511 For example, if the body of @code{B} said
23513 @smallexample @c ada
23516 function B return Integer is
23518 if some-condition-depending-on-input-data then
23529 then we could not know until run time whether the incorrect call to A would
23530 actually occur, so @code{Program_Error} might
23531 or might not be raised. It is possible for a compiler to
23532 do a better job of analyzing bodies, to
23533 determine whether or not @code{Program_Error}
23534 might be raised, but it certainly
23535 couldn't do a perfect job (that would require solving the halting problem
23536 and is provably impossible), and because this is a warning anyway, it does
23537 not seem worth the effort to do the analysis. Cases in which it
23538 would be relevant are rare.
23540 In practice, warnings of either of the forms given
23541 above will usually correspond to
23542 real errors, and should be examined carefully and eliminated.
23543 In the rare case where a warning is bogus, it can be suppressed by any of
23544 the following methods:
23548 Compile with the @option{-gnatws} switch set
23551 Suppress @code{Elaboration_Check} for the called subprogram
23554 Use pragma @code{Warnings_Off} to turn warnings off for the call
23558 For the internal elaboration check case,
23559 GNAT by default generates the
23560 necessary run-time checks to ensure
23561 that @code{Program_Error} is raised if any
23562 call fails an elaboration check. Of course this can only happen if a
23563 warning has been issued as described above. The use of pragma
23564 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23565 some of these checks, meaning that it may be possible (but is not
23566 guaranteed) for a program to be able to call a subprogram whose body
23567 is not yet elaborated, without raising a @code{Program_Error} exception.
23569 @node Controlling Elaboration in GNAT - External Calls
23570 @section Controlling Elaboration in GNAT - External Calls
23573 The previous section discussed the case in which the execution of a
23574 particular thread of elaboration code occurred entirely within a
23575 single unit. This is the easy case to handle, because a programmer
23576 has direct and total control over the order of elaboration, and
23577 furthermore, checks need only be generated in cases which are rare
23578 and which the compiler can easily detect.
23579 The situation is more complex when separate compilation is taken into account.
23580 Consider the following:
23582 @smallexample @c ada
23586 function Sqrt (Arg : Float) return Float;
23589 package body Math is
23590 function Sqrt (Arg : Float) return Float is
23599 X : Float := Math.Sqrt (0.5);
23612 where @code{Main} is the main program. When this program is executed, the
23613 elaboration code must first be executed, and one of the jobs of the
23614 binder is to determine the order in which the units of a program are
23615 to be elaborated. In this case we have four units: the spec and body
23617 the spec of @code{Stuff} and the body of @code{Main}).
23618 In what order should the four separate sections of elaboration code
23621 There are some restrictions in the order of elaboration that the binder
23622 can choose. In particular, if unit U has a @code{with}
23623 for a package @code{X}, then you
23624 are assured that the spec of @code{X}
23625 is elaborated before U , but you are
23626 not assured that the body of @code{X}
23627 is elaborated before U.
23628 This means that in the above case, the binder is allowed to choose the
23639 but that's not good, because now the call to @code{Math.Sqrt}
23640 that happens during
23641 the elaboration of the @code{Stuff}
23642 spec happens before the body of @code{Math.Sqrt} is
23643 elaborated, and hence causes @code{Program_Error} exception to be raised.
23644 At first glance, one might say that the binder is misbehaving, because
23645 obviously you want to elaborate the body of something you @code{with}
23647 that is not a general rule that can be followed in all cases. Consider
23649 @smallexample @c ada
23657 package body Y is ...
23660 package body X is ...
23666 This is a common arrangement, and, apart from the order of elaboration
23667 problems that might arise in connection with elaboration code, this works fine.
23668 A rule that says that you must first elaborate the body of anything you
23669 @code{with} cannot work in this case:
23670 the body of @code{X} @code{with}'s @code{Y},
23671 which means you would have to
23672 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
23674 you have to elaborate the body of @code{X} first, but ... and we have a
23675 loop that cannot be broken.
23677 It is true that the binder can in many cases guess an order of elaboration
23678 that is unlikely to cause a @code{Program_Error}
23679 exception to be raised, and it tries to do so (in the
23680 above example of @code{Math/Stuff/Spec}, the GNAT binder will
23682 elaborate the body of @code{Math} right after its spec, so all will be well).
23684 However, a program that blindly relies on the binder to be helpful can
23685 get into trouble, as we discussed in the previous sections, so
23687 provides a number of facilities for assisting the programmer in
23688 developing programs that are robust with respect to elaboration order.
23690 @node Default Behavior in GNAT - Ensuring Safety
23691 @section Default Behavior in GNAT - Ensuring Safety
23694 The default behavior in GNAT ensures elaboration safety. In its
23695 default mode GNAT implements the
23696 rule we previously described as the right approach. Let's restate it:
23700 @emph{If a unit has elaboration code that can directly or indirectly make a
23701 call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit
23702 in a @code{with}'ed unit, then if the @code{with}'ed unit
23703 does not have pragma @code{Pure} or
23704 @code{Preelaborate}, then the client should have an
23705 @code{Elaborate_All} for the @code{with}'ed unit.}
23709 By following this rule a client is assured that calls and instantiations
23710 can be made without risk of an exception.
23712 In this mode GNAT traces all calls that are potentially made from
23713 elaboration code, and puts in any missing implicit @code{Elaborate_All}
23715 The advantage of this approach is that no elaboration problems
23716 are possible if the binder can find an elaboration order that is
23717 consistent with these implicit @code{Elaborate_All} pragmas. The
23718 disadvantage of this approach is that no such order may exist.
23720 If the binder does not generate any diagnostics, then it means that it
23721 has found an elaboration order that is guaranteed to be safe. However,
23722 the binder may still be relying on implicitly generated
23723 @code{Elaborate_All} pragmas so portability to other compilers than
23724 GNAT is not guaranteed.
23726 If it is important to guarantee portability, then the compilations should
23729 (warn on elaboration problems) switch. This will cause warning messages
23730 to be generated indicating the missing @code{Elaborate_All} pragmas.
23731 Consider the following source program:
23733 @smallexample @c ada
23738 m : integer := k.r;
23745 where it is clear that there
23746 should be a pragma @code{Elaborate_All}
23747 for unit @code{k}. An implicit pragma will be generated, and it is
23748 likely that the binder will be able to honor it. However, if you want
23749 to port this program to some other Ada compiler than GNAT.
23750 it is safer to include the pragma explicitly in the source. If this
23751 unit is compiled with the
23753 switch, then the compiler outputs a warning:
23760 3. m : integer := k.r;
23762 >>> warning: call to "r" may raise Program_Error
23763 >>> warning: missing pragma Elaborate_All for "k"
23771 and these warnings can be used as a guide for supplying manually
23772 the missing pragmas. It is usually a bad idea to use this warning
23773 option during development. That's because it will warn you when
23774 you need to put in a pragma, but cannot warn you when it is time
23775 to take it out. So the use of pragma Elaborate_All may lead to
23776 unnecessary dependencies and even false circularities.
23778 This default mode is more restrictive than the Ada Reference
23779 Manual, and it is possible to construct programs which will compile
23780 using the dynamic model described there, but will run into a
23781 circularity using the safer static model we have described.
23783 Of course any Ada compiler must be able to operate in a mode
23784 consistent with the requirements of the Ada Reference Manual,
23785 and in particular must have the capability of implementing the
23786 standard dynamic model of elaboration with run-time checks.
23788 In GNAT, this standard mode can be achieved either by the use of
23789 the @option{-gnatE} switch on the compiler (@command{gcc} or
23790 @command{gnatmake}) command, or by the use of the configuration pragma:
23792 @smallexample @c ada
23793 pragma Elaboration_Checks (RM);
23797 Either approach will cause the unit affected to be compiled using the
23798 standard dynamic run-time elaboration checks described in the Ada
23799 Reference Manual. The static model is generally preferable, since it
23800 is clearly safer to rely on compile and link time checks rather than
23801 run-time checks. However, in the case of legacy code, it may be
23802 difficult to meet the requirements of the static model. This
23803 issue is further discussed in
23804 @ref{What to Do If the Default Elaboration Behavior Fails}.
23806 Note that the static model provides a strict subset of the allowed
23807 behavior and programs of the Ada Reference Manual, so if you do
23808 adhere to the static model and no circularities exist,
23809 then you are assured that your program will
23810 work using the dynamic model, providing that you remove any
23811 pragma Elaborate statements from the source.
23813 @node Treatment of Pragma Elaborate
23814 @section Treatment of Pragma Elaborate
23815 @cindex Pragma Elaborate
23818 The use of @code{pragma Elaborate}
23819 should generally be avoided in Ada 95 programs.
23820 The reason for this is that there is no guarantee that transitive calls
23821 will be properly handled. Indeed at one point, this pragma was placed
23822 in Annex J (Obsolescent Features), on the grounds that it is never useful.
23824 Now that's a bit restrictive. In practice, the case in which
23825 @code{pragma Elaborate} is useful is when the caller knows that there
23826 are no transitive calls, or that the called unit contains all necessary
23827 transitive @code{pragma Elaborate} statements, and legacy code often
23828 contains such uses.
23830 Strictly speaking the static mode in GNAT should ignore such pragmas,
23831 since there is no assurance at compile time that the necessary safety
23832 conditions are met. In practice, this would cause GNAT to be incompatible
23833 with correctly written Ada 83 code that had all necessary
23834 @code{pragma Elaborate} statements in place. Consequently, we made the
23835 decision that GNAT in its default mode will believe that if it encounters
23836 a @code{pragma Elaborate} then the programmer knows what they are doing,
23837 and it will trust that no elaboration errors can occur.
23839 The result of this decision is two-fold. First to be safe using the
23840 static mode, you should remove all @code{pragma Elaborate} statements.
23841 Second, when fixing circularities in existing code, you can selectively
23842 use @code{pragma Elaborate} statements to convince the static mode of
23843 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
23846 When using the static mode with @option{-gnatwl}, any use of
23847 @code{pragma Elaborate} will generate a warning about possible
23850 @node Elaboration Issues for Library Tasks
23851 @section Elaboration Issues for Library Tasks
23852 @cindex Library tasks, elaboration issues
23853 @cindex Elaboration of library tasks
23856 In this section we examine special elaboration issues that arise for
23857 programs that declare library level tasks.
23859 Generally the model of execution of an Ada program is that all units are
23860 elaborated, and then execution of the program starts. However, the
23861 declaration of library tasks definitely does not fit this model. The
23862 reason for this is that library tasks start as soon as they are declared
23863 (more precisely, as soon as the statement part of the enclosing package
23864 body is reached), that is to say before elaboration
23865 of the program is complete. This means that if such a task calls a
23866 subprogram, or an entry in another task, the callee may or may not be
23867 elaborated yet, and in the standard
23868 Reference Manual model of dynamic elaboration checks, you can even
23869 get timing dependent Program_Error exceptions, since there can be
23870 a race between the elaboration code and the task code.
23872 The static model of elaboration in GNAT seeks to avoid all such
23873 dynamic behavior, by being conservative, and the conservative
23874 approach in this particular case is to assume that all the code
23875 in a task body is potentially executed at elaboration time if
23876 a task is declared at the library level.
23878 This can definitely result in unexpected circularities. Consider
23879 the following example
23881 @smallexample @c ada
23887 type My_Int is new Integer;
23889 function Ident (M : My_Int) return My_Int;
23893 package body Decls is
23894 task body Lib_Task is
23900 function Ident (M : My_Int) return My_Int is
23908 procedure Put_Val (Arg : Decls.My_Int);
23912 package body Utils is
23913 procedure Put_Val (Arg : Decls.My_Int) is
23915 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23922 Decls.Lib_Task.Start;
23927 If the above example is compiled in the default static elaboration
23928 mode, then a circularity occurs. The circularity comes from the call
23929 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
23930 this call occurs in elaboration code, we need an implicit pragma
23931 @code{Elaborate_All} for @code{Utils}. This means that not only must
23932 the spec and body of @code{Utils} be elaborated before the body
23933 of @code{Decls}, but also the spec and body of any unit that is
23934 @code{with'ed} by the body of @code{Utils} must also be elaborated before
23935 the body of @code{Decls}. This is the transitive implication of
23936 pragma @code{Elaborate_All} and it makes sense, because in general
23937 the body of @code{Put_Val} might have a call to something in a
23938 @code{with'ed} unit.
23940 In this case, the body of Utils (actually its spec) @code{with's}
23941 @code{Decls}. Unfortunately this means that the body of @code{Decls}
23942 must be elaborated before itself, in case there is a call from the
23943 body of @code{Utils}.
23945 Here is the exact chain of events we are worrying about:
23949 In the body of @code{Decls} a call is made from within the body of a library
23950 task to a subprogram in the package @code{Utils}. Since this call may
23951 occur at elaboration time (given that the task is activated at elaboration
23952 time), we have to assume the worst, i.e. that the
23953 call does happen at elaboration time.
23956 This means that the body and spec of @code{Util} must be elaborated before
23957 the body of @code{Decls} so that this call does not cause an access before
23961 Within the body of @code{Util}, specifically within the body of
23962 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
23966 One such @code{with}'ed package is package @code{Decls}, so there
23967 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
23968 In fact there is such a call in this example, but we would have to
23969 assume that there was such a call even if it were not there, since
23970 we are not supposed to write the body of @code{Decls} knowing what
23971 is in the body of @code{Utils}; certainly in the case of the
23972 static elaboration model, the compiler does not know what is in
23973 other bodies and must assume the worst.
23976 This means that the spec and body of @code{Decls} must also be
23977 elaborated before we elaborate the unit containing the call, but
23978 that unit is @code{Decls}! This means that the body of @code{Decls}
23979 must be elaborated before itself, and that's a circularity.
23983 Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in
23984 the body of @code{Decls} you will get a true Ada Reference Manual
23985 circularity that makes the program illegal.
23987 In practice, we have found that problems with the static model of
23988 elaboration in existing code often arise from library tasks, so
23989 we must address this particular situation.
23991 Note that if we compile and run the program above, using the dynamic model of
23992 elaboration (that is to say use the @option{-gnatE} switch),
23993 then it compiles, binds,
23994 links, and runs, printing the expected result of 2. Therefore in some sense
23995 the circularity here is only apparent, and we need to capture
23996 the properties of this program that distinguish it from other library-level
23997 tasks that have real elaboration problems.
23999 We have four possible answers to this question:
24004 Use the dynamic model of elaboration.
24006 If we use the @option{-gnatE} switch, then as noted above, the program works.
24007 Why is this? If we examine the task body, it is apparent that the task cannot
24009 @code{accept} statement until after elaboration has been completed, because
24010 the corresponding entry call comes from the main program, not earlier.
24011 This is why the dynamic model works here. But that's really giving
24012 up on a precise analysis, and we prefer to take this approach only if we cannot
24014 problem in any other manner. So let us examine two ways to reorganize
24015 the program to avoid the potential elaboration problem.
24018 Split library tasks into separate packages.
24020 Write separate packages, so that library tasks are isolated from
24021 other declarations as much as possible. Let us look at a variation on
24024 @smallexample @c ada
24032 package body Decls1 is
24033 task body Lib_Task is
24041 type My_Int is new Integer;
24042 function Ident (M : My_Int) return My_Int;
24046 package body Decls2 is
24047 function Ident (M : My_Int) return My_Int is
24055 procedure Put_Val (Arg : Decls2.My_Int);
24059 package body Utils is
24060 procedure Put_Val (Arg : Decls2.My_Int) is
24062 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
24069 Decls1.Lib_Task.Start;
24074 All we have done is to split @code{Decls} into two packages, one
24075 containing the library task, and one containing everything else. Now
24076 there is no cycle, and the program compiles, binds, links and executes
24077 using the default static model of elaboration.
24080 Declare separate task types.
24082 A significant part of the problem arises because of the use of the
24083 single task declaration form. This means that the elaboration of
24084 the task type, and the elaboration of the task itself (i.e. the
24085 creation of the task) happen at the same time. A good rule
24086 of style in Ada 95 is to always create explicit task types. By
24087 following the additional step of placing task objects in separate
24088 packages from the task type declaration, many elaboration problems
24089 are avoided. Here is another modified example of the example program:
24091 @smallexample @c ada
24093 task type Lib_Task_Type is
24097 type My_Int is new Integer;
24099 function Ident (M : My_Int) return My_Int;
24103 package body Decls is
24104 task body Lib_Task_Type is
24110 function Ident (M : My_Int) return My_Int is
24118 procedure Put_Val (Arg : Decls.My_Int);
24122 package body Utils is
24123 procedure Put_Val (Arg : Decls.My_Int) is
24125 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24131 Lib_Task : Decls.Lib_Task_Type;
24137 Declst.Lib_Task.Start;
24142 What we have done here is to replace the @code{task} declaration in
24143 package @code{Decls} with a @code{task type} declaration. Then we
24144 introduce a separate package @code{Declst} to contain the actual
24145 task object. This separates the elaboration issues for
24146 the @code{task type}
24147 declaration, which causes no trouble, from the elaboration issues
24148 of the task object, which is also unproblematic, since it is now independent
24149 of the elaboration of @code{Utils}.
24150 This separation of concerns also corresponds to
24151 a generally sound engineering principle of separating declarations
24152 from instances. This version of the program also compiles, binds, links,
24153 and executes, generating the expected output.
24156 Use No_Entry_Calls_In_Elaboration_Code restriction.
24157 @cindex No_Entry_Calls_In_Elaboration_Code
24159 The previous two approaches described how a program can be restructured
24160 to avoid the special problems caused by library task bodies. in practice,
24161 however, such restructuring may be difficult to apply to existing legacy code,
24162 so we must consider solutions that do not require massive rewriting.
24164 Let us consider more carefully why our original sample program works
24165 under the dynamic model of elaboration. The reason is that the code
24166 in the task body blocks immediately on the @code{accept}
24167 statement. Now of course there is nothing to prohibit elaboration
24168 code from making entry calls (for example from another library level task),
24169 so we cannot tell in isolation that
24170 the task will not execute the accept statement during elaboration.
24172 However, in practice it is very unusual to see elaboration code
24173 make any entry calls, and the pattern of tasks starting
24174 at elaboration time and then immediately blocking on @code{accept} or
24175 @code{select} statements is very common. What this means is that
24176 the compiler is being too pessimistic when it analyzes the
24177 whole package body as though it might be executed at elaboration
24180 If we know that the elaboration code contains no entry calls, (a very safe
24181 assumption most of the time, that could almost be made the default
24182 behavior), then we can compile all units of the program under control
24183 of the following configuration pragma:
24186 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
24190 This pragma can be placed in the @file{gnat.adc} file in the usual
24191 manner. If we take our original unmodified program and compile it
24192 in the presence of a @file{gnat.adc} containing the above pragma,
24193 then once again, we can compile, bind, link, and execute, obtaining
24194 the expected result. In the presence of this pragma, the compiler does
24195 not trace calls in a task body, that appear after the first @code{accept}
24196 or @code{select} statement, and therefore does not report a potential
24197 circularity in the original program.
24199 The compiler will check to the extent it can that the above
24200 restriction is not violated, but it is not always possible to do a
24201 complete check at compile time, so it is important to use this
24202 pragma only if the stated restriction is in fact met, that is to say
24203 no task receives an entry call before elaboration of all units is completed.
24207 @node Mixing Elaboration Models
24208 @section Mixing Elaboration Models
24210 So far, we have assumed that the entire program is either compiled
24211 using the dynamic model or static model, ensuring consistency. It
24212 is possible to mix the two models, but rules have to be followed
24213 if this mixing is done to ensure that elaboration checks are not
24216 The basic rule is that @emph{a unit compiled with the static model cannot
24217 be @code{with'ed} by a unit compiled with the dynamic model}. The
24218 reason for this is that in the static model, a unit assumes that
24219 its clients guarantee to use (the equivalent of) pragma
24220 @code{Elaborate_All} so that no elaboration checks are required
24221 in inner subprograms, and this assumption is violated if the
24222 client is compiled with dynamic checks.
24224 The precise rule is as follows. A unit that is compiled with dynamic
24225 checks can only @code{with} a unit that meets at least one of the
24226 following criteria:
24231 The @code{with'ed} unit is itself compiled with dynamic elaboration
24232 checks (that is with the @option{-gnatE} switch.
24235 The @code{with'ed} unit is an internal GNAT implementation unit from
24236 the System, Interfaces, Ada, or GNAT hierarchies.
24239 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
24242 The @code{with'ing} unit (that is the client) has an explicit pragma
24243 @code{Elaborate_All} for the @code{with'ed} unit.
24248 If this rule is violated, that is if a unit with dynamic elaboration
24249 checks @code{with's} a unit that does not meet one of the above four
24250 criteria, then the binder (@code{gnatbind}) will issue a warning
24251 similar to that in the following example:
24254 warning: "x.ads" has dynamic elaboration checks and with's
24255 warning: "y.ads" which has static elaboration checks
24259 These warnings indicate that the rule has been violated, and that as a result
24260 elaboration checks may be missed in the resulting executable file.
24261 This warning may be suppressed using the @option{-ws} binder switch
24262 in the usual manner.
24264 One useful application of this mixing rule is in the case of a subsystem
24265 which does not itself @code{with} units from the remainder of the
24266 application. In this case, the entire subsystem can be compiled with
24267 dynamic checks to resolve a circularity in the subsystem, while
24268 allowing the main application that uses this subsystem to be compiled
24269 using the more reliable default static model.
24271 @node What to Do If the Default Elaboration Behavior Fails
24272 @section What to Do If the Default Elaboration Behavior Fails
24275 If the binder cannot find an acceptable order, it outputs detailed
24276 diagnostics. For example:
24282 error: elaboration circularity detected
24283 info: "proc (body)" must be elaborated before "pack (body)"
24284 info: reason: Elaborate_All probably needed in unit "pack (body)"
24285 info: recompile "pack (body)" with -gnatwl
24286 info: for full details
24287 info: "proc (body)"
24288 info: is needed by its spec:
24289 info: "proc (spec)"
24290 info: which is withed by:
24291 info: "pack (body)"
24292 info: "pack (body)" must be elaborated before "proc (body)"
24293 info: reason: pragma Elaborate in unit "proc (body)"
24299 In this case we have a cycle that the binder cannot break. On the one
24300 hand, there is an explicit pragma Elaborate in @code{proc} for
24301 @code{pack}. This means that the body of @code{pack} must be elaborated
24302 before the body of @code{proc}. On the other hand, there is elaboration
24303 code in @code{pack} that calls a subprogram in @code{proc}. This means
24304 that for maximum safety, there should really be a pragma
24305 Elaborate_All in @code{pack} for @code{proc} which would require that
24306 the body of @code{proc} be elaborated before the body of
24307 @code{pack}. Clearly both requirements cannot be satisfied.
24308 Faced with a circularity of this kind, you have three different options.
24311 @item Fix the program
24312 The most desirable option from the point of view of long-term maintenance
24313 is to rearrange the program so that the elaboration problems are avoided.
24314 One useful technique is to place the elaboration code into separate
24315 child packages. Another is to move some of the initialization code to
24316 explicitly called subprograms, where the program controls the order
24317 of initialization explicitly. Although this is the most desirable option,
24318 it may be impractical and involve too much modification, especially in
24319 the case of complex legacy code.
24321 @item Perform dynamic checks
24322 If the compilations are done using the
24324 (dynamic elaboration check) switch, then GNAT behaves in
24325 a quite different manner. Dynamic checks are generated for all calls
24326 that could possibly result in raising an exception. With this switch,
24327 the compiler does not generate implicit @code{Elaborate_All} pragmas.
24328 The behavior then is exactly as specified in the Ada 95 Reference Manual.
24329 The binder will generate an executable program that may or may not
24330 raise @code{Program_Error}, and then it is the programmer's job to ensure
24331 that it does not raise an exception. Note that it is important to
24332 compile all units with the switch, it cannot be used selectively.
24334 @item Suppress checks
24335 The drawback of dynamic checks is that they generate a
24336 significant overhead at run time, both in space and time. If you
24337 are absolutely sure that your program cannot raise any elaboration
24338 exceptions, and you still want to use the dynamic elaboration model,
24339 then you can use the configuration pragma
24340 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
24341 example this pragma could be placed in the @file{gnat.adc} file.
24343 @item Suppress checks selectively
24344 When you know that certain calls in elaboration code cannot possibly
24345 lead to an elaboration error, and the binder nevertheless generates warnings
24346 on those calls and inserts Elaborate_All pragmas that lead to elaboration
24347 circularities, it is possible to remove those warnings locally and obtain
24348 a program that will bind. Clearly this can be unsafe, and it is the
24349 responsibility of the programmer to make sure that the resulting program has
24350 no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can
24351 be used with different granularity to suppress warnings and break
24352 elaboration circularities:
24356 Place the pragma that names the called subprogram in the declarative part
24357 that contains the call.
24360 Place the pragma in the declarative part, without naming an entity. This
24361 disables warnings on all calls in the corresponding declarative region.
24364 Place the pragma in the package spec that declares the called subprogram,
24365 and name the subprogram. This disables warnings on all elaboration calls to
24369 Place the pragma in the package spec that declares the called subprogram,
24370 without naming any entity. This disables warnings on all elaboration calls to
24371 all subprograms declared in this spec.
24373 @item Use Pragma Elaborate
24374 As previously described in section @xref{Treatment of Pragma Elaborate},
24375 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
24376 that no elaboration checks are required on calls to the designated unit.
24377 There may be cases in which the caller knows that no transitive calls
24378 can occur, so that a @code{pragma Elaborate} will be sufficient in a
24379 case where @code{pragma Elaborate_All} would cause a circularity.
24383 These five cases are listed in order of decreasing safety, and therefore
24384 require increasing programmer care in their application. Consider the
24387 @smallexample @c adanocomment
24389 function F1 return Integer;
24394 function F2 return Integer;
24395 function Pure (x : integer) return integer;
24396 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
24397 -- pragma Suppress (Elaboration_Check); -- (4)
24401 package body Pack1 is
24402 function F1 return Integer is
24406 Val : integer := Pack2.Pure (11); -- Elab. call (1)
24409 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
24410 -- pragma Suppress(Elaboration_Check); -- (2)
24412 X1 := Pack2.F2 + 1; -- Elab. call (2)
24417 package body Pack2 is
24418 function F2 return Integer is
24422 function Pure (x : integer) return integer is
24424 return x ** 3 - 3 * x;
24428 with Pack1, Ada.Text_IO;
24431 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24434 In the absence of any pragmas, an attempt to bind this program produces
24435 the following diagnostics:
24441 error: elaboration circularity detected
24442 info: "pack1 (body)" must be elaborated before "pack1 (body)"
24443 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
24444 info: recompile "pack1 (body)" with -gnatwl for full details
24445 info: "pack1 (body)"
24446 info: must be elaborated along with its spec:
24447 info: "pack1 (spec)"
24448 info: which is withed by:
24449 info: "pack2 (body)"
24450 info: which must be elaborated along with its spec:
24451 info: "pack2 (spec)"
24452 info: which is withed by:
24453 info: "pack1 (body)"
24456 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24457 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24458 F2 is safe, even though F2 calls F1, because the call appears after the
24459 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24460 remove the warning on the call. It is also possible to use pragma (2)
24461 because there are no other potentially unsafe calls in the block.
24464 The call to @code{Pure} is safe because this function does not depend on the
24465 state of @code{Pack2}. Therefore any call to this function is safe, and it
24466 is correct to place pragma (3) in the corresponding package spec.
24469 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24470 warnings on all calls to functions declared therein. Note that this is not
24471 necessarily safe, and requires more detailed examination of the subprogram
24472 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24473 be already elaborated.
24477 It is hard to generalize on which of these four approaches should be
24478 taken. Obviously if it is possible to fix the program so that the default
24479 treatment works, this is preferable, but this may not always be practical.
24480 It is certainly simple enough to use
24482 but the danger in this case is that, even if the GNAT binder
24483 finds a correct elaboration order, it may not always do so,
24484 and certainly a binder from another Ada compiler might not. A
24485 combination of testing and analysis (for which the warnings generated
24488 switch can be useful) must be used to ensure that the program is free
24489 of errors. One switch that is useful in this testing is the
24490 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
24493 Normally the binder tries to find an order that has the best chance of
24494 of avoiding elaboration problems. With this switch, the binder
24495 plays a devil's advocate role, and tries to choose the order that
24496 has the best chance of failing. If your program works even with this
24497 switch, then it has a better chance of being error free, but this is still
24500 For an example of this approach in action, consider the C-tests (executable
24501 tests) from the ACVC suite. If these are compiled and run with the default
24502 treatment, then all but one of them succeed without generating any error
24503 diagnostics from the binder. However, there is one test that fails, and
24504 this is not surprising, because the whole point of this test is to ensure
24505 that the compiler can handle cases where it is impossible to determine
24506 a correct order statically, and it checks that an exception is indeed
24507 raised at run time.
24509 This one test must be compiled and run using the
24511 switch, and then it passes. Alternatively, the entire suite can
24512 be run using this switch. It is never wrong to run with the dynamic
24513 elaboration switch if your code is correct, and we assume that the
24514 C-tests are indeed correct (it is less efficient, but efficiency is
24515 not a factor in running the ACVC tests.)
24517 @node Elaboration for Access-to-Subprogram Values
24518 @section Elaboration for Access-to-Subprogram Values
24519 @cindex Access-to-subprogram
24522 The introduction of access-to-subprogram types in Ada 95 complicates
24523 the handling of elaboration. The trouble is that it becomes
24524 impossible to tell at compile time which procedure
24525 is being called. This means that it is not possible for the binder
24526 to analyze the elaboration requirements in this case.
24528 If at the point at which the access value is created
24529 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
24530 the body of the subprogram is
24531 known to have been elaborated, then the access value is safe, and its use
24532 does not require a check. This may be achieved by appropriate arrangement
24533 of the order of declarations if the subprogram is in the current unit,
24534 or, if the subprogram is in another unit, by using pragma
24535 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
24536 on the referenced unit.
24538 If the referenced body is not known to have been elaborated at the point
24539 the access value is created, then any use of the access value must do a
24540 dynamic check, and this dynamic check will fail and raise a
24541 @code{Program_Error} exception if the body has not been elaborated yet.
24542 GNAT will generate the necessary checks, and in addition, if the
24544 switch is set, will generate warnings that such checks are required.
24546 The use of dynamic dispatching for tagged types similarly generates
24547 a requirement for dynamic checks, and premature calls to any primitive
24548 operation of a tagged type before the body of the operation has been
24549 elaborated, will result in the raising of @code{Program_Error}.
24551 @node Summary of Procedures for Elaboration Control
24552 @section Summary of Procedures for Elaboration Control
24553 @cindex Elaboration control
24556 First, compile your program with the default options, using none of
24557 the special elaboration control switches. If the binder successfully
24558 binds your program, then you can be confident that, apart from issues
24559 raised by the use of access-to-subprogram types and dynamic dispatching,
24560 the program is free of elaboration errors. If it is important that the
24561 program be portable, then use the
24563 switch to generate warnings about missing @code{Elaborate_All}
24564 pragmas, and supply the missing pragmas.
24566 If the program fails to bind using the default static elaboration
24567 handling, then you can fix the program to eliminate the binder
24568 message, or recompile the entire program with the
24569 @option{-gnatE} switch to generate dynamic elaboration checks,
24570 and, if you are sure there really are no elaboration problems,
24571 use a global pragma @code{Suppress (Elaboration_Check)}.
24573 @node Other Elaboration Order Considerations
24574 @section Other Elaboration Order Considerations
24576 This section has been entirely concerned with the issue of finding a valid
24577 elaboration order, as defined by the Ada Reference Manual. In a case
24578 where several elaboration orders are valid, the task is to find one
24579 of the possible valid elaboration orders (and the static model in GNAT
24580 will ensure that this is achieved).
24582 The purpose of the elaboration rules in the Ada Reference Manual is to
24583 make sure that no entity is accessed before it has been elaborated. For
24584 a subprogram, this means that the spec and body must have been elaborated
24585 before the subprogram is called. For an object, this means that the object
24586 must have been elaborated before its value is read or written. A violation
24587 of either of these two requirements is an access before elaboration order,
24588 and this section has been all about avoiding such errors.
24590 In the case where more than one order of elaboration is possible, in the
24591 sense that access before elaboration errors are avoided, then any one of
24592 the orders is ``correct'' in the sense that it meets the requirements of
24593 the Ada Reference Manual, and no such error occurs.
24595 However, it may be the case for a given program, that there are
24596 constraints on the order of elaboration that come not from consideration
24597 of avoiding elaboration errors, but rather from extra-lingual logic
24598 requirements. Consider this example:
24600 @smallexample @c ada
24601 with Init_Constants;
24602 package Constants is
24607 package Init_Constants is
24608 procedure P; -- require a body
24609 end Init_Constants;
24612 package body Init_Constants is
24613 procedure P is begin null; end;
24617 end Init_Constants;
24621 Z : Integer := Constants.X + Constants.Y;
24625 with Text_IO; use Text_IO;
24628 Put_Line (Calc.Z'Img);
24633 In this example, there is more than one valid order of elaboration. For
24634 example both the following are correct orders:
24637 Init_Constants spec
24640 Init_Constants body
24645 Init_Constants spec
24646 Init_Constants body
24653 There is no language rule to prefer one or the other, both are correct
24654 from an order of elaboration point of view. But the programmatic effects
24655 of the two orders are very different. In the first, the elaboration routine
24656 of @code{Calc} initializes @code{Z} to zero, and then the main program
24657 runs with this value of zero. But in the second order, the elaboration
24658 routine of @code{Calc} runs after the body of Init_Constants has set
24659 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
24662 One could perhaps by applying pretty clever non-artificial intelligence
24663 to the situation guess that it is more likely that the second order of
24664 elaboration is the one desired, but there is no formal linguistic reason
24665 to prefer one over the other. In fact in this particular case, GNAT will
24666 prefer the second order, because of the rule that bodies are elaborated
24667 as soon as possible, but it's just luck that this is what was wanted
24668 (if indeed the second order was preferred).
24670 If the program cares about the order of elaboration routines in a case like
24671 this, it is important to specify the order required. In this particular
24672 case, that could have been achieved by adding to the spec of Calc:
24674 @smallexample @c ada
24675 pragma Elaborate_All (Constants);
24679 which requires that the body (if any) and spec of @code{Constants},
24680 as well as the body and spec of any unit @code{with}'ed by
24681 @code{Constants} be elaborated before @code{Calc} is elaborated.
24683 Clearly no automatic method can always guess which alternative you require,
24684 and if you are working with legacy code that had constraints of this kind
24685 which were not properly specified by adding @code{Elaborate} or
24686 @code{Elaborate_All} pragmas, then indeed it is possible that two different
24687 compilers can choose different orders.
24689 The @code{gnatbind}
24690 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
24691 out problems. This switch causes bodies to be elaborated as late as possible
24692 instead of as early as possible. In the example above, it would have forced
24693 the choice of the first elaboration order. If you get different results
24694 when using this switch, and particularly if one set of results is right,
24695 and one is wrong as far as you are concerned, it shows that you have some
24696 missing @code{Elaborate} pragmas. For the example above, we have the
24700 gnatmake -f -q main
24703 gnatmake -f -q main -bargs -p
24709 It is of course quite unlikely that both these results are correct, so
24710 it is up to you in a case like this to investigate the source of the
24711 difference, by looking at the two elaboration orders that are chosen,
24712 and figuring out which is correct, and then adding the necessary
24713 @code{Elaborate_All} pragmas to ensure the desired order.
24715 @node Inline Assembler
24716 @appendix Inline Assembler
24719 If you need to write low-level software that interacts directly
24720 with the hardware, Ada provides two ways to incorporate assembly
24721 language code into your program. First, you can import and invoke
24722 external routines written in assembly language, an Ada feature fully
24723 supported by GNAT. However, for small sections of code it may be simpler
24724 or more efficient to include assembly language statements directly
24725 in your Ada source program, using the facilities of the implementation-defined
24726 package @code{System.Machine_Code}, which incorporates the gcc
24727 Inline Assembler. The Inline Assembler approach offers a number of advantages,
24728 including the following:
24731 @item No need to use non-Ada tools
24732 @item Consistent interface over different targets
24733 @item Automatic usage of the proper calling conventions
24734 @item Access to Ada constants and variables
24735 @item Definition of intrinsic routines
24736 @item Possibility of inlining a subprogram comprising assembler code
24737 @item Code optimizer can take Inline Assembler code into account
24740 This chapter presents a series of examples to show you how to use
24741 the Inline Assembler. Although it focuses on the Intel x86,
24742 the general approach applies also to other processors.
24743 It is assumed that you are familiar with Ada
24744 and with assembly language programming.
24747 * Basic Assembler Syntax::
24748 * A Simple Example of Inline Assembler::
24749 * Output Variables in Inline Assembler::
24750 * Input Variables in Inline Assembler::
24751 * Inlining Inline Assembler Code::
24752 * Other Asm Functionality::
24755 @c ---------------------------------------------------------------------------
24756 @node Basic Assembler Syntax
24757 @section Basic Assembler Syntax
24760 The assembler used by GNAT and gcc is based not on the Intel assembly
24761 language, but rather on a language that descends from the AT&T Unix
24762 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
24763 The following table summarizes the main features of @emph{as} syntax
24764 and points out the differences from the Intel conventions.
24765 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
24766 pre-processor) documentation for further information.
24769 @item Register names
24770 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
24772 Intel: No extra punctuation; for example @code{eax}
24774 @item Immediate operand
24775 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
24777 Intel: No extra punctuation; for example @code{4}
24780 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
24782 Intel: No extra punctuation; for example @code{loc}
24784 @item Memory contents
24785 gcc / @emph{as}: No extra punctuation; for example @code{loc}
24787 Intel: Square brackets; for example @code{[loc]}
24789 @item Register contents
24790 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
24792 Intel: Square brackets; for example @code{[eax]}
24794 @item Hexadecimal numbers
24795 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
24797 Intel: Trailing ``h''; for example @code{A0h}
24800 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
24803 Intel: Implicit, deduced by assembler; for example @code{mov}
24805 @item Instruction repetition
24806 gcc / @emph{as}: Split into two lines; for example
24812 Intel: Keep on one line; for example @code{rep stosl}
24814 @item Order of operands
24815 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
24817 Intel: Destination first; for example @code{mov eax, 4}
24820 @c ---------------------------------------------------------------------------
24821 @node A Simple Example of Inline Assembler
24822 @section A Simple Example of Inline Assembler
24825 The following example will generate a single assembly language statement,
24826 @code{nop}, which does nothing. Despite its lack of run-time effect,
24827 the example will be useful in illustrating the basics of
24828 the Inline Assembler facility.
24830 @smallexample @c ada
24832 with System.Machine_Code; use System.Machine_Code;
24833 procedure Nothing is
24840 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
24841 here it takes one parameter, a @emph{template string} that must be a static
24842 expression and that will form the generated instruction.
24843 @code{Asm} may be regarded as a compile-time procedure that parses
24844 the template string and additional parameters (none here),
24845 from which it generates a sequence of assembly language instructions.
24847 The examples in this chapter will illustrate several of the forms
24848 for invoking @code{Asm}; a complete specification of the syntax
24849 is found in the @cite{GNAT Reference Manual}.
24851 Under the standard GNAT conventions, the @code{Nothing} procedure
24852 should be in a file named @file{nothing.adb}.
24853 You can build the executable in the usual way:
24857 However, the interesting aspect of this example is not its run-time behavior
24858 but rather the generated assembly code.
24859 To see this output, invoke the compiler as follows:
24861 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
24863 where the options are:
24867 compile only (no bind or link)
24869 generate assembler listing
24870 @item -fomit-frame-pointer
24871 do not set up separate stack frames
24873 do not add runtime checks
24876 This gives a human-readable assembler version of the code. The resulting
24877 file will have the same name as the Ada source file, but with a @code{.s}
24878 extension. In our example, the file @file{nothing.s} has the following
24883 .file "nothing.adb"
24885 ___gnu_compiled_ada:
24888 .globl __ada_nothing
24900 The assembly code you included is clearly indicated by
24901 the compiler, between the @code{#APP} and @code{#NO_APP}
24902 delimiters. The character before the 'APP' and 'NOAPP'
24903 can differ on different targets. For example, GNU/Linux uses '#APP' while
24904 on NT you will see '/APP'.
24906 If you make a mistake in your assembler code (such as using the
24907 wrong size modifier, or using a wrong operand for the instruction) GNAT
24908 will report this error in a temporary file, which will be deleted when
24909 the compilation is finished. Generating an assembler file will help
24910 in such cases, since you can assemble this file separately using the
24911 @emph{as} assembler that comes with gcc.
24913 Assembling the file using the command
24916 as @file{nothing.s}
24919 will give you error messages whose lines correspond to the assembler
24920 input file, so you can easily find and correct any mistakes you made.
24921 If there are no errors, @emph{as} will generate an object file
24922 @file{nothing.out}.
24924 @c ---------------------------------------------------------------------------
24925 @node Output Variables in Inline Assembler
24926 @section Output Variables in Inline Assembler
24929 The examples in this section, showing how to access the processor flags,
24930 illustrate how to specify the destination operands for assembly language
24933 @smallexample @c ada
24935 with Interfaces; use Interfaces;
24936 with Ada.Text_IO; use Ada.Text_IO;
24937 with System.Machine_Code; use System.Machine_Code;
24938 procedure Get_Flags is
24939 Flags : Unsigned_32;
24942 Asm ("pushfl" & LF & HT & -- push flags on stack
24943 "popl %%eax" & LF & HT & -- load eax with flags
24944 "movl %%eax, %0", -- store flags in variable
24945 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24946 Put_Line ("Flags register:" & Flags'Img);
24951 In order to have a nicely aligned assembly listing, we have separated
24952 multiple assembler statements in the Asm template string with linefeed
24953 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
24954 The resulting section of the assembly output file is:
24961 movl %eax, -40(%ebp)
24966 It would have been legal to write the Asm invocation as:
24969 Asm ("pushfl popl %%eax movl %%eax, %0")
24972 but in the generated assembler file, this would come out as:
24976 pushfl popl %eax movl %eax, -40(%ebp)
24980 which is not so convenient for the human reader.
24982 We use Ada comments
24983 at the end of each line to explain what the assembler instructions
24984 actually do. This is a useful convention.
24986 When writing Inline Assembler instructions, you need to precede each register
24987 and variable name with a percent sign. Since the assembler already requires
24988 a percent sign at the beginning of a register name, you need two consecutive
24989 percent signs for such names in the Asm template string, thus @code{%%eax}.
24990 In the generated assembly code, one of the percent signs will be stripped off.
24992 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
24993 variables: operands you later define using @code{Input} or @code{Output}
24994 parameters to @code{Asm}.
24995 An output variable is illustrated in
24996 the third statement in the Asm template string:
25000 The intent is to store the contents of the eax register in a variable that can
25001 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
25002 necessarily work, since the compiler might optimize by using a register
25003 to hold Flags, and the expansion of the @code{movl} instruction would not be
25004 aware of this optimization. The solution is not to store the result directly
25005 but rather to advise the compiler to choose the correct operand form;
25006 that is the purpose of the @code{%0} output variable.
25008 Information about the output variable is supplied in the @code{Outputs}
25009 parameter to @code{Asm}:
25011 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25014 The output is defined by the @code{Asm_Output} attribute of the target type;
25015 the general format is
25017 Type'Asm_Output (constraint_string, variable_name)
25020 The constraint string directs the compiler how
25021 to store/access the associated variable. In the example
25023 Unsigned_32'Asm_Output ("=m", Flags);
25025 the @code{"m"} (memory) constraint tells the compiler that the variable
25026 @code{Flags} should be stored in a memory variable, thus preventing
25027 the optimizer from keeping it in a register. In contrast,
25029 Unsigned_32'Asm_Output ("=r", Flags);
25031 uses the @code{"r"} (register) constraint, telling the compiler to
25032 store the variable in a register.
25034 If the constraint is preceded by the equal character (@strong{=}), it tells
25035 the compiler that the variable will be used to store data into it.
25037 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
25038 allowing the optimizer to choose whatever it deems best.
25040 There are a fairly large number of constraints, but the ones that are
25041 most useful (for the Intel x86 processor) are the following:
25047 global (i.e. can be stored anywhere)
25065 use one of eax, ebx, ecx or edx
25067 use one of eax, ebx, ecx, edx, esi or edi
25070 The full set of constraints is described in the gcc and @emph{as}
25071 documentation; note that it is possible to combine certain constraints
25072 in one constraint string.
25074 You specify the association of an output variable with an assembler operand
25075 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
25077 @smallexample @c ada
25079 Asm ("pushfl" & LF & HT & -- push flags on stack
25080 "popl %%eax" & LF & HT & -- load eax with flags
25081 "movl %%eax, %0", -- store flags in variable
25082 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25086 @code{%0} will be replaced in the expanded code by the appropriate operand,
25088 the compiler decided for the @code{Flags} variable.
25090 In general, you may have any number of output variables:
25093 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
25095 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
25096 of @code{Asm_Output} attributes
25100 @smallexample @c ada
25102 Asm ("movl %%eax, %0" & LF & HT &
25103 "movl %%ebx, %1" & LF & HT &
25105 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
25106 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
25107 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
25111 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
25112 in the Ada program.
25114 As a variation on the @code{Get_Flags} example, we can use the constraints
25115 string to direct the compiler to store the eax register into the @code{Flags}
25116 variable, instead of including the store instruction explicitly in the
25117 @code{Asm} template string:
25119 @smallexample @c ada
25121 with Interfaces; use Interfaces;
25122 with Ada.Text_IO; use Ada.Text_IO;
25123 with System.Machine_Code; use System.Machine_Code;
25124 procedure Get_Flags_2 is
25125 Flags : Unsigned_32;
25128 Asm ("pushfl" & LF & HT & -- push flags on stack
25129 "popl %%eax", -- save flags in eax
25130 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
25131 Put_Line ("Flags register:" & Flags'Img);
25137 The @code{"a"} constraint tells the compiler that the @code{Flags}
25138 variable will come from the eax register. Here is the resulting code:
25146 movl %eax,-40(%ebp)
25151 The compiler generated the store of eax into Flags after
25152 expanding the assembler code.
25154 Actually, there was no need to pop the flags into the eax register;
25155 more simply, we could just pop the flags directly into the program variable:
25157 @smallexample @c ada
25159 with Interfaces; use Interfaces;
25160 with Ada.Text_IO; use Ada.Text_IO;
25161 with System.Machine_Code; use System.Machine_Code;
25162 procedure Get_Flags_3 is
25163 Flags : Unsigned_32;
25166 Asm ("pushfl" & LF & HT & -- push flags on stack
25167 "pop %0", -- save flags in Flags
25168 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25169 Put_Line ("Flags register:" & Flags'Img);
25174 @c ---------------------------------------------------------------------------
25175 @node Input Variables in Inline Assembler
25176 @section Input Variables in Inline Assembler
25179 The example in this section illustrates how to specify the source operands
25180 for assembly language statements.
25181 The program simply increments its input value by 1:
25183 @smallexample @c ada
25185 with Interfaces; use Interfaces;
25186 with Ada.Text_IO; use Ada.Text_IO;
25187 with System.Machine_Code; use System.Machine_Code;
25188 procedure Increment is
25190 function Incr (Value : Unsigned_32) return Unsigned_32 is
25191 Result : Unsigned_32;
25194 Inputs => Unsigned_32'Asm_Input ("a", Value),
25195 Outputs => Unsigned_32'Asm_Output ("=a", Result));
25199 Value : Unsigned_32;
25203 Put_Line ("Value before is" & Value'Img);
25204 Value := Incr (Value);
25205 Put_Line ("Value after is" & Value'Img);
25210 The @code{Outputs} parameter to @code{Asm} specifies
25211 that the result will be in the eax register and that it is to be stored
25212 in the @code{Result} variable.
25214 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
25215 but with an @code{Asm_Input} attribute.
25216 The @code{"="} constraint, indicating an output value, is not present.
25218 You can have multiple input variables, in the same way that you can have more
25219 than one output variable.
25221 The parameter count (%0, %1) etc, now starts at the first input
25222 statement, and continues with the output statements.
25223 When both parameters use the same variable, the
25224 compiler will treat them as the same %n operand, which is the case here.
25226 Just as the @code{Outputs} parameter causes the register to be stored into the
25227 target variable after execution of the assembler statements, so does the
25228 @code{Inputs} parameter cause its variable to be loaded into the register
25229 before execution of the assembler statements.
25231 Thus the effect of the @code{Asm} invocation is:
25233 @item load the 32-bit value of @code{Value} into eax
25234 @item execute the @code{incl %eax} instruction
25235 @item store the contents of eax into the @code{Result} variable
25238 The resulting assembler file (with @option{-O2} optimization) contains:
25241 _increment__incr.1:
25254 @c ---------------------------------------------------------------------------
25255 @node Inlining Inline Assembler Code
25256 @section Inlining Inline Assembler Code
25259 For a short subprogram such as the @code{Incr} function in the previous
25260 section, the overhead of the call and return (creating / deleting the stack
25261 frame) can be significant, compared to the amount of code in the subprogram
25262 body. A solution is to apply Ada's @code{Inline} pragma to the subprogram,
25263 which directs the compiler to expand invocations of the subprogram at the
25264 point(s) of call, instead of setting up a stack frame for out-of-line calls.
25265 Here is the resulting program:
25267 @smallexample @c ada
25269 with Interfaces; use Interfaces;
25270 with Ada.Text_IO; use Ada.Text_IO;
25271 with System.Machine_Code; use System.Machine_Code;
25272 procedure Increment_2 is
25274 function Incr (Value : Unsigned_32) return Unsigned_32 is
25275 Result : Unsigned_32;
25278 Inputs => Unsigned_32'Asm_Input ("a", Value),
25279 Outputs => Unsigned_32'Asm_Output ("=a", Result));
25282 pragma Inline (Increment);
25284 Value : Unsigned_32;
25288 Put_Line ("Value before is" & Value'Img);
25289 Value := Increment (Value);
25290 Put_Line ("Value after is" & Value'Img);
25295 Compile the program with both optimization (@option{-O2}) and inlining
25296 enabled (@option{-gnatpn} instead of @option{-gnatp}).
25298 The @code{Incr} function is still compiled as usual, but at the
25299 point in @code{Increment} where our function used to be called:
25304 call _increment__incr.1
25309 the code for the function body directly appears:
25322 thus saving the overhead of stack frame setup and an out-of-line call.
25324 @c ---------------------------------------------------------------------------
25325 @node Other Asm Functionality
25326 @section Other @code{Asm} Functionality
25329 This section describes two important parameters to the @code{Asm}
25330 procedure: @code{Clobber}, which identifies register usage;
25331 and @code{Volatile}, which inhibits unwanted optimizations.
25334 * The Clobber Parameter::
25335 * The Volatile Parameter::
25338 @c ---------------------------------------------------------------------------
25339 @node The Clobber Parameter
25340 @subsection The @code{Clobber} Parameter
25343 One of the dangers of intermixing assembly language and a compiled language
25344 such as Ada is that the compiler needs to be aware of which registers are
25345 being used by the assembly code. In some cases, such as the earlier examples,
25346 the constraint string is sufficient to indicate register usage (e.g.,
25348 the eax register). But more generally, the compiler needs an explicit
25349 identification of the registers that are used by the Inline Assembly
25352 Using a register that the compiler doesn't know about
25353 could be a side effect of an instruction (like @code{mull}
25354 storing its result in both eax and edx).
25355 It can also arise from explicit register usage in your
25356 assembly code; for example:
25359 Asm ("movl %0, %%ebx" & LF & HT &
25361 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
25362 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
25366 where the compiler (since it does not analyze the @code{Asm} template string)
25367 does not know you are using the ebx register.
25369 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
25370 to identify the registers that will be used by your assembly code:
25374 Asm ("movl %0, %%ebx" & LF & HT &
25376 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
25377 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
25382 The Clobber parameter is a static string expression specifying the
25383 register(s) you are using. Note that register names are @emph{not} prefixed
25384 by a percent sign. Also, if more than one register is used then their names
25385 are separated by commas; e.g., @code{"eax, ebx"}
25387 The @code{Clobber} parameter has several additional uses:
25389 @item Use ``register'' name @code{cc} to indicate that flags might have changed
25390 @item Use ``register'' name @code{memory} if you changed a memory location
25393 @c ---------------------------------------------------------------------------
25394 @node The Volatile Parameter
25395 @subsection The @code{Volatile} Parameter
25396 @cindex Volatile parameter
25399 Compiler optimizations in the presence of Inline Assembler may sometimes have
25400 unwanted effects. For example, when an @code{Asm} invocation with an input
25401 variable is inside a loop, the compiler might move the loading of the input
25402 variable outside the loop, regarding it as a one-time initialization.
25404 If this effect is not desired, you can disable such optimizations by setting
25405 the @code{Volatile} parameter to @code{True}; for example:
25407 @smallexample @c ada
25409 Asm ("movl %0, %%ebx" & LF & HT &
25411 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
25412 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
25418 By default, @code{Volatile} is set to @code{False} unless there is no
25419 @code{Outputs} parameter.
25421 Although setting @code{Volatile} to @code{True} prevents unwanted
25422 optimizations, it will also disable other optimizations that might be
25423 important for efficiency. In general, you should set @code{Volatile}
25424 to @code{True} only if the compiler's optimizations have created
25426 @c END OF INLINE ASSEMBLER CHAPTER
25427 @c ===============================
25429 @c ***********************************
25430 @c * Compatibility and Porting Guide *
25431 @c ***********************************
25432 @node Compatibility and Porting Guide
25433 @appendix Compatibility and Porting Guide
25436 This chapter describes the compatibility issues that may arise between
25437 GNAT and other Ada 83 and Ada 95 compilation systems, and shows how GNAT
25438 can expedite porting
25439 applications developed in other Ada environments.
25442 * Compatibility with Ada 83::
25443 * Implementation-dependent characteristics::
25444 * Compatibility with Other Ada 95 Systems::
25445 * Representation Clauses::
25446 * Compatibility with DEC Ada 83::
25448 * Transitioning from Alpha to Integrity OpenVMS::
25452 @node Compatibility with Ada 83
25453 @section Compatibility with Ada 83
25454 @cindex Compatibility (between Ada 83 and Ada 95)
25457 Ada 95 is designed to be highly upwards compatible with Ada 83. In
25458 particular, the design intention is that the difficulties associated
25459 with moving from Ada 83 to Ada 95 should be no greater than those
25460 that occur when moving from one Ada 83 system to another.
25462 However, there are a number of points at which there are minor
25463 incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains
25464 full details of these issues,
25465 and should be consulted for a complete treatment.
25467 following subsections treat the most likely issues to be encountered.
25470 * Legal Ada 83 programs that are illegal in Ada 95::
25471 * More deterministic semantics::
25472 * Changed semantics::
25473 * Other language compatibility issues::
25476 @node Legal Ada 83 programs that are illegal in Ada 95
25477 @subsection Legal Ada 83 programs that are illegal in Ada 95
25480 @item Character literals
25481 Some uses of character literals are ambiguous. Since Ada 95 has introduced
25482 @code{Wide_Character} as a new predefined character type, some uses of
25483 character literals that were legal in Ada 83 are illegal in Ada 95.
25485 @smallexample @c ada
25486 for Char in 'A' .. 'Z' loop ... end loop;
25489 The problem is that @code{'A'} and @code{'Z'} could be from either
25490 @code{Character} or @code{Wide_Character}. The simplest correction
25491 is to make the type explicit; e.g.:
25492 @smallexample @c ada
25493 for Char in Character range 'A' .. 'Z' loop ... end loop;
25496 @item New reserved words
25497 The identifiers @code{abstract}, @code{aliased}, @code{protected},
25498 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
25499 Existing Ada 83 code using any of these identifiers must be edited to
25500 use some alternative name.
25502 @item Freezing rules
25503 The rules in Ada 95 are slightly different with regard to the point at
25504 which entities are frozen, and representation pragmas and clauses are
25505 not permitted past the freeze point. This shows up most typically in
25506 the form of an error message complaining that a representation item
25507 appears too late, and the appropriate corrective action is to move
25508 the item nearer to the declaration of the entity to which it refers.
25510 A particular case is that representation pragmas
25513 extended DEC Ada 83 compatibility pragmas such as @code{Export_Procedure})
25515 cannot be applied to a subprogram body. If necessary, a separate subprogram
25516 declaration must be introduced to which the pragma can be applied.
25518 @item Optional bodies for library packages
25519 In Ada 83, a package that did not require a package body was nevertheless
25520 allowed to have one. This lead to certain surprises in compiling large
25521 systems (situations in which the body could be unexpectedly ignored by the
25522 binder). In Ada 95, if a package does not require a body then it is not
25523 permitted to have a body. To fix this problem, simply remove a redundant
25524 body if it is empty, or, if it is non-empty, introduce a dummy declaration
25525 into the spec that makes the body required. One approach is to add a private
25526 part to the package declaration (if necessary), and define a parameterless
25527 procedure called @code{Requires_Body}, which must then be given a dummy
25528 procedure body in the package body, which then becomes required.
25529 Another approach (assuming that this does not introduce elaboration
25530 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
25531 since one effect of this pragma is to require the presence of a package body.
25533 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
25534 In Ada 95, the exception @code{Numeric_Error} is a renaming of
25535 @code{Constraint_Error}.
25536 This means that it is illegal to have separate exception handlers for
25537 the two exceptions. The fix is simply to remove the handler for the
25538 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
25539 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
25541 @item Indefinite subtypes in generics
25542 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
25543 as the actual for a generic formal private type, but then the instantiation
25544 would be illegal if there were any instances of declarations of variables
25545 of this type in the generic body. In Ada 95, to avoid this clear violation
25546 of the methodological principle known as the ``contract model'',
25547 the generic declaration explicitly indicates whether
25548 or not such instantiations are permitted. If a generic formal parameter
25549 has explicit unknown discriminants, indicated by using @code{(<>)} after the
25550 type name, then it can be instantiated with indefinite types, but no
25551 stand-alone variables can be declared of this type. Any attempt to declare
25552 such a variable will result in an illegality at the time the generic is
25553 declared. If the @code{(<>)} notation is not used, then it is illegal
25554 to instantiate the generic with an indefinite type.
25555 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
25556 It will show up as a compile time error, and
25557 the fix is usually simply to add the @code{(<>)} to the generic declaration.
25560 @node More deterministic semantics
25561 @subsection More deterministic semantics
25565 Conversions from real types to integer types round away from 0. In Ada 83
25566 the conversion Integer(2.5) could deliver either 2 or 3 as its value. This
25567 implementation freedom was intended to support unbiased rounding in
25568 statistical applications, but in practice it interfered with portability.
25569 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
25570 is required. Numeric code may be affected by this change in semantics.
25571 Note, though, that this issue is no worse than already existed in Ada 83
25572 when porting code from one vendor to another.
25575 The Real-Time Annex introduces a set of policies that define the behavior of
25576 features that were implementation dependent in Ada 83, such as the order in
25577 which open select branches are executed.
25580 @node Changed semantics
25581 @subsection Changed semantics
25584 The worst kind of incompatibility is one where a program that is legal in
25585 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
25586 possible in Ada 83. Fortunately this is extremely rare, but the one
25587 situation that you should be alert to is the change in the predefined type
25588 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
25591 @item range of @code{Character}
25592 The range of @code{Standard.Character} is now the full 256 characters
25593 of Latin-1, whereas in most Ada 83 implementations it was restricted
25594 to 128 characters. Although some of the effects of
25595 this change will be manifest in compile-time rejection of legal
25596 Ada 83 programs it is possible for a working Ada 83 program to have
25597 a different effect in Ada 95, one that was not permitted in Ada 83.
25598 As an example, the expression
25599 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
25600 delivers @code{255} as its value.
25601 In general, you should look at the logic of any
25602 character-processing Ada 83 program and see whether it needs to be adapted
25603 to work correctly with Latin-1. Note that the predefined Ada 95 API has a
25604 character handling package that may be relevant if code needs to be adapted
25605 to account for the additional Latin-1 elements.
25606 The desirable fix is to
25607 modify the program to accommodate the full character set, but in some cases
25608 it may be convenient to define a subtype or derived type of Character that
25609 covers only the restricted range.
25613 @node Other language compatibility issues
25614 @subsection Other language compatibility issues
25616 @item @option{-gnat83 switch}
25617 All implementations of GNAT provide a switch that causes GNAT to operate
25618 in Ada 83 mode. In this mode, some but not all compatibility problems
25619 of the type described above are handled automatically. For example, the
25620 new Ada 95 reserved words are treated simply as identifiers as in Ada 83.
25622 in practice, it is usually advisable to make the necessary modifications
25623 to the program to remove the need for using this switch.
25624 See @ref{Compiling Different Versions of Ada}.
25626 @item Support for removed Ada 83 pragmas and attributes
25627 A number of pragmas and attributes from Ada 83 have been removed from Ada 95,
25628 generally because they have been replaced by other mechanisms. Ada 95
25629 compilers are allowed, but not required, to implement these missing
25630 elements. In contrast with some other Ada 95 compilers, GNAT implements all
25631 such pragmas and attributes, eliminating this compatibility concern. These
25632 include @code{pragma Interface} and the floating point type attributes
25633 (@code{Emax}, @code{Mantissa}, etc.), among other items.
25636 @node Implementation-dependent characteristics
25637 @section Implementation-dependent characteristics
25639 Although the Ada language defines the semantics of each construct as
25640 precisely as practical, in some situations (for example for reasons of
25641 efficiency, or where the effect is heavily dependent on the host or target
25642 platform) the implementation is allowed some freedom. In porting Ada 83
25643 code to GNAT, you need to be aware of whether / how the existing code
25644 exercised such implementation dependencies. Such characteristics fall into
25645 several categories, and GNAT offers specific support in assisting the
25646 transition from certain Ada 83 compilers.
25649 * Implementation-defined pragmas::
25650 * Implementation-defined attributes::
25652 * Elaboration order::
25653 * Target-specific aspects::
25656 @node Implementation-defined pragmas
25657 @subsection Implementation-defined pragmas
25660 Ada compilers are allowed to supplement the language-defined pragmas, and
25661 these are a potential source of non-portability. All GNAT-defined pragmas
25662 are described in the GNAT Reference Manual, and these include several that
25663 are specifically intended to correspond to other vendors' Ada 83 pragmas.
25664 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
25666 compatibility with DEC Ada 83, GNAT supplies the pragmas
25667 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
25668 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
25669 and @code{Volatile}.
25670 Other relevant pragmas include @code{External} and @code{Link_With}.
25671 Some vendor-specific
25672 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
25674 avoiding compiler rejection of units that contain such pragmas; they are not
25675 relevant in a GNAT context and hence are not otherwise implemented.
25677 @node Implementation-defined attributes
25678 @subsection Implementation-defined attributes
25680 Analogous to pragmas, the set of attributes may be extended by an
25681 implementation. All GNAT-defined attributes are described in the
25682 @cite{GNAT Reference Manual}, and these include several that are specifically
25684 to correspond to other vendors' Ada 83 attributes. For migrating from VADS,
25685 the attribute @code{VADS_Size} may be useful. For compatibility with DEC
25686 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
25690 @subsection Libraries
25692 Vendors may supply libraries to supplement the standard Ada API. If Ada 83
25693 code uses vendor-specific libraries then there are several ways to manage
25697 If the source code for the libraries (specifications and bodies) are
25698 available, then the libraries can be migrated in the same way as the
25701 If the source code for the specifications but not the bodies are
25702 available, then you can reimplement the bodies.
25704 Some new Ada 95 features obviate the need for library support. For
25705 example most Ada 83 vendors supplied a package for unsigned integers. The
25706 Ada 95 modular type feature is the preferred way to handle this need, so
25707 instead of migrating or reimplementing the unsigned integer package it may
25708 be preferable to retrofit the application using modular types.
25711 @node Elaboration order
25712 @subsection Elaboration order
25714 The implementation can choose any elaboration order consistent with the unit
25715 dependency relationship. This freedom means that some orders can result in
25716 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
25717 to invoke a subprogram its body has been elaborated, or to instantiate a
25718 generic before the generic body has been elaborated. By default GNAT
25719 attempts to choose a safe order (one that will not encounter access before
25720 elaboration problems) by implicitly inserting Elaborate_All pragmas where
25721 needed. However, this can lead to the creation of elaboration circularities
25722 and a resulting rejection of the program by gnatbind. This issue is
25723 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
25724 In brief, there are several
25725 ways to deal with this situation:
25729 Modify the program to eliminate the circularities, e.g. by moving
25730 elaboration-time code into explicitly-invoked procedures
25732 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
25733 @code{Elaborate} pragmas, and then inhibit the generation of implicit
25734 @code{Elaborate_All}
25735 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
25736 (by selectively suppressing elaboration checks via pragma
25737 @code{Suppress(Elaboration_Check)} when it is safe to do so).
25740 @node Target-specific aspects
25741 @subsection Target-specific aspects
25743 Low-level applications need to deal with machine addresses, data
25744 representations, interfacing with assembler code, and similar issues. If
25745 such an Ada 83 application is being ported to different target hardware (for
25746 example where the byte endianness has changed) then you will need to
25747 carefully examine the program logic; the porting effort will heavily depend
25748 on the robustness of the original design. Moreover, Ada 95 is sometimes
25749 incompatible with typical Ada 83 compiler practices regarding implicit
25750 packing, the meaning of the Size attribute, and the size of access values.
25751 GNAT's approach to these issues is described in @ref{Representation Clauses}.
25753 @node Compatibility with Other Ada 95 Systems
25754 @section Compatibility with Other Ada 95 Systems
25757 Providing that programs avoid the use of implementation dependent and
25758 implementation defined features of Ada 95, as documented in the Ada 95
25759 reference manual, there should be a high degree of portability between
25760 GNAT and other Ada 95 systems. The following are specific items which
25761 have proved troublesome in moving GNAT programs to other Ada 95
25762 compilers, but do not affect porting code to GNAT@.
25765 @item Ada 83 Pragmas and Attributes
25766 Ada 95 compilers are allowed, but not required, to implement the missing
25767 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
25768 GNAT implements all such pragmas and attributes, eliminating this as
25769 a compatibility concern, but some other Ada 95 compilers reject these
25770 pragmas and attributes.
25772 @item Special-needs Annexes
25773 GNAT implements the full set of special needs annexes. At the
25774 current time, it is the only Ada 95 compiler to do so. This means that
25775 programs making use of these features may not be portable to other Ada
25776 95 compilation systems.
25778 @item Representation Clauses
25779 Some other Ada 95 compilers implement only the minimal set of
25780 representation clauses required by the Ada 95 reference manual. GNAT goes
25781 far beyond this minimal set, as described in the next section.
25784 @node Representation Clauses
25785 @section Representation Clauses
25788 The Ada 83 reference manual was quite vague in describing both the minimal
25789 required implementation of representation clauses, and also their precise
25790 effects. The Ada 95 reference manual is much more explicit, but the minimal
25791 set of capabilities required in Ada 95 is quite limited.
25793 GNAT implements the full required set of capabilities described in the
25794 Ada 95 reference manual, but also goes much beyond this, and in particular
25795 an effort has been made to be compatible with existing Ada 83 usage to the
25796 greatest extent possible.
25798 A few cases exist in which Ada 83 compiler behavior is incompatible with
25799 requirements in the Ada 95 reference manual. These are instances of
25800 intentional or accidental dependence on specific implementation dependent
25801 characteristics of these Ada 83 compilers. The following is a list of
25802 the cases most likely to arise in existing legacy Ada 83 code.
25805 @item Implicit Packing
25806 Some Ada 83 compilers allowed a Size specification to cause implicit
25807 packing of an array or record. This could cause expensive implicit
25808 conversions for change of representation in the presence of derived
25809 types, and the Ada design intends to avoid this possibility.
25810 Subsequent AI's were issued to make it clear that such implicit
25811 change of representation in response to a Size clause is inadvisable,
25812 and this recommendation is represented explicitly in the Ada 95 RM
25813 as implementation advice that is followed by GNAT@.
25814 The problem will show up as an error
25815 message rejecting the size clause. The fix is simply to provide
25816 the explicit pragma @code{Pack}, or for more fine tuned control, provide
25817 a Component_Size clause.
25819 @item Meaning of Size Attribute
25820 The Size attribute in Ada 95 for discrete types is defined as being the
25821 minimal number of bits required to hold values of the type. For example,
25822 on a 32-bit machine, the size of Natural will typically be 31 and not
25823 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and
25824 some 32 in this situation. This problem will usually show up as a compile
25825 time error, but not always. It is a good idea to check all uses of the
25826 'Size attribute when porting Ada 83 code. The GNAT specific attribute
25827 Object_Size can provide a useful way of duplicating the behavior of
25828 some Ada 83 compiler systems.
25830 @item Size of Access Types
25831 A common assumption in Ada 83 code is that an access type is in fact a pointer,
25832 and that therefore it will be the same size as a System.Address value. This
25833 assumption is true for GNAT in most cases with one exception. For the case of
25834 a pointer to an unconstrained array type (where the bounds may vary from one
25835 value of the access type to another), the default is to use a ``fat pointer'',
25836 which is represented as two separate pointers, one to the bounds, and one to
25837 the array. This representation has a number of advantages, including improved
25838 efficiency. However, it may cause some difficulties in porting existing Ada 83
25839 code which makes the assumption that, for example, pointers fit in 32 bits on
25840 a machine with 32-bit addressing.
25842 To get around this problem, GNAT also permits the use of ``thin pointers'' for
25843 access types in this case (where the designated type is an unconstrained array
25844 type). These thin pointers are indeed the same size as a System.Address value.
25845 To specify a thin pointer, use a size clause for the type, for example:
25847 @smallexample @c ada
25848 type X is access all String;
25849 for X'Size use Standard'Address_Size;
25853 which will cause the type X to be represented using a single pointer.
25854 When using this representation, the bounds are right behind the array.
25855 This representation is slightly less efficient, and does not allow quite
25856 such flexibility in the use of foreign pointers or in using the
25857 Unrestricted_Access attribute to create pointers to non-aliased objects.
25858 But for any standard portable use of the access type it will work in
25859 a functionally correct manner and allow porting of existing code.
25860 Note that another way of forcing a thin pointer representation
25861 is to use a component size clause for the element size in an array,
25862 or a record representation clause for an access field in a record.
25865 @node Compatibility with DEC Ada 83
25866 @section Compatibility with DEC Ada 83
25869 The VMS version of GNAT fully implements all the pragmas and attributes
25870 provided by DEC Ada 83, as well as providing the standard DEC Ada 83
25871 libraries, including Starlet. In addition, data layouts and parameter
25872 passing conventions are highly compatible. This means that porting
25873 existing DEC Ada 83 code to GNAT in VMS systems should be easier than
25874 most other porting efforts. The following are some of the most
25875 significant differences between GNAT and DEC Ada 83.
25878 @item Default floating-point representation
25879 In GNAT, the default floating-point format is IEEE, whereas in DEC Ada 83,
25880 it is VMS format. GNAT does implement the necessary pragmas
25881 (Long_Float, Float_Representation) for changing this default.
25884 The package System in GNAT exactly corresponds to the definition in the
25885 Ada 95 reference manual, which means that it excludes many of the
25886 DEC Ada 83 extensions. However, a separate package Aux_DEC is provided
25887 that contains the additional definitions, and a special pragma,
25888 Extend_System allows this package to be treated transparently as an
25889 extension of package System.
25892 The definitions provided by Aux_DEC are exactly compatible with those
25893 in the DEC Ada 83 version of System, with one exception.
25894 DEC Ada provides the following declarations:
25896 @smallexample @c ada
25897 TO_ADDRESS (INTEGER)
25898 TO_ADDRESS (UNSIGNED_LONGWORD)
25899 TO_ADDRESS (universal_integer)
25903 The version of TO_ADDRESS taking a universal integer argument is in fact
25904 an extension to Ada 83 not strictly compatible with the reference manual.
25905 In GNAT, we are constrained to be exactly compatible with the standard,
25906 and this means we cannot provide this capability. In DEC Ada 83, the
25907 point of this definition is to deal with a call like:
25909 @smallexample @c ada
25910 TO_ADDRESS (16#12777#);
25914 Normally, according to the Ada 83 standard, one would expect this to be
25915 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
25916 of TO_ADDRESS@. However, in DEC Ada 83, there is no ambiguity, since the
25917 definition using universal_integer takes precedence.
25919 In GNAT, since the version with universal_integer cannot be supplied, it is
25920 not possible to be 100% compatible. Since there are many programs using
25921 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
25922 to change the name of the function in the UNSIGNED_LONGWORD case, so the
25923 declarations provided in the GNAT version of AUX_Dec are:
25925 @smallexample @c ada
25926 function To_Address (X : Integer) return Address;
25927 pragma Pure_Function (To_Address);
25929 function To_Address_Long (X : Unsigned_Longword)
25931 pragma Pure_Function (To_Address_Long);
25935 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
25936 change the name to TO_ADDRESS_LONG@.
25938 @item Task_Id values
25939 The Task_Id values assigned will be different in the two systems, and GNAT
25940 does not provide a specified value for the Task_Id of the environment task,
25941 which in GNAT is treated like any other declared task.
25944 For full details on these and other less significant compatibility issues,
25945 see appendix E of the Digital publication entitled @cite{DEC Ada, Technical
25946 Overview and Comparison on DIGITAL Platforms}.
25948 For GNAT running on other than VMS systems, all the DEC Ada 83 pragmas and
25949 attributes are recognized, although only a subset of them can sensibly
25950 be implemented. The description of pragmas in this reference manual
25951 indicates whether or not they are applicable to non-VMS systems.
25955 @node Transitioning from Alpha to Integrity OpenVMS
25956 @section Transitioning from Alpha to Integrity OpenVMS
25959 * Introduction to transitioning::
25960 * Migration of 32 bit code::
25961 * Taking advantage of 64 bit addressing::
25962 * Technical details::
25965 @node Introduction to transitioning
25966 @subsection Introduction to transitioning
25969 This guide is meant to assist users of GNAT Pro
25970 for Alpha OpenVMS who are planning to transition to the IA64 architecture.
25971 GNAT Pro for Open VMS Integrity has been designed to meet
25976 Providing a full conforming implementation of the Ada 95 language
25979 Allowing maximum backward compatibility, thus easing migration of existing
25983 Supplying a path for exploiting the full IA64 address range
25987 Ada's strong typing semantics has made it
25988 impractical to have different 32-bit and 64-bit modes. As soon as
25989 one object could possibly be outside the 32-bit address space, this
25990 would make it necessary for the @code{System.Address} type to be 64 bits.
25991 In particular, this would cause inconsistencies if 32-bit code is
25992 called from 64-bit code that raises an exception.
25994 This issue has been resolved by always using 64-bit addressing
25995 at the system level, but allowing for automatic conversions between
25996 32-bit and 64-bit addresses where required. Thus users who
25997 do not currently require 64-bit addressing capabilities, can
25998 recompile their code with only minimal changes (and indeed
25999 if the code is written in portable Ada, with no assumptions about
26000 the size of the @code{Address} type, then no changes at all are necessary).
26002 this approach provides a simple, gradual upgrade path to future
26003 use of larger memories than available for 32-bit systems.
26004 Also, newly written applications or libraries will by default
26005 be fully compatible with future systems exploiting 64-bit
26006 addressing capabilities present in IA64.
26008 @ref{Migration of 32 bit code}, will focus on porting applications
26009 that do not require more than 2 GB of
26010 addressable memory. This code will be referred to as
26011 @emph{32-bit code}.
26012 For applications intending to exploit the full ia64 address space,
26013 @ref{Taking advantage of 64 bit addressing},
26014 will consider further changes that may be required.
26015 Such code is called @emph{64-bit code} in the
26016 remainder of this guide.
26019 @node Migration of 32 bit code
26020 @subsection Migration of 32-bit code
26025 * Unchecked conversions::
26026 * Predefined constants::
26027 * Single source compatibility::
26028 * Experience with source compatibility::
26031 @node Address types
26032 @subsubsection Address types
26035 To solve the problem of mixing 64-bit and 32-bit addressing,
26036 while maintaining maximum backward compatibility, the following
26037 approach has been taken:
26041 @code{System.Address} always has a size of 64 bits
26044 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
26049 Since @code{System.Short_Address} is a subtype of @code{System.Address},
26050 a @code{Short_Address}
26051 may be used where an @code{Address} is required, and vice versa, without
26052 needing explicit type conversions.
26053 By virtue of the Open VMS Integrity parameter passing conventions,
26055 and exported subprograms that have 32-bit address parameters are
26056 compatible with those that have 64-bit address parameters.
26057 (See @ref{Making code 64 bit clean} for details.)
26059 The areas that may need attention are those where record types have
26060 been defined that contain components of the type @code{System.Address}, and
26061 where objects of this type are passed to code expecting a record layout with
26064 Different compilers on different platforms cannot be
26065 expected to represent the same type in the same way,
26066 since alignment constraints
26067 and other system-dependent properties affect the compiler's decision.
26068 For that reason, Ada code
26069 generally uses representation clauses to specify the expected
26070 layout where required.
26072 If such a representation clause uses 32 bits for a component having
26073 the type @code{System.Address}, GNAT Pro for OpenVMS Integrity will detect
26074 that error and produce a specific diagnostic message.
26075 The developer should then determine whether the representation
26076 should be 64 bits or not and make either of two changes:
26077 change the size to 64 bits and leave the type as @code{System.Address}, or
26078 leave the size as 32 bits and change the type to @code{System.Short_Address}.
26079 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
26080 required in any code setting or accessing the field; the compiler will
26081 automatically perform any needed conversions between address
26085 @subsubsection Access types
26088 By default, objects designated by access values are always
26089 allocated in the 32-bit
26090 address space. Thus legacy code will never contain
26091 any objects that are not addressable with 32-bit addresses, and
26092 the compiler will never raise exceptions as result of mixing
26093 32-bit and 64-bit addresses.
26095 However, the access values themselves are represented in 64 bits, for optimum
26096 performance and future compatibility with 64-bit code. As was
26097 the case with @code{System.Address}, the compiler will give an error message
26098 if an object or record component has a representation clause that
26099 requires the access value to fit in 32 bits. In such a situation,
26100 an explicit size clause for the access type, specifying 32 bits,
26101 will have the desired effect.
26103 General access types (declared with @code{access all}) can never be
26104 32 bits, as values of such types must be able to refer to any object
26105 of the designated type,
26106 including objects residing outside the 32-bit address range.
26107 Existing Ada 83 code will not contain such type definitions,
26108 however, since general access types were introduced in Ada 95.
26110 @node Unchecked conversions
26111 @subsubsection Unchecked conversions
26114 In the case of an @code{Unchecked_Conversion} where the source type is a
26115 64-bit access type or the type @code{System.Address}, and the target
26116 type is a 32-bit type, the compiler will generate a warning.
26117 Even though the generated code will still perform the required
26118 conversions, it is highly recommended in these cases to use
26119 respectively a 32-bit access type or @code{System.Short_Address}
26120 as the source type.
26122 @node Predefined constants
26123 @subsubsection Predefined constants
26126 The following predefined constants have changed:
26128 @multitable {@code{System.Address_Size}} {2**32} {2**64}
26129 @item @b{Constant} @tab @b{Old} @tab @b{New}
26130 @item @code{System.Word_Size} @tab 32 @tab 64
26131 @item @code{System.Memory_Size} @tab 2**32 @tab 2**64
26132 @item @code{System.Address_Size} @tab 32 @tab 64
26136 If you need to refer to the specific
26137 memory size of a 32-bit implementation, instead of the
26138 actual memory size, use @code{System.Short_Memory_Size}
26139 rather than @code{System.Memory_Size}.
26140 Similarly, references to @code{System.Address_Size} may need
26141 to be replaced by @code{System.Short_Address'Size}.
26142 The program @command{gnatfind} may be useful for locating
26143 references to the above constants, so that you can verify that they
26146 @node Single source compatibility
26147 @subsubsection Single source compatibility
26150 In order to allow the same source code to be compiled on
26151 both Alpha and IA64 platforms, GNAT Pro for Alpha/OpenVMS
26152 defines @code{System.Short_Address} and System.Short_Memory_Size
26153 as aliases of respectively @code{System.Address} and
26154 @code{System.Memory_Size}.
26155 (These aliases also leave the door open for a possible
26156 future ``upgrade'' of OpenVMS Alpha to a 64-bit address space.)
26158 @node Experience with source compatibility
26159 @subsubsection Experience with source compatibility
26162 The Security Server and STARLET provide an interesting ``test case''
26163 for source compatibility issues, since it is in such system code
26164 where assumptions about @code{Address} size might be expected to occur.
26165 Indeed, there were a small number of occasions in the Security Server
26166 file @file{jibdef.ads}
26167 where a representation clause for a record type specified
26168 32 bits for a component of type @code{Address}.
26169 All of these errors were detected by the compiler.
26170 The repair was obvious and immediate; to simply replace @code{Address} by
26171 @code{Short_Address}.
26173 In the case of STARLET, there were several record types that should
26174 have had representation clauses but did not. In these record types
26175 there was an implicit assumption that an @code{Address} value occupied
26177 These compiled without error, but their usage resulted in run-time error
26178 returns from STARLET system calls.
26179 To assist in the compile-time detection of such situations, we
26180 plan to include a switch to generate a warning message when a
26181 record component is of type @code{Address}.
26184 @c ****************************************
26185 @node Taking advantage of 64 bit addressing
26186 @subsection Taking advantage of 64-bit addressing
26189 * Making code 64 bit clean::
26190 * Allocating memory from the 64 bit storage pool::
26191 * Restrictions on use of 64 bit objects::
26192 * Using 64 bit storage pools by default::
26193 * General access types::
26194 * STARLET and other predefined libraries::
26197 @node Making code 64 bit clean
26198 @subsubsection Making code 64-bit clean
26201 In order to prevent problems that may occur when (parts of) a
26202 system start using memory outside the 32-bit address range,
26203 we recommend some additional guidelines:
26207 For imported subprograms that take parameters of the
26208 type @code{System.Address}, ensure that these subprograms can
26209 indeed handle 64-bit addresses. If not, or when in doubt,
26210 change the subprogram declaration to specify
26211 @code{System.Short_Address} instead.
26214 Resolve all warnings related to size mismatches in
26215 unchecked conversions. Failing to do so causes
26216 erroneous execution if the source object is outside
26217 the 32-bit address space.
26220 (optional) Explicitly use the 32-bit storage pool
26221 for access types used in a 32-bit context, or use
26222 generic access types where possible
26223 (@pxref{Restrictions on use of 64 bit objects}).
26227 If these rules are followed, the compiler will automatically insert
26228 any necessary checks to ensure that no addresses or access values
26229 passed to 32-bit code ever refer to objects outside the 32-bit
26231 Any attempt to do this will raise @code{Constraint_Error}.
26233 @node Allocating memory from the 64 bit storage pool
26234 @subsubsection Allocating memory from the 64-bit storage pool
26237 For any access type @code{T} that potentially requires memory allocations
26238 beyond the 32-bit address space,
26239 use the following representation clause:
26241 @smallexample @c ada
26242 for T'Storage_Pool use System.Pool_64;
26246 @node Restrictions on use of 64 bit objects
26247 @subsubsection Restrictions on use of 64-bit objects
26250 Taking the address of an object allocated from a 64-bit storage pool,
26251 and then passing this address to a subprogram expecting
26252 @code{System.Short_Address},
26253 or assigning it to a variable of type @code{Short_Address}, will cause
26254 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
26255 (@pxref{Making code 64 bit clean}), or checks are suppressed,
26256 no exception is raised and execution
26257 will become erroneous.
26259 @node Using 64 bit storage pools by default
26260 @subsubsection Using 64-bit storage pools by default
26263 In some cases it may be desirable to have the compiler allocate
26264 from 64-bit storage pools by default. This may be the case for
26265 libraries that are 64-bit clean, but may be used in both 32-bit
26266 and 64-bit contexts. For these cases the following configuration
26267 pragma may be specified:
26269 @smallexample @c ada
26270 pragma Pool_64_Default;
26274 Any code compiled in the context of this pragma will by default
26275 use the @code{System.Pool_64} storage pool. This default may be overridden
26276 for a specific access type @code{T} by the representation clause:
26278 @smallexample @c ada
26279 for T'Storage_Pool use System.Pool_32;
26283 Any object whose address may be passed to a subprogram with a
26284 @code{Short_Address} argument, or assigned to a variable of type
26285 @code{Short_Address}, needs to be allocated from this pool.
26287 @node General access types
26288 @subsubsection General access types
26291 Objects designated by access values from a
26292 general access type (declared with @code{access all}) are never allocated
26293 from a 64-bit storage pool. Code that uses general access types will
26294 accept objects allocated in either 32-bit or 64-bit address spaces,
26295 but never allocate objects outside the 32-bit address space.
26296 Using general access types ensures maximum compatibility with both
26297 32-bit and 64-bit code.
26300 @node STARLET and other predefined libraries
26301 @subsubsection STARLET and other predefined libraries
26304 All code that comes as part of GNAT is 64-bit clean, but the
26305 restrictions given in @ref{Restrictions on use of 64 bit objects},
26306 still apply. Look at the package
26307 specifications to see in which contexts objects allocated
26308 in 64-bit address space are acceptable.
26310 @node Technical details
26311 @subsection Technical details
26314 GNAT Pro for Open VMS Integrity takes advantage of the freedom given in the Ada
26315 standard with respect to the type of @code{System.Address}. Previous versions
26316 of GNAT Pro have defined this type as private and implemented it as
26319 In order to allow defining @code{System.Short_Address} as a proper subtype,
26320 and to match the implicit sign extension in parameter passing,
26321 in GNAT Pro for Open VMS Integrity, @code{System.Address} is defined as a
26322 visible (i.e., non-private) integer type.
26323 Standard operations on the type, such as the binary operators ``+'', ``-'',
26324 etc., that take @code{Address} operands and return an @code{Address} result,
26325 have been hidden by declaring these
26326 @code{abstract}, an Ada 95 feature that helps avoid the potential ambiguities
26327 that would otherwise result from overloading.
26328 (Note that, although @code{Address} is a visible integer type,
26329 good programming practice dictates against exploiting the type's
26330 integer properties such as literals, since this will compromise
26333 Defining @code{Address} as a visible integer type helps achieve
26334 maximum compatibility for existing Ada code,
26335 without sacrificing the capabilities of the IA64 architecture.
26339 @c ************************************************
26341 @node Microsoft Windows Topics
26342 @appendix Microsoft Windows Topics
26348 This chapter describes topics that are specific to the Microsoft Windows
26349 platforms (NT, 2000, and XP Professional).
26352 * Using GNAT on Windows::
26353 * Using a network installation of GNAT::
26354 * CONSOLE and WINDOWS subsystems::
26355 * Temporary Files::
26356 * Mixed-Language Programming on Windows::
26357 * Windows Calling Conventions::
26358 * Introduction to Dynamic Link Libraries (DLLs)::
26359 * Using DLLs with GNAT::
26360 * Building DLLs with GNAT::
26361 * Building DLLs with GNAT Project files::
26362 * Building DLLs with gnatdll::
26363 * GNAT and Windows Resources::
26364 * Debugging a DLL::
26365 * GNAT and COM/DCOM Objects::
26368 @node Using GNAT on Windows
26369 @section Using GNAT on Windows
26372 One of the strengths of the GNAT technology is that its tool set
26373 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
26374 @code{gdb} debugger, etc.) is used in the same way regardless of the
26377 On Windows this tool set is complemented by a number of Microsoft-specific
26378 tools that have been provided to facilitate interoperability with Windows
26379 when this is required. With these tools:
26384 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
26388 You can use any Dynamically Linked Library (DLL) in your Ada code (both
26389 relocatable and non-relocatable DLLs are supported).
26392 You can build Ada DLLs for use in other applications. These applications
26393 can be written in a language other than Ada (e.g., C, C++, etc). Again both
26394 relocatable and non-relocatable Ada DLLs are supported.
26397 You can include Windows resources in your Ada application.
26400 You can use or create COM/DCOM objects.
26404 Immediately below are listed all known general GNAT-for-Windows restrictions.
26405 Other restrictions about specific features like Windows Resources and DLLs
26406 are listed in separate sections below.
26411 It is not possible to use @code{GetLastError} and @code{SetLastError}
26412 when tasking, protected records, or exceptions are used. In these
26413 cases, in order to implement Ada semantics, the GNAT run-time system
26414 calls certain Win32 routines that set the last error variable to 0 upon
26415 success. It should be possible to use @code{GetLastError} and
26416 @code{SetLastError} when tasking, protected record, and exception
26417 features are not used, but it is not guaranteed to work.
26420 It is not possible to link against Microsoft libraries except for
26421 import libraries. The library must be built to be compatible with
26422 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
26423 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
26424 not be compatible with the GNAT runtime. Even if the library is
26425 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
26428 When the compilation environment is located on FAT32 drives, users may
26429 experience recompilations of the source files that have not changed if
26430 Daylight Saving Time (DST) state has changed since the last time files
26431 were compiled. NTFS drives do not have this problem.
26434 No components of the GNAT toolset use any entries in the Windows
26435 registry. The only entries that can be created are file associations and
26436 PATH settings, provided the user has chosen to create them at installation
26437 time, as well as some minimal book-keeping information needed to correctly
26438 uninstall or integrate different GNAT products.
26441 @node Using a network installation of GNAT
26442 @section Using a network installation of GNAT
26445 Make sure the system on which GNAT is installed is accessible from the
26446 current machine, i.e. the install location is shared over the network.
26447 Shared resources are accessed on Windows by means of UNC paths, which
26448 have the format @code{\\server\sharename\path}
26450 In order to use such a network installation, simply add the UNC path of the
26451 @file{bin} directory of your GNAT installation in front of your PATH. For
26452 example, if GNAT is installed in @file{\GNAT} directory of a share location
26453 called @file{c-drive} on a machine @file{LOKI}, the following command will
26456 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
26458 Be aware that every compilation using the network installation results in the
26459 transfer of large amounts of data across the network and will likely cause
26460 serious performance penalty.
26462 @node CONSOLE and WINDOWS subsystems
26463 @section CONSOLE and WINDOWS subsystems
26464 @cindex CONSOLE Subsystem
26465 @cindex WINDOWS Subsystem
26469 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
26470 (which is the default subsystem) will always create a console when
26471 launching the application. This is not something desirable when the
26472 application has a Windows GUI. To get rid of this console the
26473 application must be using the @code{WINDOWS} subsystem. To do so
26474 the @option{-mwindows} linker option must be specified.
26477 $ gnatmake winprog -largs -mwindows
26480 @node Temporary Files
26481 @section Temporary Files
26482 @cindex Temporary files
26485 It is possible to control where temporary files gets created by setting
26486 the TMP environment variable. The file will be created:
26489 @item Under the directory pointed to by the TMP environment variable if
26490 this directory exists.
26492 @item Under c:\temp, if the TMP environment variable is not set (or not
26493 pointing to a directory) and if this directory exists.
26495 @item Under the current working directory otherwise.
26499 This allows you to determine exactly where the temporary
26500 file will be created. This is particularly useful in networked
26501 environments where you may not have write access to some
26504 @node Mixed-Language Programming on Windows
26505 @section Mixed-Language Programming on Windows
26508 Developing pure Ada applications on Windows is no different than on
26509 other GNAT-supported platforms. However, when developing or porting an
26510 application that contains a mix of Ada and C/C++, the choice of your
26511 Windows C/C++ development environment conditions your overall
26512 interoperability strategy.
26514 If you use @command{gcc} to compile the non-Ada part of your application,
26515 there are no Windows-specific restrictions that affect the overall
26516 interoperability with your Ada code. If you plan to use
26517 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
26518 the following limitations:
26522 You cannot link your Ada code with an object or library generated with
26523 Microsoft tools if these use the @code{.tls} section (Thread Local
26524 Storage section) since the GNAT linker does not yet support this section.
26527 You cannot link your Ada code with an object or library generated with
26528 Microsoft tools if these use I/O routines other than those provided in
26529 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
26530 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
26531 libraries can cause a conflict with @code{msvcrt.dll} services. For
26532 instance Visual C++ I/O stream routines conflict with those in
26537 If you do want to use the Microsoft tools for your non-Ada code and hit one
26538 of the above limitations, you have two choices:
26542 Encapsulate your non Ada code in a DLL to be linked with your Ada
26543 application. In this case, use the Microsoft or whatever environment to
26544 build the DLL and use GNAT to build your executable
26545 (@pxref{Using DLLs with GNAT}).
26548 Or you can encapsulate your Ada code in a DLL to be linked with the
26549 other part of your application. In this case, use GNAT to build the DLL
26550 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
26551 environment to build your executable.
26554 @node Windows Calling Conventions
26555 @section Windows Calling Conventions
26560 * C Calling Convention::
26561 * Stdcall Calling Convention::
26562 * DLL Calling Convention::
26566 When a subprogram @code{F} (caller) calls a subprogram @code{G}
26567 (callee), there are several ways to push @code{G}'s parameters on the
26568 stack and there are several possible scenarios to clean up the stack
26569 upon @code{G}'s return. A calling convention is an agreed upon software
26570 protocol whereby the responsibilities between the caller (@code{F}) and
26571 the callee (@code{G}) are clearly defined. Several calling conventions
26572 are available for Windows:
26576 @code{C} (Microsoft defined)
26579 @code{Stdcall} (Microsoft defined)
26582 @code{DLL} (GNAT specific)
26585 @node C Calling Convention
26586 @subsection @code{C} Calling Convention
26589 This is the default calling convention used when interfacing to C/C++
26590 routines compiled with either @command{gcc} or Microsoft Visual C++.
26592 In the @code{C} calling convention subprogram parameters are pushed on the
26593 stack by the caller from right to left. The caller itself is in charge of
26594 cleaning up the stack after the call. In addition, the name of a routine
26595 with @code{C} calling convention is mangled by adding a leading underscore.
26597 The name to use on the Ada side when importing (or exporting) a routine
26598 with @code{C} calling convention is the name of the routine. For
26599 instance the C function:
26602 int get_val (long);
26606 should be imported from Ada as follows:
26608 @smallexample @c ada
26610 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26611 pragma Import (C, Get_Val, External_Name => "get_val");
26616 Note that in this particular case the @code{External_Name} parameter could
26617 have been omitted since, when missing, this parameter is taken to be the
26618 name of the Ada entity in lower case. When the @code{Link_Name} parameter
26619 is missing, as in the above example, this parameter is set to be the
26620 @code{External_Name} with a leading underscore.
26622 When importing a variable defined in C, you should always use the @code{C}
26623 calling convention unless the object containing the variable is part of a
26624 DLL (in which case you should use the @code{DLL} calling convention,
26625 @pxref{DLL Calling Convention}).
26627 @node Stdcall Calling Convention
26628 @subsection @code{Stdcall} Calling Convention
26631 This convention, which was the calling convention used for Pascal
26632 programs, is used by Microsoft for all the routines in the Win32 API for
26633 efficiency reasons. It must be used to import any routine for which this
26634 convention was specified.
26636 In the @code{Stdcall} calling convention subprogram parameters are pushed
26637 on the stack by the caller from right to left. The callee (and not the
26638 caller) is in charge of cleaning the stack on routine exit. In addition,
26639 the name of a routine with @code{Stdcall} calling convention is mangled by
26640 adding a leading underscore (as for the @code{C} calling convention) and a
26641 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
26642 bytes) of the parameters passed to the routine.
26644 The name to use on the Ada side when importing a C routine with a
26645 @code{Stdcall} calling convention is the name of the C routine. The leading
26646 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
26647 the compiler. For instance the Win32 function:
26650 @b{APIENTRY} int get_val (long);
26654 should be imported from Ada as follows:
26656 @smallexample @c ada
26658 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26659 pragma Import (Stdcall, Get_Val);
26660 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
26665 As for the @code{C} calling convention, when the @code{External_Name}
26666 parameter is missing, it is taken to be the name of the Ada entity in lower
26667 case. If instead of writing the above import pragma you write:
26669 @smallexample @c ada
26671 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26672 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
26677 then the imported routine is @code{_retrieve_val@@4}. However, if instead
26678 of specifying the @code{External_Name} parameter you specify the
26679 @code{Link_Name} as in the following example:
26681 @smallexample @c ada
26683 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26684 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
26689 then the imported routine is @code{retrieve_val@@4}, that is, there is no
26690 trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always
26691 added at the end of the @code{Link_Name} by the compiler.
26694 Note, that in some special cases a DLL's entry point name lacks a trailing
26695 @code{@@}@code{@i{nn}} while the exported name generated for a call has it.
26696 The @code{gnatdll} tool, which creates the import library for the DLL, is able
26697 to handle those cases (@pxref{Using gnatdll} for the description of
26700 @node DLL Calling Convention
26701 @subsection @code{DLL} Calling Convention
26704 This convention, which is GNAT-specific, must be used when you want to
26705 import in Ada a variables defined in a DLL. For functions and procedures
26706 this convention is equivalent to the @code{Stdcall} convention. As an
26707 example, if a DLL contains a variable defined as:
26714 then, to access this variable from Ada you should write:
26716 @smallexample @c ada
26718 My_Var : Interfaces.C.int;
26719 pragma Import (DLL, My_Var);
26723 The remarks concerning the @code{External_Name} and @code{Link_Name}
26724 parameters given in the previous sections equally apply to the @code{DLL}
26725 calling convention.
26727 @node Introduction to Dynamic Link Libraries (DLLs)
26728 @section Introduction to Dynamic Link Libraries (DLLs)
26732 A Dynamically Linked Library (DLL) is a library that can be shared by
26733 several applications running under Windows. A DLL can contain any number of
26734 routines and variables.
26736 One advantage of DLLs is that you can change and enhance them without
26737 forcing all the applications that depend on them to be relinked or
26738 recompiled. However, you should be aware than all calls to DLL routines are
26739 slower since, as you will understand below, such calls are indirect.
26741 To illustrate the remainder of this section, suppose that an application
26742 wants to use the services of a DLL @file{API.dll}. To use the services
26743 provided by @file{API.dll} you must statically link against the DLL or
26744 an import library which contains a jump table with an entry for each
26745 routine and variable exported by the DLL. In the Microsoft world this
26746 import library is called @file{API.lib}. When using GNAT this import
26747 library is called either @file{libAPI.a} or @file{libapi.a} (names are
26750 After you have linked your application with the DLL or the import library
26751 and you run your application, here is what happens:
26755 Your application is loaded into memory.
26758 The DLL @file{API.dll} is mapped into the address space of your
26759 application. This means that:
26763 The DLL will use the stack of the calling thread.
26766 The DLL will use the virtual address space of the calling process.
26769 The DLL will allocate memory from the virtual address space of the calling
26773 Handles (pointers) can be safely exchanged between routines in the DLL
26774 routines and routines in the application using the DLL.
26778 The entries in the jump table (from the import library @file{libAPI.a}
26779 or @file{API.lib} or automatically created when linking against a DLL)
26780 which is part of your application are initialized with the addresses
26781 of the routines and variables in @file{API.dll}.
26784 If present in @file{API.dll}, routines @code{DllMain} or
26785 @code{DllMainCRTStartup} are invoked. These routines typically contain
26786 the initialization code needed for the well-being of the routines and
26787 variables exported by the DLL.
26791 There is an additional point which is worth mentioning. In the Windows
26792 world there are two kind of DLLs: relocatable and non-relocatable
26793 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
26794 in the target application address space. If the addresses of two
26795 non-relocatable DLLs overlap and these happen to be used by the same
26796 application, a conflict will occur and the application will run
26797 incorrectly. Hence, when possible, it is always preferable to use and
26798 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
26799 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
26800 User's Guide) removes the debugging symbols from the DLL but the DLL can
26801 still be relocated.
26803 As a side note, an interesting difference between Microsoft DLLs and
26804 Unix shared libraries, is the fact that on most Unix systems all public
26805 routines are exported by default in a Unix shared library, while under
26806 Windows it is possible (but not required) to list exported routines in
26807 a definition file (@pxref{The Definition File}).
26809 @node Using DLLs with GNAT
26810 @section Using DLLs with GNAT
26813 * Creating an Ada Spec for the DLL Services::
26814 * Creating an Import Library::
26818 To use the services of a DLL, say @file{API.dll}, in your Ada application
26823 The Ada spec for the routines and/or variables you want to access in
26824 @file{API.dll}. If not available this Ada spec must be built from the C/C++
26825 header files provided with the DLL.
26828 The import library (@file{libAPI.a} or @file{API.lib}). As previously
26829 mentioned an import library is a statically linked library containing the
26830 import table which will be filled at load time to point to the actual
26831 @file{API.dll} routines. Sometimes you don't have an import library for the
26832 DLL you want to use. The following sections will explain how to build
26833 one. Note that this is optional.
26836 The actual DLL, @file{API.dll}.
26840 Once you have all the above, to compile an Ada application that uses the
26841 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
26842 you simply issue the command
26845 $ gnatmake my_ada_app -largs -lAPI
26849 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
26850 tells the GNAT linker to look first for a library named @file{API.lib}
26851 (Microsoft-style name) and if not found for a library named @file{libAPI.a}
26852 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
26853 contains the following pragma
26855 @smallexample @c ada
26856 pragma Linker_Options ("-lAPI");
26860 you do not have to add @option{-largs -lAPI} at the end of the
26861 @command{gnatmake} command.
26863 If any one of the items above is missing you will have to create it
26864 yourself. The following sections explain how to do so using as an
26865 example a fictitious DLL called @file{API.dll}.
26867 @node Creating an Ada Spec for the DLL Services
26868 @subsection Creating an Ada Spec for the DLL Services
26871 A DLL typically comes with a C/C++ header file which provides the
26872 definitions of the routines and variables exported by the DLL. The Ada
26873 equivalent of this header file is a package spec that contains definitions
26874 for the imported entities. If the DLL you intend to use does not come with
26875 an Ada spec you have to generate one such spec yourself. For example if
26876 the header file of @file{API.dll} is a file @file{api.h} containing the
26877 following two definitions:
26889 then the equivalent Ada spec could be:
26891 @smallexample @c ada
26894 with Interfaces.C.Strings;
26899 function Get (Str : C.Strings.Chars_Ptr) return C.int;
26902 pragma Import (C, Get);
26903 pragma Import (DLL, Some_Var);
26910 Note that a variable is @strong{always imported with a DLL convention}. A
26911 function can have @code{C}, @code{Stdcall} or @code{DLL} convention. For
26912 subprograms, the @code{DLL} convention is a synonym of @code{Stdcall}
26913 (@pxref{Windows Calling Conventions}).
26915 @node Creating an Import Library
26916 @subsection Creating an Import Library
26917 @cindex Import library
26920 * The Definition File::
26921 * GNAT-Style Import Library::
26922 * Microsoft-Style Import Library::
26926 If a Microsoft-style import library @file{API.lib} or a GNAT-style
26927 import library @file{libAPI.a} is available with @file{API.dll} you
26928 can skip this section. You can also skip this section if
26929 @file{API.dll} is built with GNU tools as in this case it is possible
26930 to link directly against the DLL. Otherwise read on.
26932 @node The Definition File
26933 @subsubsection The Definition File
26934 @cindex Definition file
26938 As previously mentioned, and unlike Unix systems, the list of symbols
26939 that are exported from a DLL must be provided explicitly in Windows.
26940 The main goal of a definition file is precisely that: list the symbols
26941 exported by a DLL. A definition file (usually a file with a @code{.def}
26942 suffix) has the following structure:
26948 [DESCRIPTION @i{string}]
26958 @item LIBRARY @i{name}
26959 This section, which is optional, gives the name of the DLL.
26961 @item DESCRIPTION @i{string}
26962 This section, which is optional, gives a description string that will be
26963 embedded in the import library.
26966 This section gives the list of exported symbols (procedures, functions or
26967 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
26968 section of @file{API.def} looks like:
26982 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
26983 (@pxref{Windows Calling Conventions}) for a Stdcall
26984 calling convention function in the exported symbols list.
26987 There can actually be other sections in a definition file, but these
26988 sections are not relevant to the discussion at hand.
26990 @node GNAT-Style Import Library
26991 @subsubsection GNAT-Style Import Library
26994 To create a static import library from @file{API.dll} with the GNAT tools
26995 you should proceed as follows:
26999 Create the definition file @file{API.def} (@pxref{The Definition File}).
27000 For that use the @code{dll2def} tool as follows:
27003 $ dll2def API.dll > API.def
27007 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
27008 to standard output the list of entry points in the DLL. Note that if
27009 some routines in the DLL have the @code{Stdcall} convention
27010 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
27011 suffix then you'll have to edit @file{api.def} to add it, and specify
27012 @code{-k} to @code{gnatdll} when creating the import library.
27015 Here are some hints to find the right @code{@@}@i{nn} suffix.
27019 If you have the Microsoft import library (.lib), it is possible to get
27020 the right symbols by using Microsoft @code{dumpbin} tool (see the
27021 corresponding Microsoft documentation for further details).
27024 $ dumpbin /exports api.lib
27028 If you have a message about a missing symbol at link time the compiler
27029 tells you what symbol is expected. You just have to go back to the
27030 definition file and add the right suffix.
27034 Build the import library @code{libAPI.a}, using @code{gnatdll}
27035 (@pxref{Using gnatdll}) as follows:
27038 $ gnatdll -e API.def -d API.dll
27042 @code{gnatdll} takes as input a definition file @file{API.def} and the
27043 name of the DLL containing the services listed in the definition file
27044 @file{API.dll}. The name of the static import library generated is
27045 computed from the name of the definition file as follows: if the
27046 definition file name is @i{xyz}@code{.def}, the import library name will
27047 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
27048 @option{-e} could have been removed because the name of the definition
27049 file (before the ``@code{.def}'' suffix) is the same as the name of the
27050 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
27053 @node Microsoft-Style Import Library
27054 @subsubsection Microsoft-Style Import Library
27057 With GNAT you can either use a GNAT-style or Microsoft-style import
27058 library. A Microsoft import library is needed only if you plan to make an
27059 Ada DLL available to applications developed with Microsoft
27060 tools (@pxref{Mixed-Language Programming on Windows}).
27062 To create a Microsoft-style import library for @file{API.dll} you
27063 should proceed as follows:
27067 Create the definition file @file{API.def} from the DLL. For this use either
27068 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
27069 tool (see the corresponding Microsoft documentation for further details).
27072 Build the actual import library using Microsoft's @code{lib} utility:
27075 $ lib -machine:IX86 -def:API.def -out:API.lib
27079 If you use the above command the definition file @file{API.def} must
27080 contain a line giving the name of the DLL:
27087 See the Microsoft documentation for further details about the usage of
27091 @node Building DLLs with GNAT
27092 @section Building DLLs with GNAT
27093 @cindex DLLs, building
27096 This section explain how to build DLLs using the GNAT built-in DLL
27097 support. With the following procedure it is straight forward to build
27098 and use DLLs with GNAT.
27102 @item building object files
27104 The first step is to build all objects files that are to be included
27105 into the DLL. This is done by using the standard @command{gnatmake} tool.
27107 @item building the DLL
27109 To build the DLL you must use @command{gcc}'s @code{-shared}
27110 option. It is quite simple to use this method:
27113 $ gcc -shared -o api.dll obj1.o obj2.o ...
27116 It is important to note that in this case all symbols found in the
27117 object files are automatically exported. It is possible to restrict
27118 the set of symbols to export by passing to @command{gcc} a definition
27119 file, @pxref{The Definition File}. For example:
27122 $ gcc -shared -o api.dll api.def obj1.o obj2.o ...
27125 If you use a definition file you must export the elaboration procedures
27126 for every package that required one. Elaboration procedures are named
27127 using the package name followed by "_E".
27129 @item preparing DLL to be used
27131 For the DLL to be used by client programs the bodies must be hidden
27132 from it and the .ali set with read-only attribute. This is very important
27133 otherwise GNAT will recompile all packages and will not actually use
27134 the code in the DLL. For example:
27138 $ copy *.ads *.ali api.dll apilib
27139 $ attrib +R apilib\*.ali
27144 At this point it is possible to use the DLL by directly linking
27145 against it. Note that you must use the GNAT shared runtime when using
27146 GNAT shared libraries. This is achieved by using @code{-shared} binder's
27150 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
27153 @node Building DLLs with GNAT Project files
27154 @section Building DLLs with GNAT Project files
27155 @cindex DLLs, building
27158 There is nothing specific to Windows in this area. @pxref{Library Projects}.
27160 @node Building DLLs with gnatdll
27161 @section Building DLLs with gnatdll
27162 @cindex DLLs, building
27165 * Limitations When Using Ada DLLs from Ada::
27166 * Exporting Ada Entities::
27167 * Ada DLLs and Elaboration::
27168 * Ada DLLs and Finalization::
27169 * Creating a Spec for Ada DLLs::
27170 * Creating the Definition File::
27175 Note that it is preferred to use the built-in GNAT DLL support
27176 (@pxref{Building DLLs with GNAT}) or GNAT Project files
27177 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
27179 This section explains how to build DLLs containing Ada code using
27180 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
27181 remainder of this section.
27183 The steps required to build an Ada DLL that is to be used by Ada as well as
27184 non-Ada applications are as follows:
27188 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
27189 @code{Stdcall} calling convention to avoid any Ada name mangling for the
27190 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
27191 skip this step if you plan to use the Ada DLL only from Ada applications.
27194 Your Ada code must export an initialization routine which calls the routine
27195 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
27196 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
27197 routine exported by the Ada DLL must be invoked by the clients of the DLL
27198 to initialize the DLL.
27201 When useful, the DLL should also export a finalization routine which calls
27202 routine @code{adafinal} generated by @command{gnatbind} to perform the
27203 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
27204 The finalization routine exported by the Ada DLL must be invoked by the
27205 clients of the DLL when the DLL services are no further needed.
27208 You must provide a spec for the services exported by the Ada DLL in each
27209 of the programming languages to which you plan to make the DLL available.
27212 You must provide a definition file listing the exported entities
27213 (@pxref{The Definition File}).
27216 Finally you must use @code{gnatdll} to produce the DLL and the import
27217 library (@pxref{Using gnatdll}).
27221 Note that a relocatable DLL stripped using the @code{strip} binutils
27222 tool will not be relocatable anymore. To build a DLL without debug
27223 information pass @code{-largs -s} to @code{gnatdll}.
27225 @node Limitations When Using Ada DLLs from Ada
27226 @subsection Limitations When Using Ada DLLs from Ada
27229 When using Ada DLLs from Ada applications there is a limitation users
27230 should be aware of. Because on Windows the GNAT run time is not in a DLL of
27231 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
27232 each Ada DLL includes the services of the GNAT run time that are necessary
27233 to the Ada code inside the DLL. As a result, when an Ada program uses an
27234 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
27235 one in the main program.
27237 It is therefore not possible to exchange GNAT run-time objects between the
27238 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
27239 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
27242 It is completely safe to exchange plain elementary, array or record types,
27243 Windows object handles, etc.
27245 @node Exporting Ada Entities
27246 @subsection Exporting Ada Entities
27247 @cindex Export table
27250 Building a DLL is a way to encapsulate a set of services usable from any
27251 application. As a result, the Ada entities exported by a DLL should be
27252 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
27253 any Ada name mangling. Please note that the @code{Stdcall} convention
27254 should only be used for subprograms, not for variables. As an example here
27255 is an Ada package @code{API}, spec and body, exporting two procedures, a
27256 function, and a variable:
27258 @smallexample @c ada
27261 with Interfaces.C; use Interfaces;
27263 Count : C.int := 0;
27264 function Factorial (Val : C.int) return C.int;
27266 procedure Initialize_API;
27267 procedure Finalize_API;
27268 -- Initialization & Finalization routines. More in the next section.
27270 pragma Export (C, Initialize_API);
27271 pragma Export (C, Finalize_API);
27272 pragma Export (C, Count);
27273 pragma Export (C, Factorial);
27279 @smallexample @c ada
27282 package body API is
27283 function Factorial (Val : C.int) return C.int is
27286 Count := Count + 1;
27287 for K in 1 .. Val loop
27293 procedure Initialize_API is
27295 pragma Import (C, Adainit);
27298 end Initialize_API;
27300 procedure Finalize_API is
27301 procedure Adafinal;
27302 pragma Import (C, Adafinal);
27312 If the Ada DLL you are building will only be used by Ada applications
27313 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
27314 convention. As an example, the previous package could be written as
27317 @smallexample @c ada
27321 Count : Integer := 0;
27322 function Factorial (Val : Integer) return Integer;
27324 procedure Initialize_API;
27325 procedure Finalize_API;
27326 -- Initialization and Finalization routines.
27332 @smallexample @c ada
27335 package body API is
27336 function Factorial (Val : Integer) return Integer is
27337 Fact : Integer := 1;
27339 Count := Count + 1;
27340 for K in 1 .. Val loop
27347 -- The remainder of this package body is unchanged.
27354 Note that if you do not export the Ada entities with a @code{C} or
27355 @code{Stdcall} convention you will have to provide the mangled Ada names
27356 in the definition file of the Ada DLL
27357 (@pxref{Creating the Definition File}).
27359 @node Ada DLLs and Elaboration
27360 @subsection Ada DLLs and Elaboration
27361 @cindex DLLs and elaboration
27364 The DLL that you are building contains your Ada code as well as all the
27365 routines in the Ada library that are needed by it. The first thing a
27366 user of your DLL must do is elaborate the Ada code
27367 (@pxref{Elaboration Order Handling in GNAT}).
27369 To achieve this you must export an initialization routine
27370 (@code{Initialize_API} in the previous example), which must be invoked
27371 before using any of the DLL services. This elaboration routine must call
27372 the Ada elaboration routine @code{adainit} generated by the GNAT binder
27373 (@pxref{Binding with Non-Ada Main Programs}). See the body of
27374 @code{Initialize_Api} for an example. Note that the GNAT binder is
27375 automatically invoked during the DLL build process by the @code{gnatdll}
27376 tool (@pxref{Using gnatdll}).
27378 When a DLL is loaded, Windows systematically invokes a routine called
27379 @code{DllMain}. It would therefore be possible to call @code{adainit}
27380 directly from @code{DllMain} without having to provide an explicit
27381 initialization routine. Unfortunately, it is not possible to call
27382 @code{adainit} from the @code{DllMain} if your program has library level
27383 tasks because access to the @code{DllMain} entry point is serialized by
27384 the system (that is, only a single thread can execute ``through'' it at a
27385 time), which means that the GNAT run time will deadlock waiting for the
27386 newly created task to complete its initialization.
27388 @node Ada DLLs and Finalization
27389 @subsection Ada DLLs and Finalization
27390 @cindex DLLs and finalization
27393 When the services of an Ada DLL are no longer needed, the client code should
27394 invoke the DLL finalization routine, if available. The DLL finalization
27395 routine is in charge of releasing all resources acquired by the DLL. In the
27396 case of the Ada code contained in the DLL, this is achieved by calling
27397 routine @code{adafinal} generated by the GNAT binder
27398 (@pxref{Binding with Non-Ada Main Programs}).
27399 See the body of @code{Finalize_Api} for an
27400 example. As already pointed out the GNAT binder is automatically invoked
27401 during the DLL build process by the @code{gnatdll} tool
27402 (@pxref{Using gnatdll}).
27404 @node Creating a Spec for Ada DLLs
27405 @subsection Creating a Spec for Ada DLLs
27408 To use the services exported by the Ada DLL from another programming
27409 language (e.g. C), you have to translate the specs of the exported Ada
27410 entities in that language. For instance in the case of @code{API.dll},
27411 the corresponding C header file could look like:
27416 extern int *_imp__count;
27417 #define count (*_imp__count)
27418 int factorial (int);
27424 It is important to understand that when building an Ada DLL to be used by
27425 other Ada applications, you need two different specs for the packages
27426 contained in the DLL: one for building the DLL and the other for using
27427 the DLL. This is because the @code{DLL} calling convention is needed to
27428 use a variable defined in a DLL, but when building the DLL, the variable
27429 must have either the @code{Ada} or @code{C} calling convention. As an
27430 example consider a DLL comprising the following package @code{API}:
27432 @smallexample @c ada
27436 Count : Integer := 0;
27438 -- Remainder of the package omitted.
27445 After producing a DLL containing package @code{API}, the spec that
27446 must be used to import @code{API.Count} from Ada code outside of the
27449 @smallexample @c ada
27454 pragma Import (DLL, Count);
27460 @node Creating the Definition File
27461 @subsection Creating the Definition File
27464 The definition file is the last file needed to build the DLL. It lists
27465 the exported symbols. As an example, the definition file for a DLL
27466 containing only package @code{API} (where all the entities are exported
27467 with a @code{C} calling convention) is:
27482 If the @code{C} calling convention is missing from package @code{API},
27483 then the definition file contains the mangled Ada names of the above
27484 entities, which in this case are:
27493 api__initialize_api
27498 @node Using gnatdll
27499 @subsection Using @code{gnatdll}
27503 * gnatdll Example::
27504 * gnatdll behind the Scenes::
27509 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
27510 and non-Ada sources that make up your DLL have been compiled.
27511 @code{gnatdll} is actually in charge of two distinct tasks: build the
27512 static import library for the DLL and the actual DLL. The form of the
27513 @code{gnatdll} command is
27517 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
27522 where @i{list-of-files} is a list of ALI and object files. The object
27523 file list must be the exact list of objects corresponding to the non-Ada
27524 sources whose services are to be included in the DLL. The ALI file list
27525 must be the exact list of ALI files for the corresponding Ada sources
27526 whose services are to be included in the DLL. If @i{list-of-files} is
27527 missing, only the static import library is generated.
27530 You may specify any of the following switches to @code{gnatdll}:
27533 @item -a[@var{address}]
27534 @cindex @option{-a} (@code{gnatdll})
27535 Build a non-relocatable DLL at @var{address}. If @var{address} is not
27536 specified the default address @var{0x11000000} will be used. By default,
27537 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
27538 advise the reader to build relocatable DLL.
27540 @item -b @var{address}
27541 @cindex @option{-b} (@code{gnatdll})
27542 Set the relocatable DLL base address. By default the address is
27545 @item -bargs @var{opts}
27546 @cindex @option{-bargs} (@code{gnatdll})
27547 Binder options. Pass @var{opts} to the binder.
27549 @item -d @var{dllfile}
27550 @cindex @option{-d} (@code{gnatdll})
27551 @var{dllfile} is the name of the DLL. This switch must be present for
27552 @code{gnatdll} to do anything. The name of the generated import library is
27553 obtained algorithmically from @var{dllfile} as shown in the following
27554 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
27555 @code{libxyz.a}. The name of the definition file to use (if not specified
27556 by option @option{-e}) is obtained algorithmically from @var{dllfile}
27557 as shown in the following example:
27558 if @var{dllfile} is @code{xyz.dll}, the definition
27559 file used is @code{xyz.def}.
27561 @item -e @var{deffile}
27562 @cindex @option{-e} (@code{gnatdll})
27563 @var{deffile} is the name of the definition file.
27566 @cindex @option{-g} (@code{gnatdll})
27567 Generate debugging information. This information is stored in the object
27568 file and copied from there to the final DLL file by the linker,
27569 where it can be read by the debugger. You must use the
27570 @option{-g} switch if you plan on using the debugger or the symbolic
27574 @cindex @option{-h} (@code{gnatdll})
27575 Help mode. Displays @code{gnatdll} switch usage information.
27578 @cindex @option{-I} (@code{gnatdll})
27579 Direct @code{gnatdll} to search the @var{dir} directory for source and
27580 object files needed to build the DLL.
27581 (@pxref{Search Paths and the Run-Time Library (RTL)}).
27584 @cindex @option{-k} (@code{gnatdll})
27585 Removes the @code{@@}@i{nn} suffix from the import library's exported
27586 names, but keeps them for the link names. You must specify this
27587 option if you want to use a @code{Stdcall} function in a DLL for which
27588 the @code{@@}@i{nn} suffix has been removed. This is the case for most
27589 of the Windows NT DLL for example. This option has no effect when
27590 @option{-n} option is specified.
27592 @item -l @var{file}
27593 @cindex @option{-l} (@code{gnatdll})
27594 The list of ALI and object files used to build the DLL are listed in
27595 @var{file}, instead of being given in the command line. Each line in
27596 @var{file} contains the name of an ALI or object file.
27599 @cindex @option{-n} (@code{gnatdll})
27600 No Import. Do not create the import library.
27603 @cindex @option{-q} (@code{gnatdll})
27604 Quiet mode. Do not display unnecessary messages.
27607 @cindex @option{-v} (@code{gnatdll})
27608 Verbose mode. Display extra information.
27610 @item -largs @var{opts}
27611 @cindex @option{-largs} (@code{gnatdll})
27612 Linker options. Pass @var{opts} to the linker.
27615 @node gnatdll Example
27616 @subsubsection @code{gnatdll} Example
27619 As an example the command to build a relocatable DLL from @file{api.adb}
27620 once @file{api.adb} has been compiled and @file{api.def} created is
27623 $ gnatdll -d api.dll api.ali
27627 The above command creates two files: @file{libapi.a} (the import
27628 library) and @file{api.dll} (the actual DLL). If you want to create
27629 only the DLL, just type:
27632 $ gnatdll -d api.dll -n api.ali
27636 Alternatively if you want to create just the import library, type:
27639 $ gnatdll -d api.dll
27642 @node gnatdll behind the Scenes
27643 @subsubsection @code{gnatdll} behind the Scenes
27646 This section details the steps involved in creating a DLL. @code{gnatdll}
27647 does these steps for you. Unless you are interested in understanding what
27648 goes on behind the scenes, you should skip this section.
27650 We use the previous example of a DLL containing the Ada package @code{API},
27651 to illustrate the steps necessary to build a DLL. The starting point is a
27652 set of objects that will make up the DLL and the corresponding ALI
27653 files. In the case of this example this means that @file{api.o} and
27654 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
27659 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
27660 the information necessary to generate relocation information for the
27666 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
27671 In addition to the base file, the @command{gnatlink} command generates an
27672 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
27673 asks @command{gnatlink} to generate the routines @code{DllMain} and
27674 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
27675 is loaded into memory.
27678 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
27679 export table (@file{api.exp}). The export table contains the relocation
27680 information in a form which can be used during the final link to ensure
27681 that the Windows loader is able to place the DLL anywhere in memory.
27685 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27686 --output-exp api.exp
27691 @code{gnatdll} builds the base file using the new export table. Note that
27692 @command{gnatbind} must be called once again since the binder generated file
27693 has been deleted during the previous call to @command{gnatlink}.
27698 $ gnatlink api -o api.jnk api.exp -mdll
27699 -Wl,--base-file,api.base
27704 @code{gnatdll} builds the new export table using the new base file and
27705 generates the DLL import library @file{libAPI.a}.
27709 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27710 --output-exp api.exp --output-lib libAPI.a
27715 Finally @code{gnatdll} builds the relocatable DLL using the final export
27721 $ gnatlink api api.exp -o api.dll -mdll
27726 @node Using dlltool
27727 @subsubsection Using @code{dlltool}
27730 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
27731 DLLs and static import libraries. This section summarizes the most
27732 common @code{dlltool} switches. The form of the @code{dlltool} command
27736 $ dlltool [@var{switches}]
27740 @code{dlltool} switches include:
27743 @item --base-file @var{basefile}
27744 @cindex @option{--base-file} (@command{dlltool})
27745 Read the base file @var{basefile} generated by the linker. This switch
27746 is used to create a relocatable DLL.
27748 @item --def @var{deffile}
27749 @cindex @option{--def} (@command{dlltool})
27750 Read the definition file.
27752 @item --dllname @var{name}
27753 @cindex @option{--dllname} (@command{dlltool})
27754 Gives the name of the DLL. This switch is used to embed the name of the
27755 DLL in the static import library generated by @code{dlltool} with switch
27756 @option{--output-lib}.
27759 @cindex @option{-k} (@command{dlltool})
27760 Kill @code{@@}@i{nn} from exported names
27761 (@pxref{Windows Calling Conventions}
27762 for a discussion about @code{Stdcall}-style symbols.
27765 @cindex @option{--help} (@command{dlltool})
27766 Prints the @code{dlltool} switches with a concise description.
27768 @item --output-exp @var{exportfile}
27769 @cindex @option{--output-exp} (@command{dlltool})
27770 Generate an export file @var{exportfile}. The export file contains the
27771 export table (list of symbols in the DLL) and is used to create the DLL.
27773 @item --output-lib @i{libfile}
27774 @cindex @option{--output-lib} (@command{dlltool})
27775 Generate a static import library @var{libfile}.
27778 @cindex @option{-v} (@command{dlltool})
27781 @item --as @i{assembler-name}
27782 @cindex @option{--as} (@command{dlltool})
27783 Use @i{assembler-name} as the assembler. The default is @code{as}.
27786 @node GNAT and Windows Resources
27787 @section GNAT and Windows Resources
27788 @cindex Resources, windows
27791 * Building Resources::
27792 * Compiling Resources::
27793 * Using Resources::
27797 Resources are an easy way to add Windows specific objects to your
27798 application. The objects that can be added as resources include:
27827 This section explains how to build, compile and use resources.
27829 @node Building Resources
27830 @subsection Building Resources
27831 @cindex Resources, building
27834 A resource file is an ASCII file. By convention resource files have an
27835 @file{.rc} extension.
27836 The easiest way to build a resource file is to use Microsoft tools
27837 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
27838 @code{dlgedit.exe} to build dialogs.
27839 It is always possible to build an @file{.rc} file yourself by writing a
27842 It is not our objective to explain how to write a resource file. A
27843 complete description of the resource script language can be found in the
27844 Microsoft documentation.
27846 @node Compiling Resources
27847 @subsection Compiling Resources
27850 @cindex Resources, compiling
27853 This section describes how to build a GNAT-compatible (COFF) object file
27854 containing the resources. This is done using the Resource Compiler
27855 @code{windres} as follows:
27858 $ windres -i myres.rc -o myres.o
27862 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
27863 file. You can specify an alternate preprocessor (usually named
27864 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
27865 parameter. A list of all possible options may be obtained by entering
27866 the command @code{windres} @option{--help}.
27868 It is also possible to use the Microsoft resource compiler @code{rc.exe}
27869 to produce a @file{.res} file (binary resource file). See the
27870 corresponding Microsoft documentation for further details. In this case
27871 you need to use @code{windres} to translate the @file{.res} file to a
27872 GNAT-compatible object file as follows:
27875 $ windres -i myres.res -o myres.o
27878 @node Using Resources
27879 @subsection Using Resources
27880 @cindex Resources, using
27883 To include the resource file in your program just add the
27884 GNAT-compatible object file for the resource(s) to the linker
27885 arguments. With @command{gnatmake} this is done by using the @option{-largs}
27889 $ gnatmake myprog -largs myres.o
27892 @node Debugging a DLL
27893 @section Debugging a DLL
27894 @cindex DLL debugging
27897 * Program and DLL Both Built with GCC/GNAT::
27898 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
27902 Debugging a DLL is similar to debugging a standard program. But
27903 we have to deal with two different executable parts: the DLL and the
27904 program that uses it. We have the following four possibilities:
27908 The program and the DLL are built with @code{GCC/GNAT}.
27910 The program is built with foreign tools and the DLL is built with
27913 The program is built with @code{GCC/GNAT} and the DLL is built with
27919 In this section we address only cases one and two above.
27920 There is no point in trying to debug
27921 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
27922 information in it. To do so you must use a debugger compatible with the
27923 tools suite used to build the DLL.
27925 @node Program and DLL Both Built with GCC/GNAT
27926 @subsection Program and DLL Both Built with GCC/GNAT
27929 This is the simplest case. Both the DLL and the program have @code{GDB}
27930 compatible debugging information. It is then possible to break anywhere in
27931 the process. Let's suppose here that the main procedure is named
27932 @code{ada_main} and that in the DLL there is an entry point named
27936 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
27937 program must have been built with the debugging information (see GNAT -g
27938 switch). Here are the step-by-step instructions for debugging it:
27941 @item Launch @code{GDB} on the main program.
27947 @item Break on the main procedure and run the program.
27950 (gdb) break ada_main
27955 This step is required to be able to set a breakpoint inside the DLL. As long
27956 as the program is not run, the DLL is not loaded. This has the
27957 consequence that the DLL debugging information is also not loaded, so it is not
27958 possible to set a breakpoint in the DLL.
27960 @item Set a breakpoint inside the DLL
27963 (gdb) break ada_dll
27970 At this stage a breakpoint is set inside the DLL. From there on
27971 you can use the standard approach to debug the whole program
27972 (@pxref{Running and Debugging Ada Programs}).
27974 To break on the @code{DllMain} routine it is not possible to follow
27975 the procedure above. At the time the program stop on @code{ada_main}
27976 the @code{DllMain} routine as already been called. Either you can use
27977 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
27980 @item Launch @code{GDB} on the main program.
27986 @item Load DLL symbols
27989 (gdb) add-sym api.dll
27992 @item Set a breakpoint inside the DLL
27995 (gdb) break ada_dll.adb:45
27998 Note that at this point it is not possible to break using the routine symbol
27999 directly as the program is not yet running. The solution is to break
28000 on the proper line (break in @file{ada_dll.adb} line 45).
28002 @item Start the program
28010 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
28011 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
28014 * Debugging the DLL Directly::
28015 * Attaching to a Running Process::
28019 In this case things are slightly more complex because it is not possible to
28020 start the main program and then break at the beginning to load the DLL and the
28021 associated DLL debugging information. It is not possible to break at the
28022 beginning of the program because there is no @code{GDB} debugging information,
28023 and therefore there is no direct way of getting initial control. This
28024 section addresses this issue by describing some methods that can be used
28025 to break somewhere in the DLL to debug it.
28028 First suppose that the main procedure is named @code{main} (this is for
28029 example some C code built with Microsoft Visual C) and that there is a
28030 DLL named @code{test.dll} containing an Ada entry point named
28034 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
28035 been built with debugging information (see GNAT -g option).
28037 @node Debugging the DLL Directly
28038 @subsubsection Debugging the DLL Directly
28042 Launch the debugger on the DLL.
28048 @item Set a breakpoint on a DLL subroutine.
28051 (gdb) break ada_dll.adb:45
28054 Note that at this point it is not possible to break using the routine symbol
28055 directly as the program is not yet running. The solution is to break
28056 on the proper line (break in @file{ada_dll.adb} line 45).
28059 Specify the executable file to @code{GDB}.
28062 (gdb) exec-file main.exe
28073 This will run the program until it reaches the breakpoint that has been
28074 set. From that point you can use the standard way to debug a program
28075 as described in (@pxref{Running and Debugging Ada Programs}).
28080 It is also possible to debug the DLL by attaching to a running process.
28082 @node Attaching to a Running Process
28083 @subsubsection Attaching to a Running Process
28084 @cindex DLL debugging, attach to process
28087 With @code{GDB} it is always possible to debug a running process by
28088 attaching to it. It is possible to debug a DLL this way. The limitation
28089 of this approach is that the DLL must run long enough to perform the
28090 attach operation. It may be useful for instance to insert a time wasting
28091 loop in the code of the DLL to meet this criterion.
28095 @item Launch the main program @file{main.exe}.
28101 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
28102 that the process PID for @file{main.exe} is 208.
28110 @item Attach to the running process to be debugged.
28116 @item Load the process debugging information.
28119 (gdb) symbol-file main.exe
28122 @item Break somewhere in the DLL.
28125 (gdb) break ada_dll
28128 @item Continue process execution.
28137 This last step will resume the process execution, and stop at
28138 the breakpoint we have set. From there you can use the standard
28139 approach to debug a program as described in
28140 (@pxref{Running and Debugging Ada Programs}).
28142 @node GNAT and COM/DCOM Objects
28143 @section GNAT and COM/DCOM Objects
28148 This section is temporarily left blank.
28152 @c **********************************
28153 @c * GNU Free Documentation License *
28154 @c **********************************
28156 @c GNU Free Documentation License
28158 @node Index,,GNU Free Documentation License, Top
28164 @c Put table of contents at end, otherwise it precedes the "title page" in
28165 @c the .txt version
28166 @c Edit the pdf file to move the contents to the beginning, after the title