1 \input texinfo @c -*-texinfo-*-
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
6 @c GNAT DOCUMENTATION o
10 @c Copyright (C) 1992-2006, AdaCore 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''.
128 @title @value{EDITION} User's Guide
132 @titlefont{@i{@value{PLATFORM}}}
135 @subtitle GNAT, The GNU Ada 95 Compiler
137 @author Ada Core Technologies, Inc.
139 @vskip 0pt plus 1filll
146 @node Top, About This Guide, (dir), (dir)
147 @top @value{EDITION} User's Guide
150 @value{EDITION} User's Guide @value{PLATFORM}
153 GNAT, The GNU Ada 95 Compiler@*
154 GCC version @value{version-GCC}@*
161 * Getting Started with GNAT::
162 * The GNAT Compilation Model::
163 * Compiling Using gcc::
164 * Binding Using gnatbind::
165 * Linking Using gnatlink::
166 * The GNAT Make Program gnatmake::
167 * Improving Performance::
168 * Renaming Files Using gnatchop::
169 * Configuration Pragmas::
170 * Handling Arbitrary File Naming Conventions Using gnatname::
171 * GNAT Project Manager::
172 * The Cross-Referencing Tools gnatxref and gnatfind::
173 * The GNAT Pretty-Printer gnatpp::
174 * The GNAT Metric Tool gnatmetric::
175 * File Name Krunching Using gnatkr::
176 * Preprocessing Using gnatprep::
178 * The GNAT Run-Time Library Builder gnatlbr::
180 * The GNAT Library Browser gnatls::
181 * Cleaning Up Using gnatclean::
183 * GNAT and Libraries::
184 * Using the GNU make Utility::
186 * Memory Management Issues::
187 * Stack Related Facilities::
188 * Verifying properties using gnatcheck::
189 * Creating Sample Bodies Using gnatstub::
190 * Other Utility Programs::
191 * Running and Debugging Ada Programs::
193 * Compatibility with HP Ada::
195 * Platform-Specific Information for the Run-Time Libraries::
196 * Example of Binder Output File::
197 * Elaboration Order Handling in GNAT::
199 * Compatibility and Porting Guide::
201 * Microsoft Windows Topics::
203 * GNU Free Documentation License::
206 --- The Detailed Node Listing ---
210 * What This Guide Contains::
211 * What You Should Know before Reading This Guide::
212 * Related Information::
215 Getting Started with GNAT
218 * Running a Simple Ada Program::
219 * Running a Program with Multiple Units::
220 * Using the gnatmake Utility::
222 * Editing with Emacs::
225 * Introduction to GPS::
226 * Introduction to Glide and GVD::
229 The GNAT Compilation Model
231 * Source Representation::
232 * Foreign Language Representation::
233 * File Naming Rules::
234 * Using Other File Names::
235 * Alternative File Naming Schemes::
236 * Generating Object Files::
237 * Source Dependencies::
238 * The Ada Library Information Files::
239 * Binding an Ada Program::
240 * Mixed Language Programming::
242 * Building Mixed Ada & C++ Programs::
243 * Comparison between GNAT and C/C++ Compilation Models::
245 * Comparison between GNAT and Conventional Ada Library Models::
247 * Placement of temporary files::
250 Foreign Language Representation
253 * Other 8-Bit Codes::
254 * Wide Character Encodings::
256 Compiling Ada Programs With gcc
258 * Compiling Programs::
260 * Search Paths and the Run-Time Library (RTL)::
261 * Order of Compilation Issues::
266 * Output and Error Message Control::
267 * Warning Message Control::
268 * Debugging and Assertion Control::
269 * Validity Checking::
272 * Using gcc for Syntax Checking::
273 * Using gcc for Semantic Checking::
274 * Compiling Different Versions of Ada::
275 * Character Set Control::
276 * File Naming Control::
277 * Subprogram Inlining Control::
278 * Auxiliary Output Control::
279 * Debugging Control::
280 * Exception Handling Control::
281 * Units to Sources Mapping Files::
282 * Integrated Preprocessing::
287 Binding Ada Programs With gnatbind
290 * Switches for gnatbind::
291 * Command-Line Access::
292 * Search Paths for gnatbind::
293 * Examples of gnatbind Usage::
295 Switches for gnatbind
297 * Consistency-Checking Modes::
298 * Binder Error Message Control::
299 * Elaboration Control::
301 * Binding with Non-Ada Main Programs::
302 * Binding Programs with No Main Subprogram::
304 Linking Using gnatlink
307 * Switches for gnatlink::
309 The GNAT Make Program gnatmake
312 * Switches for gnatmake::
313 * Mode Switches for gnatmake::
314 * Notes on the Command Line::
315 * How gnatmake Works::
316 * Examples of gnatmake Usage::
318 Improving Performance
319 * Performance Considerations::
320 * Reducing Size of Ada Executables with gnatelim::
321 * Reducing Size of Executables with unused subprogram/data elimination::
323 Performance Considerations
324 * Controlling Run-Time Checks::
325 * Use of Restrictions::
326 * Optimization Levels::
327 * Debugging Optimized Code::
328 * Inlining of Subprograms::
329 * Other Optimization Switches::
330 * Optimization and Strict Aliasing::
332 * Coverage Analysis::
335 Reducing Size of Ada Executables with gnatelim
338 * Correcting the List of Eliminate Pragmas::
339 * Making Your Executables Smaller::
340 * Summary of the gnatelim Usage Cycle::
342 Reducing Size of Executables with unused subprogram/data elimination
343 * About unused subprogram/data elimination::
344 * Compilation options::
346 Renaming Files Using gnatchop
348 * Handling Files with Multiple Units::
349 * Operating gnatchop in Compilation Mode::
350 * Command Line for gnatchop::
351 * Switches for gnatchop::
352 * Examples of gnatchop Usage::
354 Configuration Pragmas
356 * Handling of Configuration Pragmas::
357 * The Configuration Pragmas Files::
359 Handling Arbitrary File Naming Conventions Using gnatname
361 * Arbitrary File Naming Conventions::
363 * Switches for gnatname::
364 * Examples of gnatname Usage::
369 * Examples of Project Files::
370 * Project File Syntax::
371 * Objects and Sources in Project Files::
372 * Importing Projects::
373 * Project Extension::
374 * Project Hierarchy Extension::
375 * External References in Project Files::
376 * Packages in Project Files::
377 * Variables from Imported Projects::
380 * Stand-alone Library Projects::
381 * Switches Related to Project Files::
382 * Tools Supporting Project Files::
383 * An Extended Example::
384 * Project File Complete Syntax::
386 The Cross-Referencing Tools gnatxref and gnatfind
388 * gnatxref Switches::
389 * gnatfind Switches::
390 * Project Files for gnatxref and gnatfind::
391 * Regular Expressions in gnatfind and gnatxref::
392 * Examples of gnatxref Usage::
393 * Examples of gnatfind Usage::
395 The GNAT Pretty-Printer gnatpp
397 * Switches for gnatpp::
400 The GNAT Metrics Tool gnatmetric
402 * Switches for gnatmetric::
404 File Name Krunching Using gnatkr
409 * Examples of gnatkr Usage::
411 Preprocessing Using gnatprep
414 * Switches for gnatprep::
415 * Form of Definitions File::
416 * Form of Input Text for gnatprep::
419 The GNAT Run-Time Library Builder gnatlbr
422 * Switches for gnatlbr::
423 * Examples of gnatlbr Usage::
426 The GNAT Library Browser gnatls
429 * Switches for gnatls::
430 * Examples of gnatls Usage::
432 Cleaning Up Using gnatclean
434 * Running gnatclean::
435 * Switches for gnatclean::
436 @c * Examples of gnatclean Usage::
442 * Introduction to Libraries in GNAT::
443 * General Ada Libraries::
444 * Stand-alone Ada Libraries::
445 * Rebuilding the GNAT Run-Time Library::
447 Using the GNU make Utility
449 * Using gnatmake in a Makefile::
450 * Automatically Creating a List of Directories::
451 * Generating the Command Line Switches::
452 * Overcoming Command Line Length Limits::
455 Memory Management Issues
457 * Some Useful Memory Pools::
458 * The GNAT Debug Pool Facility::
463 Stack Related Facilities
465 * Stack Overflow Checking::
466 * Static Stack Usage Analysis::
467 * Dynamic Stack Usage Analysis::
469 Some Useful Memory Pools
471 The GNAT Debug Pool Facility
477 * Switches for gnatmem::
478 * Example of gnatmem Usage::
481 Verifying properties using gnatcheck
483 * Format of the Report File::
484 * General gnatcheck Switches::
485 * gnatcheck Rule Options::
486 * Add the Results of Compiler Checks to gnatcheck Output::
488 Sample Bodies Using gnatstub
491 * Switches for gnatstub::
493 Other Utility Programs
495 * Using Other Utility Programs with GNAT::
496 * The External Symbol Naming Scheme of GNAT::
498 * Ada Mode for Glide::
500 * Converting Ada Files to html with gnathtml::
502 Running and Debugging Ada Programs
504 * The GNAT Debugger GDB::
506 * Introduction to GDB Commands::
507 * Using Ada Expressions::
508 * Calling User-Defined Subprograms::
509 * Using the Next Command in a Function::
512 * Debugging Generic Units::
513 * GNAT Abnormal Termination or Failure to Terminate::
514 * Naming Conventions for GNAT Source Files::
515 * Getting Internal Debugging Information::
523 Compatibility with HP Ada
525 * Ada 95 Compatibility::
526 * Differences in the Definition of Package System::
527 * Language-Related Features::
528 * The Package STANDARD::
529 * The Package SYSTEM::
530 * Tasking and Task-Related Features::
531 * Pragmas and Pragma-Related Features::
532 * Library of Predefined Units::
534 * Main Program Definition::
535 * Implementation-Defined Attributes::
536 * Compiler and Run-Time Interfacing::
537 * Program Compilation and Library Management::
539 * Implementation Limits::
540 * Tools and Utilities::
542 Language-Related Features
544 * Integer Types and Representations::
545 * Floating-Point Types and Representations::
546 * Pragmas Float_Representation and Long_Float::
547 * Fixed-Point Types and Representations::
548 * Record and Array Component Alignment::
550 * Other Representation Clauses::
552 Tasking and Task-Related Features
554 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
555 * Assigning Task IDs::
556 * Task IDs and Delays::
557 * Task-Related Pragmas::
558 * Scheduling and Task Priority::
560 * External Interrupts::
562 Pragmas and Pragma-Related Features
564 * Restrictions on the Pragma INLINE::
565 * Restrictions on the Pragma INTERFACE::
566 * Restrictions on the Pragma SYSTEM_NAME::
568 Library of Predefined Units
570 * Changes to DECLIB::
574 * Shared Libraries and Options Files::
578 Platform-Specific Information for the Run-Time Libraries
580 * Summary of Run-Time Configurations::
581 * Specifying a Run-Time Library::
582 * Choosing the Scheduling Policy::
583 * Solaris-Specific Considerations::
584 * Linux-Specific Considerations::
585 * AIX-Specific Considerations::
587 Example of Binder Output File
589 Elaboration Order Handling in GNAT
591 * Elaboration Code in Ada 95::
592 * Checking the Elaboration Order in Ada 95::
593 * Controlling the Elaboration Order in Ada 95::
594 * Controlling Elaboration in GNAT - Internal Calls::
595 * Controlling Elaboration in GNAT - External Calls::
596 * Default Behavior in GNAT - Ensuring Safety::
597 * Treatment of Pragma Elaborate::
598 * Elaboration Issues for Library Tasks::
599 * Mixing Elaboration Models::
600 * What to Do If the Default Elaboration Behavior Fails::
601 * Elaboration for Access-to-Subprogram Values::
602 * Summary of Procedures for Elaboration Control::
603 * Other Elaboration Order Considerations::
607 * Basic Assembler Syntax::
608 * A Simple Example of Inline Assembler::
609 * Output Variables in Inline Assembler::
610 * Input Variables in Inline Assembler::
611 * Inlining Inline Assembler Code::
612 * Other Asm Functionality::
614 Compatibility and Porting Guide
616 * Compatibility with Ada 83::
617 * Implementation-dependent characteristics::
619 @c This brief section is only in the non-VMS version
620 @c The complete chapter on HP Ada issues is in the VMS version
621 * Compatibility with HP Ada 83::
623 * Compatibility with Other Ada 95 Systems::
624 * Representation Clauses::
626 * Transitioning to 64-Bit GNAT for OpenVMS::
630 Microsoft Windows Topics
632 * Using GNAT on Windows::
633 * CONSOLE and WINDOWS subsystems::
635 * Mixed-Language Programming on Windows::
636 * Windows Calling Conventions::
637 * Introduction to Dynamic Link Libraries (DLLs)::
638 * Using DLLs with GNAT::
639 * Building DLLs with GNAT::
640 * GNAT and Windows Resources::
642 * Setting Stack Size from gnatlink::
643 * Setting Heap Size from gnatlink::
650 @node About This Guide
651 @unnumbered About This Guide
655 This guide describes the use of @value{EDITION},
656 a full language compiler for the Ada
657 95 programming language, implemented on OpenVMS for HP's Alpha and
658 Integrity server (I64) platforms.
661 This guide describes the use of @value{EDITION},
662 a compiler and software development
663 toolset for the full Ada 95 programming language.
665 It describes the features of the compiler and tools, and details
666 how to use them to build Ada 95 applications.
669 For ease of exposition, ``GNAT Pro'' will be referred to simply as
670 ``GNAT'' in the remainder of this document.
674 * What This Guide Contains::
675 * What You Should Know before Reading This Guide::
676 * Related Information::
680 @node What This Guide Contains
681 @unnumberedsec What This Guide Contains
684 This guide contains the following chapters:
688 @ref{Getting Started with GNAT}, describes how to get started compiling
689 and running Ada programs with the GNAT Ada programming environment.
691 @ref{The GNAT Compilation Model}, describes the compilation model used
695 @ref{Compiling Using gcc}, describes how to compile
696 Ada programs with @command{gcc}, the Ada compiler.
699 @ref{Binding Using gnatbind}, describes how to
700 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
704 @ref{Linking Using gnatlink},
705 describes @command{gnatlink}, a
706 program that provides for linking using the GNAT run-time library to
707 construct a program. @command{gnatlink} can also incorporate foreign language
708 object units into the executable.
711 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
712 utility that automatically determines the set of sources
713 needed by an Ada compilation unit, and executes the necessary compilations
717 @ref{Improving Performance}, shows various techniques for making your
718 Ada program run faster or take less space.
719 It discusses the effect of the compiler's optimization switch and
720 also describes the @command{gnatelim} tool and unused subprogram/data
724 @ref{Renaming Files Using gnatchop}, describes
725 @code{gnatchop}, a utility that allows you to preprocess a file that
726 contains Ada source code, and split it into one or more new files, one
727 for each compilation unit.
730 @ref{Configuration Pragmas}, describes the configuration pragmas
734 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
735 shows how to override the default GNAT file naming conventions,
736 either for an individual unit or globally.
739 @ref{GNAT Project Manager}, describes how to use project files
740 to organize large projects.
743 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
744 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
745 way to navigate through sources.
748 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
749 version of an Ada source file with control over casing, indentation,
750 comment placement, and other elements of program presentation style.
753 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
754 metrics for an Ada source file, such as the number of types and subprograms,
755 and assorted complexity measures.
758 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
759 file name krunching utility, used to handle shortened
760 file names on operating systems with a limit on the length of names.
763 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
764 preprocessor utility that allows a single source file to be used to
765 generate multiple or parameterized source files, by means of macro
770 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
771 a tool for rebuilding the GNAT run time with user-supplied
772 configuration pragmas.
776 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
777 utility that displays information about compiled units, including dependences
778 on the corresponding sources files, and consistency of compilations.
781 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
782 to delete files that are produced by the compiler, binder and linker.
786 @ref{GNAT and Libraries}, describes the process of creating and using
787 Libraries with GNAT. It also describes how to recompile the GNAT run-time
791 @ref{Using the GNU make Utility}, describes some techniques for using
792 the GNAT toolset in Makefiles.
796 @ref{Memory Management Issues}, describes some useful predefined storage pools
797 and in particular the GNAT Debug Pool facility, which helps detect incorrect
800 It also describes @command{gnatmem}, a utility that monitors dynamic
801 allocation and deallocation and helps detect ``memory leaks''.
805 @ref{Stack Related Facilities}, describes some useful tools associated with
806 stack checking and analysis.
809 @ref{Verifying properties using gnatcheck}, discusses @code{gnatcheck},
810 a utility that checks Ada code against a set of rules.
813 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
814 a utility that generates empty but compilable bodies for library units.
817 @ref{Other Utility Programs}, discusses several other GNAT utilities,
818 including @code{gnathtml}.
821 @ref{Running and Debugging Ada Programs}, describes how to run and debug
826 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
827 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
828 developed by Digital Equipment Corporation and currently supported by HP.}
829 for OpenVMS Alpha. This product was formerly known as DEC Ada,
832 historical compatibility reasons, the relevant libraries still use the
837 @ref{Platform-Specific Information for the Run-Time Libraries},
838 describes the various run-time
839 libraries supported by GNAT on various platforms and explains how to
840 choose a particular library.
843 @ref{Example of Binder Output File}, shows the source code for the binder
844 output file for a sample program.
847 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
848 you deal with elaboration order issues.
851 @ref{Inline Assembler}, shows how to use the inline assembly facility
855 @ref{Compatibility and Porting Guide}, includes sections on compatibility
856 of GNAT with other Ada 83 and Ada 95 compilation systems, to assist
857 in porting code from other environments.
861 @ref{Microsoft Windows Topics}, presents information relevant to the
862 Microsoft Windows platform.
866 @c *************************************************
867 @node What You Should Know before Reading This Guide
868 @c *************************************************
869 @unnumberedsec What You Should Know before Reading This Guide
871 @cindex Ada 95 Language Reference Manual
873 This user's guide assumes that you are familiar with Ada 95 language, as
874 described in the International Standard ANSI/ISO/IEC-8652:1995, January
877 @node Related Information
878 @unnumberedsec Related Information
881 For further information about related tools, refer to the following
886 @cite{GNAT Reference Manual}, which contains all reference
887 material for the GNAT implementation of Ada 95.
891 @cite{Using the GNAT Programming System}, which describes the GPS
892 integrated development environment.
895 @cite{GNAT Programming System Tutorial}, which introduces the
896 main GPS features through examples.
900 @cite{Ada 95 Language Reference Manual}, which contains all reference
901 material for the Ada 95 programming language.
904 @cite{Debugging with GDB}
906 , located in the GNU:[DOCS] directory,
908 contains all details on the use of the GNU source-level debugger.
911 @cite{GNU Emacs Manual}
913 , located in the GNU:[DOCS] directory if the EMACS kit is installed,
915 contains full information on the extensible editor and programming
922 @unnumberedsec Conventions
924 @cindex Typographical conventions
927 Following are examples of the typographical and graphic conventions used
932 @code{Functions}, @code{utility program names}, @code{standard names},
939 @file{File Names}, @file{button names}, and @file{field names}.
948 [optional information or parameters]
951 Examples are described by text
953 and then shown this way.
958 Commands that are entered by the user are preceded in this manual by the
959 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
960 uses this sequence as a prompt, then the commands will appear exactly as
961 you see them in the manual. If your system uses some other prompt, then
962 the command will appear with the @code{$} replaced by whatever prompt
963 character you are using.
966 Full file names are shown with the ``@code{/}'' character
967 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
968 If you are using GNAT on a Windows platform, please note that
969 the ``@code{\}'' character should be used instead.
972 @c ****************************
973 @node Getting Started with GNAT
974 @chapter Getting Started with GNAT
977 This chapter describes some simple ways of using GNAT to build
978 executable Ada programs.
980 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
981 show how to use the command line environment.
982 @ref{Introduction to Glide and GVD}, provides a brief
983 introduction to the visually-oriented IDE for GNAT.
984 Supplementing Glide on some platforms is GPS, the
985 GNAT Programming System, which offers a richer graphical
986 ``look and feel'', enhanced configurability, support for
987 development in other programming language, comprehensive
988 browsing features, and many other capabilities.
989 For information on GPS please refer to
990 @cite{Using the GNAT Programming System}.
995 * Running a Simple Ada Program::
996 * Running a Program with Multiple Units::
997 * Using the gnatmake Utility::
999 * Editing with Emacs::
1002 * Introduction to GPS::
1003 * Introduction to Glide and GVD::
1008 @section Running GNAT
1011 Three steps are needed to create an executable file from an Ada source
1016 The source file(s) must be compiled.
1018 The file(s) must be bound using the GNAT binder.
1020 All appropriate object files must be linked to produce an executable.
1024 All three steps are most commonly handled by using the @command{gnatmake}
1025 utility program that, given the name of the main program, automatically
1026 performs the necessary compilation, binding and linking steps.
1028 @node Running a Simple Ada Program
1029 @section Running a Simple Ada Program
1032 Any text editor may be used to prepare an Ada program.
1035 used, the optional Ada mode may be helpful in laying out the program.
1038 program text is a normal text file. We will suppose in our initial
1039 example that you have used your editor to prepare the following
1040 standard format text file:
1042 @smallexample @c ada
1044 with Ada.Text_IO; use Ada.Text_IO;
1047 Put_Line ("Hello WORLD!");
1053 This file should be named @file{hello.adb}.
1054 With the normal default file naming conventions, GNAT requires
1056 contain a single compilation unit whose file name is the
1058 with periods replaced by hyphens; the
1059 extension is @file{ads} for a
1060 spec and @file{adb} for a body.
1061 You can override this default file naming convention by use of the
1062 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1063 Alternatively, if you want to rename your files according to this default
1064 convention, which is probably more convenient if you will be using GNAT
1065 for all your compilations, then the @code{gnatchop} utility
1066 can be used to generate correctly-named source files
1067 (@pxref{Renaming Files Using gnatchop}).
1069 You can compile the program using the following command (@code{$} is used
1070 as the command prompt in the examples in this document):
1077 @command{gcc} is the command used to run the compiler. This compiler is
1078 capable of compiling programs in several languages, including Ada 95 and
1079 C. It assumes that you have given it an Ada program if the file extension is
1080 either @file{.ads} or @file{.adb}, and it will then call
1081 the GNAT compiler to compile the specified file.
1084 The @option{-c} switch is required. It tells @command{gcc} to only do a
1085 compilation. (For C programs, @command{gcc} can also do linking, but this
1086 capability is not used directly for Ada programs, so the @option{-c}
1087 switch must always be present.)
1090 This compile command generates a file
1091 @file{hello.o}, which is the object
1092 file corresponding to your Ada program. It also generates
1093 an ``Ada Library Information'' file @file{hello.ali},
1094 which contains additional information used to check
1095 that an Ada program is consistent.
1096 To build an executable file,
1097 use @code{gnatbind} to bind the program
1098 and @command{gnatlink} to link it. The
1099 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1100 @file{ALI} file, but the default extension of @file{.ali} can
1101 be omitted. This means that in the most common case, the argument
1102 is simply the name of the main program:
1110 A simpler method of carrying out these steps is to use
1112 a master program that invokes all the required
1113 compilation, binding and linking tools in the correct order. In particular,
1114 @command{gnatmake} automatically recompiles any sources that have been
1115 modified since they were last compiled, or sources that depend
1116 on such modified sources, so that ``version skew'' is avoided.
1117 @cindex Version skew (avoided by @command{gnatmake})
1120 $ gnatmake hello.adb
1124 The result is an executable program called @file{hello}, which can be
1132 assuming that the current directory is on the search path
1133 for executable programs.
1136 and, if all has gone well, you will see
1143 appear in response to this command.
1145 @c ****************************************
1146 @node Running a Program with Multiple Units
1147 @section Running a Program with Multiple Units
1150 Consider a slightly more complicated example that has three files: a
1151 main program, and the spec and body of a package:
1153 @smallexample @c ada
1156 package Greetings is
1161 with Ada.Text_IO; use Ada.Text_IO;
1162 package body Greetings is
1165 Put_Line ("Hello WORLD!");
1168 procedure Goodbye is
1170 Put_Line ("Goodbye WORLD!");
1187 Following the one-unit-per-file rule, place this program in the
1188 following three separate files:
1192 spec of package @code{Greetings}
1195 body of package @code{Greetings}
1198 body of main program
1202 To build an executable version of
1203 this program, we could use four separate steps to compile, bind, and link
1204 the program, as follows:
1208 $ gcc -c greetings.adb
1214 Note that there is no required order of compilation when using GNAT.
1215 In particular it is perfectly fine to compile the main program first.
1216 Also, it is not necessary to compile package specs in the case where
1217 there is an accompanying body; you only need to compile the body. If you want
1218 to submit these files to the compiler for semantic checking and not code
1219 generation, then use the
1220 @option{-gnatc} switch:
1223 $ gcc -c greetings.ads -gnatc
1227 Although the compilation can be done in separate steps as in the
1228 above example, in practice it is almost always more convenient
1229 to use the @command{gnatmake} tool. All you need to know in this case
1230 is the name of the main program's source file. The effect of the above four
1231 commands can be achieved with a single one:
1234 $ gnatmake gmain.adb
1238 In the next section we discuss the advantages of using @command{gnatmake} in
1241 @c *****************************
1242 @node Using the gnatmake Utility
1243 @section Using the @command{gnatmake} Utility
1246 If you work on a program by compiling single components at a time using
1247 @command{gcc}, you typically keep track of the units you modify. In order to
1248 build a consistent system, you compile not only these units, but also any
1249 units that depend on the units you have modified.
1250 For example, in the preceding case,
1251 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1252 you edit @file{greetings.ads}, you must recompile both
1253 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1254 units that depend on @file{greetings.ads}.
1256 @code{gnatbind} will warn you if you forget one of these compilation
1257 steps, so that it is impossible to generate an inconsistent program as a
1258 result of forgetting to do a compilation. Nevertheless it is tedious and
1259 error-prone to keep track of dependencies among units.
1260 One approach to handle the dependency-bookkeeping is to use a
1261 makefile. However, makefiles present maintenance problems of their own:
1262 if the dependencies change as you change the program, you must make
1263 sure that the makefile is kept up-to-date manually, which is also an
1264 error-prone process.
1266 The @command{gnatmake} utility takes care of these details automatically.
1267 Invoke it using either one of the following forms:
1270 $ gnatmake gmain.adb
1271 $ gnatmake ^gmain^GMAIN^
1275 The argument is the name of the file containing the main program;
1276 you may omit the extension. @command{gnatmake}
1277 examines the environment, automatically recompiles any files that need
1278 recompiling, and binds and links the resulting set of object files,
1279 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1280 In a large program, it
1281 can be extremely helpful to use @command{gnatmake}, because working out by hand
1282 what needs to be recompiled can be difficult.
1284 Note that @command{gnatmake}
1285 takes into account all the Ada 95 rules that
1286 establish dependencies among units. These include dependencies that result
1287 from inlining subprogram bodies, and from
1288 generic instantiation. Unlike some other
1289 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1290 found by the compiler on a previous compilation, which may possibly
1291 be wrong when sources change. @command{gnatmake} determines the exact set of
1292 dependencies from scratch each time it is run.
1295 @node Editing with Emacs
1296 @section Editing with Emacs
1300 Emacs is an extensible self-documenting text editor that is available in a
1301 separate VMSINSTAL kit.
1303 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1304 click on the Emacs Help menu and run the Emacs Tutorial.
1305 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1306 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1308 Documentation on Emacs and other tools is available in Emacs under the
1309 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1310 use the middle mouse button to select a topic (e.g. Emacs).
1312 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1313 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1314 get to the Emacs manual.
1315 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1318 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1319 which is sufficiently extensible to provide for a complete programming
1320 environment and shell for the sophisticated user.
1324 @node Introduction to GPS
1325 @section Introduction to GPS
1326 @cindex GPS (GNAT Programming System)
1327 @cindex GNAT Programming System (GPS)
1329 Although the command line interface (@command{gnatmake}, etc.) alone
1330 is sufficient, a graphical Interactive Development
1331 Environment can make it easier for you to compose, navigate, and debug
1332 programs. This section describes the main features of GPS
1333 (``GNAT Programming System''), the GNAT graphical IDE.
1334 You will see how to use GPS to build and debug an executable, and
1335 you will also learn some of the basics of the GNAT ``project'' facility.
1337 GPS enables you to do much more than is presented here;
1338 e.g., you can produce a call graph, interface to a third-party
1339 Version Control System, and inspect the generated assembly language
1341 Indeed, GPS also supports languages other than Ada.
1342 Such additional information, and an explanation of all of the GPS menu
1343 items. may be found in the on-line help, which includes
1344 a user's guide and a tutorial (these are also accessible from the GNAT
1348 * Building a New Program with GPS::
1349 * Simple Debugging with GPS::
1352 @node Building a New Program with GPS
1353 @subsection Building a New Program with GPS
1355 GPS invokes the GNAT compilation tools using information
1356 contained in a @emph{project} (also known as a @emph{project file}):
1357 a collection of properties such
1358 as source directories, identities of main subprograms, tool switches, etc.,
1359 and their associated values.
1360 See @ref{GNAT Project Manager} for details.
1361 In order to run GPS, you will need to either create a new project
1362 or else open an existing one.
1364 This section will explain how you can use GPS to create a project,
1365 to associate Ada source files with a project, and to build and run
1369 @item @emph{Creating a project}
1371 Invoke GPS, either from the command line or the platform's IDE.
1372 After it starts, GPS will display a ``Welcome'' screen with three
1377 @code{Start with default project in directory}
1380 @code{Create new project with wizard}
1383 @code{Open existing project}
1387 Select @code{Create new project with wizard} and press @code{OK}.
1388 A new window will appear. In the text box labeled with
1389 @code{Enter the name of the project to create}, type @file{sample}
1390 as the project name.
1391 In the next box, browse to choose the directory in which you
1392 would like to create the project file.
1393 After selecting an appropriate directory, press @code{Forward}.
1395 A window will appear with the title
1396 @code{Version Control System Configuration}.
1397 Simply press @code{Forward}.
1399 A window will appear with the title
1400 @code{Please select the source directories for this project}.
1401 The directory that you specified for the project file will be selected
1402 by default as the one to use for sources; simply press @code{Forward}.
1404 A window will appear with the title
1405 @code{Please select the build directory for this project}.
1406 The directory that you specified for the project file will be selected
1407 by default for object files and executables;
1408 simply press @code{Forward}.
1410 A window will appear with the title
1411 @code{Please select the main units for this project}.
1412 You will supply this information later, after creating the source file.
1413 Simply press @code{Forward} for now.
1415 A window will appear with the title
1416 @code{Please select the switches to build the project}.
1417 Press @code{Apply}. This will create a project file named
1418 @file{sample.prj} in the directory that you had specified.
1420 @item @emph{Creating and saving the source file}
1422 After you create the new project, a GPS window will appear, which is
1423 partitioned into two main sections:
1427 A @emph{Workspace area}, initially greyed out, which you will use for
1428 creating and editing source files
1431 Directly below, a @emph{Messages area}, which initially displays a
1432 ``Welcome'' message.
1433 (If the Messages area is not visible, drag its border upward to expand it.)
1437 Select @code{File} on the menu bar, and then the @code{New} command.
1438 The Workspace area will become white, and you can now
1439 enter the source program explicitly.
1440 Type the following text
1442 @smallexample @c ada
1444 with Ada.Text_IO; use Ada.Text_IO;
1447 Put_Line("Hello from GPS!");
1453 Select @code{File}, then @code{Save As}, and enter the source file name
1455 The file will be saved in the same directory you specified as the
1456 location of the default project file.
1458 @item @emph{Updating the project file}
1460 You need to add the new source file to the project.
1462 the @code{Project} menu and then @code{Edit project properties}.
1463 Click the @code{Main files} tab on the left, and then the
1465 Choose @file{hello.adb} from the list, and press @code{Open}.
1466 The project settings window will reflect this action.
1469 @item @emph{Building and running the program}
1471 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1472 and select @file{hello.adb}.
1473 The Messages window will display the resulting invocations of @command{gcc},
1474 @command{gnatbind}, and @command{gnatlink}
1475 (reflecting the default switch settings from the
1476 project file that you created) and then a ``successful compilation/build''
1479 To run the program, choose the @code{Build} menu, then @code{Run}, and
1480 select @command{hello}.
1481 An @emph{Arguments Selection} window will appear.
1482 There are no command line arguments, so just click @code{OK}.
1484 The Messages window will now display the program's output (the string
1485 @code{Hello from GPS}), and at the bottom of the GPS window a status
1486 update is displayed (@code{Run: hello}).
1487 Close the GPS window (or select @code{File}, then @code{Exit}) to
1488 terminate this GPS session.
1491 @node Simple Debugging with GPS
1492 @subsection Simple Debugging with GPS
1494 This section illustrates basic debugging techniques (setting breakpoints,
1495 examining/modifying variables, single stepping).
1498 @item @emph{Opening a project}
1500 Start GPS and select @code{Open existing project}; browse to
1501 specify the project file @file{sample.prj} that you had created in the
1504 @item @emph{Creating a source file}
1506 Select @code{File}, then @code{New}, and type in the following program:
1508 @smallexample @c ada
1510 with Ada.Text_IO; use Ada.Text_IO;
1511 procedure Example is
1512 Line : String (1..80);
1515 Put_Line("Type a line of text at each prompt; an empty line to exit");
1519 Put_Line (Line (1..N) );
1527 Select @code{File}, then @code{Save as}, and enter the file name
1530 @item @emph{Updating the project file}
1532 Add @code{Example} as a new main unit for the project:
1535 Select @code{Project}, then @code{Edit Project Properties}.
1538 Select the @code{Main files} tab, click @code{Add}, then
1539 select the file @file{example.adb} from the list, and
1541 You will see the file name appear in the list of main units
1547 @item @emph{Building/running the executable}
1549 To build the executable
1550 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1552 Run the program to see its effect (in the Messages area).
1553 Each line that you enter is displayed; an empty line will
1554 cause the loop to exit and the program to terminate.
1556 @item @emph{Debugging the program}
1558 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1559 which are required for debugging, are on by default when you create
1561 Thus unless you intentionally remove these settings, you will be able
1562 to debug any program that you develop using GPS.
1565 @item @emph{Initializing}
1567 Select @code{Debug}, then @code{Initialize}, then @file{example}
1569 @item @emph{Setting a breakpoint}
1571 After performing the initialization step, you will observe a small
1572 icon to the right of each line number.
1573 This serves as a toggle for breakpoints; clicking the icon will
1574 set a breakpoint at the corresponding line (the icon will change to
1575 a red circle with an ``x''), and clicking it again
1576 will remove the breakpoint / reset the icon.
1578 For purposes of this example, set a breakpoint at line 10 (the
1579 statement @code{Put_Line@ (Line@ (1..N));}
1581 @item @emph{Starting program execution}
1583 Select @code{Debug}, then @code{Run}. When the
1584 @code{Program Arguments} window appears, click @code{OK}.
1585 A console window will appear; enter some line of text,
1586 e.g. @code{abcde}, at the prompt.
1587 The program will pause execution when it gets to the
1588 breakpoint, and the corresponding line is highlighted.
1590 @item @emph{Examining a variable}
1592 Move the mouse over one of the occurrences of the variable @code{N}.
1593 You will see the value (5) displayed, in ``tool tip'' fashion.
1594 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1595 You will see information about @code{N} appear in the @code{Debugger Data}
1596 pane, showing the value as 5.
1598 @item @emph{Assigning a new value to a variable}
1600 Right click on the @code{N} in the @code{Debugger Data} pane, and
1601 select @code{Set value of N}.
1602 When the input window appears, enter the value @code{4} and click
1604 This value does not automatically appear in the @code{Debugger Data}
1605 pane; to see it, right click again on the @code{N} in the
1606 @code{Debugger Data} pane and select @code{Update value}.
1607 The new value, 4, will appear in red.
1609 @item @emph{Single stepping}
1611 Select @code{Debug}, then @code{Next}.
1612 This will cause the next statement to be executed, in this case the
1613 call of @code{Put_Line} with the string slice.
1614 Notice in the console window that the displayed string is simply
1615 @code{abcd} and not @code{abcde} which you had entered.
1616 This is because the upper bound of the slice is now 4 rather than 5.
1618 @item @emph{Removing a breakpoint}
1620 Toggle the breakpoint icon at line 10.
1622 @item @emph{Resuming execution from a breakpoint}
1624 Select @code{Debug}, then @code{Continue}.
1625 The program will reach the next iteration of the loop, and
1626 wait for input after displaying the prompt.
1627 This time, just hit the @kbd{Enter} key.
1628 The value of @code{N} will be 0, and the program will terminate.
1629 The console window will disappear.
1633 @node Introduction to Glide and GVD
1634 @section Introduction to Glide and GVD
1638 This section describes the main features of Glide,
1639 a GNAT graphical IDE, and also shows how to use the basic commands in GVD,
1640 the GNU Visual Debugger.
1641 These tools may be present in addition to, or in place of, GPS on some
1643 Additional information on Glide and GVD may be found
1644 in the on-line help for these tools.
1647 * Building a New Program with Glide::
1648 * Simple Debugging with GVD::
1649 * Other Glide Features::
1652 @node Building a New Program with Glide
1653 @subsection Building a New Program with Glide
1655 The simplest way to invoke Glide is to enter @command{glide}
1656 at the command prompt. It will generally be useful to issue this
1657 as a background command, thus allowing you to continue using
1658 your command window for other purposes while Glide is running:
1665 Glide will start up with an initial screen displaying the top-level menu items
1666 as well as some other information. The menu selections are as follows
1668 @item @code{Buffers}
1679 For this introductory example, you will need to create a new Ada source file.
1680 First, select the @code{Files} menu. This will pop open a menu with around
1681 a dozen or so items. To create a file, select the @code{Open file...} choice.
1682 Depending on the platform, you may see a pop-up window where you can browse
1683 to an appropriate directory and then enter the file name, or else simply
1684 see a line at the bottom of the Glide window where you can likewise enter
1685 the file name. Note that in Glide, when you attempt to open a non-existent
1686 file, the effect is to create a file with that name. For this example enter
1687 @file{hello.adb} as the name of the file.
1689 A new buffer will now appear, occupying the entire Glide window,
1690 with the file name at the top. The menu selections are slightly different
1691 from the ones you saw on the opening screen; there is an @code{Entities} item,
1692 and in place of @code{Glide} there is now an @code{Ada} item. Glide uses
1693 the file extension to identify the source language, so @file{adb} indicates
1696 You will enter some of the source program lines explicitly,
1697 and use the syntax-oriented template mechanism to enter other lines.
1698 First, type the following text:
1700 with Ada.Text_IO; use Ada.Text_IO;
1706 Observe that Glide uses different colors to distinguish reserved words from
1707 identifiers. Also, after the @code{procedure Hello is} line, the cursor is
1708 automatically indented in anticipation of declarations. When you enter
1709 @code{begin}, Glide recognizes that there are no declarations and thus places
1710 @code{begin} flush left. But after the @code{begin} line the cursor is again
1711 indented, where the statement(s) will be placed.
1713 The main part of the program will be a @code{for} loop. Instead of entering
1714 the text explicitly, however, use a statement template. Select the @code{Ada}
1715 item on the top menu bar, move the mouse to the @code{Statements} item,
1716 and you will see a large selection of alternatives. Choose @code{for loop}.
1717 You will be prompted (at the bottom of the buffer) for a loop name;
1718 simply press the @key{Enter} key since a loop name is not needed.
1719 You should see the beginning of a @code{for} loop appear in the source
1720 program window. You will now be prompted for the name of the loop variable;
1721 enter a line with the identifier @code{ind} (lower case). Note that,
1722 by default, Glide capitalizes the name (you can override such behavior
1723 if you wish, although this is outside the scope of this introduction).
1724 Next, Glide prompts you for the loop range; enter a line containing
1725 @code{1..5} and you will see this also appear in the source program,
1726 together with the remaining elements of the @code{for} loop syntax.
1728 Next enter the statement (with an intentional error, a missing semicolon)
1729 that will form the body of the loop:
1731 Put_Line("Hello, World" & Integer'Image(I))
1735 Finally, type @code{end Hello;} as the last line in the program.
1736 Now save the file: choose the @code{File} menu item, and then the
1737 @code{Save buffer} selection. You will see a message at the bottom
1738 of the buffer confirming that the file has been saved.
1740 You are now ready to attempt to build the program. Select the @code{Ada}
1741 item from the top menu bar. Although we could choose simply to compile
1742 the file, we will instead attempt to do a build (which invokes
1743 @command{gnatmake}) since, if the compile is successful, we want to build
1744 an executable. Thus select @code{Ada build}. This will fail because of the
1745 compilation error, and you will notice that the Glide window has been split:
1746 the top window contains the source file, and the bottom window contains the
1747 output from the GNAT tools. Glide allows you to navigate from a compilation
1748 error to the source file position corresponding to the error: click the
1749 middle mouse button (or simultaneously press the left and right buttons,
1750 on a two-button mouse) on the diagnostic line in the tool window. The
1751 focus will shift to the source window, and the cursor will be positioned
1752 on the character at which the error was detected.
1754 Correct the error: type in a semicolon to terminate the statement.
1755 Although you can again save the file explicitly, you can also simply invoke
1756 @code{Ada} @result{} @code{Build} and you will be prompted to save the file.
1757 This time the build will succeed; the tool output window shows you the
1758 options that are supplied by default. The GNAT tools' output (e.g.
1759 object and ALI files, executable) will go in the directory from which
1762 To execute the program, choose @code{Ada} and then @code{Run}.
1763 You should see the program's output displayed in the bottom window:
1773 @node Simple Debugging with GVD
1774 @subsection Simple Debugging with GVD
1777 This section describes how to set breakpoints, examine/modify variables,
1778 and step through execution.
1780 In order to enable debugging, you need to pass the @option{-g} switch
1781 to both the compiler and to @command{gnatlink}. If you are using
1782 the command line, passing @option{-g} to @command{gnatmake} will have
1783 this effect. You can then launch GVD, e.g. on the @code{hello} program,
1784 by issuing the command:
1791 If you are using Glide, then @option{-g} is passed to the relevant tools
1792 by default when you do a build. Start the debugger by selecting the
1793 @code{Ada} menu item, and then @code{Debug}.
1795 GVD comes up in a multi-part window. One pane shows the names of files
1796 comprising your executable; another pane shows the source code of the current
1797 unit (initially your main subprogram), another pane shows the debugger output
1798 and user interactions, and the fourth pane (the data canvas at the top
1799 of the window) displays data objects that you have selected.
1801 To the left of the source file pane, you will notice green dots adjacent
1802 to some lines. These are lines for which object code exists and where
1803 breakpoints can thus be set. You set/reset a breakpoint by clicking
1804 the green dot. When a breakpoint is set, the dot is replaced by an @code{X}
1805 in a red circle. Clicking the circle toggles the breakpoint off,
1806 and the red circle is replaced by the green dot.
1808 For this example, set a breakpoint at the statement where @code{Put_Line}
1811 Start program execution by selecting the @code{Run} button on the top menu bar.
1812 (The @code{Start} button will also start your program, but it will
1813 cause program execution to break at the entry to your main subprogram.)
1814 Evidence of reaching the breakpoint will appear: the source file line will be
1815 highlighted, and the debugger interactions pane will display
1818 You can examine the values of variables in several ways. Move the mouse
1819 over an occurrence of @code{Ind} in the @code{for} loop, and you will see
1820 the value (now @code{1}) displayed. Alternatively, right-click on @code{Ind}
1821 and select @code{Display Ind}; a box showing the variable's name and value
1822 will appear in the data canvas.
1824 Although a loop index is a constant with respect to Ada semantics,
1825 you can change its value in the debugger. Right-click in the box
1826 for @code{Ind}, and select the @code{Set Value of Ind} item.
1827 Enter @code{2} as the new value, and press @command{OK}.
1828 The box for @code{Ind} shows the update.
1830 Press the @code{Step} button on the top menu bar; this will step through
1831 one line of program text (the invocation of @code{Put_Line}), and you can
1832 observe the effect of having modified @code{Ind} since the value displayed
1835 Remove the breakpoint, and resume execution by selecting the @code{Cont}
1836 button. You will see the remaining output lines displayed in the debugger
1837 interaction window, along with a message confirming normal program
1840 @node Other Glide Features
1841 @subsection Other Glide Features
1844 You may have observed that some of the menu selections contain abbreviations;
1845 e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu.
1846 These are @emph{shortcut keys} that you can use instead of selecting
1847 menu items. The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means
1848 @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead
1849 of selecting @code{Files} and then @code{Open file...}.
1851 To abort a Glide command, type @key{Ctrl-g}.
1853 If you want Glide to start with an existing source file, you can either
1854 launch Glide as above and then open the file via @code{Files} @result{}
1855 @code{Open file...}, or else simply pass the name of the source file
1856 on the command line:
1863 While you are using Glide, a number of @emph{buffers} exist.
1864 You create some explicitly; e.g., when you open/create a file.
1865 Others arise as an effect of the commands that you issue; e.g., the buffer
1866 containing the output of the tools invoked during a build. If a buffer
1867 is hidden, you can bring it into a visible window by first opening
1868 the @code{Buffers} menu and then selecting the desired entry.
1870 If a buffer occupies only part of the Glide screen and you want to expand it
1871 to fill the entire screen, then click in the buffer and then select
1872 @code{Files} @result{} @code{One Window}.
1874 If a window is occupied by one buffer and you want to split the window
1875 to bring up a second buffer, perform the following steps:
1877 @item Select @code{Files} @result{} @code{Split Window};
1878 this will produce two windows each of which holds the original buffer
1879 (these are not copies, but rather different views of the same buffer contents)
1881 @item With the focus in one of the windows,
1882 select the desired buffer from the @code{Buffers} menu
1886 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1889 @node The GNAT Compilation Model
1890 @chapter The GNAT Compilation Model
1891 @cindex GNAT compilation model
1892 @cindex Compilation model
1895 * Source Representation::
1896 * Foreign Language Representation::
1897 * File Naming Rules::
1898 * Using Other File Names::
1899 * Alternative File Naming Schemes::
1900 * Generating Object Files::
1901 * Source Dependencies::
1902 * The Ada Library Information Files::
1903 * Binding an Ada Program::
1904 * Mixed Language Programming::
1906 * Building Mixed Ada & C++ Programs::
1907 * Comparison between GNAT and C/C++ Compilation Models::
1909 * Comparison between GNAT and Conventional Ada Library Models::
1911 * Placement of temporary files::
1916 This chapter describes the compilation model used by GNAT. Although
1917 similar to that used by other languages, such as C and C++, this model
1918 is substantially different from the traditional Ada compilation models,
1919 which are based on a library. The model is initially described without
1920 reference to the library-based model. If you have not previously used an
1921 Ada compiler, you need only read the first part of this chapter. The
1922 last section describes and discusses the differences between the GNAT
1923 model and the traditional Ada compiler models. If you have used other
1924 Ada compilers, this section will help you to understand those
1925 differences, and the advantages of the GNAT model.
1927 @node Source Representation
1928 @section Source Representation
1932 Ada source programs are represented in standard text files, using
1933 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1934 7-bit ASCII set, plus additional characters used for
1935 representing foreign languages (@pxref{Foreign Language Representation}
1936 for support of non-USA character sets). The format effector characters
1937 are represented using their standard ASCII encodings, as follows:
1942 Vertical tab, @code{16#0B#}
1946 Horizontal tab, @code{16#09#}
1950 Carriage return, @code{16#0D#}
1954 Line feed, @code{16#0A#}
1958 Form feed, @code{16#0C#}
1962 Source files are in standard text file format. In addition, GNAT will
1963 recognize a wide variety of stream formats, in which the end of
1964 physical lines is marked by any of the following sequences:
1965 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1966 in accommodating files that are imported from other operating systems.
1968 @cindex End of source file
1969 @cindex Source file, end
1971 The end of a source file is normally represented by the physical end of
1972 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1973 recognized as signalling the end of the source file. Again, this is
1974 provided for compatibility with other operating systems where this
1975 code is used to represent the end of file.
1977 Each file contains a single Ada compilation unit, including any pragmas
1978 associated with the unit. For example, this means you must place a
1979 package declaration (a package @dfn{spec}) and the corresponding body in
1980 separate files. An Ada @dfn{compilation} (which is a sequence of
1981 compilation units) is represented using a sequence of files. Similarly,
1982 you will place each subunit or child unit in a separate file.
1984 @node Foreign Language Representation
1985 @section Foreign Language Representation
1988 GNAT supports the standard character sets defined in Ada 95 as well as
1989 several other non-standard character sets for use in localized versions
1990 of the compiler (@pxref{Character Set Control}).
1993 * Other 8-Bit Codes::
1994 * Wide Character Encodings::
2002 The basic character set is Latin-1. This character set is defined by ISO
2003 standard 8859, part 1. The lower half (character codes @code{16#00#}
2004 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half
2005 is used to represent additional characters. These include extended letters
2006 used by European languages, such as French accents, the vowels with umlauts
2007 used in German, and the extra letter A-ring used in Swedish.
2009 @findex Ada.Characters.Latin_1
2010 For a complete list of Latin-1 codes and their encodings, see the source
2011 file of library unit @code{Ada.Characters.Latin_1} in file
2012 @file{a-chlat1.ads}.
2013 You may use any of these extended characters freely in character or
2014 string literals. In addition, the extended characters that represent
2015 letters can be used in identifiers.
2017 @node Other 8-Bit Codes
2018 @subsection Other 8-Bit Codes
2021 GNAT also supports several other 8-bit coding schemes:
2024 @item ISO 8859-2 (Latin-2)
2027 Latin-2 letters allowed in identifiers, with uppercase and lowercase
2030 @item ISO 8859-3 (Latin-3)
2033 Latin-3 letters allowed in identifiers, with uppercase and lowercase
2036 @item ISO 8859-4 (Latin-4)
2039 Latin-4 letters allowed in identifiers, with uppercase and lowercase
2042 @item ISO 8859-5 (Cyrillic)
2045 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
2046 lowercase equivalence.
2048 @item ISO 8859-15 (Latin-9)
2051 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
2052 lowercase equivalence
2054 @item IBM PC (code page 437)
2055 @cindex code page 437
2056 This code page is the normal default for PCs in the U.S. It corresponds
2057 to the original IBM PC character set. This set has some, but not all, of
2058 the extended Latin-1 letters, but these letters do not have the same
2059 encoding as Latin-1. In this mode, these letters are allowed in
2060 identifiers with uppercase and lowercase equivalence.
2062 @item IBM PC (code page 850)
2063 @cindex code page 850
2064 This code page is a modification of 437 extended to include all the
2065 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
2066 mode, all these letters are allowed in identifiers with uppercase and
2067 lowercase equivalence.
2069 @item Full Upper 8-bit
2070 Any character in the range 80-FF allowed in identifiers, and all are
2071 considered distinct. In other words, there are no uppercase and lowercase
2072 equivalences in this range. This is useful in conjunction with
2073 certain encoding schemes used for some foreign character sets (e.g.
2074 the typical method of representing Chinese characters on the PC).
2077 No upper-half characters in the range 80-FF are allowed in identifiers.
2078 This gives Ada 83 compatibility for identifier names.
2082 For precise data on the encodings permitted, and the uppercase and lowercase
2083 equivalences that are recognized, see the file @file{csets.adb} in
2084 the GNAT compiler sources. You will need to obtain a full source release
2085 of GNAT to obtain this file.
2087 @node Wide Character Encodings
2088 @subsection Wide Character Encodings
2091 GNAT allows wide character codes to appear in character and string
2092 literals, and also optionally in identifiers, by means of the following
2093 possible encoding schemes:
2098 In this encoding, a wide character is represented by the following five
2106 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2107 characters (using uppercase letters) of the wide character code. For
2108 example, ESC A345 is used to represent the wide character with code
2110 This scheme is compatible with use of the full Wide_Character set.
2112 @item Upper-Half Coding
2113 @cindex Upper-Half Coding
2114 The wide character with encoding @code{16#abcd#} where the upper bit is on
2115 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
2116 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
2117 character, but is not required to be in the upper half. This method can
2118 be also used for shift-JIS or EUC, where the internal coding matches the
2121 @item Shift JIS Coding
2122 @cindex Shift JIS Coding
2123 A wide character is represented by a two-character sequence,
2125 @code{16#cd#}, with the restrictions described for upper-half encoding as
2126 described above. The internal character code is the corresponding JIS
2127 character according to the standard algorithm for Shift-JIS
2128 conversion. Only characters defined in the JIS code set table can be
2129 used with this encoding method.
2133 A wide character is represented by a two-character sequence
2135 @code{16#cd#}, with both characters being in the upper half. The internal
2136 character code is the corresponding JIS character according to the EUC
2137 encoding algorithm. Only characters defined in the JIS code set table
2138 can be used with this encoding method.
2141 A wide character is represented using
2142 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
2143 10646-1/Am.2. Depending on the character value, the representation
2144 is a one, two, or three byte sequence:
2149 16#0000#-16#007f#: 2#0xxxxxxx#
2150 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
2151 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
2156 where the xxx bits correspond to the left-padded bits of the
2157 16-bit character value. Note that all lower half ASCII characters
2158 are represented as ASCII bytes and all upper half characters and
2159 other wide characters are represented as sequences of upper-half
2160 (The full UTF-8 scheme allows for encoding 31-bit characters as
2161 6-byte sequences, but in this implementation, all UTF-8 sequences
2162 of four or more bytes length will be treated as illegal).
2163 @item Brackets Coding
2164 In this encoding, a wide character is represented by the following eight
2172 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2173 characters (using uppercase letters) of the wide character code. For
2174 example, [``A345''] is used to represent the wide character with code
2175 @code{16#A345#}. It is also possible (though not required) to use the
2176 Brackets coding for upper half characters. For example, the code
2177 @code{16#A3#} can be represented as @code{[``A3'']}.
2179 This scheme is compatible with use of the full Wide_Character set,
2180 and is also the method used for wide character encoding in the standard
2181 ACVC (Ada Compiler Validation Capability) test suite distributions.
2186 Note: Some of these coding schemes do not permit the full use of the
2187 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
2188 use of the upper half of the Latin-1 set.
2190 @node File Naming Rules
2191 @section File Naming Rules
2194 The default file name is determined by the name of the unit that the
2195 file contains. The name is formed by taking the full expanded name of
2196 the unit and replacing the separating dots with hyphens and using
2197 ^lowercase^uppercase^ for all letters.
2199 An exception arises if the file name generated by the above rules starts
2200 with one of the characters
2207 and the second character is a
2208 minus. In this case, the character ^tilde^dollar sign^ is used in place
2209 of the minus. The reason for this special rule is to avoid clashes with
2210 the standard names for child units of the packages System, Ada,
2211 Interfaces, and GNAT, which use the prefixes
2220 The file extension is @file{.ads} for a spec and
2221 @file{.adb} for a body. The following list shows some
2222 examples of these rules.
2229 @item arith_functions.ads
2230 Arith_Functions (package spec)
2231 @item arith_functions.adb
2232 Arith_Functions (package body)
2234 Func.Spec (child package spec)
2236 Func.Spec (child package body)
2238 Sub (subunit of Main)
2239 @item ^a~bad.adb^A$BAD.ADB^
2240 A.Bad (child package body)
2244 Following these rules can result in excessively long
2245 file names if corresponding
2246 unit names are long (for example, if child units or subunits are
2247 heavily nested). An option is available to shorten such long file names
2248 (called file name ``krunching''). This may be particularly useful when
2249 programs being developed with GNAT are to be used on operating systems
2250 with limited file name lengths. @xref{Using gnatkr}.
2252 Of course, no file shortening algorithm can guarantee uniqueness over
2253 all possible unit names; if file name krunching is used, it is your
2254 responsibility to ensure no name clashes occur. Alternatively you
2255 can specify the exact file names that you want used, as described
2256 in the next section. Finally, if your Ada programs are migrating from a
2257 compiler with a different naming convention, you can use the gnatchop
2258 utility to produce source files that follow the GNAT naming conventions.
2259 (For details @pxref{Renaming Files Using gnatchop}.)
2261 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2262 systems, case is not significant. So for example on @code{Windows XP}
2263 if the canonical name is @code{main-sub.adb}, you can use the file name
2264 @code{Main-Sub.adb} instead. However, case is significant for other
2265 operating systems, so for example, if you want to use other than
2266 canonically cased file names on a Unix system, you need to follow
2267 the procedures described in the next section.
2269 @node Using Other File Names
2270 @section Using Other File Names
2274 In the previous section, we have described the default rules used by
2275 GNAT to determine the file name in which a given unit resides. It is
2276 often convenient to follow these default rules, and if you follow them,
2277 the compiler knows without being explicitly told where to find all
2280 However, in some cases, particularly when a program is imported from
2281 another Ada compiler environment, it may be more convenient for the
2282 programmer to specify which file names contain which units. GNAT allows
2283 arbitrary file names to be used by means of the Source_File_Name pragma.
2284 The form of this pragma is as shown in the following examples:
2285 @cindex Source_File_Name pragma
2287 @smallexample @c ada
2289 pragma Source_File_Name (My_Utilities.Stacks,
2290 Spec_File_Name => "myutilst_a.ada");
2291 pragma Source_File_name (My_Utilities.Stacks,
2292 Body_File_Name => "myutilst.ada");
2297 As shown in this example, the first argument for the pragma is the unit
2298 name (in this example a child unit). The second argument has the form
2299 of a named association. The identifier
2300 indicates whether the file name is for a spec or a body;
2301 the file name itself is given by a string literal.
2303 The source file name pragma is a configuration pragma, which means that
2304 normally it will be placed in the @file{gnat.adc}
2305 file used to hold configuration
2306 pragmas that apply to a complete compilation environment.
2307 For more details on how the @file{gnat.adc} file is created and used
2308 see @ref{Handling of Configuration Pragmas}.
2309 @cindex @file{gnat.adc}
2312 GNAT allows completely arbitrary file names to be specified using the
2313 source file name pragma. However, if the file name specified has an
2314 extension other than @file{.ads} or @file{.adb} it is necessary to use
2315 a special syntax when compiling the file. The name in this case must be
2316 preceded by the special sequence @code{-x} followed by a space and the name
2317 of the language, here @code{ada}, as in:
2320 $ gcc -c -x ada peculiar_file_name.sim
2325 @command{gnatmake} handles non-standard file names in the usual manner (the
2326 non-standard file name for the main program is simply used as the
2327 argument to gnatmake). Note that if the extension is also non-standard,
2328 then it must be included in the gnatmake command, it may not be omitted.
2330 @node Alternative File Naming Schemes
2331 @section Alternative File Naming Schemes
2332 @cindex File naming schemes, alternative
2335 In the previous section, we described the use of the @code{Source_File_Name}
2336 pragma to allow arbitrary names to be assigned to individual source files.
2337 However, this approach requires one pragma for each file, and especially in
2338 large systems can result in very long @file{gnat.adc} files, and also create
2339 a maintenance problem.
2341 GNAT also provides a facility for specifying systematic file naming schemes
2342 other than the standard default naming scheme previously described. An
2343 alternative scheme for naming is specified by the use of
2344 @code{Source_File_Name} pragmas having the following format:
2345 @cindex Source_File_Name pragma
2347 @smallexample @c ada
2348 pragma Source_File_Name (
2349 Spec_File_Name => FILE_NAME_PATTERN
2350 [,Casing => CASING_SPEC]
2351 [,Dot_Replacement => STRING_LITERAL]);
2353 pragma Source_File_Name (
2354 Body_File_Name => FILE_NAME_PATTERN
2355 [,Casing => CASING_SPEC]
2356 [,Dot_Replacement => STRING_LITERAL]);
2358 pragma Source_File_Name (
2359 Subunit_File_Name => FILE_NAME_PATTERN
2360 [,Casing => CASING_SPEC]
2361 [,Dot_Replacement => STRING_LITERAL]);
2363 FILE_NAME_PATTERN ::= STRING_LITERAL
2364 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2368 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2369 It contains a single asterisk character, and the unit name is substituted
2370 systematically for this asterisk. The optional parameter
2371 @code{Casing} indicates
2372 whether the unit name is to be all upper-case letters, all lower-case letters,
2373 or mixed-case. If no
2374 @code{Casing} parameter is used, then the default is all
2375 ^lower-case^upper-case^.
2377 The optional @code{Dot_Replacement} string is used to replace any periods
2378 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2379 argument is used then separating dots appear unchanged in the resulting
2381 Although the above syntax indicates that the
2382 @code{Casing} argument must appear
2383 before the @code{Dot_Replacement} argument, but it
2384 is also permissible to write these arguments in the opposite order.
2386 As indicated, it is possible to specify different naming schemes for
2387 bodies, specs, and subunits. Quite often the rule for subunits is the
2388 same as the rule for bodies, in which case, there is no need to give
2389 a separate @code{Subunit_File_Name} rule, and in this case the
2390 @code{Body_File_name} rule is used for subunits as well.
2392 The separate rule for subunits can also be used to implement the rather
2393 unusual case of a compilation environment (e.g. a single directory) which
2394 contains a subunit and a child unit with the same unit name. Although
2395 both units cannot appear in the same partition, the Ada Reference Manual
2396 allows (but does not require) the possibility of the two units coexisting
2397 in the same environment.
2399 The file name translation works in the following steps:
2404 If there is a specific @code{Source_File_Name} pragma for the given unit,
2405 then this is always used, and any general pattern rules are ignored.
2408 If there is a pattern type @code{Source_File_Name} pragma that applies to
2409 the unit, then the resulting file name will be used if the file exists. If
2410 more than one pattern matches, the latest one will be tried first, and the
2411 first attempt resulting in a reference to a file that exists will be used.
2414 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2415 for which the corresponding file exists, then the standard GNAT default
2416 naming rules are used.
2421 As an example of the use of this mechanism, consider a commonly used scheme
2422 in which file names are all lower case, with separating periods copied
2423 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2424 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2427 @smallexample @c ada
2428 pragma Source_File_Name
2429 (Spec_File_Name => "*.1.ada");
2430 pragma Source_File_Name
2431 (Body_File_Name => "*.2.ada");
2435 The default GNAT scheme is actually implemented by providing the following
2436 default pragmas internally:
2438 @smallexample @c ada
2439 pragma Source_File_Name
2440 (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2441 pragma Source_File_Name
2442 (Body_File_Name => "*.adb", Dot_Replacement => "-");
2446 Our final example implements a scheme typically used with one of the
2447 Ada 83 compilers, where the separator character for subunits was ``__''
2448 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2449 by adding @file{.ADA}, and subunits by
2450 adding @file{.SEP}. All file names were
2451 upper case. Child units were not present of course since this was an
2452 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2453 the same double underscore separator for child units.
2455 @smallexample @c ada
2456 pragma Source_File_Name
2457 (Spec_File_Name => "*_.ADA",
2458 Dot_Replacement => "__",
2459 Casing = Uppercase);
2460 pragma Source_File_Name
2461 (Body_File_Name => "*.ADA",
2462 Dot_Replacement => "__",
2463 Casing = Uppercase);
2464 pragma Source_File_Name
2465 (Subunit_File_Name => "*.SEP",
2466 Dot_Replacement => "__",
2467 Casing = Uppercase);
2470 @node Generating Object Files
2471 @section Generating Object Files
2474 An Ada program consists of a set of source files, and the first step in
2475 compiling the program is to generate the corresponding object files.
2476 These are generated by compiling a subset of these source files.
2477 The files you need to compile are the following:
2481 If a package spec has no body, compile the package spec to produce the
2482 object file for the package.
2485 If a package has both a spec and a body, compile the body to produce the
2486 object file for the package. The source file for the package spec need
2487 not be compiled in this case because there is only one object file, which
2488 contains the code for both the spec and body of the package.
2491 For a subprogram, compile the subprogram body to produce the object file
2492 for the subprogram. The spec, if one is present, is as usual in a
2493 separate file, and need not be compiled.
2497 In the case of subunits, only compile the parent unit. A single object
2498 file is generated for the entire subunit tree, which includes all the
2502 Compile child units independently of their parent units
2503 (though, of course, the spec of all the ancestor unit must be present in order
2504 to compile a child unit).
2508 Compile generic units in the same manner as any other units. The object
2509 files in this case are small dummy files that contain at most the
2510 flag used for elaboration checking. This is because GNAT always handles generic
2511 instantiation by means of macro expansion. However, it is still necessary to
2512 compile generic units, for dependency checking and elaboration purposes.
2516 The preceding rules describe the set of files that must be compiled to
2517 generate the object files for a program. Each object file has the same
2518 name as the corresponding source file, except that the extension is
2521 You may wish to compile other files for the purpose of checking their
2522 syntactic and semantic correctness. For example, in the case where a
2523 package has a separate spec and body, you would not normally compile the
2524 spec. However, it is convenient in practice to compile the spec to make
2525 sure it is error-free before compiling clients of this spec, because such
2526 compilations will fail if there is an error in the spec.
2528 GNAT provides an option for compiling such files purely for the
2529 purposes of checking correctness; such compilations are not required as
2530 part of the process of building a program. To compile a file in this
2531 checking mode, use the @option{-gnatc} switch.
2533 @node Source Dependencies
2534 @section Source Dependencies
2537 A given object file clearly depends on the source file which is compiled
2538 to produce it. Here we are using @dfn{depends} in the sense of a typical
2539 @code{make} utility; in other words, an object file depends on a source
2540 file if changes to the source file require the object file to be
2542 In addition to this basic dependency, a given object may depend on
2543 additional source files as follows:
2547 If a file being compiled @code{with}'s a unit @var{X}, the object file
2548 depends on the file containing the spec of unit @var{X}. This includes
2549 files that are @code{with}'ed implicitly either because they are parents
2550 of @code{with}'ed child units or they are run-time units required by the
2551 language constructs used in a particular unit.
2554 If a file being compiled instantiates a library level generic unit, the
2555 object file depends on both the spec and body files for this generic
2559 If a file being compiled instantiates a generic unit defined within a
2560 package, the object file depends on the body file for the package as
2561 well as the spec file.
2565 @cindex @option{-gnatn} switch
2566 If a file being compiled contains a call to a subprogram for which
2567 pragma @code{Inline} applies and inlining is activated with the
2568 @option{-gnatn} switch, the object file depends on the file containing the
2569 body of this subprogram as well as on the file containing the spec. Note
2570 that for inlining to actually occur as a result of the use of this switch,
2571 it is necessary to compile in optimizing mode.
2573 @cindex @option{-gnatN} switch
2574 The use of @option{-gnatN} activates a more extensive inlining optimization
2575 that is performed by the front end of the compiler. This inlining does
2576 not require that the code generation be optimized. Like @option{-gnatn},
2577 the use of this switch generates additional dependencies.
2579 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
2580 to specify both options.
2583 If an object file O depends on the proper body of a subunit through inlining
2584 or instantiation, it depends on the parent unit of the subunit. This means that
2585 any modification of the parent unit or one of its subunits affects the
2589 The object file for a parent unit depends on all its subunit body files.
2592 The previous two rules meant that for purposes of computing dependencies and
2593 recompilation, a body and all its subunits are treated as an indivisible whole.
2596 These rules are applied transitively: if unit @code{A} @code{with}'s
2597 unit @code{B}, whose elaboration calls an inlined procedure in package
2598 @code{C}, the object file for unit @code{A} will depend on the body of
2599 @code{C}, in file @file{c.adb}.
2601 The set of dependent files described by these rules includes all the
2602 files on which the unit is semantically dependent, as described in the
2603 Ada 95 Language Reference Manual. However, it is a superset of what the
2604 ARM describes, because it includes generic, inline, and subunit dependencies.
2606 An object file must be recreated by recompiling the corresponding source
2607 file if any of the source files on which it depends are modified. For
2608 example, if the @code{make} utility is used to control compilation,
2609 the rule for an Ada object file must mention all the source files on
2610 which the object file depends, according to the above definition.
2611 The determination of the necessary
2612 recompilations is done automatically when one uses @command{gnatmake}.
2615 @node The Ada Library Information Files
2616 @section The Ada Library Information Files
2617 @cindex Ada Library Information files
2618 @cindex @file{ALI} files
2621 Each compilation actually generates two output files. The first of these
2622 is the normal object file that has a @file{.o} extension. The second is a
2623 text file containing full dependency information. It has the same
2624 name as the source file, but an @file{.ali} extension.
2625 This file is known as the Ada Library Information (@file{ALI}) file.
2626 The following information is contained in the @file{ALI} file.
2630 Version information (indicates which version of GNAT was used to compile
2631 the unit(s) in question)
2634 Main program information (including priority and time slice settings,
2635 as well as the wide character encoding used during compilation).
2638 List of arguments used in the @command{gcc} command for the compilation
2641 Attributes of the unit, including configuration pragmas used, an indication
2642 of whether the compilation was successful, exception model used etc.
2645 A list of relevant restrictions applying to the unit (used for consistency)
2649 Categorization information (e.g. use of pragma @code{Pure}).
2652 Information on all @code{with}'ed units, including presence of
2653 @code{Elaborate} or @code{Elaborate_All} pragmas.
2656 Information from any @code{Linker_Options} pragmas used in the unit
2659 Information on the use of @code{Body_Version} or @code{Version}
2660 attributes in the unit.
2663 Dependency information. This is a list of files, together with
2664 time stamp and checksum information. These are files on which
2665 the unit depends in the sense that recompilation is required
2666 if any of these units are modified.
2669 Cross-reference data. Contains information on all entities referenced
2670 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2671 provide cross-reference information.
2676 For a full detailed description of the format of the @file{ALI} file,
2677 see the source of the body of unit @code{Lib.Writ}, contained in file
2678 @file{lib-writ.adb} in the GNAT compiler sources.
2680 @node Binding an Ada Program
2681 @section Binding an Ada Program
2684 When using languages such as C and C++, once the source files have been
2685 compiled the only remaining step in building an executable program
2686 is linking the object modules together. This means that it is possible to
2687 link an inconsistent version of a program, in which two units have
2688 included different versions of the same header.
2690 The rules of Ada do not permit such an inconsistent program to be built.
2691 For example, if two clients have different versions of the same package,
2692 it is illegal to build a program containing these two clients.
2693 These rules are enforced by the GNAT binder, which also determines an
2694 elaboration order consistent with the Ada rules.
2696 The GNAT binder is run after all the object files for a program have
2697 been created. It is given the name of the main program unit, and from
2698 this it determines the set of units required by the program, by reading the
2699 corresponding ALI files. It generates error messages if the program is
2700 inconsistent or if no valid order of elaboration exists.
2702 If no errors are detected, the binder produces a main program, in Ada by
2703 default, that contains calls to the elaboration procedures of those
2704 compilation unit that require them, followed by
2705 a call to the main program. This Ada program is compiled to generate the
2706 object file for the main program. The name of
2707 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2708 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2711 Finally, the linker is used to build the resulting executable program,
2712 using the object from the main program from the bind step as well as the
2713 object files for the Ada units of the program.
2715 @node Mixed Language Programming
2716 @section Mixed Language Programming
2717 @cindex Mixed Language Programming
2720 This section describes how to develop a mixed-language program,
2721 specifically one that comprises units in both Ada and C.
2724 * Interfacing to C::
2725 * Calling Conventions::
2728 @node Interfacing to C
2729 @subsection Interfacing to C
2731 Interfacing Ada with a foreign language such as C involves using
2732 compiler directives to import and/or export entity definitions in each
2733 language---using @code{extern} statements in C, for instance, and the
2734 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada. For
2735 a full treatment of these topics, read Appendix B, section 1 of the Ada
2736 95 Language Reference Manual.
2738 There are two ways to build a program using GNAT that contains some Ada
2739 sources and some foreign language sources, depending on whether or not
2740 the main subprogram is written in Ada. Here is a source example with
2741 the main subprogram in Ada:
2747 void print_num (int num)
2749 printf ("num is %d.\n", num);
2755 /* num_from_Ada is declared in my_main.adb */
2756 extern int num_from_Ada;
2760 return num_from_Ada;
2764 @smallexample @c ada
2766 procedure My_Main is
2768 -- Declare then export an Integer entity called num_from_Ada
2769 My_Num : Integer := 10;
2770 pragma Export (C, My_Num, "num_from_Ada");
2772 -- Declare an Ada function spec for Get_Num, then use
2773 -- C function get_num for the implementation.
2774 function Get_Num return Integer;
2775 pragma Import (C, Get_Num, "get_num");
2777 -- Declare an Ada procedure spec for Print_Num, then use
2778 -- C function print_num for the implementation.
2779 procedure Print_Num (Num : Integer);
2780 pragma Import (C, Print_Num, "print_num");
2783 Print_Num (Get_Num);
2789 To build this example, first compile the foreign language files to
2790 generate object files:
2792 ^gcc -c file1.c^gcc -c FILE1.C^
2793 ^gcc -c file2.c^gcc -c FILE2.C^
2797 Then, compile the Ada units to produce a set of object files and ALI
2800 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2804 Run the Ada binder on the Ada main program:
2806 gnatbind my_main.ali
2810 Link the Ada main program, the Ada objects and the other language
2813 gnatlink my_main.ali file1.o file2.o
2817 The last three steps can be grouped in a single command:
2819 gnatmake my_main.adb -largs file1.o file2.o
2822 @cindex Binder output file
2824 If the main program is in a language other than Ada, then you may have
2825 more than one entry point into the Ada subsystem. You must use a special
2826 binder option to generate callable routines that initialize and
2827 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2828 Calls to the initialization and finalization routines must be inserted
2829 in the main program, or some other appropriate point in the code. The
2830 call to initialize the Ada units must occur before the first Ada
2831 subprogram is called, and the call to finalize the Ada units must occur
2832 after the last Ada subprogram returns. The binder will place the
2833 initialization and finalization subprograms into the
2834 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2835 sources. To illustrate, we have the following example:
2839 extern void adainit (void);
2840 extern void adafinal (void);
2841 extern int add (int, int);
2842 extern int sub (int, int);
2844 int main (int argc, char *argv[])
2850 /* Should print "21 + 7 = 28" */
2851 printf ("%d + %d = %d\n", a, b, add (a, b));
2852 /* Should print "21 - 7 = 14" */
2853 printf ("%d - %d = %d\n", a, b, sub (a, b));
2859 @smallexample @c ada
2862 function Add (A, B : Integer) return Integer;
2863 pragma Export (C, Add, "add");
2867 package body Unit1 is
2868 function Add (A, B : Integer) return Integer is
2876 function Sub (A, B : Integer) return Integer;
2877 pragma Export (C, Sub, "sub");
2881 package body Unit2 is
2882 function Sub (A, B : Integer) return Integer is
2891 The build procedure for this application is similar to the last
2892 example's. First, compile the foreign language files to generate object
2895 ^gcc -c main.c^gcc -c main.c^
2899 Next, compile the Ada units to produce a set of object files and ALI
2902 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2903 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2907 Run the Ada binder on every generated ALI file. Make sure to use the
2908 @option{-n} option to specify a foreign main program:
2910 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2914 Link the Ada main program, the Ada objects and the foreign language
2915 objects. You need only list the last ALI file here:
2917 gnatlink unit2.ali main.o -o exec_file
2920 This procedure yields a binary executable called @file{exec_file}.
2923 @node Calling Conventions
2924 @subsection Calling Conventions
2925 @cindex Foreign Languages
2926 @cindex Calling Conventions
2927 GNAT follows standard calling sequence conventions and will thus interface
2928 to any other language that also follows these conventions. The following
2929 Convention identifiers are recognized by GNAT:
2932 @cindex Interfacing to Ada
2933 @cindex Other Ada compilers
2934 @cindex Convention Ada
2936 This indicates that the standard Ada calling sequence will be
2937 used and all Ada data items may be passed without any limitations in the
2938 case where GNAT is used to generate both the caller and callee. It is also
2939 possible to mix GNAT generated code and code generated by another Ada
2940 compiler. In this case, the data types should be restricted to simple
2941 cases, including primitive types. Whether complex data types can be passed
2942 depends on the situation. Probably it is safe to pass simple arrays, such
2943 as arrays of integers or floats. Records may or may not work, depending
2944 on whether both compilers lay them out identically. Complex structures
2945 involving variant records, access parameters, tasks, or protected types,
2946 are unlikely to be able to be passed.
2948 Note that in the case of GNAT running
2949 on a platform that supports HP Ada 83, a higher degree of compatibility
2950 can be guaranteed, and in particular records are layed out in an identical
2951 manner in the two compilers. Note also that if output from two different
2952 compilers is mixed, the program is responsible for dealing with elaboration
2953 issues. Probably the safest approach is to write the main program in the
2954 version of Ada other than GNAT, so that it takes care of its own elaboration
2955 requirements, and then call the GNAT-generated adainit procedure to ensure
2956 elaboration of the GNAT components. Consult the documentation of the other
2957 Ada compiler for further details on elaboration.
2959 However, it is not possible to mix the tasking run time of GNAT and
2960 HP Ada 83, All the tasking operations must either be entirely within
2961 GNAT compiled sections of the program, or entirely within HP Ada 83
2962 compiled sections of the program.
2964 @cindex Interfacing to Assembly
2965 @cindex Convention Assembler
2967 Specifies assembler as the convention. In practice this has the
2968 same effect as convention Ada (but is not equivalent in the sense of being
2969 considered the same convention).
2971 @cindex Convention Asm
2974 Equivalent to Assembler.
2976 @cindex Interfacing to COBOL
2977 @cindex Convention COBOL
2980 Data will be passed according to the conventions described
2981 in section B.4 of the Ada 95 Reference Manual.
2984 @cindex Interfacing to C
2985 @cindex Convention C
2987 Data will be passed according to the conventions described
2988 in section B.3 of the Ada 95 Reference Manual.
2990 A note on interfacing to a C ``varargs'' function:
2991 @findex C varargs function
2992 @cindex Interfacing to C varargs function
2993 @cindex varargs function interfaces
2997 In C, @code{varargs} allows a function to take a variable number of
2998 arguments. There is no direct equivalent in this to Ada. One
2999 approach that can be used is to create a C wrapper for each
3000 different profile and then interface to this C wrapper. For
3001 example, to print an @code{int} value using @code{printf},
3002 create a C function @code{printfi} that takes two arguments, a
3003 pointer to a string and an int, and calls @code{printf}.
3004 Then in the Ada program, use pragma @code{Import} to
3005 interface to @code{printfi}.
3008 It may work on some platforms to directly interface to
3009 a @code{varargs} function by providing a specific Ada profile
3010 for a particular call. However, this does not work on
3011 all platforms, since there is no guarantee that the
3012 calling sequence for a two argument normal C function
3013 is the same as for calling a @code{varargs} C function with
3014 the same two arguments.
3017 @cindex Convention Default
3022 @cindex Convention External
3029 @cindex Interfacing to C++
3030 @cindex Convention C++
3032 This stands for C++. For most purposes this is identical to C.
3033 See the separate description of the specialized GNAT pragmas relating to
3034 C++ interfacing for further details.
3038 @cindex Interfacing to Fortran
3039 @cindex Convention Fortran
3041 Data will be passed according to the conventions described
3042 in section B.5 of the Ada 95 Reference Manual.
3045 This applies to an intrinsic operation, as defined in the Ada 95
3046 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
3047 this means that the body of the subprogram is provided by the compiler itself,
3048 usually by means of an efficient code sequence, and that the user does not
3049 supply an explicit body for it. In an application program, the pragma can
3050 only be applied to the following two sets of names, which the GNAT compiler
3055 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
3056 Shift_Right_Arithmetic. The corresponding subprogram declaration must have
3057 two formal parameters. The
3058 first one must be a signed integer type or a modular type with a binary
3059 modulus, and the second parameter must be of type Natural.
3060 The return type must be the same as the type of the first argument. The size
3061 of this type can only be 8, 16, 32, or 64.
3062 @item binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
3063 The corresponding operator declaration must have parameters and result type
3064 that have the same root numeric type (for example, all three are long_float
3065 types). This simplifies the definition of operations that use type checking
3066 to perform dimensional checks:
3068 @smallexample @c ada
3069 type Distance is new Long_Float;
3070 type Time is new Long_Float;
3071 type Velocity is new Long_Float;
3072 function "/" (D : Distance; T : Time)
3074 pragma Import (Intrinsic, "/");
3078 This common idiom is often programmed with a generic definition and an
3079 explicit body. The pragma makes it simpler to introduce such declarations.
3080 It incurs no overhead in compilation time or code size, because it is
3081 implemented as a single machine instruction.
3087 @cindex Convention Stdcall
3089 This is relevant only to Windows XP/2000/NT/95 implementations of GNAT,
3090 and specifies that the @code{Stdcall} calling sequence will be used,
3091 as defined by the NT API. Nevertheless, to ease building
3092 cross-platform bindings this convention will be handled as a @code{C} calling
3093 convention on non Windows platforms.
3096 @cindex Convention DLL
3098 This is equivalent to @code{Stdcall}.
3101 @cindex Convention Win32
3103 This is equivalent to @code{Stdcall}.
3107 @cindex Convention Stubbed
3109 This is a special convention that indicates that the compiler
3110 should provide a stub body that raises @code{Program_Error}.
3114 GNAT additionally provides a useful pragma @code{Convention_Identifier}
3115 that can be used to parametrize conventions and allow additional synonyms
3116 to be specified. For example if you have legacy code in which the convention
3117 identifier Fortran77 was used for Fortran, you can use the configuration
3120 @smallexample @c ada
3121 pragma Convention_Identifier (Fortran77, Fortran);
3125 And from now on the identifier Fortran77 may be used as a convention
3126 identifier (for example in an @code{Import} pragma) with the same
3130 @node Building Mixed Ada & C++ Programs
3131 @section Building Mixed Ada and C++ Programs
3134 A programmer inexperienced with mixed-language development may find that
3135 building an application containing both Ada and C++ code can be a
3136 challenge. As a matter of fact, interfacing with C++ has not been
3137 standardized in the Ada 95 Reference Manual due to the immaturity of --
3138 and lack of standards for -- C++ at the time. This section gives a few
3139 hints that should make this task easier. The first section addresses
3140 the differences regarding interfacing with C. The second section
3141 looks into the delicate problem of linking the complete application from
3142 its Ada and C++ parts. The last section gives some hints on how the GNAT
3143 run time can be adapted in order to allow inter-language dispatching
3144 with a new C++ compiler.
3147 * Interfacing to C++::
3148 * Linking a Mixed C++ & Ada Program::
3149 * A Simple Example::
3150 * Adapting the Run Time to a New C++ Compiler::
3153 @node Interfacing to C++
3154 @subsection Interfacing to C++
3157 GNAT supports interfacing with C++ compilers generating code that is
3158 compatible with the standard Application Binary Interface of the given
3162 Interfacing can be done at 3 levels: simple data, subprograms, and
3163 classes. In the first two cases, GNAT offers a specific @var{Convention
3164 CPP} that behaves exactly like @var{Convention C}. Usually, C++ mangles
3165 the names of subprograms, and currently, GNAT does not provide any help
3166 to solve the demangling problem. This problem can be addressed in two
3170 by modifying the C++ code in order to force a C convention using
3171 the @code{extern "C"} syntax.
3174 by figuring out the mangled name and use it as the Link_Name argument of
3179 Interfacing at the class level can be achieved by using the GNAT specific
3180 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
3181 Reference Manual for additional information.
3183 @node Linking a Mixed C++ & Ada Program
3184 @subsection Linking a Mixed C++ & Ada Program
3187 Usually the linker of the C++ development system must be used to link
3188 mixed applications because most C++ systems will resolve elaboration
3189 issues (such as calling constructors on global class instances)
3190 transparently during the link phase. GNAT has been adapted to ease the
3191 use of a foreign linker for the last phase. Three cases can be
3196 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3197 The C++ linker can simply be called by using the C++ specific driver
3198 called @code{c++}. Note that this setup is not very common because it
3199 may involve recompiling the whole GCC tree from sources, which makes it
3200 harder to upgrade the compilation system for one language without
3201 destabilizing the other.
3206 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
3210 Using GNAT and G++ from two different GCC installations: If both
3211 compilers are on the PATH, the previous method may be used. It is
3212 important to note that environment variables such as C_INCLUDE_PATH,
3213 GCC_EXEC_PREFIX, BINUTILS_ROOT, and GCC_ROOT will affect both compilers
3214 at the same time and may make one of the two compilers operate
3215 improperly if set during invocation of the wrong compiler. It is also
3216 very important that the linker uses the proper @file{libgcc.a} GCC
3217 library -- that is, the one from the C++ compiler installation. The
3218 implicit link command as suggested in the gnatmake command from the
3219 former example can be replaced by an explicit link command with the
3220 full-verbosity option in order to verify which library is used:
3223 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3225 If there is a problem due to interfering environment variables, it can
3226 be worked around by using an intermediate script. The following example
3227 shows the proper script to use when GNAT has not been installed at its
3228 default location and g++ has been installed at its default location:
3236 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3240 Using a non-GNU C++ compiler: The commands previously described can be
3241 used to insure that the C++ linker is used. Nonetheless, you need to add
3242 a few more parameters to the link command line, depending on the exception
3245 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3246 to the libgcc libraries are required:
3251 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3252 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3255 Where CC is the name of the non-GNU C++ compiler.
3257 If the @code{zero cost} exception mechanism is used, and the platform
3258 supports automatic registration of exception tables (e.g. Solaris or IRIX),
3259 paths to more objects are required:
3264 CC `gcc -print-file-name=crtbegin.o` $* \
3265 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3266 `gcc -print-file-name=crtend.o`
3267 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3270 If the @code{zero cost} exception mechanism is used, and the platform
3271 doesn't support automatic registration of exception tables (e.g. HP-UX,
3272 Tru64 or AIX), the simple approach described above will not work and
3273 a pre-linking phase using GNAT will be necessary.
3277 @node A Simple Example
3278 @subsection A Simple Example
3280 The following example, provided as part of the GNAT examples, shows how
3281 to achieve procedural interfacing between Ada and C++ in both
3282 directions. The C++ class A has two methods. The first method is exported
3283 to Ada by the means of an extern C wrapper function. The second method
3284 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3285 a limited record with a layout comparable to the C++ class. The Ada
3286 subprogram, in turn, calls the C++ method. So, starting from the C++
3287 main program, the process passes back and forth between the two
3291 Here are the compilation commands:
3293 $ gnatmake -c simple_cpp_interface
3296 $ gnatbind -n simple_cpp_interface
3297 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3298 -lstdc++ ex7.o cpp_main.o
3302 Here are the corresponding sources:
3310 void adainit (void);
3311 void adafinal (void);
3312 void method1 (A *t);
3334 class A : public Origin @{
3336 void method1 (void);
3337 void method2 (int v);
3347 extern "C" @{ void ada_method2 (A *t, int v);@}
3349 void A::method1 (void)
3352 printf ("in A::method1, a_value = %d \n",a_value);
3356 void A::method2 (int v)
3358 ada_method2 (this, v);
3359 printf ("in A::method2, a_value = %d \n",a_value);
3366 printf ("in A::A, a_value = %d \n",a_value);
3370 @b{package} @b{body} Simple_Cpp_Interface @b{is}
3372 @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
3376 @b{end} Ada_Method2;
3378 @b{end} Simple_Cpp_Interface;
3380 @b{package} Simple_Cpp_Interface @b{is}
3381 @b{type} A @b{is} @b{limited}
3386 @b{pragma} Convention (C, A);
3388 @b{procedure} Method1 (This : @b{in} @b{out} A);
3389 @b{pragma} Import (C, Method1);
3391 @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
3392 @b{pragma} Export (C, Ada_Method2);
3394 @b{end} Simple_Cpp_Interface;
3397 @node Adapting the Run Time to a New C++ Compiler
3398 @subsection Adapting the Run Time to a New C++ Compiler
3400 GNAT offers the capability to derive Ada 95 tagged types directly from
3401 preexisting C++ classes and . See ``Interfacing with C++'' in the
3402 @cite{GNAT Reference Manual}. The mechanism used by GNAT for achieving
3404 has been made user configurable through a GNAT library unit
3405 @code{Interfaces.CPP}. The default version of this file is adapted to
3406 the GNU C++ compiler. Internal knowledge of the virtual
3407 table layout used by the new C++ compiler is needed to configure
3408 properly this unit. The Interface of this unit is known by the compiler
3409 and cannot be changed except for the value of the constants defining the
3410 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
3411 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
3412 of this unit for more details.
3414 @node Comparison between GNAT and C/C++ Compilation Models
3415 @section Comparison between GNAT and C/C++ Compilation Models
3418 The GNAT model of compilation is close to the C and C++ models. You can
3419 think of Ada specs as corresponding to header files in C. As in C, you
3420 don't need to compile specs; they are compiled when they are used. The
3421 Ada @code{with} is similar in effect to the @code{#include} of a C
3424 One notable difference is that, in Ada, you may compile specs separately
3425 to check them for semantic and syntactic accuracy. This is not always
3426 possible with C headers because they are fragments of programs that have
3427 less specific syntactic or semantic rules.
3429 The other major difference is the requirement for running the binder,
3430 which performs two important functions. First, it checks for
3431 consistency. In C or C++, the only defense against assembling
3432 inconsistent programs lies outside the compiler, in a makefile, for
3433 example. The binder satisfies the Ada requirement that it be impossible
3434 to construct an inconsistent program when the compiler is used in normal
3437 @cindex Elaboration order control
3438 The other important function of the binder is to deal with elaboration
3439 issues. There are also elaboration issues in C++ that are handled
3440 automatically. This automatic handling has the advantage of being
3441 simpler to use, but the C++ programmer has no control over elaboration.
3442 Where @code{gnatbind} might complain there was no valid order of
3443 elaboration, a C++ compiler would simply construct a program that
3444 malfunctioned at run time.
3447 @node Comparison between GNAT and Conventional Ada Library Models
3448 @section Comparison between GNAT and Conventional Ada Library Models
3451 This section is intended for Ada programmers who have
3452 used an Ada compiler implementing the traditional Ada library
3453 model, as described in the Ada 95 Language Reference Manual.
3455 @cindex GNAT library
3456 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3457 source files themselves acts as the library. Compiling Ada programs does
3458 not generate any centralized information, but rather an object file and
3459 a ALI file, which are of interest only to the binder and linker.
3460 In a traditional system, the compiler reads information not only from
3461 the source file being compiled, but also from the centralized library.
3462 This means that the effect of a compilation depends on what has been
3463 previously compiled. In particular:
3467 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3468 to the version of the unit most recently compiled into the library.
3471 Inlining is effective only if the necessary body has already been
3472 compiled into the library.
3475 Compiling a unit may obsolete other units in the library.
3479 In GNAT, compiling one unit never affects the compilation of any other
3480 units because the compiler reads only source files. Only changes to source
3481 files can affect the results of a compilation. In particular:
3485 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3486 to the source version of the unit that is currently accessible to the
3491 Inlining requires the appropriate source files for the package or
3492 subprogram bodies to be available to the compiler. Inlining is always
3493 effective, independent of the order in which units are complied.
3496 Compiling a unit never affects any other compilations. The editing of
3497 sources may cause previous compilations to be out of date if they
3498 depended on the source file being modified.
3502 The most important result of these differences is that order of compilation
3503 is never significant in GNAT. There is no situation in which one is
3504 required to do one compilation before another. What shows up as order of
3505 compilation requirements in the traditional Ada library becomes, in
3506 GNAT, simple source dependencies; in other words, there is only a set
3507 of rules saying what source files must be present when a file is
3511 @node Placement of temporary files
3512 @section Placement of temporary files
3513 @cindex Temporary files (user control over placement)
3516 GNAT creates temporary files in the directory designated by the environment
3517 variable @env{TMPDIR}.
3518 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3519 for detailed information on how environment variables are resolved.
3520 For most users the easiest way to make use of this feature is to simply
3521 define @env{TMPDIR} as a job level logical name).
3522 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3523 for compiler temporary files, then you can include something like the
3524 following command in your @file{LOGIN.COM} file:
3527 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3531 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3532 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3533 designated by @env{TEMP}.
3534 If none of these environment variables are defined then GNAT uses the
3535 directory designated by the logical name @code{SYS$SCRATCH:}
3536 (by default the user's home directory). If all else fails
3537 GNAT uses the current directory for temporary files.
3540 @c *************************
3541 @node Compiling Using gcc
3542 @chapter Compiling Using @command{gcc}
3545 This chapter discusses how to compile Ada programs using the @command{gcc}
3546 command. It also describes the set of switches
3547 that can be used to control the behavior of the compiler.
3549 * Compiling Programs::
3550 * Switches for gcc::
3551 * Search Paths and the Run-Time Library (RTL)::
3552 * Order of Compilation Issues::
3556 @node Compiling Programs
3557 @section Compiling Programs
3560 The first step in creating an executable program is to compile the units
3561 of the program using the @command{gcc} command. You must compile the
3566 the body file (@file{.adb}) for a library level subprogram or generic
3570 the spec file (@file{.ads}) for a library level package or generic
3571 package that has no body
3574 the body file (@file{.adb}) for a library level package
3575 or generic package that has a body
3580 You need @emph{not} compile the following files
3585 the spec of a library unit which has a body
3592 because they are compiled as part of compiling related units. GNAT
3594 when the corresponding body is compiled, and subunits when the parent is
3597 @cindex cannot generate code
3598 If you attempt to compile any of these files, you will get one of the
3599 following error messages (where fff is the name of the file you compiled):
3602 cannot generate code for file @var{fff} (package spec)
3603 to check package spec, use -gnatc
3605 cannot generate code for file @var{fff} (missing subunits)
3606 to check parent unit, use -gnatc
3608 cannot generate code for file @var{fff} (subprogram spec)
3609 to check subprogram spec, use -gnatc
3611 cannot generate code for file @var{fff} (subunit)
3612 to check subunit, use -gnatc
3616 As indicated by the above error messages, if you want to submit
3617 one of these files to the compiler to check for correct semantics
3618 without generating code, then use the @option{-gnatc} switch.
3620 The basic command for compiling a file containing an Ada unit is
3623 $ gcc -c [@var{switches}] @file{file name}
3627 where @var{file name} is the name of the Ada file (usually
3629 @file{.ads} for a spec or @file{.adb} for a body).
3632 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3634 The result of a successful compilation is an object file, which has the
3635 same name as the source file but an extension of @file{.o} and an Ada
3636 Library Information (ALI) file, which also has the same name as the
3637 source file, but with @file{.ali} as the extension. GNAT creates these
3638 two output files in the current directory, but you may specify a source
3639 file in any directory using an absolute or relative path specification
3640 containing the directory information.
3643 @command{gcc} is actually a driver program that looks at the extensions of
3644 the file arguments and loads the appropriate compiler. For example, the
3645 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3646 These programs are in directories known to the driver program (in some
3647 configurations via environment variables you set), but need not be in
3648 your path. The @command{gcc} driver also calls the assembler and any other
3649 utilities needed to complete the generation of the required object
3652 It is possible to supply several file names on the same @command{gcc}
3653 command. This causes @command{gcc} to call the appropriate compiler for
3654 each file. For example, the following command lists three separate
3655 files to be compiled:
3658 $ gcc -c x.adb y.adb z.c
3662 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3663 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3664 The compiler generates three object files @file{x.o}, @file{y.o} and
3665 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3666 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3669 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3672 @node Switches for gcc
3673 @section Switches for @command{gcc}
3676 The @command{gcc} command accepts switches that control the
3677 compilation process. These switches are fully described in this section.
3678 First we briefly list all the switches, in alphabetical order, then we
3679 describe the switches in more detail in functionally grouped sections.
3681 More switches exist for GCC than those documented here, especially
3682 for specific targets. However, their use is not recommended as
3683 they may change code generation in ways that are incompatible with
3684 the Ada run-time library, or can cause inconsistencies between
3688 * Output and Error Message Control::
3689 * Warning Message Control::
3690 * Debugging and Assertion Control::
3691 * Validity Checking::
3694 * Using gcc for Syntax Checking::
3695 * Using gcc for Semantic Checking::
3696 * Compiling Different Versions of Ada::
3697 * Character Set Control::
3698 * File Naming Control::
3699 * Subprogram Inlining Control::
3700 * Auxiliary Output Control::
3701 * Debugging Control::
3702 * Exception Handling Control::
3703 * Units to Sources Mapping Files::
3704 * Integrated Preprocessing::
3705 * Code Generation Control::
3714 @cindex @option{-b} (@command{gcc})
3715 @item -b @var{target}
3716 Compile your program to run on @var{target}, which is the name of a
3717 system configuration. You must have a GNAT cross-compiler built if
3718 @var{target} is not the same as your host system.
3721 @cindex @option{-B} (@command{gcc})
3722 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3723 from @var{dir} instead of the default location. Only use this switch
3724 when multiple versions of the GNAT compiler are available. See the
3725 @command{gcc} manual page for further details. You would normally use the
3726 @option{-b} or @option{-V} switch instead.
3729 @cindex @option{-c} (@command{gcc})
3730 Compile. Always use this switch when compiling Ada programs.
3732 Note: for some other languages when using @command{gcc}, notably in
3733 the case of C and C++, it is possible to use
3734 use @command{gcc} without a @option{-c} switch to
3735 compile and link in one step. In the case of GNAT, you
3736 cannot use this approach, because the binder must be run
3737 and @command{gcc} cannot be used to run the GNAT binder.
3741 @cindex @option{-fno-inline} (@command{gcc})
3742 Suppresses all back-end inlining, even if other optimization or inlining
3744 This includes suppression of inlining that results
3745 from the use of the pragma @code{Inline_Always}.
3746 See also @option{-gnatn} and @option{-gnatN}.
3748 @item -fno-strict-aliasing
3749 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3750 Causes the compiler to avoid assumptions regarding non-aliasing
3751 of objects of different types. See
3752 @ref{Optimization and Strict Aliasing} for details.
3755 @cindex @option{-fstack-check} (@command{gcc})
3756 Activates stack checking.
3757 See @ref{Stack Overflow Checking} for details.
3760 @cindex @option{-fstack-usage} (@command{gcc})
3761 Makes the compiler output stack usage information for the program, on a
3762 per-function basis. See @ref{Static Stack Usage Analysis} for details.
3764 @item -fcallgraph-info[=su]
3765 @cindex @option{-fcallgraph-info} (@command{gcc})
3766 Makes the compiler output callgraph information for the program, on a
3767 per-file basis. The information is generated in the VCG format. It can
3768 be decorated with stack-usage per-node information.
3771 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3772 Generate debugging information. This information is stored in the object
3773 file and copied from there to the final executable file by the linker,
3774 where it can be read by the debugger. You must use the
3775 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3778 @cindex @option{-gnat83} (@command{gcc})
3779 Enforce Ada 83 restrictions.
3782 @cindex @option{-gnat95} (@command{gcc})
3783 Enforce Ada 95 restrictions.
3786 @cindex @option{-gnat05} (@command{gcc})
3787 Allow full Ada 2005 features.
3790 @cindex @option{-gnata} (@command{gcc})
3791 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3792 activated. Note that these pragmas can also be controlled using the
3793 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3796 @cindex @option{-gnatA} (@command{gcc})
3797 Avoid processing @file{gnat.adc}. If a gnat.adc file is present,
3801 @cindex @option{-gnatb} (@command{gcc})
3802 Generate brief messages to @file{stderr} even if verbose mode set.
3805 @cindex @option{-gnatc} (@command{gcc})
3806 Check syntax and semantics only (no code generation attempted).
3809 @cindex @option{-gnatd} (@command{gcc})
3810 Specify debug options for the compiler. The string of characters after
3811 the @option{-gnatd} specify the specific debug options. The possible
3812 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3813 compiler source file @file{debug.adb} for details of the implemented
3814 debug options. Certain debug options are relevant to applications
3815 programmers, and these are documented at appropriate points in this
3819 @cindex @option{-gnatD} (@command{gcc})
3820 Create expanded source files for source level debugging. This switch
3821 also suppress generation of cross-reference information
3822 (see @option{-gnatx}).
3824 @item -gnatec=@var{path}
3825 @cindex @option{-gnatec} (@command{gcc})
3826 Specify a configuration pragma file
3828 (the equal sign is optional)
3830 (@pxref{The Configuration Pragmas Files}).
3832 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
3833 @cindex @option{-gnateD} (@command{gcc})
3834 Defines a symbol, associated with value, for preprocessing.
3835 (@pxref{Integrated Preprocessing}).
3838 @cindex @option{-gnatef} (@command{gcc})
3839 Display full source path name in brief error messages.
3841 @item -gnatem=@var{path}
3842 @cindex @option{-gnatem} (@command{gcc})
3843 Specify a mapping file
3845 (the equal sign is optional)
3847 (@pxref{Units to Sources Mapping Files}).
3849 @item -gnatep=@var{file}
3850 @cindex @option{-gnatep} (@command{gcc})
3851 Specify a preprocessing data file
3853 (the equal sign is optional)
3855 (@pxref{Integrated Preprocessing}).
3858 @cindex @option{-gnatE} (@command{gcc})
3859 Full dynamic elaboration checks.
3862 @cindex @option{-gnatf} (@command{gcc})
3863 Full errors. Multiple errors per line, all undefined references, do not
3864 attempt to suppress cascaded errors.
3867 @cindex @option{-gnatF} (@command{gcc})
3868 Externals names are folded to all uppercase.
3871 @cindex @option{-gnatg} (@command{gcc})
3872 Internal GNAT implementation mode. This should not be used for
3873 applications programs, it is intended only for use by the compiler
3874 and its run-time library. For documentation, see the GNAT sources.
3875 Note that @option{-gnatg} implies @option{-gnatwu} so that warnings
3876 are generated on unreferenced entities, and all warnings are treated
3880 @cindex @option{-gnatG} (@command{gcc})
3881 List generated expanded code in source form.
3883 @item ^-gnath^/HELP^
3884 @cindex @option{^-gnath^/HELP^} (@command{gcc})
3885 Output usage information. The output is written to @file{stdout}.
3887 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3888 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
3889 Identifier character set
3891 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3894 For details of the possible selections for @var{c},
3895 see @ref{Character Set Control}.
3899 @cindex @option{-gnatjnn} (@command{gcc})
3900 Reformat error messages to fit on nn character lines
3902 @item -gnatk=@var{n}
3903 @cindex @option{-gnatk} (@command{gcc})
3904 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3907 @cindex @option{-gnatl} (@command{gcc})
3908 Output full source listing with embedded error messages.
3911 @cindex @option{-gnatL} (@command{gcc})
3912 Used in conjunction with -gnatG or -gnatD to intersperse original
3913 source lines (as comment lines with line numbers) in the expanded
3916 @item -gnatm=@var{n}
3917 @cindex @option{-gnatm} (@command{gcc})
3918 Limit number of detected error or warning messages to @var{n}
3919 where @var{n} is in the range 1..999_999. The default setting if
3920 no switch is given is 9999. Compilation is terminated if this
3921 limit is exceeded. The equal sign here is optional.
3924 @cindex @option{-gnatn} (@command{gcc})
3925 Activate inlining for subprograms for which
3926 pragma @code{inline} is specified. This inlining is performed
3927 by the GCC back-end.
3930 @cindex @option{-gnatN} (@command{gcc})
3931 Activate front end inlining for subprograms for which
3932 pragma @code{Inline} is specified. This inlining is performed
3933 by the front end and will be visible in the
3934 @option{-gnatG} output.
3935 In some cases, this has proved more effective than the back end
3936 inlining resulting from the use of
3939 @option{-gnatN} automatically implies
3940 @option{-gnatn} so it is not necessary
3941 to specify both options. There are a few cases that the back-end inlining
3942 catches that cannot be dealt with in the front-end.
3945 @cindex @option{-gnato} (@command{gcc})
3946 Enable numeric overflow checking (which is not normally enabled by
3947 default). Not that division by zero is a separate check that is not
3948 controlled by this switch (division by zero checking is on by default).
3951 @cindex @option{-gnatp} (@command{gcc})
3952 Suppress all checks.
3955 @cindex @option{-gnatP} (@command{gcc})
3956 Enable polling. This is required on some systems (notably Windows NT) to
3957 obtain asynchronous abort and asynchronous transfer of control capability.
3958 See the description of pragma Polling in the GNAT Reference Manual for
3962 @cindex @option{-gnatq} (@command{gcc})
3963 Don't quit; try semantics, even if parse errors.
3966 @cindex @option{-gnatQ} (@command{gcc})
3967 Don't quit; generate @file{ALI} and tree files even if illegalities.
3969 @item ^-gnatR[0/1/2/3[s]]^/REPRESENTATION_INFO^
3970 @cindex @option{-gnatR} (@command{gcc})
3971 Output representation information for declared types and objects.
3974 @cindex @option{-gnats} (@command{gcc})
3978 @cindex @option{-gnatS} (@command{gcc})
3979 Print package Standard.
3982 @cindex @option{-gnatt} (@command{gcc})
3983 Generate tree output file.
3985 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
3986 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
3987 All compiler tables start at @var{nnn} times usual starting size.
3990 @cindex @option{-gnatu} (@command{gcc})
3991 List units for this compilation.
3994 @cindex @option{-gnatU} (@command{gcc})
3995 Tag all error messages with the unique string ``error:''
3998 @cindex @option{-gnatv} (@command{gcc})
3999 Verbose mode. Full error output with source lines to @file{stdout}.
4002 @cindex @option{-gnatV} (@command{gcc})
4003 Control level of validity checking. See separate section describing
4006 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}[,...])^
4007 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4009 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4010 the exact warnings that
4011 are enabled or disabled (@pxref{Warning Message Control}).
4013 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4014 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4015 Wide character encoding method
4017 (@var{e}=n/h/u/s/e/8).
4020 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4024 @cindex @option{-gnatx} (@command{gcc})
4025 Suppress generation of cross-reference information.
4027 @item ^-gnaty^/STYLE_CHECKS=(option,option..)^
4028 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4029 Enable built-in style checks (@pxref{Style Checking}).
4031 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4032 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4033 Distribution stub generation and compilation
4035 (@var{m}=r/c for receiver/caller stubs).
4038 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4039 to be generated and compiled).
4042 @item ^-I^/SEARCH=^@var{dir}
4043 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4045 Direct GNAT to search the @var{dir} directory for source files needed by
4046 the current compilation
4047 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4049 @item ^-I-^/NOCURRENT_DIRECTORY^
4050 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4052 Except for the source file named in the command line, do not look for source
4053 files in the directory containing the source file named in the command line
4054 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4058 @cindex @option{-mbig-switch} (@command{gcc})
4059 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4060 This standard gcc switch causes the compiler to use larger offsets in its
4061 jump table representation for @code{case} statements.
4062 This may result in less efficient code, but is sometimes necessary
4063 (for example on HP-UX targets)
4064 @cindex HP-UX and @option{-mbig-switch} option
4065 in order to compile large and/or nested @code{case} statements.
4068 @cindex @option{-o} (@command{gcc})
4069 This switch is used in @command{gcc} to redirect the generated object file
4070 and its associated ALI file. Beware of this switch with GNAT, because it may
4071 cause the object file and ALI file to have different names which in turn
4072 may confuse the binder and the linker.
4076 @cindex @option{-nostdinc} (@command{gcc})
4077 Inhibit the search of the default location for the GNAT Run Time
4078 Library (RTL) source files.
4081 @cindex @option{-nostdlib} (@command{gcc})
4082 Inhibit the search of the default location for the GNAT Run Time
4083 Library (RTL) ALI files.
4087 @cindex @option{-O} (@command{gcc})
4088 @var{n} controls the optimization level.
4092 No optimization, the default setting if no @option{-O} appears
4095 Normal optimization, the default if you specify @option{-O} without
4096 an operand. A good compromise between code quality and compilation
4100 Extensive optimization, may improve execution time, possibly at the cost of
4101 substantially increased compilation time.
4108 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4109 Equivalent to @option{/OPTIMIZE=NONE}.
4110 This is the default behavior in the absence of an @option{/OPTMIZE}
4113 @item /OPTIMIZE[=(keyword[,...])]
4114 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4115 Selects the level of optimization for your program. The supported
4116 keywords are as follows:
4119 Perform most optimizations, including those that
4121 This is the default if the @option{/OPTMIZE} qualifier is supplied
4122 without keyword options.
4125 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4128 Perform some optimizations, but omit ones that are costly.
4131 Same as @code{SOME}.
4134 Try to unroll loops. This keyword may be specified together with
4135 any keyword above other than @code{NONE}. Loop unrolling
4136 usually, but not always, improves the performance of programs.
4141 @item -pass-exit-codes
4142 @cindex @option{-pass-exit-codes} (@command{gcc})
4143 Catch exit codes from the compiler and use the most meaningful as
4147 @item --RTS=@var{rts-path}
4148 @cindex @option{--RTS} (@command{gcc})
4149 Specifies the default location of the runtime library. Same meaning as the
4150 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4153 @cindex @option{^-S^/ASM^} (@command{gcc})
4154 ^Used in place of @option{-c} to^Used to^
4155 cause the assembler source file to be
4156 generated, using @file{^.s^.S^} as the extension,
4157 instead of the object file.
4158 This may be useful if you need to examine the generated assembly code.
4160 @item ^-fverbose-asm^/VERBOSE_ASM^
4161 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4162 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4163 to cause the generated assembly code file to be annotated with variable
4164 names, making it significantly easier to follow.
4167 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4168 Show commands generated by the @command{gcc} driver. Normally used only for
4169 debugging purposes or if you need to be sure what version of the
4170 compiler you are executing.
4174 @cindex @option{-V} (@command{gcc})
4175 Execute @var{ver} version of the compiler. This is the @command{gcc}
4176 version, not the GNAT version.
4179 @item ^-w^NO_BACK_END_WARNINGS^
4180 @cindex @option{-w} (@command{gcc})
4181 Turn off warnings generated by the back end of the compiler. Use of
4182 this switch also causes the default for front end warnings to be set
4183 to suppress (as though @option{-gnatws} had appeared at the start of
4189 @c Combining qualifiers does not work on VMS
4190 You may combine a sequence of GNAT switches into a single switch. For
4191 example, the combined switch
4193 @cindex Combining GNAT switches
4199 is equivalent to specifying the following sequence of switches:
4202 -gnato -gnatf -gnati3
4207 The following restrictions apply to the combination of switches
4212 The switch @option{-gnatc} if combined with other switches must come
4213 first in the string.
4216 The switch @option{-gnats} if combined with other switches must come
4217 first in the string.
4221 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4222 may not be combined with any other switches.
4226 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4227 switch), then all further characters in the switch are interpreted
4228 as style modifiers (see description of @option{-gnaty}).
4231 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4232 switch), then all further characters in the switch are interpreted
4233 as debug flags (see description of @option{-gnatd}).
4236 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4237 switch), then all further characters in the switch are interpreted
4238 as warning mode modifiers (see description of @option{-gnatw}).
4241 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4242 switch), then all further characters in the switch are interpreted
4243 as validity checking options (see description of @option{-gnatV}).
4247 @node Output and Error Message Control
4248 @subsection Output and Error Message Control
4252 The standard default format for error messages is called ``brief format''.
4253 Brief format messages are written to @file{stderr} (the standard error
4254 file) and have the following form:
4257 e.adb:3:04: Incorrect spelling of keyword "function"
4258 e.adb:4:20: ";" should be "is"
4262 The first integer after the file name is the line number in the file,
4263 and the second integer is the column number within the line.
4264 @code{glide} can parse the error messages
4265 and point to the referenced character.
4266 The following switches provide control over the error message
4272 @cindex @option{-gnatv} (@command{gcc})
4275 The v stands for verbose.
4277 The effect of this setting is to write long-format error
4278 messages to @file{stdout} (the standard output file.
4279 The same program compiled with the
4280 @option{-gnatv} switch would generate:
4284 3. funcion X (Q : Integer)
4286 >>> Incorrect spelling of keyword "function"
4289 >>> ";" should be "is"
4294 The vertical bar indicates the location of the error, and the @samp{>>>}
4295 prefix can be used to search for error messages. When this switch is
4296 used the only source lines output are those with errors.
4299 @cindex @option{-gnatl} (@command{gcc})
4301 The @code{l} stands for list.
4303 This switch causes a full listing of
4304 the file to be generated. In the case where a body is
4305 compiled, the corresponding spec is also listed, along
4306 with any subunits. Typical output from compiling a package
4307 body @file{p.adb} might look like:
4309 @smallexample @c ada
4313 1. package body p is
4315 3. procedure a is separate;
4326 2. pragma Elaborate_Body
4350 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4351 standard output is redirected, a brief summary is written to
4352 @file{stderr} (standard error) giving the number of error messages and
4353 warning messages generated.
4355 @item -^gnatl^OUTPUT_FILE^=file
4356 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4357 This has the same effect as @code{-gnatl} except that the output is
4358 written to a file instead of to standard output. If the given name
4359 @file{fname} does not start with a period, then it is the full name
4360 of the file to be written. If @file{fname} is an extension, it is
4361 appended to the name of the file being compiled. For example, if
4362 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4363 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4366 @cindex @option{-gnatU} (@command{gcc})
4367 This switch forces all error messages to be preceded by the unique
4368 string ``error:''. This means that error messages take a few more
4369 characters in space, but allows easy searching for and identification
4373 @cindex @option{-gnatb} (@command{gcc})
4375 The @code{b} stands for brief.
4377 This switch causes GNAT to generate the
4378 brief format error messages to @file{stderr} (the standard error
4379 file) as well as the verbose
4380 format message or full listing (which as usual is written to
4381 @file{stdout} (the standard output file).
4383 @item -gnatm=@var{n}
4384 @cindex @option{-gnatm} (@command{gcc})
4386 The @code{m} stands for maximum.
4388 @var{n} is a decimal integer in the
4389 range of 1 to 999 and limits the number of error messages to be
4390 generated. For example, using @option{-gnatm2} might yield
4393 e.adb:3:04: Incorrect spelling of keyword "function"
4394 e.adb:5:35: missing ".."
4395 fatal error: maximum errors reached
4396 compilation abandoned
4400 Note that the equal sign is optional, so the switches
4401 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4404 @cindex @option{-gnatf} (@command{gcc})
4405 @cindex Error messages, suppressing
4407 The @code{f} stands for full.
4409 Normally, the compiler suppresses error messages that are likely to be
4410 redundant. This switch causes all error
4411 messages to be generated. In particular, in the case of
4412 references to undefined variables. If a given variable is referenced
4413 several times, the normal format of messages is
4415 e.adb:7:07: "V" is undefined (more references follow)
4419 where the parenthetical comment warns that there are additional
4420 references to the variable @code{V}. Compiling the same program with the
4421 @option{-gnatf} switch yields
4424 e.adb:7:07: "V" is undefined
4425 e.adb:8:07: "V" is undefined
4426 e.adb:8:12: "V" is undefined
4427 e.adb:8:16: "V" is undefined
4428 e.adb:9:07: "V" is undefined
4429 e.adb:9:12: "V" is undefined
4433 The @option{-gnatf} switch also generates additional information for
4434 some error messages. Some examples are:
4438 Full details on entities not available in high integrity mode
4440 Details on possibly non-portable unchecked conversion
4442 List possible interpretations for ambiguous calls
4444 Additional details on incorrect parameters
4448 @cindex @option{-gnatjnn} (@command{gcc})
4449 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4450 with continuation lines are treated as though the continuation lines were
4451 separate messages (and so a warning with two continuation lines counts as
4452 three warnings, and is listed as three separate messages).
4454 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4455 messages are output in a different manner. A message and all its continuation
4456 lines are treated as a unit, and count as only one warning or message in the
4457 statistics totals. Furthermore, the message is reformatted so that no line
4458 is longer than nn characters.
4461 @cindex @option{-gnatq} (@command{gcc})
4463 The @code{q} stands for quit (really ``don't quit'').
4465 In normal operation mode, the compiler first parses the program and
4466 determines if there are any syntax errors. If there are, appropriate
4467 error messages are generated and compilation is immediately terminated.
4469 GNAT to continue with semantic analysis even if syntax errors have been
4470 found. This may enable the detection of more errors in a single run. On
4471 the other hand, the semantic analyzer is more likely to encounter some
4472 internal fatal error when given a syntactically invalid tree.
4475 @cindex @option{-gnatQ} (@command{gcc})
4476 In normal operation mode, the @file{ALI} file is not generated if any
4477 illegalities are detected in the program. The use of @option{-gnatQ} forces
4478 generation of the @file{ALI} file. This file is marked as being in
4479 error, so it cannot be used for binding purposes, but it does contain
4480 reasonably complete cross-reference information, and thus may be useful
4481 for use by tools (e.g. semantic browsing tools or integrated development
4482 environments) that are driven from the @file{ALI} file. This switch
4483 implies @option{-gnatq}, since the semantic phase must be run to get a
4484 meaningful ALI file.
4486 In addition, if @option{-gnatt} is also specified, then the tree file is
4487 generated even if there are illegalities. It may be useful in this case
4488 to also specify @option{-gnatq} to ensure that full semantic processing
4489 occurs. The resulting tree file can be processed by ASIS, for the purpose
4490 of providing partial information about illegal units, but if the error
4491 causes the tree to be badly malformed, then ASIS may crash during the
4494 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4495 being in error, @command{gnatmake} will attempt to recompile the source when it
4496 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4498 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4499 since ALI files are never generated if @option{-gnats} is set.
4503 @node Warning Message Control
4504 @subsection Warning Message Control
4505 @cindex Warning messages
4507 In addition to error messages, which correspond to illegalities as defined
4508 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
4511 First, the compiler considers some constructs suspicious and generates a
4512 warning message to alert you to a possible error. Second, if the
4513 compiler detects a situation that is sure to raise an exception at
4514 run time, it generates a warning message. The following shows an example
4515 of warning messages:
4517 e.adb:4:24: warning: creation of object may raise Storage_Error
4518 e.adb:10:17: warning: static value out of range
4519 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4523 GNAT considers a large number of situations as appropriate
4524 for the generation of warning messages. As always, warnings are not
4525 definite indications of errors. For example, if you do an out-of-range
4526 assignment with the deliberate intention of raising a
4527 @code{Constraint_Error} exception, then the warning that may be
4528 issued does not indicate an error. Some of the situations for which GNAT
4529 issues warnings (at least some of the time) are given in the following
4530 list. This list is not complete, and new warnings are often added to
4531 subsequent versions of GNAT. The list is intended to give a general idea
4532 of the kinds of warnings that are generated.
4536 Possible infinitely recursive calls
4539 Out-of-range values being assigned
4542 Possible order of elaboration problems
4548 Address clauses with possibly unaligned values, or where an attempt is
4549 made to overlay a smaller variable with a larger one.
4552 Fixed-point type declarations with a null range
4555 Direct_IO or Sequential_IO instantiated with a type that has access values
4558 Variables that are never assigned a value
4561 Variables that are referenced before being initialized
4564 Task entries with no corresponding @code{accept} statement
4567 Duplicate accepts for the same task entry in a @code{select}
4570 Objects that take too much storage
4573 Unchecked conversion between types of differing sizes
4576 Missing @code{return} statement along some execution path in a function
4579 Incorrect (unrecognized) pragmas
4582 Incorrect external names
4585 Allocation from empty storage pool
4588 Potentially blocking operation in protected type
4591 Suspicious parenthesization of expressions
4594 Mismatching bounds in an aggregate
4597 Attempt to return local value by reference
4600 Premature instantiation of a generic body
4603 Attempt to pack aliased components
4606 Out of bounds array subscripts
4609 Wrong length on string assignment
4612 Violations of style rules if style checking is enabled
4615 Unused @code{with} clauses
4618 @code{Bit_Order} usage that does not have any effect
4621 @code{Standard.Duration} used to resolve universal fixed expression
4624 Dereference of possibly null value
4627 Declaration that is likely to cause storage error
4630 Internal GNAT unit @code{with}'ed by application unit
4633 Values known to be out of range at compile time
4636 Unreferenced labels and variables
4639 Address overlays that could clobber memory
4642 Unexpected initialization when address clause present
4645 Bad alignment for address clause
4648 Useless type conversions
4651 Redundant assignment statements and other redundant constructs
4654 Useless exception handlers
4657 Accidental hiding of name by child unit
4660 Access before elaboration detected at compile time
4663 A range in a @code{for} loop that is known to be null or might be null
4668 The following section lists compiler switches that are available
4669 to control the handling of warning messages. It is also possible
4670 to exercise much finer control over what warnings are issued and
4671 suppressed using the GNAT pragma Warnings, which is documented
4672 in the GNAT Reference manual.
4677 @emph{Activate all optional errors.}
4678 @cindex @option{-gnatwa} (@command{gcc})
4679 This switch activates most optional warning messages, see remaining list
4680 in this section for details on optional warning messages that can be
4681 individually controlled. The warnings that are not turned on by this
4683 @option{-gnatwd} (implicit dereferencing),
4684 @option{-gnatwh} (hiding),
4685 @option{-gnatwl} (elaboration warnings),
4686 and @option{-gnatwt} (tracking of deleted conditional code).
4687 All other optional warnings are turned on.
4690 @emph{Suppress all optional errors.}
4691 @cindex @option{-gnatwA} (@command{gcc})
4692 This switch suppresses all optional warning messages, see remaining list
4693 in this section for details on optional warning messages that can be
4694 individually controlled.
4697 @emph{Activate warnings on bad fixed values.}
4698 @cindex @option{-gnatwb} (@command{gcc})
4699 @cindex Bad fixed values
4700 @cindex Fixed-point Small value
4702 This switch activates warnings for static fixed-point expressions whose
4703 value is not an exact multiple of Small. Such values are implementation
4704 dependent, since an implementation is free to choose either of the multiples
4705 that surround the value. GNAT always chooses the closer one, but this is not
4706 required behavior, and it is better to specify a value that is an exact
4707 multiple, ensuring predictable execution. The default is that such warnings
4711 @emph{Suppress warnings on bad fixed values.}
4712 @cindex @option{-gnatwB} (@command{gcc})
4713 This switch suppresses warnings for static fixed-point expressions whose
4714 value is not an exact multiple of Small.
4717 @emph{Activate warnings on conditionals.}
4718 @cindex @option{-gnatwc} (@command{gcc})
4719 @cindex Conditionals, constant
4720 This switch activates warnings for conditional expressions used in
4721 tests that are known to be True or False at compile time. The default
4722 is that such warnings are not generated.
4723 Note that this warning does
4724 not get issued for the use of boolean variables or constants whose
4725 values are known at compile time, since this is a standard technique
4726 for conditional compilation in Ada, and this would generate too many
4727 false positive warnings.
4729 This warning option also activates a special test for comparisons using
4730 the operators ``>='' and`` <=''.
4731 If the compiler can tell that only the equality condition is possible,
4732 then it will warn that the ``>'' or ``<'' part of the test
4733 is useless and that the operator could be replaced by ``=''.
4734 An example would be comparing a @code{Natural} variable <= 0.
4736 This warning can also be turned on using @option{-gnatwa}.
4739 @emph{Suppress warnings on conditionals.}
4740 @cindex @option{-gnatwC} (@command{gcc})
4741 This switch suppresses warnings for conditional expressions used in
4742 tests that are known to be True or False at compile time.
4745 @emph{Activate warnings on implicit dereferencing.}
4746 @cindex @option{-gnatwd} (@command{gcc})
4747 If this switch is set, then the use of a prefix of an access type
4748 in an indexed component, slice, or selected component without an
4749 explicit @code{.all} will generate a warning. With this warning
4750 enabled, access checks occur only at points where an explicit
4751 @code{.all} appears in the source code (assuming no warnings are
4752 generated as a result of this switch). The default is that such
4753 warnings are not generated.
4754 Note that @option{-gnatwa} does not affect the setting of
4755 this warning option.
4758 @emph{Suppress warnings on implicit dereferencing.}
4759 @cindex @option{-gnatwD} (@command{gcc})
4760 @cindex Implicit dereferencing
4761 @cindex Dereferencing, implicit
4762 This switch suppresses warnings for implicit dereferences in
4763 indexed components, slices, and selected components.
4766 @emph{Treat warnings as errors.}
4767 @cindex @option{-gnatwe} (@command{gcc})
4768 @cindex Warnings, treat as error
4769 This switch causes warning messages to be treated as errors.
4770 The warning string still appears, but the warning messages are counted
4771 as errors, and prevent the generation of an object file.
4774 @emph{Activate warnings on unreferenced formals.}
4775 @cindex @option{-gnatwf} (@command{gcc})
4776 @cindex Formals, unreferenced
4777 This switch causes a warning to be generated if a formal parameter
4778 is not referenced in the body of the subprogram. This warning can
4779 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
4780 default is that these warnings are not generated.
4783 @emph{Suppress warnings on unreferenced formals.}
4784 @cindex @option{-gnatwF} (@command{gcc})
4785 This switch suppresses warnings for unreferenced formal
4786 parameters. Note that the
4787 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4788 effect of warning on unreferenced entities other than subprogram
4792 @emph{Activate warnings on unrecognized pragmas.}
4793 @cindex @option{-gnatwg} (@command{gcc})
4794 @cindex Pragmas, unrecognized
4795 This switch causes a warning to be generated if an unrecognized
4796 pragma is encountered. Apart from issuing this warning, the
4797 pragma is ignored and has no effect. This warning can
4798 also be turned on using @option{-gnatwa}. The default
4799 is that such warnings are issued (satisfying the Ada Reference
4800 Manual requirement that such warnings appear).
4803 @emph{Suppress warnings on unrecognized pragmas.}
4804 @cindex @option{-gnatwG} (@command{gcc})
4805 This switch suppresses warnings for unrecognized pragmas.
4808 @emph{Activate warnings on hiding.}
4809 @cindex @option{-gnatwh} (@command{gcc})
4810 @cindex Hiding of Declarations
4811 This switch activates warnings on hiding declarations.
4812 A declaration is considered hiding
4813 if it is for a non-overloadable entity, and it declares an entity with the
4814 same name as some other entity that is directly or use-visible. The default
4815 is that such warnings are not generated.
4816 Note that @option{-gnatwa} does not affect the setting of this warning option.
4819 @emph{Suppress warnings on hiding.}
4820 @cindex @option{-gnatwH} (@command{gcc})
4821 This switch suppresses warnings on hiding declarations.
4824 @emph{Activate warnings on implementation units.}
4825 @cindex @option{-gnatwi} (@command{gcc})
4826 This switch activates warnings for a @code{with} of an internal GNAT
4827 implementation unit, defined as any unit from the @code{Ada},
4828 @code{Interfaces}, @code{GNAT},
4829 ^^@code{DEC},^ or @code{System}
4830 hierarchies that is not
4831 documented in either the Ada Reference Manual or the GNAT
4832 Programmer's Reference Manual. Such units are intended only
4833 for internal implementation purposes and should not be @code{with}'ed
4834 by user programs. The default is that such warnings are generated
4835 This warning can also be turned on using @option{-gnatwa}.
4838 @emph{Disable warnings on implementation units.}
4839 @cindex @option{-gnatwI} (@command{gcc})
4840 This switch disables warnings for a @code{with} of an internal GNAT
4841 implementation unit.
4844 @emph{Activate warnings on obsolescent features (Annex J).}
4845 @cindex @option{-gnatwj} (@command{gcc})
4846 @cindex Features, obsolescent
4847 @cindex Obsolescent features
4848 If this warning option is activated, then warnings are generated for
4849 calls to subprograms marked with @code{pragma Obsolescent} and
4850 for use of features in Annex J of the Ada Reference Manual. In the
4851 case of Annex J, not all features are flagged. In particular use
4852 of the renamed packages (like @code{Text_IO}) and use of package
4853 @code{ASCII} are not flagged, since these are very common and
4854 would generate many annoying positive warnings. The default is that
4855 such warnings are not generated. This warning is also turned on by
4856 the use of @option{-gnatwa}.
4858 In addition to the above cases, warnings are also generated for
4859 GNAT features that have been provided in past versions but which
4860 have been superseded (typically by features in the new Ada standard).
4861 For example, @code{pragma Ravenscar} will be flagged since its
4862 function is replaced by @code{pragma Profile(Ravenscar)}.
4864 Note that this warning option functions differently from the
4865 restriction @code{No_Obsolescent_Features} in two respects.
4866 First, the restriction applies only to annex J features.
4867 Second, the restriction does flag uses of package @code{ASCII}.
4870 @emph{Suppress warnings on obsolescent features (Annex J).}
4871 @cindex @option{-gnatwJ} (@command{gcc})
4872 This switch disables warnings on use of obsolescent features.
4875 @emph{Activate warnings on variables that could be constants.}
4876 @cindex @option{-gnatwk} (@command{gcc})
4877 This switch activates warnings for variables that are initialized but
4878 never modified, and then could be declared constants. The default is that
4879 such warnings are not given.
4880 This warning can also be turned on using @option{-gnatwa}.
4883 @emph{Suppress warnings on variables that could be constants.}
4884 @cindex @option{-gnatwK} (@command{gcc})
4885 This switch disables warnings on variables that could be declared constants.
4888 @emph{Activate warnings for missing elaboration pragmas.}
4889 @cindex @option{-gnatwl} (@command{gcc})
4890 @cindex Elaboration, warnings
4891 This switch activates warnings on missing
4892 @code{Elaborate_All} and @code{Elaborate} pragmas.
4893 See the section in this guide on elaboration checking for details on
4894 when such pragmas should be used. Warnings are also generated if you
4895 are using the static mode of elaboration, and a @code{pragma Elaborate}
4896 is encountered. The default is that such warnings
4898 This warning is not automatically turned on by the use of @option{-gnatwa}.
4901 @emph{Suppress warnings for missing elaboration pragmas.}
4902 @cindex @option{-gnatwL} (@command{gcc})
4903 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
4904 See the section in this guide on elaboration checking for details on
4905 when such pragmas should be used.
4908 @emph{Activate warnings on modified but unreferenced variables.}
4909 @cindex @option{-gnatwm} (@command{gcc})
4910 This switch activates warnings for variables that are assigned (using
4911 an initialization value or with one or more assignment statements) but
4912 whose value is never read. The warning is suppressed for volatile
4913 variables and also for variables that are renamings of other variables
4914 or for which an address clause is given.
4915 This warning can also be turned on using @option{-gnatwa}.
4916 The default is that these warnings are not given.
4919 @emph{Disable warnings on modified but unreferenced variables.}
4920 @cindex @option{-gnatwM} (@command{gcc})
4921 This switch disables warnings for variables that are assigned or
4922 initialized, but never read.
4925 @emph{Set normal warnings mode.}
4926 @cindex @option{-gnatwn} (@command{gcc})
4927 This switch sets normal warning mode, in which enabled warnings are
4928 issued and treated as warnings rather than errors. This is the default
4929 mode. the switch @option{-gnatwn} can be used to cancel the effect of
4930 an explicit @option{-gnatws} or
4931 @option{-gnatwe}. It also cancels the effect of the
4932 implicit @option{-gnatwe} that is activated by the
4933 use of @option{-gnatg}.
4936 @emph{Activate warnings on address clause overlays.}
4937 @cindex @option{-gnatwo} (@command{gcc})
4938 @cindex Address Clauses, warnings
4939 This switch activates warnings for possibly unintended initialization
4940 effects of defining address clauses that cause one variable to overlap
4941 another. The default is that such warnings are generated.
4942 This warning can also be turned on using @option{-gnatwa}.
4945 @emph{Suppress warnings on address clause overlays.}
4946 @cindex @option{-gnatwO} (@command{gcc})
4947 This switch suppresses warnings on possibly unintended initialization
4948 effects of defining address clauses that cause one variable to overlap
4952 @emph{Activate warnings on ineffective pragma Inlines.}
4953 @cindex @option{-gnatwp} (@command{gcc})
4954 @cindex Inlining, warnings
4955 This switch activates warnings for failure of front end inlining
4956 (activated by @option{-gnatN}) to inline a particular call. There are
4957 many reasons for not being able to inline a call, including most
4958 commonly that the call is too complex to inline. The default is
4959 that such warnings are not given.
4960 This warning can also be turned on using @option{-gnatwa}.
4963 @emph{Suppress warnings on ineffective pragma Inlines.}
4964 @cindex @option{-gnatwP} (@command{gcc})
4965 This switch suppresses warnings on ineffective pragma Inlines. If the
4966 inlining mechanism cannot inline a call, it will simply ignore the
4970 @emph{Activate warnings on questionable missing parentheses.}
4971 @cindex @option{-gnatwq} (@command{gcc})
4972 @cindex Parentheses, warnings
4973 This switch activates warnings for cases where parentheses are not used and
4974 the result is potential ambiguity from a readers point of view. For example
4975 (not a > b) when a and b are modular means (not (a) > b) and very likely the
4976 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
4977 quite likely ((-x) mod 5) was intended. In such situations it seems best to
4978 follow the rule of always parenthesizing to make the association clear, and
4979 this warning switch warns if such parentheses are not present. The default
4980 is that these warnings are not given.
4981 This warning can also be turned on using @option{-gnatwa}.
4984 @emph{Suppress warnings on questionable missing parentheses.}
4985 @cindex @option{-gnatwQ} (@command{gcc})
4986 This switch suppresses warnings for cases where the association is not
4987 clear and the use of parentheses is preferred.
4990 @emph{Activate warnings on redundant constructs.}
4991 @cindex @option{-gnatwr} (@command{gcc})
4992 This switch activates warnings for redundant constructs. The following
4993 is the current list of constructs regarded as redundant:
4997 Assignment of an item to itself.
4999 Type conversion that converts an expression to its own type.
5001 Use of the attribute @code{Base} where @code{typ'Base} is the same
5004 Use of pragma @code{Pack} when all components are placed by a record
5005 representation clause.
5007 Exception handler containing only a reraise statement (raise with no
5008 operand) which has no effect.
5010 Use of the operator abs on an operand that is known at compile time
5013 Comparison of boolean expressions to an explicit True value.
5016 This warning can also be turned on using @option{-gnatwa}.
5017 The default is that warnings for redundant constructs are not given.
5020 @emph{Suppress warnings on redundant constructs.}
5021 @cindex @option{-gnatwR} (@command{gcc})
5022 This switch suppresses warnings for redundant constructs.
5025 @emph{Suppress all warnings.}
5026 @cindex @option{-gnatws} (@command{gcc})
5027 This switch completely suppresses the
5028 output of all warning messages from the GNAT front end.
5029 Note that it does not suppress warnings from the @command{gcc} back end.
5030 To suppress these back end warnings as well, use the switch @option{-w}
5031 in addition to @option{-gnatws}.
5034 @emph{Activate warnings for tracking of deleted conditional code.}
5035 @cindex @option{-gnatwt} (@command{gcc})
5036 @cindex Deactivated code, warnings
5037 @cindex Deleted code, warnings
5038 This switch activates warnings for tracking of code in conditionals (IF and
5039 CASE statements) that is detected to be dead code which cannot be executed, and
5040 which is removed by the front end. This warning is off by default, and is not
5041 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5042 useful for detecting deactivated code in certified applications.
5045 @emph{Suppress warnings for tracking of deleted conditional code.}
5046 @cindex @option{-gnatwT} (@command{gcc})
5047 This switch suppresses warnings for tracking of deleted conditional code.
5050 @emph{Activate warnings on unused entities.}
5051 @cindex @option{-gnatwu} (@command{gcc})
5052 This switch activates warnings to be generated for entities that
5053 are declared but not referenced, and for units that are @code{with}'ed
5055 referenced. In the case of packages, a warning is also generated if
5056 no entities in the package are referenced. This means that if the package
5057 is referenced but the only references are in @code{use}
5058 clauses or @code{renames}
5059 declarations, a warning is still generated. A warning is also generated
5060 for a generic package that is @code{with}'ed but never instantiated.
5061 In the case where a package or subprogram body is compiled, and there
5062 is a @code{with} on the corresponding spec
5063 that is only referenced in the body,
5064 a warning is also generated, noting that the
5065 @code{with} can be moved to the body. The default is that
5066 such warnings are not generated.
5067 This switch also activates warnings on unreferenced formals
5068 (it includes the effect of @option{-gnatwf}).
5069 This warning can also be turned on using @option{-gnatwa}.
5072 @emph{Suppress warnings on unused entities.}
5073 @cindex @option{-gnatwU} (@command{gcc})
5074 This switch suppresses warnings for unused entities and packages.
5075 It also turns off warnings on unreferenced formals (and thus includes
5076 the effect of @option{-gnatwF}).
5079 @emph{Activate warnings on unassigned variables.}
5080 @cindex @option{-gnatwv} (@command{gcc})
5081 @cindex Unassigned variable warnings
5082 This switch activates warnings for access to variables which
5083 may not be properly initialized. The default is that
5084 such warnings are generated.
5085 This warning can also be turned on using @option{-gnatwa}.
5088 @emph{Suppress warnings on unassigned variables.}
5089 @cindex @option{-gnatwV} (@command{gcc})
5090 This switch suppresses warnings for access to variables which
5091 may not be properly initialized.
5094 @emph{Activate warnings on wrong low bound assumption.}
5095 @cindex @option{-gnatww} (@command{gcc})
5096 @cindex String indexing warnings
5097 This switch activates warnings for indexing an unconstrained string parameter
5098 with a literal or S'Length. This is a case where the code is assuming that the
5099 low bound is one, which is in general not true (for example when a slice is
5100 passed). The default is that such warnings are generated.
5101 This warning can also be turned on using @option{-gnatwa}.
5105 @emph{Suppress warnings on wrong low bound assumption.}
5106 @cindex @option{-gnatwW} (@command{gcc})
5107 This switch activates warnings for indexing an unconstrained string parameter
5108 with a literal or S'Length. This warning can also be suppressed by providing
5109 an Assert pragma that checks the low bound, for example:
5111 @smallexample @c ada
5112 procedure K (S : String) is
5113 pragma Assert (S'First = 1);
5118 @emph{Activate warnings on Export/Import pragmas.}
5119 @cindex @option{-gnatwx} (@command{gcc})
5120 @cindex Export/Import pragma warnings
5121 This switch activates warnings on Export/Import pragmas when
5122 the compiler detects a possible conflict between the Ada and
5123 foreign language calling sequences. For example, the use of
5124 default parameters in a convention C procedure is dubious
5125 because the C compiler cannot supply the proper default, so
5126 a warning is issued. The default is that such warnings are
5128 This warning can also be turned on using @option{-gnatwa}.
5131 @emph{Suppress warnings on Export/Import pragmas.}
5132 @cindex @option{-gnatwX} (@command{gcc})
5133 This switch suppresses warnings on Export/Import pragmas.
5134 The sense of this is that you are telling the compiler that
5135 you know what you are doing in writing the pragma, and it
5136 should not complain at you.
5139 @emph{Activate warnings for Ada 2005 compatibility issues.}
5140 @cindex @option{-gnatwy} (@command{gcc})
5141 @cindex Ada 2005 compatibility issues warnings
5142 For the most part Ada 2005 is upwards compatible with Ada 95,
5143 but there are some exceptions (for example the fact that
5144 @code{interface} is now a reserved word in Ada 2005). This
5145 switch activates several warnings to help in identifying
5146 and correcting such incompatibilities. The default is that
5147 these warnings are generated. Note that at one point Ada 2005
5148 was called Ada 0Y, hence the choice of character.
5149 This warning can also be turned on using @option{-gnatwa}.
5152 @emph{Disable warnings for Ada 2005 compatibility issues.}
5153 @cindex @option{-gnatwY} (@command{gcc})
5154 @cindex Ada 2005 compatibility issues warnings
5155 This switch suppresses several warnings intended to help in identifying
5156 incompatibilities between Ada 95 and Ada 2005.
5159 @emph{Activate warnings on unchecked conversions.}
5160 @cindex @option{-gnatwz} (@command{gcc})
5161 @cindex Unchecked_Conversion warnings
5162 This switch activates warnings for unchecked conversions
5163 where the types are known at compile time to have different
5165 is that such warnings are generated.
5166 This warning can also be turned on using @option{-gnatwa}.
5169 @emph{Suppress warnings on unchecked conversions.}
5170 @cindex @option{-gnatwZ} (@command{gcc})
5171 This switch suppresses warnings for unchecked conversions
5172 where the types are known at compile time to have different
5175 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5176 @cindex @option{-Wuninitialized}
5177 The warnings controlled by the @option{-gnatw} switch are generated by the
5178 front end of the compiler. In some cases, the @option{^gcc^GCC^} back end
5179 can provide additional warnings. One such useful warning is provided by
5180 @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^}. This must be used in
5181 conjunction with turning on optimization mode. This causes the flow
5182 analysis circuits of the back end optimizer to output additional
5183 warnings about uninitialized variables.
5185 @item ^-w^/NO_BACK_END_WARNINGS^
5187 This switch suppresses warnings from the @option{^gcc^GCC^} back end. The
5188 code generator detects a number of warning situations that are missed
5189 by the @option{GNAT} front end, and this switch can be used to suppress them.
5190 The use of this switch also sets the default front end warning mode to
5191 @option{-gnatws}, that is, front end warnings suppressed as well.
5197 A string of warning parameters can be used in the same parameter. For example:
5204 will turn on all optional warnings except for elaboration pragma warnings,
5205 and also specify that warnings should be treated as errors.
5207 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5232 @node Debugging and Assertion Control
5233 @subsection Debugging and Assertion Control
5237 @cindex @option{-gnata} (@command{gcc})
5243 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5244 are ignored. This switch, where @samp{a} stands for assert, causes
5245 @code{Assert} and @code{Debug} pragmas to be activated.
5247 The pragmas have the form:
5251 @b{pragma} Assert (@var{Boolean-expression} [,
5252 @var{static-string-expression}])
5253 @b{pragma} Debug (@var{procedure call})
5258 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5259 If the result is @code{True}, the pragma has no effect (other than
5260 possible side effects from evaluating the expression). If the result is
5261 @code{False}, the exception @code{Assert_Failure} declared in the package
5262 @code{System.Assertions} is
5263 raised (passing @var{static-string-expression}, if present, as the
5264 message associated with the exception). If no string expression is
5265 given the default is a string giving the file name and line number
5268 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5269 @code{pragma Debug} may appear within a declaration sequence, allowing
5270 debugging procedures to be called between declarations.
5273 @item /DEBUG[=debug-level]
5275 Specifies how much debugging information is to be included in
5276 the resulting object file where 'debug-level' is one of the following:
5279 Include both debugger symbol records and traceback
5281 This is the default setting.
5283 Include both debugger symbol records and traceback in
5286 Excludes both debugger symbol records and traceback
5287 the object file. Same as /NODEBUG.
5289 Includes only debugger symbol records in the object
5290 file. Note that this doesn't include traceback information.
5295 @node Validity Checking
5296 @subsection Validity Checking
5297 @findex Validity Checking
5300 The Ada 95 Reference Manual has specific requirements for checking
5301 for invalid values. In particular, RM 13.9.1 requires that the
5302 evaluation of invalid values (for example from unchecked conversions),
5303 not result in erroneous execution. In GNAT, the result of such an
5304 evaluation in normal default mode is to either use the value
5305 unmodified, or to raise Constraint_Error in those cases where use
5306 of the unmodified value would cause erroneous execution. The cases
5307 where unmodified values might lead to erroneous execution are case
5308 statements (where a wild jump might result from an invalid value),
5309 and subscripts on the left hand side (where memory corruption could
5310 occur as a result of an invalid value).
5312 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5315 The @code{x} argument is a string of letters that
5316 indicate validity checks that are performed or not performed in addition
5317 to the default checks described above.
5320 The options allowed for this qualifier
5321 indicate validity checks that are performed or not performed in addition
5322 to the default checks described above.
5328 @emph{All validity checks.}
5329 @cindex @option{-gnatVa} (@command{gcc})
5330 All validity checks are turned on.
5332 That is, @option{-gnatVa} is
5333 equivalent to @option{gnatVcdfimorst}.
5337 @emph{Validity checks for copies.}
5338 @cindex @option{-gnatVc} (@command{gcc})
5339 The right hand side of assignments, and the initializing values of
5340 object declarations are validity checked.
5343 @emph{Default (RM) validity checks.}
5344 @cindex @option{-gnatVd} (@command{gcc})
5345 Some validity checks are done by default following normal Ada semantics
5347 A check is done in case statements that the expression is within the range
5348 of the subtype. If it is not, Constraint_Error is raised.
5349 For assignments to array components, a check is done that the expression used
5350 as index is within the range. If it is not, Constraint_Error is raised.
5351 Both these validity checks may be turned off using switch @option{-gnatVD}.
5352 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5353 switch @option{-gnatVd} will leave the checks turned on.
5354 Switch @option{-gnatVD} should be used only if you are sure that all such
5355 expressions have valid values. If you use this switch and invalid values
5356 are present, then the program is erroneous, and wild jumps or memory
5357 overwriting may occur.
5360 @emph{Validity checks for elementary components.}
5361 @cindex @option{-gnatVe} (@command{gcc})
5362 In the absence of this switch, assignments to record or array components are
5363 not validity checked, even if validity checks for assignments generally
5364 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5365 require valid data, but assignment of individual components does. So for
5366 example, there is a difference between copying the elements of an array with a
5367 slice assignment, compared to assigning element by element in a loop. This
5368 switch allows you to turn off validity checking for components, even when they
5369 are assigned component by component.
5372 @emph{Validity checks for floating-point values.}
5373 @cindex @option{-gnatVf} (@command{gcc})
5374 In the absence of this switch, validity checking occurs only for discrete
5375 values. If @option{-gnatVf} is specified, then validity checking also applies
5376 for floating-point values, and NaN's and infinities are considered invalid,
5377 as well as out of range values for constrained types. Note that this means
5378 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
5379 in which floating-point values are checked depends on the setting of other
5380 options. For example,
5381 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5382 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5383 (the order does not matter) specifies that floating-point parameters of mode
5384 @code{in} should be validity checked.
5387 @emph{Validity checks for @code{in} mode parameters}
5388 @cindex @option{-gnatVi} (@command{gcc})
5389 Arguments for parameters of mode @code{in} are validity checked in function
5390 and procedure calls at the point of call.
5393 @emph{Validity checks for @code{in out} mode parameters.}
5394 @cindex @option{-gnatVm} (@command{gcc})
5395 Arguments for parameters of mode @code{in out} are validity checked in
5396 procedure calls at the point of call. The @code{'m'} here stands for
5397 modify, since this concerns parameters that can be modified by the call.
5398 Note that there is no specific option to test @code{out} parameters,
5399 but any reference within the subprogram will be tested in the usual
5400 manner, and if an invalid value is copied back, any reference to it
5401 will be subject to validity checking.
5404 @emph{No validity checks.}
5405 @cindex @option{-gnatVn} (@command{gcc})
5406 This switch turns off all validity checking, including the default checking
5407 for case statements and left hand side subscripts. Note that the use of
5408 the switch @option{-gnatp} suppresses all run-time checks, including
5409 validity checks, and thus implies @option{-gnatVn}. When this switch
5410 is used, it cancels any other @option{-gnatV} previously issued.
5413 @emph{Validity checks for operator and attribute operands.}
5414 @cindex @option{-gnatVo} (@command{gcc})
5415 Arguments for predefined operators and attributes are validity checked.
5416 This includes all operators in package @code{Standard},
5417 the shift operators defined as intrinsic in package @code{Interfaces}
5418 and operands for attributes such as @code{Pos}. Checks are also made
5419 on individual component values for composite comparisons, and on the
5420 expressions in type conversions and qualified expressions. Checks are
5421 also made on explicit ranges using .. (e.g. slices, loops etc).
5424 @emph{Validity checks for parameters.}
5425 @cindex @option{-gnatVp} (@command{gcc})
5426 This controls the treatment of parameters within a subprogram (as opposed
5427 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5428 of parameters on a call. If either of these call options is used, then
5429 normally an assumption is made within a subprogram that the input arguments
5430 have been validity checking at the point of call, and do not need checking
5431 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5432 is not made, and parameters are not assumed to be valid, so their validity
5433 will be checked (or rechecked) within the subprogram.
5436 @emph{Validity checks for function returns.}
5437 @cindex @option{-gnatVr} (@command{gcc})
5438 The expression in @code{return} statements in functions is validity
5442 @emph{Validity checks for subscripts.}
5443 @cindex @option{-gnatVs} (@command{gcc})
5444 All subscripts expressions are checked for validity, whether they appear
5445 on the right side or left side (in default mode only left side subscripts
5446 are validity checked).
5449 @emph{Validity checks for tests.}
5450 @cindex @option{-gnatVt} (@command{gcc})
5451 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5452 statements are checked, as well as guard expressions in entry calls.
5457 The @option{-gnatV} switch may be followed by
5458 ^a string of letters^a list of options^
5459 to turn on a series of validity checking options.
5461 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5462 specifies that in addition to the default validity checking, copies and
5463 function return expressions are to be validity checked.
5464 In order to make it easier
5465 to specify the desired combination of effects,
5467 the upper case letters @code{CDFIMORST} may
5468 be used to turn off the corresponding lower case option.
5471 the prefix @code{NO} on an option turns off the corresponding validity
5474 @item @code{NOCOPIES}
5475 @item @code{NODEFAULT}
5476 @item @code{NOFLOATS}
5477 @item @code{NOIN_PARAMS}
5478 @item @code{NOMOD_PARAMS}
5479 @item @code{NOOPERANDS}
5480 @item @code{NORETURNS}
5481 @item @code{NOSUBSCRIPTS}
5482 @item @code{NOTESTS}
5486 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5487 turns on all validity checking options except for
5488 checking of @code{@b{in out}} procedure arguments.
5490 The specification of additional validity checking generates extra code (and
5491 in the case of @option{-gnatVa} the code expansion can be substantial.
5492 However, these additional checks can be very useful in detecting
5493 uninitialized variables, incorrect use of unchecked conversion, and other
5494 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5495 is useful in conjunction with the extra validity checking, since this
5496 ensures that wherever possible uninitialized variables have invalid values.
5498 See also the pragma @code{Validity_Checks} which allows modification of
5499 the validity checking mode at the program source level, and also allows for
5500 temporary disabling of validity checks.
5502 @node Style Checking
5503 @subsection Style Checking
5504 @findex Style checking
5507 The @option{-gnaty^x^(option,option,...)^} switch
5508 @cindex @option{-gnaty} (@command{gcc})
5509 causes the compiler to
5510 enforce specified style rules. A limited set of style rules has been used
5511 in writing the GNAT sources themselves. This switch allows user programs
5512 to activate all or some of these checks. If the source program fails a
5513 specified style check, an appropriate warning message is given, preceded by
5514 the character sequence ``(style)''.
5516 @code{(option,option,...)} is a sequence of keywords
5519 The string @var{x} is a sequence of letters or digits
5521 indicating the particular style
5522 checks to be performed. The following checks are defined:
5527 @emph{Specify indentation level.}
5528 If a digit from 1-9 appears
5529 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5530 then proper indentation is checked, with the digit indicating the
5531 indentation level required.
5532 The general style of required indentation is as specified by
5533 the examples in the Ada Reference Manual. Full line comments must be
5534 aligned with the @code{--} starting on a column that is a multiple of
5535 the alignment level.
5538 @emph{Check attribute casing.}
5539 If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty}
5540 then attribute names, including the case of keywords such as @code{digits}
5541 used as attributes names, must be written in mixed case, that is, the
5542 initial letter and any letter following an underscore must be uppercase.
5543 All other letters must be lowercase.
5546 @emph{Blanks not allowed at statement end.}
5547 If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then
5548 trailing blanks are not allowed at the end of statements. The purpose of this
5549 rule, together with h (no horizontal tabs), is to enforce a canonical format
5550 for the use of blanks to separate source tokens.
5553 @emph{Check comments.}
5554 If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty}
5555 then comments must meet the following set of rules:
5560 The ``@code{--}'' that starts the column must either start in column one,
5561 or else at least one blank must precede this sequence.
5564 Comments that follow other tokens on a line must have at least one blank
5565 following the ``@code{--}'' at the start of the comment.
5568 Full line comments must have two blanks following the ``@code{--}'' that
5569 starts the comment, with the following exceptions.
5572 A line consisting only of the ``@code{--}'' characters, possibly preceded
5573 by blanks is permitted.
5576 A comment starting with ``@code{--x}'' where @code{x} is a special character
5578 This allows proper processing of the output generated by specialized tools
5579 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5581 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5582 special character is defined as being in one of the ASCII ranges
5583 @code{16#21#..16#2F#} or @code{16#3A#..16#3F#}.
5584 Note that this usage is not permitted
5585 in GNAT implementation units (i.e. when @option{-gnatg} is used).
5588 A line consisting entirely of minus signs, possibly preceded by blanks, is
5589 permitted. This allows the construction of box comments where lines of minus
5590 signs are used to form the top and bottom of the box.
5593 A comment that starts and ends with ``@code{--}'' is permitted as long as at
5594 least one blank follows the initial ``@code{--}''. Together with the preceding
5595 rule, this allows the construction of box comments, as shown in the following
5598 ---------------------------
5599 -- This is a box comment --
5600 -- with two text lines. --
5601 ---------------------------
5605 @item ^d^DOS_LINE_ENDINGS^
5606 @emph{Check no DOS line terminators present.}
5607 If the ^letter d^word DOS_LINE_ENDINGS^ appears in the string after
5608 @option{-gnaty} then all lines must be terminated by a single ASCII.LF
5609 character (in particular the DOS line terminator sequence CR/LF is not
5613 @emph{Check end/exit labels.}
5614 If the ^letter e^word END^ appears in the string after @option{-gnaty} then
5615 optional labels on @code{end} statements ending subprograms and on
5616 @code{exit} statements exiting named loops, are required to be present.
5619 @emph{No form feeds or vertical tabs.}
5620 If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then
5621 neither form feeds nor vertical tab characters are permitted
5625 @emph{No horizontal tabs.}
5626 If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then
5627 horizontal tab characters are not permitted in the source text.
5628 Together with the b (no blanks at end of line) check, this
5629 enforces a canonical form for the use of blanks to separate
5633 @emph{Check if-then layout.}
5634 If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty},
5635 then the keyword @code{then} must appear either on the same
5636 line as corresponding @code{if}, or on a line on its own, lined
5637 up under the @code{if} with at least one non-blank line in between
5638 containing all or part of the condition to be tested.
5641 @emph{check mode IN keywords}
5642 If the ^letter I (upper case)^word IN_MODE^ appears in the string
5643 after @option{-gnaty} then mode @code{in} (the default mode) is not
5644 allowed to be given explicitly. @code{in out} is fine,
5645 but not @code{in} on its own.
5648 @emph{Check keyword casing.}
5649 If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then
5650 all keywords must be in lower case (with the exception of keywords
5651 such as @code{digits} used as attribute names to which this check
5655 @emph{Check layout.}
5656 If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then
5657 layout of statement and declaration constructs must follow the
5658 recommendations in the Ada Reference Manual, as indicated by the
5659 form of the syntax rules. For example an @code{else} keyword must
5660 be lined up with the corresponding @code{if} keyword.
5662 There are two respects in which the style rule enforced by this check
5663 option are more liberal than those in the Ada Reference Manual. First
5664 in the case of record declarations, it is permissible to put the
5665 @code{record} keyword on the same line as the @code{type} keyword, and
5666 then the @code{end} in @code{end record} must line up under @code{type}.
5667 For example, either of the following two layouts is acceptable:
5669 @smallexample @c ada
5685 Second, in the case of a block statement, a permitted alternative
5686 is to put the block label on the same line as the @code{declare} or
5687 @code{begin} keyword, and then line the @code{end} keyword up under
5688 the block label. For example both the following are permitted:
5690 @smallexample @c ada
5708 The same alternative format is allowed for loops. For example, both of
5709 the following are permitted:
5711 @smallexample @c ada
5713 Clear : while J < 10 loop
5724 @item ^Lnnn^MAX_NESTING=nnn^
5725 @emph{Set maximum nesting level}
5726 If the sequence ^Lnnn^MAX_NESTING=nnn^, where nnn is a decimal number in
5727 the range 0-999, appears in the string after @option{-gnaty} then the
5728 maximum level of nesting of constructs (including subprograms, loops,
5729 blocks, packages, and conditionals) may not exceed the given value. A
5730 value of zero disconnects this style check.
5732 @item ^m^LINE_LENGTH^
5733 @emph{Check maximum line length.}
5734 If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty}
5735 then the length of source lines must not exceed 79 characters, including
5736 any trailing blanks. The value of 79 allows convenient display on an
5737 80 character wide device or window, allowing for possible special
5738 treatment of 80 character lines. Note that this count is of
5739 characters in the source text. This means that a tab character counts
5740 as one character in this count but a wide character sequence counts as
5741 a single character (however many bytes are needed in the encoding).
5743 @item ^Mnnn^MAX_LENGTH=nnn^
5744 @emph{Set maximum line length.}
5745 If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in
5746 the string after @option{-gnaty} then the length of lines must not exceed the
5747 given value. The maximum value that can be specified is 32767.
5749 @item ^n^STANDARD_CASING^
5750 @emph{Check casing of entities in Standard.}
5751 If the ^letter n^word STANDARD_CASING^ appears in the string
5752 after @option{-gnaty} then any identifier from Standard must be cased
5753 to match the presentation in the Ada Reference Manual (for example,
5754 @code{Integer} and @code{ASCII.NUL}).
5756 @item ^o^ORDERED_SUBPROGRAMS^
5757 @emph{Check order of subprogram bodies.}
5758 If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string
5759 after @option{-gnaty} then all subprogram bodies in a given scope
5760 (e.g. a package body) must be in alphabetical order. The ordering
5761 rule uses normal Ada rules for comparing strings, ignoring casing
5762 of letters, except that if there is a trailing numeric suffix, then
5763 the value of this suffix is used in the ordering (e.g. Junk2 comes
5767 @emph{Check pragma casing.}
5768 If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then
5769 pragma names must be written in mixed case, that is, the
5770 initial letter and any letter following an underscore must be uppercase.
5771 All other letters must be lowercase.
5773 @item ^r^REFERENCES^
5774 @emph{Check references.}
5775 If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty}
5776 then all identifier references must be cased in the same way as the
5777 corresponding declaration. No specific casing style is imposed on
5778 identifiers. The only requirement is for consistency of references
5782 @emph{Check separate specs.}
5783 If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then
5784 separate declarations (``specs'') are required for subprograms (a
5785 body is not allowed to serve as its own declaration). The only
5786 exception is that parameterless library level procedures are
5787 not required to have a separate declaration. This exception covers
5788 the most frequent form of main program procedures.
5791 @emph{Check token spacing.}
5792 If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then
5793 the following token spacing rules are enforced:
5798 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
5801 The token @code{=>} must be surrounded by spaces.
5804 The token @code{<>} must be preceded by a space or a left parenthesis.
5807 Binary operators other than @code{**} must be surrounded by spaces.
5808 There is no restriction on the layout of the @code{**} binary operator.
5811 Colon must be surrounded by spaces.
5814 Colon-equal (assignment, initialization) must be surrounded by spaces.
5817 Comma must be the first non-blank character on the line, or be
5818 immediately preceded by a non-blank character, and must be followed
5822 If the token preceding a left parenthesis ends with a letter or digit, then
5823 a space must separate the two tokens.
5826 A right parenthesis must either be the first non-blank character on
5827 a line, or it must be preceded by a non-blank character.
5830 A semicolon must not be preceded by a space, and must not be followed by
5831 a non-blank character.
5834 A unary plus or minus may not be followed by a space.
5837 A vertical bar must be surrounded by spaces.
5840 @item ^u^UNNECESSARY_BLANK_LINES^
5841 @emph{Check unnecessary blank lines.}
5842 Check for unnecessary blank lines. A blank line is considered
5843 unnecessary if it appears at the end of the file, or if more than
5844 one blank line occurs in sequence.
5846 @item ^x^XTRA_PARENS^
5847 @emph{Check extra parentheses.}
5848 Check for the use of an unnecessary extra level of parentheses (C-style)
5849 around conditions in @code{if} statements, @code{while} statements and
5850 @code{exit} statements.
5855 In the above rules, appearing in column one is always permitted, that is,
5856 counts as meeting either a requirement for a required preceding space,
5857 or as meeting a requirement for no preceding space.
5859 Appearing at the end of a line is also always permitted, that is, counts
5860 as meeting either a requirement for a following space, or as meeting
5861 a requirement for no following space.
5864 If any of these style rules is violated, a message is generated giving
5865 details on the violation. The initial characters of such messages are
5866 always ``@code{(style)}''. Note that these messages are treated as warning
5867 messages, so they normally do not prevent the generation of an object
5868 file. The @option{-gnatwe} switch can be used to treat warning messages,
5869 including style messages, as fatal errors.
5873 @option{-gnaty} on its own (that is not
5874 followed by any letters or digits),
5875 is equivalent to @code{gnaty3abcefhiklmnprst}, that is all checking
5876 options enabled with the exception of @option{-gnatyo},
5877 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
5880 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
5881 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
5882 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
5884 an indentation level of 3 is set. This is similar to the standard
5885 checking option that is used for the GNAT sources.
5894 clears any previously set style checks.
5896 @node Run-Time Checks
5897 @subsection Run-Time Checks
5898 @cindex Division by zero
5899 @cindex Access before elaboration
5900 @cindex Checks, division by zero
5901 @cindex Checks, access before elaboration
5902 @cindex Checks, stack overflow checking
5905 If you compile with the default options, GNAT will insert many run-time
5906 checks into the compiled code, including code that performs range
5907 checking against constraints, but not arithmetic overflow checking for
5908 integer operations (including division by zero), checks for access
5909 before elaboration on subprogram calls, or stack overflow checking. All
5910 other run-time checks, as required by the Ada 95 Reference Manual, are
5911 generated by default. The following @command{gcc} switches refine this
5917 @cindex @option{-gnatp} (@command{gcc})
5918 @cindex Suppressing checks
5919 @cindex Checks, suppressing
5921 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
5922 had been present in the source. Validity checks are also suppressed (in
5923 other words @option{-gnatp} also implies @option{-gnatVn}.
5924 Use this switch to improve the performance
5925 of the code at the expense of safety in the presence of invalid data or
5929 @cindex @option{-gnato} (@command{gcc})
5930 @cindex Overflow checks
5931 @cindex Check, overflow
5932 Enables overflow checking for integer operations.
5933 This causes GNAT to generate slower and larger executable
5934 programs by adding code to check for overflow (resulting in raising
5935 @code{Constraint_Error} as required by standard Ada
5936 semantics). These overflow checks correspond to situations in which
5937 the true value of the result of an operation may be outside the base
5938 range of the result type. The following example shows the distinction:
5940 @smallexample @c ada
5941 X1 : Integer := Integer'Last;
5942 X2 : Integer range 1 .. 5 := 5;
5943 X3 : Integer := Integer'Last;
5944 X4 : Integer range 1 .. 5 := 5;
5945 F : Float := 2.0E+20;
5954 Here the first addition results in a value that is outside the base range
5955 of Integer, and hence requires an overflow check for detection of the
5956 constraint error. Thus the first assignment to @code{X1} raises a
5957 @code{Constraint_Error} exception only if @option{-gnato} is set.
5959 The second increment operation results in a violation
5960 of the explicit range constraint, and such range checks are always
5961 performed (unless specifically suppressed with a pragma @code{suppress}
5962 or the use of @option{-gnatp}).
5964 The two conversions of @code{F} both result in values that are outside
5965 the base range of type @code{Integer} and thus will raise
5966 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
5967 The fact that the result of the second conversion is assigned to
5968 variable @code{X4} with a restricted range is irrelevant, since the problem
5969 is in the conversion, not the assignment.
5971 Basically the rule is that in the default mode (@option{-gnato} not
5972 used), the generated code assures that all integer variables stay
5973 within their declared ranges, or within the base range if there is
5974 no declared range. This prevents any serious problems like indexes
5975 out of range for array operations.
5977 What is not checked in default mode is an overflow that results in
5978 an in-range, but incorrect value. In the above example, the assignments
5979 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
5980 range of the target variable, but the result is wrong in the sense that
5981 it is too large to be represented correctly. Typically the assignment
5982 to @code{X1} will result in wrap around to the largest negative number.
5983 The conversions of @code{F} will result in some @code{Integer} value
5984 and if that integer value is out of the @code{X4} range then the
5985 subsequent assignment would generate an exception.
5987 @findex Machine_Overflows
5988 Note that the @option{-gnato} switch does not affect the code generated
5989 for any floating-point operations; it applies only to integer
5991 For floating-point, GNAT has the @code{Machine_Overflows}
5992 attribute set to @code{False} and the normal mode of operation is to
5993 generate IEEE NaN and infinite values on overflow or invalid operations
5994 (such as dividing 0.0 by 0.0).
5996 The reason that we distinguish overflow checking from other kinds of
5997 range constraint checking is that a failure of an overflow check can
5998 generate an incorrect value, but cannot cause erroneous behavior. This
5999 is unlike the situation with a constraint check on an array subscript,
6000 where failure to perform the check can result in random memory description,
6001 or the range check on a case statement, where failure to perform the check
6002 can cause a wild jump.
6004 Note again that @option{-gnato} is off by default, so overflow checking is
6005 not performed in default mode. This means that out of the box, with the
6006 default settings, GNAT does not do all the checks expected from the
6007 language description in the Ada Reference Manual. If you want all constraint
6008 checks to be performed, as described in this Manual, then you must
6009 explicitly use the -gnato switch either on the @command{gnatmake} or
6010 @command{gcc} command.
6013 @cindex @option{-gnatE} (@command{gcc})
6014 @cindex Elaboration checks
6015 @cindex Check, elaboration
6016 Enables dynamic checks for access-before-elaboration
6017 on subprogram calls and generic instantiations.
6018 For full details of the effect and use of this switch,
6019 @xref{Compiling Using gcc}.
6022 @cindex @option{-fstack-check} (@command{gcc})
6023 @cindex Stack Overflow Checking
6024 @cindex Checks, stack overflow checking
6025 Activates stack overflow checking. For full details of the effect and use of
6026 this switch see @ref{Stack Overflow Checking}.
6031 The setting of these switches only controls the default setting of the
6032 checks. You may modify them using either @code{Suppress} (to remove
6033 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6036 @node Using gcc for Syntax Checking
6037 @subsection Using @command{gcc} for Syntax Checking
6040 @cindex @option{-gnats} (@command{gcc})
6044 The @code{s} stands for ``syntax''.
6047 Run GNAT in syntax checking only mode. For
6048 example, the command
6051 $ gcc -c -gnats x.adb
6055 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6056 series of files in a single command
6058 , and can use wild cards to specify such a group of files.
6059 Note that you must specify the @option{-c} (compile
6060 only) flag in addition to the @option{-gnats} flag.
6063 You may use other switches in conjunction with @option{-gnats}. In
6064 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6065 format of any generated error messages.
6067 When the source file is empty or contains only empty lines and/or comments,
6068 the output is a warning:
6071 $ gcc -c -gnats -x ada toto.txt
6072 toto.txt:1:01: warning: empty file, contains no compilation units
6076 Otherwise, the output is simply the error messages, if any. No object file or
6077 ALI file is generated by a syntax-only compilation. Also, no units other
6078 than the one specified are accessed. For example, if a unit @code{X}
6079 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6080 check only mode does not access the source file containing unit
6083 @cindex Multiple units, syntax checking
6084 Normally, GNAT allows only a single unit in a source file. However, this
6085 restriction does not apply in syntax-check-only mode, and it is possible
6086 to check a file containing multiple compilation units concatenated
6087 together. This is primarily used by the @code{gnatchop} utility
6088 (@pxref{Renaming Files Using gnatchop}).
6091 @node Using gcc for Semantic Checking
6092 @subsection Using @command{gcc} for Semantic Checking
6095 @cindex @option{-gnatc} (@command{gcc})
6099 The @code{c} stands for ``check''.
6101 Causes the compiler to operate in semantic check mode,
6102 with full checking for all illegalities specified in the
6103 Ada 95 Reference Manual, but without generation of any object code
6104 (no object file is generated).
6106 Because dependent files must be accessed, you must follow the GNAT
6107 semantic restrictions on file structuring to operate in this mode:
6111 The needed source files must be accessible
6112 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6115 Each file must contain only one compilation unit.
6118 The file name and unit name must match (@pxref{File Naming Rules}).
6121 The output consists of error messages as appropriate. No object file is
6122 generated. An @file{ALI} file is generated for use in the context of
6123 cross-reference tools, but this file is marked as not being suitable
6124 for binding (since no object file is generated).
6125 The checking corresponds exactly to the notion of
6126 legality in the Ada 95 Reference Manual.
6128 Any unit can be compiled in semantics-checking-only mode, including
6129 units that would not normally be compiled (subunits,
6130 and specifications where a separate body is present).
6133 @node Compiling Different Versions of Ada
6134 @subsection Compiling Different Versions of Ada
6136 @cindex Compatibility with Ada 83
6139 @cindex Ada 2005 mode
6141 GNAT is primarily an Ada 95 compiler, but the switches described in
6142 this section allow operation in Ada 83 compatibility mode, and also
6143 allow the use of a preliminary implementation of many of the expected
6144 new features in Ada 2005, the forthcoming new version of the standard.
6146 @item -gnat83 (Ada 83 Compatibility Mode)
6147 @cindex @option{-gnat83} (@command{gcc})
6148 @cindex ACVC, Ada 83 tests
6151 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
6152 specify that an Ada 83 program is to be compiled in Ada 83 mode. If you specify
6153 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
6154 where this can be done easily.
6155 It is not possible to guarantee this switch does a perfect
6156 job; for example, some subtle tests, such as are
6157 found in earlier ACVC tests (and that have been removed from the ACATS suite
6158 for Ada 95), might not compile correctly.
6159 Nevertheless, this switch may be useful in some circumstances, for example
6160 where, due to contractual reasons, legacy code needs to be maintained
6161 using only Ada 83 features.
6163 With few exceptions (most notably the need to use @code{<>} on
6164 @cindex Generic formal parameters
6165 unconstrained generic formal parameters, the use of the new Ada 95
6166 reserved words, and the use of packages
6167 with optional bodies), it is not necessary to use the
6168 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6169 exceptions, Ada 95 is upwardly compatible with Ada 83. This
6170 means that a correct Ada 83 program is usually also a correct Ada 95
6172 For further information, please refer to @ref{Compatibility and Porting Guide}.
6174 @item -gnat95 (Ada 95 mode)
6175 @cindex @option{-gnat95} (@command{gcc})
6178 GNAT is primarily an Ada 95 compiler, and all current releases of GNAT Pro
6179 compile in Ada 95 mode by default. Typically, Ada 95 is sufficiently upwards
6180 compatible with Ada 83, that legacy Ada 83 programs may be compiled using
6181 this default Ada95 mode without problems (see section above describing the
6182 use of @option{-gnat83} to run in Ada 83 mode).
6184 In Ada 95 mode, the use of Ada 2005 features will in general cause error
6185 messages or warnings. Some specialized releases of GNAT (notably the GPL
6186 edition) operate in Ada 2005 mode by default (see section below
6187 describing the use of @option{-gnat05} to run in Ada 2005 mode). For such
6188 versions the @option{-gnat95} switch may be used to enforce Ada 95 mode.
6189 This option also can be used to cancel the effect of a previous
6190 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6192 @item -gnat05 (Ada 2005 mode)
6193 @cindex @option{-gnat05} (@command{gcc})
6196 Although GNAT is primarily an Ada 95 compiler, it can be set to operate
6197 in Ada 2005 mode using this option. Although the new standard has not
6198 yet been issued (as of early 2005), many features have been discussed and
6199 approved in ``Ada Issues'' (AI's). For the text of these AI's, see
6200 @url{www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}. Included with GNAT
6201 releases is a file @file{features-ada0y} that describes the current set
6202 of implemented Ada 2005 features.
6204 If these features are used in Ada 95 mode (which is the normal default),
6205 then error messages or warnings may be
6206 generated, reflecting the fact that these new features are otherwise
6207 unauthorized extensions to Ada 95. The use of the @option{-gnat05}
6208 switch (or an equivalent pragma) causes these messages to be suppressed.
6210 Note that some specialized releases of GNAT (notably the GPL edition)
6211 have Ada 2005 mode on by default, and in such environments,
6212 the Ada 2005 features can be used freely without the use of switches.
6216 @node Character Set Control
6217 @subsection Character Set Control
6219 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6220 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6223 Normally GNAT recognizes the Latin-1 character set in source program
6224 identifiers, as described in the Ada 95 Reference Manual.
6226 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6227 single character ^^or word^ indicating the character set, as follows:
6231 ISO 8859-1 (Latin-1) identifiers
6234 ISO 8859-2 (Latin-2) letters allowed in identifiers
6237 ISO 8859-3 (Latin-3) letters allowed in identifiers
6240 ISO 8859-4 (Latin-4) letters allowed in identifiers
6243 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6246 ISO 8859-15 (Latin-9) letters allowed in identifiers
6249 IBM PC letters (code page 437) allowed in identifiers
6252 IBM PC letters (code page 850) allowed in identifiers
6254 @item ^f^FULL_UPPER^
6255 Full upper-half codes allowed in identifiers
6258 No upper-half codes allowed in identifiers
6261 Wide-character codes (that is, codes greater than 255)
6262 allowed in identifiers
6265 @xref{Foreign Language Representation}, for full details on the
6266 implementation of these character sets.
6268 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6269 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6270 Specify the method of encoding for wide characters.
6271 @var{e} is one of the following:
6276 Hex encoding (brackets coding also recognized)
6279 Upper half encoding (brackets encoding also recognized)
6282 Shift/JIS encoding (brackets encoding also recognized)
6285 EUC encoding (brackets encoding also recognized)
6288 UTF-8 encoding (brackets encoding also recognized)
6291 Brackets encoding only (default value)
6293 For full details on these encoding
6294 methods see @ref{Wide Character Encodings}.
6295 Note that brackets coding is always accepted, even if one of the other
6296 options is specified, so for example @option{-gnatW8} specifies that both
6297 brackets and @code{UTF-8} encodings will be recognized. The units that are
6298 with'ed directly or indirectly will be scanned using the specified
6299 representation scheme, and so if one of the non-brackets scheme is
6300 used, it must be used consistently throughout the program. However,
6301 since brackets encoding is always recognized, it may be conveniently
6302 used in standard libraries, allowing these libraries to be used with
6303 any of the available coding schemes.
6304 scheme. If no @option{-gnatW?} parameter is present, then the default
6305 representation is Brackets encoding only.
6307 Note that the wide character representation that is specified (explicitly
6308 or by default) for the main program also acts as the default encoding used
6309 for Wide_Text_IO files if not specifically overridden by a WCEM form
6313 @node File Naming Control
6314 @subsection File Naming Control
6317 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6318 @cindex @option{-gnatk} (@command{gcc})
6319 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6320 1-999, indicates the maximum allowable length of a file name (not
6321 including the @file{.ads} or @file{.adb} extension). The default is not
6322 to enable file name krunching.
6324 For the source file naming rules, @xref{File Naming Rules}.
6327 @node Subprogram Inlining Control
6328 @subsection Subprogram Inlining Control
6333 @cindex @option{-gnatn} (@command{gcc})
6335 The @code{n} here is intended to suggest the first syllable of the
6338 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6339 inlining to actually occur, optimization must be enabled. To enable
6340 inlining of subprograms specified by pragma @code{Inline},
6341 you must also specify this switch.
6342 In the absence of this switch, GNAT does not attempt
6343 inlining and does not need to access the bodies of
6344 subprograms for which @code{pragma Inline} is specified if they are not
6345 in the current unit.
6347 If you specify this switch the compiler will access these bodies,
6348 creating an extra source dependency for the resulting object file, and
6349 where possible, the call will be inlined.
6350 For further details on when inlining is possible
6351 see @ref{Inlining of Subprograms}.
6354 @cindex @option{-gnatN} (@command{gcc})
6355 The front end inlining activated by this switch is generally more extensive,
6356 and quite often more effective than the standard @option{-gnatn} inlining mode.
6357 It will also generate additional dependencies.
6359 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
6360 to specify both options.
6363 @node Auxiliary Output Control
6364 @subsection Auxiliary Output Control
6368 @cindex @option{-gnatt} (@command{gcc})
6369 @cindex Writing internal trees
6370 @cindex Internal trees, writing to file
6371 Causes GNAT to write the internal tree for a unit to a file (with the
6372 extension @file{.adt}.
6373 This not normally required, but is used by separate analysis tools.
6375 these tools do the necessary compilations automatically, so you should
6376 not have to specify this switch in normal operation.
6379 @cindex @option{-gnatu} (@command{gcc})
6380 Print a list of units required by this compilation on @file{stdout}.
6381 The listing includes all units on which the unit being compiled depends
6382 either directly or indirectly.
6385 @item -pass-exit-codes
6386 @cindex @option{-pass-exit-codes} (@command{gcc})
6387 If this switch is not used, the exit code returned by @command{gcc} when
6388 compiling multiple files indicates whether all source files have
6389 been successfully used to generate object files or not.
6391 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
6392 exit status and allows an integrated development environment to better
6393 react to a compilation failure. Those exit status are:
6397 There was an error in at least one source file.
6399 At least one source file did not generate an object file.
6401 The compiler died unexpectedly (internal error for example).
6403 An object file has been generated for every source file.
6408 @node Debugging Control
6409 @subsection Debugging Control
6413 @cindex Debugging options
6416 @cindex @option{-gnatd} (@command{gcc})
6417 Activate internal debugging switches. @var{x} is a letter or digit, or
6418 string of letters or digits, which specifies the type of debugging
6419 outputs desired. Normally these are used only for internal development
6420 or system debugging purposes. You can find full documentation for these
6421 switches in the body of the @code{Debug} unit in the compiler source
6422 file @file{debug.adb}.
6426 @cindex @option{-gnatG} (@command{gcc})
6427 This switch causes the compiler to generate auxiliary output containing
6428 a pseudo-source listing of the generated expanded code. Like most Ada
6429 compilers, GNAT works by first transforming the high level Ada code into
6430 lower level constructs. For example, tasking operations are transformed
6431 into calls to the tasking run-time routines. A unique capability of GNAT
6432 is to list this expanded code in a form very close to normal Ada source.
6433 This is very useful in understanding the implications of various Ada
6434 usage on the efficiency of the generated code. There are many cases in
6435 Ada (e.g. the use of controlled types), where simple Ada statements can
6436 generate a lot of run-time code. By using @option{-gnatG} you can identify
6437 these cases, and consider whether it may be desirable to modify the coding
6438 approach to improve efficiency.
6440 The format of the output is very similar to standard Ada source, and is
6441 easily understood by an Ada programmer. The following special syntactic
6442 additions correspond to low level features used in the generated code that
6443 do not have any exact analogies in pure Ada source form. The following
6444 is a partial list of these special constructions. See the specification
6445 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6447 If the switch @option{-gnatL} is used in conjunction with
6448 @cindex @option{-gnatL} (@command{gcc})
6449 @option{-gnatG}, then the original source lines are interspersed
6450 in the expanded source (as comment lines with the original line number).
6453 @item new @var{xxx} [storage_pool = @var{yyy}]
6454 Shows the storage pool being used for an allocator.
6456 @item at end @var{procedure-name};
6457 Shows the finalization (cleanup) procedure for a scope.
6459 @item (if @var{expr} then @var{expr} else @var{expr})
6460 Conditional expression equivalent to the @code{x?y:z} construction in C.
6462 @item @var{target}^^^(@var{source})
6463 A conversion with floating-point truncation instead of rounding.
6465 @item @var{target}?(@var{source})
6466 A conversion that bypasses normal Ada semantic checking. In particular
6467 enumeration types and fixed-point types are treated simply as integers.
6469 @item @var{target}?^^^(@var{source})
6470 Combines the above two cases.
6472 @item @var{x} #/ @var{y}
6473 @itemx @var{x} #mod @var{y}
6474 @itemx @var{x} #* @var{y}
6475 @itemx @var{x} #rem @var{y}
6476 A division or multiplication of fixed-point values which are treated as
6477 integers without any kind of scaling.
6479 @item free @var{expr} [storage_pool = @var{xxx}]
6480 Shows the storage pool associated with a @code{free} statement.
6482 @item [subtype or type declaration]
6483 Used to list an equivalent declaration for an internally generated
6484 type that is referenced elsewhere in the listing.
6486 @item freeze @var{type-name} [@var{actions}]
6487 Shows the point at which @var{type-name} is frozen, with possible
6488 associated actions to be performed at the freeze point.
6490 @item reference @var{itype}
6491 Reference (and hence definition) to internal type @var{itype}.
6493 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6494 Intrinsic function call.
6496 @item @var{label-name} : label
6497 Declaration of label @var{labelname}.
6499 @item #$ @var{subprogram-name}
6500 An implicit call to a run-time support routine
6501 (to meet the requirement of H.3.1(9) in a
6504 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
6505 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6506 @var{expr}, but handled more efficiently).
6508 @item [constraint_error]
6509 Raise the @code{Constraint_Error} exception.
6511 @item @var{expression}'reference
6512 A pointer to the result of evaluating @var{expression}.
6514 @item @var{target-type}!(@var{source-expression})
6515 An unchecked conversion of @var{source-expression} to @var{target-type}.
6517 @item [@var{numerator}/@var{denominator}]
6518 Used to represent internal real literals (that) have no exact
6519 representation in base 2-16 (for example, the result of compile time
6520 evaluation of the expression 1.0/27.0).
6524 @cindex @option{-gnatD} (@command{gcc})
6525 When used in conjunction with @option{-gnatG}, this switch causes
6526 the expanded source, as described above for
6527 @option{-gnatG} to be written to files with names
6528 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6529 instead of to the standard output file. For
6530 example, if the source file name is @file{hello.adb}, then a file
6531 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written. The debugging
6532 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
6533 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6534 you to do source level debugging using the generated code which is
6535 sometimes useful for complex code, for example to find out exactly
6536 which part of a complex construction raised an exception. This switch
6537 also suppress generation of cross-reference information (see
6538 @option{-gnatx}) since otherwise the cross-reference information
6539 would refer to the @file{^.dg^.DG^} file, which would cause
6540 confusion since this is not the original source file.
6542 Note that @option{-gnatD} actually implies @option{-gnatG}
6543 automatically, so it is not necessary to give both options.
6544 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6546 If the switch @option{-gnatL} is used in conjunction with
6547 @cindex @option{-gnatL} (@command{gcc})
6548 @option{-gnatDG}, then the original source lines are interspersed
6549 in the expanded source (as comment lines with the original line number).
6552 @item -gnatR[0|1|2|3[s]]
6553 @cindex @option{-gnatR} (@command{gcc})
6554 This switch controls output from the compiler of a listing showing
6555 representation information for declared types and objects. For
6556 @option{-gnatR0}, no information is output (equivalent to omitting
6557 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6558 so @option{-gnatR} with no parameter has the same effect), size and alignment
6559 information is listed for declared array and record types. For
6560 @option{-gnatR2}, size and alignment information is listed for all
6561 expressions for values that are computed at run time for
6562 variant records. These symbolic expressions have a mostly obvious
6563 format with #n being used to represent the value of the n'th
6564 discriminant. See source files @file{repinfo.ads/adb} in the
6565 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6566 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
6567 the output is to a file with the name @file{^file.rep^file_REP^} where
6568 file is the name of the corresponding source file.
6571 @item /REPRESENTATION_INFO
6572 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
6573 This qualifier controls output from the compiler of a listing showing
6574 representation information for declared types and objects. For
6575 @option{/REPRESENTATION_INFO=NONE}, no information is output
6576 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6577 @option{/REPRESENTATION_INFO} without option is equivalent to
6578 @option{/REPRESENTATION_INFO=ARRAYS}.
6579 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6580 information is listed for declared array and record types. For
6581 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6582 is listed for all expression information for values that are computed
6583 at run time for variant records. These symbolic expressions have a mostly
6584 obvious format with #n being used to represent the value of the n'th
6585 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6586 @code{GNAT} sources for full details on the format of
6587 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6588 If _FILE is added at the end of an option
6589 (e.g. @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6590 then the output is to a file with the name @file{file_REP} where
6591 file is the name of the corresponding source file.
6593 Note that it is possible for record components to have zero size. In
6594 this case, the component clause uses an obvious extension of permitted
6595 Ada syntax, for example @code{at 0 range 0 .. -1}.
6598 @cindex @option{-gnatS} (@command{gcc})
6599 The use of the switch @option{-gnatS} for an
6600 Ada compilation will cause the compiler to output a
6601 representation of package Standard in a form very
6602 close to standard Ada. It is not quite possible to
6603 do this entirely in standard Ada (since new
6604 numeric base types cannot be created in standard
6605 Ada), but the output is easily
6606 readable to any Ada programmer, and is useful to
6607 determine the characteristics of target dependent
6608 types in package Standard.
6611 @cindex @option{-gnatx} (@command{gcc})
6612 Normally the compiler generates full cross-referencing information in
6613 the @file{ALI} file. This information is used by a number of tools,
6614 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
6615 suppresses this information. This saves some space and may slightly
6616 speed up compilation, but means that these tools cannot be used.
6619 @node Exception Handling Control
6620 @subsection Exception Handling Control
6623 GNAT uses two methods for handling exceptions at run-time. The
6624 @code{setjmp/longjmp} method saves the context when entering
6625 a frame with an exception handler. Then when an exception is
6626 raised, the context can be restored immediately, without the
6627 need for tracing stack frames. This method provides very fast
6628 exception propagation, but introduces significant overhead for
6629 the use of exception handlers, even if no exception is raised.
6631 The other approach is called ``zero cost'' exception handling.
6632 With this method, the compiler builds static tables to describe
6633 the exception ranges. No dynamic code is required when entering
6634 a frame containing an exception handler. When an exception is
6635 raised, the tables are used to control a back trace of the
6636 subprogram invocation stack to locate the required exception
6637 handler. This method has considerably poorer performance for
6638 the propagation of exceptions, but there is no overhead for
6639 exception handlers if no exception is raised. Note that in this
6640 mode and in the context of mixed Ada and C/C++ programming,
6641 to propagate an exception through a C/C++ code, the C/C++ code
6642 must be compiled with the @option{-funwind-tables} GCC's
6645 The following switches can be used to control which of the
6646 two exception handling methods is used.
6652 @cindex @option{--RTS=sjlj} (@command{gnatmake})
6653 This switch causes the setjmp/longjmp run-time to be used
6654 for exception handling. If this is the default mechanism for the
6655 target (see below), then this has no effect. If the default
6656 mechanism for the target is zero cost exceptions, then
6657 this switch can be used to modify this default, and must be
6658 used for all units in the partition.
6659 This option is rarely used. One case in which it may be
6660 advantageous is if you have an application where exception
6661 raising is common and the overall performance of the
6662 application is improved by favoring exception propagation.
6665 @cindex @option{--RTS=zcx} (@command{gnatmake})
6666 @cindex Zero Cost Exceptions
6667 This switch causes the zero cost approach to be used
6668 for exception handling. If this is the default mechanism for the
6669 target (see below), then this has no effect. If the default
6670 mechanism for the target is setjmp/longjmp exceptions, then
6671 this switch can be used to modify this default, and must be
6672 used for all units in the partition.
6673 This option can only be used if the zero cost approach
6674 is available for the target in use (see below).
6678 The same option @option{--RTS} must be used both for @command{gcc}
6679 and @command{gnatbind}. Passing this option to @command{gnatmake}
6680 (@pxref{Switches for gnatmake}) will ensure the required consistency
6681 through the compilation and binding steps.
6683 The @code{setjmp/longjmp} approach is available on all targets, while
6684 the @code{zero cost} approach is available on selected targets.
6685 To determine whether zero cost exceptions can be used for a
6686 particular target, look at the private part of the file system.ads.
6687 Either @code{GCC_ZCX_Support} or @code{Front_End_ZCX_Support} must
6688 be True to use the zero cost approach. If both of these switches
6689 are set to False, this means that zero cost exception handling
6690 is not yet available for that target. The switch
6691 @code{ZCX_By_Default} indicates the default approach. If this
6692 switch is set to True, then the @code{zero cost} approach is
6695 @node Units to Sources Mapping Files
6696 @subsection Units to Sources Mapping Files
6700 @item -gnatem^^=^@var{path}
6701 @cindex @option{-gnatem} (@command{gcc})
6702 A mapping file is a way to communicate to the compiler two mappings:
6703 from unit names to file names (without any directory information) and from
6704 file names to path names (with full directory information). These mappings
6705 are used by the compiler to short-circuit the path search.
6707 The use of mapping files is not required for correct operation of the
6708 compiler, but mapping files can improve efficiency, particularly when
6709 sources are read over a slow network connection. In normal operation,
6710 you need not be concerned with the format or use of mapping files,
6711 and the @option{-gnatem} switch is not a switch that you would use
6712 explicitly. it is intended only for use by automatic tools such as
6713 @command{gnatmake} running under the project file facility. The
6714 description here of the format of mapping files is provided
6715 for completeness and for possible use by other tools.
6717 A mapping file is a sequence of sets of three lines. In each set,
6718 the first line is the unit name, in lower case, with ``@code{%s}''
6720 specifications and ``@code{%b}'' appended for bodies; the second line is the
6721 file name; and the third line is the path name.
6727 /gnat/project1/sources/main.2.ada
6730 When the switch @option{-gnatem} is specified, the compiler will create
6731 in memory the two mappings from the specified file. If there is any problem
6732 (non existent file, truncated file or duplicate entries), no mapping
6735 Several @option{-gnatem} switches may be specified; however, only the last
6736 one on the command line will be taken into account.
6738 When using a project file, @command{gnatmake} create a temporary mapping file
6739 and communicates it to the compiler using this switch.
6743 @node Integrated Preprocessing
6744 @subsection Integrated Preprocessing
6747 GNAT sources may be preprocessed immediately before compilation; the actual
6748 text of the source is not the text of the source file, but is derived from it
6749 through a process called preprocessing. Integrated preprocessing is specified
6750 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
6751 indicates, through a text file, the preprocessing data to be used.
6752 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
6755 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
6756 used when Integrated Preprocessing is used. The reason is that preprocessing
6757 with another Preprocessing Data file without changing the sources will
6758 not trigger recompilation without this switch.
6761 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
6762 always trigger recompilation for sources that are preprocessed,
6763 because @command{gnatmake} cannot compute the checksum of the source after
6767 The actual preprocessing function is described in details in section
6768 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
6769 preprocessing is triggered and parameterized.
6773 @item -gnatep=@var{file}
6774 @cindex @option{-gnatep} (@command{gcc})
6775 This switch indicates to the compiler the file name (without directory
6776 information) of the preprocessor data file to use. The preprocessor data file
6777 should be found in the source directories.
6780 A preprocessing data file is a text file with significant lines indicating
6781 how should be preprocessed either a specific source or all sources not
6782 mentioned in other lines. A significant line is a non empty, non comment line.
6783 Comments are similar to Ada comments.
6786 Each significant line starts with either a literal string or the character '*'.
6787 A literal string is the file name (without directory information) of the source
6788 to preprocess. A character '*' indicates the preprocessing for all the sources
6789 that are not specified explicitly on other lines (order of the lines is not
6790 significant). It is an error to have two lines with the same file name or two
6791 lines starting with the character '*'.
6794 After the file name or the character '*', another optional literal string
6795 indicating the file name of the definition file to be used for preprocessing
6796 (@pxref{Form of Definitions File}). The definition files are found by the
6797 compiler in one of the source directories. In some cases, when compiling
6798 a source in a directory other than the current directory, if the definition
6799 file is in the current directory, it may be necessary to add the current
6800 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
6801 the compiler would not find the definition file.
6804 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
6805 be found. Those ^switches^switches^ are:
6810 Causes both preprocessor lines and the lines deleted by
6811 preprocessing to be replaced by blank lines, preserving the line number.
6812 This ^switch^switch^ is always implied; however, if specified after @option{-c}
6813 it cancels the effect of @option{-c}.
6816 Causes both preprocessor lines and the lines deleted
6817 by preprocessing to be retained as comments marked
6818 with the special string ``@code{--! }''.
6820 @item -Dsymbol=value
6821 Define or redefine a symbol, associated with value. A symbol is an Ada
6822 identifier, or an Ada reserved word, with the exception of @code{if},
6823 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6824 @code{value} is either a literal string, an Ada identifier or any Ada reserved
6825 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
6826 same name defined in a definition file.
6829 Causes a sorted list of symbol names and values to be
6830 listed on the standard output file.
6833 Causes undefined symbols to be treated as having the value @code{FALSE}
6835 of a preprocessor test. In the absence of this option, an undefined symbol in
6836 a @code{#if} or @code{#elsif} test will be treated as an error.
6841 Examples of valid lines in a preprocessor data file:
6844 "toto.adb" "prep.def" -u
6845 -- preprocess "toto.adb", using definition file "prep.def",
6846 -- undefined symbol are False.
6849 -- preprocess all other sources without a definition file;
6850 -- suppressed lined are commented; symbol VERSION has the value V101.
6852 "titi.adb" "prep2.def" -s
6853 -- preprocess "titi.adb", using definition file "prep2.def";
6854 -- list all symbols with their values.
6857 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
6858 @cindex @option{-gnateD} (@command{gcc})
6859 Define or redefine a preprocessing symbol, associated with value. If no value
6860 is given on the command line, then the value of the symbol is @code{True}.
6861 A symbol is an identifier, following normal Ada (case-insensitive)
6862 rules for its syntax, and value is any sequence (including an empty sequence)
6863 of characters from the set (letters, digits, period, underline).
6864 Ada reserved words may be used as symbols, with the exceptions of @code{if},
6865 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6868 A symbol declared with this ^switch^switch^ on the command line replaces a
6869 symbol with the same name either in a definition file or specified with a
6870 ^switch^switch^ -D in the preprocessor data file.
6873 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
6877 @node Code Generation Control
6878 @subsection Code Generation Control
6882 The GCC technology provides a wide range of target dependent
6883 @option{-m} switches for controlling
6884 details of code generation with respect to different versions of
6885 architectures. This includes variations in instruction sets (e.g.
6886 different members of the power pc family), and different requirements
6887 for optimal arrangement of instructions (e.g. different members of
6888 the x86 family). The list of available @option{-m} switches may be
6889 found in the GCC documentation.
6891 Use of these @option{-m} switches may in some cases result in improved
6894 The GNAT Pro technology is tested and qualified without any
6895 @option{-m} switches,
6896 so generally the most reliable approach is to avoid the use of these
6897 switches. However, we generally expect most of these switches to work
6898 successfully with GNAT Pro, and many customers have reported successful
6899 use of these options.
6901 Our general advice is to avoid the use of @option{-m} switches unless
6902 special needs lead to requirements in this area. In particular,
6903 there is no point in using @option{-m} switches to improve performance
6904 unless you actually see a performance improvement.
6908 @subsection Return Codes
6909 @cindex Return Codes
6910 @cindex @option{/RETURN_CODES=VMS}
6913 On VMS, GNAT compiled programs return POSIX-style codes by default,
6914 e.g. @option{/RETURN_CODES=POSIX}.
6916 To enable VMS style return codes, use GNAT BIND and LINK with the option
6917 @option{/RETURN_CODES=VMS}. For example:
6920 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
6921 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
6925 Programs built with /RETURN_CODES=VMS are suitable to be called in
6926 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
6927 are suitable for spawning with appropriate GNAT RTL routines.
6931 @node Search Paths and the Run-Time Library (RTL)
6932 @section Search Paths and the Run-Time Library (RTL)
6935 With the GNAT source-based library system, the compiler must be able to
6936 find source files for units that are needed by the unit being compiled.
6937 Search paths are used to guide this process.
6939 The compiler compiles one source file whose name must be given
6940 explicitly on the command line. In other words, no searching is done
6941 for this file. To find all other source files that are needed (the most
6942 common being the specs of units), the compiler examines the following
6943 directories, in the following order:
6947 The directory containing the source file of the main unit being compiled
6948 (the file name on the command line).
6951 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
6952 @command{gcc} command line, in the order given.
6955 @findex ADA_PRJ_INCLUDE_FILE
6956 Each of the directories listed in the text file whose name is given
6957 by the @code{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
6960 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
6961 driver when project files are used. It should not normally be set
6965 @findex ADA_INCLUDE_PATH
6966 Each of the directories listed in the value of the
6967 @code{ADA_INCLUDE_PATH} ^environment variable^logical name^.
6969 Construct this value
6970 exactly as the @code{PATH} environment variable: a list of directory
6971 names separated by colons (semicolons when working with the NT version).
6974 Normally, define this value as a logical name containing a comma separated
6975 list of directory names.
6977 This variable can also be defined by means of an environment string
6978 (an argument to the HP C exec* set of functions).
6982 DEFINE ANOTHER_PATH FOO:[BAG]
6983 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
6986 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
6987 first, followed by the standard Ada 95
6988 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
6989 If this is not redefined, the user will obtain the HP Ada 83 IO packages
6990 (Text_IO, Sequential_IO, etc)
6991 instead of the Ada95 packages. Thus, in order to get the Ada 95
6992 packages by default, ADA_INCLUDE_PATH must be redefined.
6996 The content of the @file{ada_source_path} file which is part of the GNAT
6997 installation tree and is used to store standard libraries such as the
6998 GNAT Run Time Library (RTL) source files.
7000 @ref{Installing a library}
7005 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7006 inhibits the use of the directory
7007 containing the source file named in the command line. You can still
7008 have this directory on your search path, but in this case it must be
7009 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7011 Specifying the switch @option{-nostdinc}
7012 inhibits the search of the default location for the GNAT Run Time
7013 Library (RTL) source files.
7015 The compiler outputs its object files and ALI files in the current
7018 Caution: The object file can be redirected with the @option{-o} switch;
7019 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7020 so the @file{ALI} file will not go to the right place. Therefore, you should
7021 avoid using the @option{-o} switch.
7025 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7026 children make up the GNAT RTL, together with the simple @code{System.IO}
7027 package used in the @code{"Hello World"} example. The sources for these units
7028 are needed by the compiler and are kept together in one directory. Not
7029 all of the bodies are needed, but all of the sources are kept together
7030 anyway. In a normal installation, you need not specify these directory
7031 names when compiling or binding. Either the environment variables or
7032 the built-in defaults cause these files to be found.
7034 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7035 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7036 consisting of child units of @code{GNAT}. This is a collection of generally
7037 useful types, subprograms, etc. See the @cite{GNAT Reference Manual} for
7040 Besides simplifying access to the RTL, a major use of search paths is
7041 in compiling sources from multiple directories. This can make
7042 development environments much more flexible.
7044 @node Order of Compilation Issues
7045 @section Order of Compilation Issues
7048 If, in our earlier example, there was a spec for the @code{hello}
7049 procedure, it would be contained in the file @file{hello.ads}; yet this
7050 file would not have to be explicitly compiled. This is the result of the
7051 model we chose to implement library management. Some of the consequences
7052 of this model are as follows:
7056 There is no point in compiling specs (except for package
7057 specs with no bodies) because these are compiled as needed by clients. If
7058 you attempt a useless compilation, you will receive an error message.
7059 It is also useless to compile subunits because they are compiled as needed
7063 There are no order of compilation requirements: performing a
7064 compilation never obsoletes anything. The only way you can obsolete
7065 something and require recompilations is to modify one of the
7066 source files on which it depends.
7069 There is no library as such, apart from the ALI files
7070 (@pxref{The Ada Library Information Files}, for information on the format
7071 of these files). For now we find it convenient to create separate ALI files,
7072 but eventually the information therein may be incorporated into the object
7076 When you compile a unit, the source files for the specs of all units
7077 that it @code{with}'s, all its subunits, and the bodies of any generics it
7078 instantiates must be available (reachable by the search-paths mechanism
7079 described above), or you will receive a fatal error message.
7086 The following are some typical Ada compilation command line examples:
7089 @item $ gcc -c xyz.adb
7090 Compile body in file @file{xyz.adb} with all default options.
7093 @item $ gcc -c -O2 -gnata xyz-def.adb
7096 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7099 Compile the child unit package in file @file{xyz-def.adb} with extensive
7100 optimizations, and pragma @code{Assert}/@code{Debug} statements
7103 @item $ gcc -c -gnatc abc-def.adb
7104 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7108 @node Binding Using gnatbind
7109 @chapter Binding Using @code{gnatbind}
7113 * Running gnatbind::
7114 * Switches for gnatbind::
7115 * Command-Line Access::
7116 * Search Paths for gnatbind::
7117 * Examples of gnatbind Usage::
7121 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7122 to bind compiled GNAT objects. The @code{gnatbind} program performs
7123 four separate functions:
7127 Checks that a program is consistent, in accordance with the rules in
7128 Chapter 10 of the Ada 95 Reference Manual. In particular, error
7129 messages are generated if a program uses inconsistent versions of a
7133 Checks that an acceptable order of elaboration exists for the program
7134 and issues an error message if it cannot find an order of elaboration
7135 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
7138 Generates a main program incorporating the given elaboration order.
7139 This program is a small Ada package (body and spec) that
7140 must be subsequently compiled
7141 using the GNAT compiler. The necessary compilation step is usually
7142 performed automatically by @command{gnatlink}. The two most important
7143 functions of this program
7144 are to call the elaboration routines of units in an appropriate order
7145 and to call the main program.
7148 Determines the set of object files required by the given main program.
7149 This information is output in the forms of comments in the generated program,
7150 to be read by the @command{gnatlink} utility used to link the Ada application.
7153 @node Running gnatbind
7154 @section Running @code{gnatbind}
7157 The form of the @code{gnatbind} command is
7160 $ gnatbind [@i{switches}] @i{mainprog}[.ali] [@i{switches}]
7164 where @file{@i{mainprog}.adb} is the Ada file containing the main program
7165 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
7166 package in two files whose names are
7167 @file{b~@i{mainprog}.ads}, and @file{b~@i{mainprog}.adb}.
7168 For example, if given the
7169 parameter @file{hello.ali}, for a main program contained in file
7170 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7171 and @file{b~hello.adb}.
7173 When doing consistency checking, the binder takes into consideration
7174 any source files it can locate. For example, if the binder determines
7175 that the given main program requires the package @code{Pack}, whose
7177 file is @file{pack.ali} and whose corresponding source spec file is
7178 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7179 (using the same search path conventions as previously described for the
7180 @command{gcc} command). If it can locate this source file, it checks that
7182 or source checksums of the source and its references to in @file{ALI} files
7183 match. In other words, any @file{ALI} files that mentions this spec must have
7184 resulted from compiling this version of the source file (or in the case
7185 where the source checksums match, a version close enough that the
7186 difference does not matter).
7188 @cindex Source files, use by binder
7189 The effect of this consistency checking, which includes source files, is
7190 that the binder ensures that the program is consistent with the latest
7191 version of the source files that can be located at bind time. Editing a
7192 source file without compiling files that depend on the source file cause
7193 error messages to be generated by the binder.
7195 For example, suppose you have a main program @file{hello.adb} and a
7196 package @code{P}, from file @file{p.ads} and you perform the following
7201 Enter @code{gcc -c hello.adb} to compile the main program.
7204 Enter @code{gcc -c p.ads} to compile package @code{P}.
7207 Edit file @file{p.ads}.
7210 Enter @code{gnatbind hello}.
7214 At this point, the file @file{p.ali} contains an out-of-date time stamp
7215 because the file @file{p.ads} has been edited. The attempt at binding
7216 fails, and the binder generates the following error messages:
7219 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7220 error: "p.ads" has been modified and must be recompiled
7224 Now both files must be recompiled as indicated, and then the bind can
7225 succeed, generating a main program. You need not normally be concerned
7226 with the contents of this file, but for reference purposes a sample
7227 binder output file is given in @ref{Example of Binder Output File}.
7229 In most normal usage, the default mode of @command{gnatbind} which is to
7230 generate the main package in Ada, as described in the previous section.
7231 In particular, this means that any Ada programmer can read and understand
7232 the generated main program. It can also be debugged just like any other
7233 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7234 @command{gnatbind} and @command{gnatlink}.
7236 However for some purposes it may be convenient to generate the main
7237 program in C rather than Ada. This may for example be helpful when you
7238 are generating a mixed language program with the main program in C. The
7239 GNAT compiler itself is an example.
7240 The use of the @option{^-C^/BIND_FILE=C^} switch
7241 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7242 be generated in C (and compiled using the gnu C compiler).
7244 @node Switches for gnatbind
7245 @section Switches for @command{gnatbind}
7248 The following switches are available with @code{gnatbind}; details will
7249 be presented in subsequent sections.
7252 * Consistency-Checking Modes::
7253 * Binder Error Message Control::
7254 * Elaboration Control::
7256 * Binding with Non-Ada Main Programs::
7257 * Binding Programs with No Main Subprogram::
7262 @item ^-aO^/OBJECT_SEARCH^
7263 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7264 Specify directory to be searched for ALI files.
7266 @item ^-aI^/SOURCE_SEARCH^
7267 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7268 Specify directory to be searched for source file.
7270 @item ^-A^/BIND_FILE=ADA^
7271 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
7272 Generate binder program in Ada (default)
7274 @item ^-b^/REPORT_ERRORS=BRIEF^
7275 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
7276 Generate brief messages to @file{stderr} even if verbose mode set.
7278 @item ^-c^/NOOUTPUT^
7279 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
7280 Check only, no generation of binder output file.
7282 @item ^-C^/BIND_FILE=C^
7283 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
7284 Generate binder program in C
7286 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}[k|m]
7287 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}[k|m]} (@command{gnatbind})
7288 This switch can be used to change the default task stack size value
7289 to a specified size @var{nn}, which is expressed in bytes by default, or
7290 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7292 In the absence of a [k|m] suffix, this switch is equivalent, in effect,
7293 to completing all task specs with
7294 @smallexample @c ada
7295 pragma Storage_Size (nn);
7297 When they do not already have such a pragma.
7299 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}[k|m]
7300 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
7301 This switch can be used to change the default secondary stack size value
7302 to a specified size @var{nn}, which is expressed in bytes by default, or
7303 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7306 The secondary stack is used to deal with functions that return a variable
7307 sized result, for example a function returning an unconstrained
7308 String. There are two ways in which this secondary stack is allocated.
7310 For most targets, the secondary stack is growing on demand and is allocated
7311 as a chain of blocks in the heap. The -D option is not very
7312 relevant. It only give some control over the size of the allocated
7313 blocks (whose size is the minimum of the default secondary stack size value,
7314 and the actual size needed for the current allocation request).
7316 For certain targets, notably VxWorks 653,
7317 the secondary stack is allocated by carving off a fixed ratio chunk of the
7318 primary task stack. The -D option is used to defined the
7319 size of the environment task's secondary stack.
7321 @item ^-e^/ELABORATION_DEPENDENCIES^
7322 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
7323 Output complete list of elaboration-order dependencies.
7325 @item ^-E^/STORE_TRACEBACKS^
7326 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
7327 Store tracebacks in exception occurrences when the target supports it.
7328 This is the default with the zero cost exception mechanism.
7330 @c The following may get moved to an appendix
7331 This option is currently supported on the following targets:
7332 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
7334 See also the packages @code{GNAT.Traceback} and
7335 @code{GNAT.Traceback.Symbolic} for more information.
7337 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
7338 @command{gcc} option.
7341 @item ^-F^/FORCE_ELABS_FLAGS^
7342 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
7343 Force the checks of elaboration flags. @command{gnatbind} does not normally
7344 generate checks of elaboration flags for the main executable, except when
7345 a Stand-Alone Library is used. However, there are cases when this cannot be
7346 detected by gnatbind. An example is importing an interface of a Stand-Alone
7347 Library through a pragma Import and only specifying through a linker switch
7348 this Stand-Alone Library. This switch is used to guarantee that elaboration
7349 flag checks are generated.
7352 @cindex @option{^-h^/HELP^} (@command{gnatbind})
7353 Output usage (help) information
7356 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7357 Specify directory to be searched for source and ALI files.
7359 @item ^-I-^/NOCURRENT_DIRECTORY^
7360 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
7361 Do not look for sources in the current directory where @code{gnatbind} was
7362 invoked, and do not look for ALI files in the directory containing the
7363 ALI file named in the @code{gnatbind} command line.
7365 @item ^-l^/ORDER_OF_ELABORATION^
7366 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
7367 Output chosen elaboration order.
7369 @item ^-Lxxx^/BUILD_LIBRARY=xxx^
7370 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
7371 Bind the units for library building. In this case the adainit and
7372 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
7373 are renamed to ^xxxinit^XXXINIT^ and
7374 ^xxxfinal^XXXFINAL^.
7375 Implies ^-n^/NOCOMPILE^.
7377 (@xref{GNAT and Libraries}, for more details.)
7380 On OpenVMS, these init and final procedures are exported in uppercase
7381 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
7382 the init procedure will be "TOTOINIT" and the exported name of the final
7383 procedure will be "TOTOFINAL".
7386 @item ^-Mxyz^/RENAME_MAIN=xyz^
7387 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
7388 Rename generated main program from main to xyz. This option is
7389 supported on cross environments only.
7391 @item ^-m^/ERROR_LIMIT=^@var{n}
7392 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
7393 Limit number of detected errors to @var{n}, where @var{n} is
7394 in the range 1..999_999. The default value if no switch is
7395 given is 9999. Binding is terminated if the limit is exceeded.
7397 Furthermore, under Windows, the sources pointed to by the libraries path
7398 set in the registry are not searched for.
7402 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7406 @cindex @option{-nostdinc} (@command{gnatbind})
7407 Do not look for sources in the system default directory.
7410 @cindex @option{-nostdlib} (@command{gnatbind})
7411 Do not look for library files in the system default directory.
7413 @item --RTS=@var{rts-path}
7414 @cindex @option{--RTS} (@code{gnatbind})
7415 Specifies the default location of the runtime library. Same meaning as the
7416 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
7418 @item ^-o ^/OUTPUT=^@var{file}
7419 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7420 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7421 Note that if this option is used, then linking must be done manually,
7422 gnatlink cannot be used.
7424 @item ^-O^/OBJECT_LIST^
7425 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7428 @item ^-p^/PESSIMISTIC_ELABORATION^
7429 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7430 Pessimistic (worst-case) elaboration order
7432 @item ^-s^/READ_SOURCES=ALL^
7433 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7434 Require all source files to be present.
7436 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7437 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7438 Specifies the value to be used when detecting uninitialized scalar
7439 objects with pragma Initialize_Scalars.
7440 The @var{xxx} ^string specified with the switch^option^ may be either
7442 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7443 @item ``@option{^lo^LOW^}'' for the lowest possible value
7444 @item ``@option{^hi^HIGH^}'' for the highest possible value
7445 @item ``@option{xx}'' for a value consisting of repeated bytes with the
7446 value 16#xx# (i.e. xx is a string of two hexadecimal digits).
7449 In addition, you can specify @option{-Sev} to indicate that the value is
7450 to be set at run time. In this case, the program will look for an environment
7451 @cindex GNAT_INIT_SCALARS
7452 variable of the form @code{GNAT_INIT_SCALARS=xx}, where xx is one
7453 of @option{in/lo/hi/xx} with the same meanings as above.
7454 If no environment variable is found, or if it does not have a valid value,
7455 then the default is @option{in} (invalid values).
7459 @cindex @option{-static} (@code{gnatbind})
7460 Link against a static GNAT run time.
7463 @cindex @option{-shared} (@code{gnatbind})
7464 Link against a shared GNAT run time when available.
7467 @item ^-t^/NOTIME_STAMP_CHECK^
7468 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7469 Tolerate time stamp and other consistency errors
7471 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7472 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7473 Set the time slice value to @var{n} milliseconds. If the system supports
7474 the specification of a specific time slice value, then the indicated value
7475 is used. If the system does not support specific time slice values, but
7476 does support some general notion of round-robin scheduling, then any
7477 nonzero value will activate round-robin scheduling.
7479 A value of zero is treated specially. It turns off time
7480 slicing, and in addition, indicates to the tasking run time that the
7481 semantics should match as closely as possible the Annex D
7482 requirements of the Ada RM, and in particular sets the default
7483 scheduling policy to @code{FIFO_Within_Priorities}.
7485 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
7486 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
7487 Enable dynamic stack usage, with n result stored and displayed at program
7488 termination. Results that can't be stored are displayed on the fly, at task
7489 termination. This option is currently not supported on OpenVMS I64 platforms.
7491 @item ^-v^/REPORT_ERRORS=VERBOSE^
7492 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7493 Verbose mode. Write error messages, header, summary output to
7498 @cindex @option{-w} (@code{gnatbind})
7499 Warning mode (@var{x}=s/e for suppress/treat as error)
7503 @item /WARNINGS=NORMAL
7504 @cindex @option{/WARNINGS} (@code{gnatbind})
7505 Normal warnings mode. Warnings are issued but ignored
7507 @item /WARNINGS=SUPPRESS
7508 @cindex @option{/WARNINGS} (@code{gnatbind})
7509 All warning messages are suppressed
7511 @item /WARNINGS=ERROR
7512 @cindex @option{/WARNINGS} (@code{gnatbind})
7513 Warning messages are treated as fatal errors
7516 @item ^-x^/READ_SOURCES=NONE^
7517 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7518 Exclude source files (check object consistency only).
7521 @item /READ_SOURCES=AVAILABLE
7522 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7523 Default mode, in which sources are checked for consistency only if
7527 @item ^-z^/ZERO_MAIN^
7528 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7534 You may obtain this listing of switches by running @code{gnatbind} with
7538 @node Consistency-Checking Modes
7539 @subsection Consistency-Checking Modes
7542 As described earlier, by default @code{gnatbind} checks
7543 that object files are consistent with one another and are consistent
7544 with any source files it can locate. The following switches control binder
7549 @item ^-s^/READ_SOURCES=ALL^
7550 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
7551 Require source files to be present. In this mode, the binder must be
7552 able to locate all source files that are referenced, in order to check
7553 their consistency. In normal mode, if a source file cannot be located it
7554 is simply ignored. If you specify this switch, a missing source
7557 @item ^-x^/READ_SOURCES=NONE^
7558 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
7559 Exclude source files. In this mode, the binder only checks that ALI
7560 files are consistent with one another. Source files are not accessed.
7561 The binder runs faster in this mode, and there is still a guarantee that
7562 the resulting program is self-consistent.
7563 If a source file has been edited since it was last compiled, and you
7564 specify this switch, the binder will not detect that the object
7565 file is out of date with respect to the source file. Note that this is the
7566 mode that is automatically used by @command{gnatmake} because in this
7567 case the checking against sources has already been performed by
7568 @command{gnatmake} in the course of compilation (i.e. before binding).
7571 @item /READ_SOURCES=AVAILABLE
7572 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
7573 This is the default mode in which source files are checked if they are
7574 available, and ignored if they are not available.
7578 @node Binder Error Message Control
7579 @subsection Binder Error Message Control
7582 The following switches provide control over the generation of error
7583 messages from the binder:
7587 @item ^-v^/REPORT_ERRORS=VERBOSE^
7588 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7589 Verbose mode. In the normal mode, brief error messages are generated to
7590 @file{stderr}. If this switch is present, a header is written
7591 to @file{stdout} and any error messages are directed to @file{stdout}.
7592 All that is written to @file{stderr} is a brief summary message.
7594 @item ^-b^/REPORT_ERRORS=BRIEF^
7595 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
7596 Generate brief error messages to @file{stderr} even if verbose mode is
7597 specified. This is relevant only when used with the
7598 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
7602 @cindex @option{-m} (@code{gnatbind})
7603 Limits the number of error messages to @var{n}, a decimal integer in the
7604 range 1-999. The binder terminates immediately if this limit is reached.
7607 @cindex @option{-M} (@code{gnatbind})
7608 Renames the generated main program from @code{main} to @code{xxx}.
7609 This is useful in the case of some cross-building environments, where
7610 the actual main program is separate from the one generated
7614 @item ^-ws^/WARNINGS=SUPPRESS^
7615 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
7617 Suppress all warning messages.
7619 @item ^-we^/WARNINGS=ERROR^
7620 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
7621 Treat any warning messages as fatal errors.
7624 @item /WARNINGS=NORMAL
7625 Standard mode with warnings generated, but warnings do not get treated
7629 @item ^-t^/NOTIME_STAMP_CHECK^
7630 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7631 @cindex Time stamp checks, in binder
7632 @cindex Binder consistency checks
7633 @cindex Consistency checks, in binder
7634 The binder performs a number of consistency checks including:
7638 Check that time stamps of a given source unit are consistent
7640 Check that checksums of a given source unit are consistent
7642 Check that consistent versions of @code{GNAT} were used for compilation
7644 Check consistency of configuration pragmas as required
7648 Normally failure of such checks, in accordance with the consistency
7649 requirements of the Ada Reference Manual, causes error messages to be
7650 generated which abort the binder and prevent the output of a binder
7651 file and subsequent link to obtain an executable.
7653 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
7654 into warnings, so that
7655 binding and linking can continue to completion even in the presence of such
7656 errors. The result may be a failed link (due to missing symbols), or a
7657 non-functional executable which has undefined semantics.
7658 @emph{This means that
7659 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
7663 @node Elaboration Control
7664 @subsection Elaboration Control
7667 The following switches provide additional control over the elaboration
7668 order. For full details see @ref{Elaboration Order Handling in GNAT}.
7671 @item ^-p^/PESSIMISTIC_ELABORATION^
7672 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
7673 Normally the binder attempts to choose an elaboration order that is
7674 likely to minimize the likelihood of an elaboration order error resulting
7675 in raising a @code{Program_Error} exception. This switch reverses the
7676 action of the binder, and requests that it deliberately choose an order
7677 that is likely to maximize the likelihood of an elaboration error.
7678 This is useful in ensuring portability and avoiding dependence on
7679 accidental fortuitous elaboration ordering.
7681 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
7683 elaboration checking is used (@option{-gnatE} switch used for compilation).
7684 This is because in the default static elaboration mode, all necessary
7685 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
7686 These implicit pragmas are still respected by the binder in
7687 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
7688 safe elaboration order is assured.
7691 @node Output Control
7692 @subsection Output Control
7695 The following switches allow additional control over the output
7696 generated by the binder.
7701 @item ^-A^/BIND_FILE=ADA^
7702 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
7703 Generate binder program in Ada (default). The binder program is named
7704 @file{b~@var{mainprog}.adb} by default. This can be changed with
7705 @option{^-o^/OUTPUT^} @code{gnatbind} option.
7707 @item ^-c^/NOOUTPUT^
7708 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
7709 Check only. Do not generate the binder output file. In this mode the
7710 binder performs all error checks but does not generate an output file.
7712 @item ^-C^/BIND_FILE=C^
7713 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
7714 Generate binder program in C. The binder program is named
7715 @file{b_@var{mainprog}.c}.
7716 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
7719 @item ^-e^/ELABORATION_DEPENDENCIES^
7720 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
7721 Output complete list of elaboration-order dependencies, showing the
7722 reason for each dependency. This output can be rather extensive but may
7723 be useful in diagnosing problems with elaboration order. The output is
7724 written to @file{stdout}.
7727 @cindex @option{^-h^/HELP^} (@code{gnatbind})
7728 Output usage information. The output is written to @file{stdout}.
7730 @item ^-K^/LINKER_OPTION_LIST^
7731 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
7732 Output linker options to @file{stdout}. Includes library search paths,
7733 contents of pragmas Ident and Linker_Options, and libraries added
7736 @item ^-l^/ORDER_OF_ELABORATION^
7737 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
7738 Output chosen elaboration order. The output is written to @file{stdout}.
7740 @item ^-O^/OBJECT_LIST^
7741 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
7742 Output full names of all the object files that must be linked to provide
7743 the Ada component of the program. The output is written to @file{stdout}.
7744 This list includes the files explicitly supplied and referenced by the user
7745 as well as implicitly referenced run-time unit files. The latter are
7746 omitted if the corresponding units reside in shared libraries. The
7747 directory names for the run-time units depend on the system configuration.
7749 @item ^-o ^/OUTPUT=^@var{file}
7750 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
7751 Set name of output file to @var{file} instead of the normal
7752 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
7753 binder generated body filename. In C mode you would normally give
7754 @var{file} an extension of @file{.c} because it will be a C source program.
7755 Note that if this option is used, then linking must be done manually.
7756 It is not possible to use gnatlink in this case, since it cannot locate
7759 @item ^-r^/RESTRICTION_LIST^
7760 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
7761 Generate list of @code{pragma Restrictions} that could be applied to
7762 the current unit. This is useful for code audit purposes, and also may
7763 be used to improve code generation in some cases.
7767 @node Binding with Non-Ada Main Programs
7768 @subsection Binding with Non-Ada Main Programs
7771 In our description so far we have assumed that the main
7772 program is in Ada, and that the task of the binder is to generate a
7773 corresponding function @code{main} that invokes this Ada main
7774 program. GNAT also supports the building of executable programs where
7775 the main program is not in Ada, but some of the called routines are
7776 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
7777 The following switch is used in this situation:
7781 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
7782 No main program. The main program is not in Ada.
7786 In this case, most of the functions of the binder are still required,
7787 but instead of generating a main program, the binder generates a file
7788 containing the following callable routines:
7793 You must call this routine to initialize the Ada part of the program by
7794 calling the necessary elaboration routines. A call to @code{adainit} is
7795 required before the first call to an Ada subprogram.
7797 Note that it is assumed that the basic execution environment must be setup
7798 to be appropriate for Ada execution at the point where the first Ada
7799 subprogram is called. In particular, if the Ada code will do any
7800 floating-point operations, then the FPU must be setup in an appropriate
7801 manner. For the case of the x86, for example, full precision mode is
7802 required. The procedure GNAT.Float_Control.Reset may be used to ensure
7803 that the FPU is in the right state.
7807 You must call this routine to perform any library-level finalization
7808 required by the Ada subprograms. A call to @code{adafinal} is required
7809 after the last call to an Ada subprogram, and before the program
7814 If the @option{^-n^/NOMAIN^} switch
7815 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7816 @cindex Binder, multiple input files
7817 is given, more than one ALI file may appear on
7818 the command line for @code{gnatbind}. The normal @dfn{closure}
7819 calculation is performed for each of the specified units. Calculating
7820 the closure means finding out the set of units involved by tracing
7821 @code{with} references. The reason it is necessary to be able to
7822 specify more than one ALI file is that a given program may invoke two or
7823 more quite separate groups of Ada units.
7825 The binder takes the name of its output file from the last specified ALI
7826 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
7827 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
7828 The output is an Ada unit in source form that can
7829 be compiled with GNAT unless the -C switch is used in which case the
7830 output is a C source file, which must be compiled using the C compiler.
7831 This compilation occurs automatically as part of the @command{gnatlink}
7834 Currently the GNAT run time requires a FPU using 80 bits mode
7835 precision. Under targets where this is not the default it is required to
7836 call GNAT.Float_Control.Reset before using floating point numbers (this
7837 include float computation, float input and output) in the Ada code. A
7838 side effect is that this could be the wrong mode for the foreign code
7839 where floating point computation could be broken after this call.
7841 @node Binding Programs with No Main Subprogram
7842 @subsection Binding Programs with No Main Subprogram
7845 It is possible to have an Ada program which does not have a main
7846 subprogram. This program will call the elaboration routines of all the
7847 packages, then the finalization routines.
7849 The following switch is used to bind programs organized in this manner:
7852 @item ^-z^/ZERO_MAIN^
7853 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7854 Normally the binder checks that the unit name given on the command line
7855 corresponds to a suitable main subprogram. When this switch is used,
7856 a list of ALI files can be given, and the execution of the program
7857 consists of elaboration of these units in an appropriate order.
7860 @node Command-Line Access
7861 @section Command-Line Access
7864 The package @code{Ada.Command_Line} provides access to the command-line
7865 arguments and program name. In order for this interface to operate
7866 correctly, the two variables
7878 are declared in one of the GNAT library routines. These variables must
7879 be set from the actual @code{argc} and @code{argv} values passed to the
7880 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
7881 generates the C main program to automatically set these variables.
7882 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
7883 set these variables. If they are not set, the procedures in
7884 @code{Ada.Command_Line} will not be available, and any attempt to use
7885 them will raise @code{Constraint_Error}. If command line access is
7886 required, your main program must set @code{gnat_argc} and
7887 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
7890 @node Search Paths for gnatbind
7891 @section Search Paths for @code{gnatbind}
7894 The binder takes the name of an ALI file as its argument and needs to
7895 locate source files as well as other ALI files to verify object consistency.
7897 For source files, it follows exactly the same search rules as @command{gcc}
7898 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
7899 directories searched are:
7903 The directory containing the ALI file named in the command line, unless
7904 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
7907 All directories specified by @option{^-I^/SEARCH^}
7908 switches on the @code{gnatbind}
7909 command line, in the order given.
7912 @findex ADA_PRJ_OBJECTS_FILE
7913 Each of the directories listed in the text file whose name is given
7914 by the @code{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
7917 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7918 driver when project files are used. It should not normally be set
7922 @findex ADA_OBJECTS_PATH
7923 Each of the directories listed in the value of the
7924 @code{ADA_OBJECTS_PATH} ^environment variable^logical name^.
7926 Construct this value
7927 exactly as the @code{PATH} environment variable: a list of directory
7928 names separated by colons (semicolons when working with the NT version
7932 Normally, define this value as a logical name containing a comma separated
7933 list of directory names.
7935 This variable can also be defined by means of an environment string
7936 (an argument to the HP C exec* set of functions).
7940 DEFINE ANOTHER_PATH FOO:[BAG]
7941 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7944 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7945 first, followed by the standard Ada 95
7946 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
7947 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7948 (Text_IO, Sequential_IO, etc)
7949 instead of the Ada95 packages. Thus, in order to get the Ada 95
7950 packages by default, ADA_OBJECTS_PATH must be redefined.
7954 The content of the @file{ada_object_path} file which is part of the GNAT
7955 installation tree and is used to store standard libraries such as the
7956 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
7959 @ref{Installing a library}
7964 In the binder the switch @option{^-I^/SEARCH^}
7965 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7966 is used to specify both source and
7967 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
7968 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7969 instead if you want to specify
7970 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
7971 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
7972 if you want to specify library paths
7973 only. This means that for the binder
7974 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
7975 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
7976 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
7977 The binder generates the bind file (a C language source file) in the
7978 current working directory.
7984 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7985 children make up the GNAT Run-Time Library, together with the package
7986 GNAT and its children, which contain a set of useful additional
7987 library functions provided by GNAT. The sources for these units are
7988 needed by the compiler and are kept together in one directory. The ALI
7989 files and object files generated by compiling the RTL are needed by the
7990 binder and the linker and are kept together in one directory, typically
7991 different from the directory containing the sources. In a normal
7992 installation, you need not specify these directory names when compiling
7993 or binding. Either the environment variables or the built-in defaults
7994 cause these files to be found.
7996 Besides simplifying access to the RTL, a major use of search paths is
7997 in compiling sources from multiple directories. This can make
7998 development environments much more flexible.
8000 @node Examples of gnatbind Usage
8001 @section Examples of @code{gnatbind} Usage
8004 This section contains a number of examples of using the GNAT binding
8005 utility @code{gnatbind}.
8008 @item gnatbind hello
8009 The main program @code{Hello} (source program in @file{hello.adb}) is
8010 bound using the standard switch settings. The generated main program is
8011 @file{b~hello.adb}. This is the normal, default use of the binder.
8014 @item gnatbind hello -o mainprog.adb
8017 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8019 The main program @code{Hello} (source program in @file{hello.adb}) is
8020 bound using the standard switch settings. The generated main program is
8021 @file{mainprog.adb} with the associated spec in
8022 @file{mainprog.ads}. Note that you must specify the body here not the
8023 spec, in the case where the output is in Ada. Note that if this option
8024 is used, then linking must be done manually, since gnatlink will not
8025 be able to find the generated file.
8028 @item gnatbind main -C -o mainprog.c -x
8031 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
8033 The main program @code{Main} (source program in
8034 @file{main.adb}) is bound, excluding source files from the
8035 consistency checking, generating
8036 the file @file{mainprog.c}.
8039 @item gnatbind -x main_program -C -o mainprog.c
8040 This command is exactly the same as the previous example. Switches may
8041 appear anywhere in the command line, and single letter switches may be
8042 combined into a single switch.
8046 @item gnatbind -n math dbase -C -o ada-control.c
8049 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
8051 The main program is in a language other than Ada, but calls to
8052 subprograms in packages @code{Math} and @code{Dbase} appear. This call
8053 to @code{gnatbind} generates the file @file{ada-control.c} containing
8054 the @code{adainit} and @code{adafinal} routines to be called before and
8055 after accessing the Ada units.
8058 @c ------------------------------------
8059 @node Linking Using gnatlink
8060 @chapter Linking Using @command{gnatlink}
8061 @c ------------------------------------
8065 This chapter discusses @command{gnatlink}, a tool that links
8066 an Ada program and builds an executable file. This utility
8067 invokes the system linker ^(via the @command{gcc} command)^^
8068 with a correct list of object files and library references.
8069 @command{gnatlink} automatically determines the list of files and
8070 references for the Ada part of a program. It uses the binder file
8071 generated by the @command{gnatbind} to determine this list.
8074 * Running gnatlink::
8075 * Switches for gnatlink::
8078 @node Running gnatlink
8079 @section Running @command{gnatlink}
8082 The form of the @command{gnatlink} command is
8085 $ gnatlink [@var{switches}] @var{mainprog}[.ali]
8086 [@var{non-Ada objects}] [@var{linker options}]
8090 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8092 or linker options) may be in any order, provided that no non-Ada object may
8093 be mistaken for a main @file{ALI} file.
8094 Any file name @file{F} without the @file{.ali}
8095 extension will be taken as the main @file{ALI} file if a file exists
8096 whose name is the concatenation of @file{F} and @file{.ali}.
8099 @file{@var{mainprog}.ali} references the ALI file of the main program.
8100 The @file{.ali} extension of this file can be omitted. From this
8101 reference, @command{gnatlink} locates the corresponding binder file
8102 @file{b~@var{mainprog}.adb} and, using the information in this file along
8103 with the list of non-Ada objects and linker options, constructs a
8104 linker command file to create the executable.
8106 The arguments other than the @command{gnatlink} switches and the main
8107 @file{ALI} file are passed to the linker uninterpreted.
8108 They typically include the names of
8109 object files for units written in other languages than Ada and any library
8110 references required to resolve references in any of these foreign language
8111 units, or in @code{Import} pragmas in any Ada units.
8113 @var{linker options} is an optional list of linker specific
8115 The default linker called by gnatlink is @var{gcc} which in
8116 turn calls the appropriate system linker.
8117 Standard options for the linker such as @option{-lmy_lib} or
8118 @option{-Ldir} can be added as is.
8119 For options that are not recognized by
8120 @var{gcc} as linker options, use the @var{gcc} switches @option{-Xlinker} or
8122 Refer to the GCC documentation for
8123 details. Here is an example showing how to generate a linker map:
8126 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8129 Using @var{linker options} it is possible to set the program stack and
8132 See @ref{Setting Stack Size from gnatlink} and
8133 @ref{Setting Heap Size from gnatlink}.
8136 @command{gnatlink} determines the list of objects required by the Ada
8137 program and prepends them to the list of objects passed to the linker.
8138 @command{gnatlink} also gathers any arguments set by the use of
8139 @code{pragma Linker_Options} and adds them to the list of arguments
8140 presented to the linker.
8143 @command{gnatlink} accepts the following types of extra files on the command
8144 line: objects (.OBJ), libraries (.OLB), sharable images (.EXE), and
8145 options files (.OPT). These are recognized and handled according to their
8149 @node Switches for gnatlink
8150 @section Switches for @command{gnatlink}
8153 The following switches are available with the @command{gnatlink} utility:
8158 @item ^-A^/BIND_FILE=ADA^
8159 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
8160 The binder has generated code in Ada. This is the default.
8162 @item ^-C^/BIND_FILE=C^
8163 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
8164 If instead of generating a file in Ada, the binder has generated one in
8165 C, then the linker needs to know about it. Use this switch to signal
8166 to @command{gnatlink} that the binder has generated C code rather than
8169 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8170 @cindex Command line length
8171 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8172 On some targets, the command line length is limited, and @command{gnatlink}
8173 will generate a separate file for the linker if the list of object files
8175 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8176 to be generated even if
8177 the limit is not exceeded. This is useful in some cases to deal with
8178 special situations where the command line length is exceeded.
8181 @cindex Debugging information, including
8182 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8183 The option to include debugging information causes the Ada bind file (in
8184 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8185 @option{^-g^/DEBUG^}.
8186 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8187 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8188 Without @option{^-g^/DEBUG^}, the binder removes these files by
8189 default. The same procedure apply if a C bind file was generated using
8190 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8191 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8193 @item ^-n^/NOCOMPILE^
8194 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8195 Do not compile the file generated by the binder. This may be used when
8196 a link is rerun with different options, but there is no need to recompile
8200 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8201 Causes additional information to be output, including a full list of the
8202 included object files. This switch option is most useful when you want
8203 to see what set of object files are being used in the link step.
8205 @item ^-v -v^/VERBOSE/VERBOSE^
8206 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8207 Very verbose mode. Requests that the compiler operate in verbose mode when
8208 it compiles the binder file, and that the system linker run in verbose mode.
8210 @item ^-o ^/EXECUTABLE=^@var{exec-name}
8211 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
8212 @var{exec-name} specifies an alternate name for the generated
8213 executable program. If this switch is omitted, the executable has the same
8214 name as the main unit. For example, @code{gnatlink try.ali} creates
8215 an executable called @file{^try^TRY.EXE^}.
8218 @item -b @var{target}
8219 @cindex @option{-b} (@command{gnatlink})
8220 Compile your program to run on @var{target}, which is the name of a
8221 system configuration. You must have a GNAT cross-compiler built if
8222 @var{target} is not the same as your host system.
8225 @cindex @option{-B} (@command{gnatlink})
8226 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8227 from @var{dir} instead of the default location. Only use this switch
8228 when multiple versions of the GNAT compiler are available. See the
8229 @command{gcc} manual page for further details. You would normally use the
8230 @option{-b} or @option{-V} switch instead.
8232 @item --GCC=@var{compiler_name}
8233 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8234 Program used for compiling the binder file. The default is
8235 @command{gcc}. You need to use quotes around @var{compiler_name} if
8236 @code{compiler_name} contains spaces or other separator characters.
8237 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8238 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8239 inserted after your command name. Thus in the above example the compiler
8240 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8241 A limitation of this syntax is that the name and path name of the executable
8242 itself must not include any embedded spaces. If several
8243 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
8244 is taken into account. However, all the additional switches are also taken
8246 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8247 @option{--GCC="bar -x -y -z -t"}.
8249 @item --LINK=@var{name}
8250 @cindex @option{--LINK=} (@command{gnatlink})
8251 @var{name} is the name of the linker to be invoked. This is especially
8252 useful in mixed language programs since languages such as C++ require
8253 their own linker to be used. When this switch is omitted, the default
8254 name for the linker is @command{gcc}. When this switch is used, the
8255 specified linker is called instead of @command{gcc} with exactly the same
8256 parameters that would have been passed to @command{gcc} so if the desired
8257 linker requires different parameters it is necessary to use a wrapper
8258 script that massages the parameters before invoking the real linker. It
8259 may be useful to control the exact invocation by using the verbose
8265 @item /DEBUG=TRACEBACK
8266 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
8267 This qualifier causes sufficient information to be included in the
8268 executable file to allow a traceback, but does not include the full
8269 symbol information needed by the debugger.
8271 @item /IDENTIFICATION="<string>"
8272 @code{"<string>"} specifies the string to be stored in the image file
8273 identification field in the image header.
8274 It overrides any pragma @code{Ident} specified string.
8276 @item /NOINHIBIT-EXEC
8277 Generate the executable file even if there are linker warnings.
8279 @item /NOSTART_FILES
8280 Don't link in the object file containing the ``main'' transfer address.
8281 Used when linking with a foreign language main program compiled with an
8285 Prefer linking with object libraries over sharable images, even without
8291 @node The GNAT Make Program gnatmake
8292 @chapter The GNAT Make Program @command{gnatmake}
8296 * Running gnatmake::
8297 * Switches for gnatmake::
8298 * Mode Switches for gnatmake::
8299 * Notes on the Command Line::
8300 * How gnatmake Works::
8301 * Examples of gnatmake Usage::
8304 A typical development cycle when working on an Ada program consists of
8305 the following steps:
8309 Edit some sources to fix bugs.
8315 Compile all sources affected.
8325 The third step can be tricky, because not only do the modified files
8326 @cindex Dependency rules
8327 have to be compiled, but any files depending on these files must also be
8328 recompiled. The dependency rules in Ada can be quite complex, especially
8329 in the presence of overloading, @code{use} clauses, generics and inlined
8332 @command{gnatmake} automatically takes care of the third and fourth steps
8333 of this process. It determines which sources need to be compiled,
8334 compiles them, and binds and links the resulting object files.
8336 Unlike some other Ada make programs, the dependencies are always
8337 accurately recomputed from the new sources. The source based approach of
8338 the GNAT compilation model makes this possible. This means that if
8339 changes to the source program cause corresponding changes in
8340 dependencies, they will always be tracked exactly correctly by
8343 @node Running gnatmake
8344 @section Running @command{gnatmake}
8347 The usual form of the @command{gnatmake} command is
8350 $ gnatmake [@var{switches}] @var{file_name}
8351 [@var{file_names}] [@var{mode_switches}]
8355 The only required argument is one @var{file_name}, which specifies
8356 a compilation unit that is a main program. Several @var{file_names} can be
8357 specified: this will result in several executables being built.
8358 If @code{switches} are present, they can be placed before the first
8359 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8360 If @var{mode_switches} are present, they must always be placed after
8361 the last @var{file_name} and all @code{switches}.
8363 If you are using standard file extensions (.adb and .ads), then the
8364 extension may be omitted from the @var{file_name} arguments. However, if
8365 you are using non-standard extensions, then it is required that the
8366 extension be given. A relative or absolute directory path can be
8367 specified in a @var{file_name}, in which case, the input source file will
8368 be searched for in the specified directory only. Otherwise, the input
8369 source file will first be searched in the directory where
8370 @command{gnatmake} was invoked and if it is not found, it will be search on
8371 the source path of the compiler as described in
8372 @ref{Search Paths and the Run-Time Library (RTL)}.
8374 All @command{gnatmake} output (except when you specify
8375 @option{^-M^/DEPENDENCIES_LIST^}) is to
8376 @file{stderr}. The output produced by the
8377 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8380 @node Switches for gnatmake
8381 @section Switches for @command{gnatmake}
8384 You may specify any of the following switches to @command{gnatmake}:
8389 @item --GCC=@var{compiler_name}
8390 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
8391 Program used for compiling. The default is `@command{gcc}'. You need to use
8392 quotes around @var{compiler_name} if @code{compiler_name} contains
8393 spaces or other separator characters. As an example @option{--GCC="foo -x
8394 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
8395 compiler. A limitation of this syntax is that the name and path name of
8396 the executable itself must not include any embedded spaces. Note that
8397 switch @option{-c} is always inserted after your command name. Thus in the
8398 above example the compiler command that will be used by @command{gnatmake}
8399 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
8400 used, only the last @var{compiler_name} is taken into account. However,
8401 all the additional switches are also taken into account. Thus,
8402 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8403 @option{--GCC="bar -x -y -z -t"}.
8405 @item --GNATBIND=@var{binder_name}
8406 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
8407 Program used for binding. The default is `@code{gnatbind}'. You need to
8408 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8409 or other separator characters. As an example @option{--GNATBIND="bar -x
8410 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
8411 binder. Binder switches that are normally appended by @command{gnatmake}
8412 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8413 A limitation of this syntax is that the name and path name of the executable
8414 itself must not include any embedded spaces.
8416 @item --GNATLINK=@var{linker_name}
8417 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
8418 Program used for linking. The default is `@command{gnatlink}'. You need to
8419 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8420 or other separator characters. As an example @option{--GNATLINK="lan -x
8421 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
8422 linker. Linker switches that are normally appended by @command{gnatmake} to
8423 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
8424 A limitation of this syntax is that the name and path name of the executable
8425 itself must not include any embedded spaces.
8429 @item ^-a^/ALL_FILES^
8430 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
8431 Consider all files in the make process, even the GNAT internal system
8432 files (for example, the predefined Ada library files), as well as any
8433 locked files. Locked files are files whose ALI file is write-protected.
8435 @command{gnatmake} does not check these files,
8436 because the assumption is that the GNAT internal files are properly up
8437 to date, and also that any write protected ALI files have been properly
8438 installed. Note that if there is an installation problem, such that one
8439 of these files is not up to date, it will be properly caught by the
8441 You may have to specify this switch if you are working on GNAT
8442 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8443 in conjunction with @option{^-f^/FORCE_COMPILE^}
8444 if you need to recompile an entire application,
8445 including run-time files, using special configuration pragmas,
8446 such as a @code{Normalize_Scalars} pragma.
8449 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8452 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8455 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8458 @item ^-b^/ACTIONS=BIND^
8459 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
8460 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8461 compilation and binding, but no link.
8462 Can be combined with @option{^-l^/ACTIONS=LINK^}
8463 to do binding and linking. When not combined with
8464 @option{^-c^/ACTIONS=COMPILE^}
8465 all the units in the closure of the main program must have been previously
8466 compiled and must be up to date. The root unit specified by @var{file_name}
8467 may be given without extension, with the source extension or, if no GNAT
8468 Project File is specified, with the ALI file extension.
8470 @item ^-c^/ACTIONS=COMPILE^
8471 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
8472 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8473 is also specified. Do not perform linking, except if both
8474 @option{^-b^/ACTIONS=BIND^} and
8475 @option{^-l^/ACTIONS=LINK^} are also specified.
8476 If the root unit specified by @var{file_name} is not a main unit, this is the
8477 default. Otherwise @command{gnatmake} will attempt binding and linking
8478 unless all objects are up to date and the executable is more recent than
8482 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
8483 Use a temporary mapping file. A mapping file is a way to communicate to the
8484 compiler two mappings: from unit names to file names (without any directory
8485 information) and from file names to path names (with full directory
8486 information). These mappings are used by the compiler to short-circuit the path
8487 search. When @command{gnatmake} is invoked with this switch, it will create
8488 a temporary mapping file, initially populated by the project manager,
8489 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8490 Each invocation of the compiler will add the newly accessed sources to the
8491 mapping file. This will improve the source search during the next invocation
8494 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8495 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
8496 Use a specific mapping file. The file, specified as a path name (absolute or
8497 relative) by this switch, should already exist, otherwise the switch is
8498 ineffective. The specified mapping file will be communicated to the compiler.
8499 This switch is not compatible with a project file
8500 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8501 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8503 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
8504 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
8505 Put all object files and ALI file in directory @var{dir}.
8506 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
8507 and ALI files go in the current working directory.
8509 This switch cannot be used when using a project file.
8513 @cindex @option{-eL} (@command{gnatmake})
8514 Follow all symbolic links when processing project files.
8517 @item ^-f^/FORCE_COMPILE^
8518 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
8519 Force recompilations. Recompile all sources, even though some object
8520 files may be up to date, but don't recompile predefined or GNAT internal
8521 files or locked files (files with a write-protected ALI file),
8522 unless the @option{^-a^/ALL_FILES^} switch is also specified.
8524 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
8525 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
8526 When using project files, if some errors or warnings are detected during
8527 parsing and verbose mode is not in effect (no use of switch
8528 ^-v^/VERBOSE^), then error lines start with the full path name of the project
8529 file, rather than its simple file name.
8531 @item ^-i^/IN_PLACE^
8532 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
8533 In normal mode, @command{gnatmake} compiles all object files and ALI files
8534 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
8535 then instead object files and ALI files that already exist are overwritten
8536 in place. This means that once a large project is organized into separate
8537 directories in the desired manner, then @command{gnatmake} will automatically
8538 maintain and update this organization. If no ALI files are found on the
8539 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
8540 the new object and ALI files are created in the
8541 directory containing the source being compiled. If another organization
8542 is desired, where objects and sources are kept in different directories,
8543 a useful technique is to create dummy ALI files in the desired directories.
8544 When detecting such a dummy file, @command{gnatmake} will be forced to
8545 recompile the corresponding source file, and it will be put the resulting
8546 object and ALI files in the directory where it found the dummy file.
8548 @item ^-j^/PROCESSES=^@var{n}
8549 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
8550 @cindex Parallel make
8551 Use @var{n} processes to carry out the (re)compilations. On a
8552 multiprocessor machine compilations will occur in parallel. In the
8553 event of compilation errors, messages from various compilations might
8554 get interspersed (but @command{gnatmake} will give you the full ordered
8555 list of failing compiles at the end). If this is problematic, rerun
8556 the make process with n set to 1 to get a clean list of messages.
8558 @item ^-k^/CONTINUE_ON_ERROR^
8559 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
8560 Keep going. Continue as much as possible after a compilation error. To
8561 ease the programmer's task in case of compilation errors, the list of
8562 sources for which the compile fails is given when @command{gnatmake}
8565 If @command{gnatmake} is invoked with several @file{file_names} and with this
8566 switch, if there are compilation errors when building an executable,
8567 @command{gnatmake} will not attempt to build the following executables.
8569 @item ^-l^/ACTIONS=LINK^
8570 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
8571 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
8572 and linking. Linking will not be performed if combined with
8573 @option{^-c^/ACTIONS=COMPILE^}
8574 but not with @option{^-b^/ACTIONS=BIND^}.
8575 When not combined with @option{^-b^/ACTIONS=BIND^}
8576 all the units in the closure of the main program must have been previously
8577 compiled and must be up to date, and the main program needs to have been bound.
8578 The root unit specified by @var{file_name}
8579 may be given without extension, with the source extension or, if no GNAT
8580 Project File is specified, with the ALI file extension.
8582 @item ^-m^/MINIMAL_RECOMPILATION^
8583 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
8584 Specify that the minimum necessary amount of recompilations
8585 be performed. In this mode @command{gnatmake} ignores time
8586 stamp differences when the only
8587 modifications to a source file consist in adding/removing comments,
8588 empty lines, spaces or tabs. This means that if you have changed the
8589 comments in a source file or have simply reformatted it, using this
8590 switch will tell gnatmake not to recompile files that depend on it
8591 (provided other sources on which these files depend have undergone no
8592 semantic modifications). Note that the debugging information may be
8593 out of date with respect to the sources if the @option{-m} switch causes
8594 a compilation to be switched, so the use of this switch represents a
8595 trade-off between compilation time and accurate debugging information.
8597 @item ^-M^/DEPENDENCIES_LIST^
8598 @cindex Dependencies, producing list
8599 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
8600 Check if all objects are up to date. If they are, output the object
8601 dependences to @file{stdout} in a form that can be directly exploited in
8602 a @file{Makefile}. By default, each source file is prefixed with its
8603 (relative or absolute) directory name. This name is whatever you
8604 specified in the various @option{^-aI^/SOURCE_SEARCH^}
8605 and @option{^-I^/SEARCH^} switches. If you use
8606 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
8607 @option{^-q^/QUIET^}
8608 (see below), only the source file names,
8609 without relative paths, are output. If you just specify the
8610 @option{^-M^/DEPENDENCIES_LIST^}
8611 switch, dependencies of the GNAT internal system files are omitted. This
8612 is typically what you want. If you also specify
8613 the @option{^-a^/ALL_FILES^} switch,
8614 dependencies of the GNAT internal files are also listed. Note that
8615 dependencies of the objects in external Ada libraries (see switch
8616 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
8619 @item ^-n^/DO_OBJECT_CHECK^
8620 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
8621 Don't compile, bind, or link. Checks if all objects are up to date.
8622 If they are not, the full name of the first file that needs to be
8623 recompiled is printed.
8624 Repeated use of this option, followed by compiling the indicated source
8625 file, will eventually result in recompiling all required units.
8627 @item ^-o ^/EXECUTABLE=^@var{exec_name}
8628 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
8629 Output executable name. The name of the final executable program will be
8630 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
8631 name for the executable will be the name of the input file in appropriate form
8632 for an executable file on the host system.
8634 This switch cannot be used when invoking @command{gnatmake} with several
8637 @item ^-P^/PROJECT_FILE=^@var{project}
8638 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
8639 Use project file @var{project}. Only one such switch can be used.
8640 @xref{gnatmake and Project Files}.
8643 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
8644 Quiet. When this flag is not set, the commands carried out by
8645 @command{gnatmake} are displayed.
8647 @item ^-s^/SWITCH_CHECK/^
8648 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
8649 Recompile if compiler switches have changed since last compilation.
8650 All compiler switches but -I and -o are taken into account in the
8652 orders between different ``first letter'' switches are ignored, but
8653 orders between same switches are taken into account. For example,
8654 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
8655 is equivalent to @option{-O -g}.
8657 This switch is recommended when Integrated Preprocessing is used.
8660 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
8661 Unique. Recompile at most the main files. It implies -c. Combined with
8662 -f, it is equivalent to calling the compiler directly. Note that using
8663 ^-u^/UNIQUE^ with a project file and no main has a special meaning
8664 (@pxref{Project Files and Main Subprograms}).
8666 @item ^-U^/ALL_PROJECTS^
8667 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
8668 When used without a project file or with one or several mains on the command
8669 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
8670 on the command line, all sources of all project files are checked and compiled
8671 if not up to date, and libraries are rebuilt, if necessary.
8674 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
8675 Verbose. Display the reason for all recompilations @command{gnatmake}
8676 decides are necessary, with the highest verbosity level.
8678 @item ^-vl^/LOW_VERBOSITY^
8679 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
8680 Verbosity level Low. Display fewer lines than in verbosity Medium.
8682 @item ^-vm^/MEDIUM_VERBOSITY^
8683 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
8684 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
8686 @item ^-vh^/HIGH_VERBOSITY^
8687 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
8688 Verbosity level High. Equivalent to ^-v^/REASONS^.
8690 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
8691 Indicate the verbosity of the parsing of GNAT project files.
8692 @xref{Switches Related to Project Files}.
8694 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
8695 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
8696 Indicate that sources that are not part of any Project File may be compiled.
8697 Normally, when using Project Files, only sources that are part of a Project
8698 File may be compile. When this switch is used, a source outside of all Project
8699 Files may be compiled. The ALI file and the object file will be put in the
8700 object directory of the main Project. The compilation switches used will only
8701 be those specified on the command line.
8703 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
8704 Indicate that external variable @var{name} has the value @var{value}.
8705 The Project Manager will use this value for occurrences of
8706 @code{external(name)} when parsing the project file.
8707 @xref{Switches Related to Project Files}.
8710 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
8711 No main subprogram. Bind and link the program even if the unit name
8712 given on the command line is a package name. The resulting executable
8713 will execute the elaboration routines of the package and its closure,
8714 then the finalization routines.
8717 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
8718 Enable debugging. This switch is simply passed to the compiler and to the
8724 @item @command{gcc} @asis{switches}
8726 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
8727 is passed to @command{gcc} (e.g. @option{-O}, @option{-gnato,} etc.)
8730 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
8731 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
8732 automatically treated as a compiler switch, and passed on to all
8733 compilations that are carried out.
8738 Source and library search path switches:
8742 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
8743 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
8744 When looking for source files also look in directory @var{dir}.
8745 The order in which source files search is undertaken is
8746 described in @ref{Search Paths and the Run-Time Library (RTL)}.
8748 @item ^-aL^/SKIP_MISSING=^@var{dir}
8749 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
8750 Consider @var{dir} as being an externally provided Ada library.
8751 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
8752 files have been located in directory @var{dir}. This allows you to have
8753 missing bodies for the units in @var{dir} and to ignore out of date bodies
8754 for the same units. You still need to specify
8755 the location of the specs for these units by using the switches
8756 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
8757 or @option{^-I^/SEARCH=^@var{dir}}.
8758 Note: this switch is provided for compatibility with previous versions
8759 of @command{gnatmake}. The easier method of causing standard libraries
8760 to be excluded from consideration is to write-protect the corresponding
8763 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
8764 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
8765 When searching for library and object files, look in directory
8766 @var{dir}. The order in which library files are searched is described in
8767 @ref{Search Paths for gnatbind}.
8769 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
8770 @cindex Search paths, for @command{gnatmake}
8771 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
8772 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
8773 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8775 @item ^-I^/SEARCH=^@var{dir}
8776 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
8777 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
8778 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8780 @item ^-I-^/NOCURRENT_DIRECTORY^
8781 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
8782 @cindex Source files, suppressing search
8783 Do not look for source files in the directory containing the source
8784 file named in the command line.
8785 Do not look for ALI or object files in the directory
8786 where @command{gnatmake} was invoked.
8788 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
8789 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
8790 @cindex Linker libraries
8791 Add directory @var{dir} to the list of directories in which the linker
8792 will search for libraries. This is equivalent to
8793 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
8795 Furthermore, under Windows, the sources pointed to by the libraries path
8796 set in the registry are not searched for.
8800 @cindex @option{-nostdinc} (@command{gnatmake})
8801 Do not look for source files in the system default directory.
8804 @cindex @option{-nostdlib} (@command{gnatmake})
8805 Do not look for library files in the system default directory.
8807 @item --RTS=@var{rts-path}
8808 @cindex @option{--RTS} (@command{gnatmake})
8809 Specifies the default location of the runtime library. GNAT looks for the
8811 in the following directories, and stops as soon as a valid runtime is found
8812 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
8813 @file{ada_object_path} present):
8816 @item <current directory>/$rts_path
8818 @item <default-search-dir>/$rts_path
8820 @item <default-search-dir>/rts-$rts_path
8824 The selected path is handled like a normal RTS path.
8828 @node Mode Switches for gnatmake
8829 @section Mode Switches for @command{gnatmake}
8832 The mode switches (referred to as @code{mode_switches}) allow the
8833 inclusion of switches that are to be passed to the compiler itself, the
8834 binder or the linker. The effect of a mode switch is to cause all
8835 subsequent switches up to the end of the switch list, or up to the next
8836 mode switch, to be interpreted as switches to be passed on to the
8837 designated component of GNAT.
8841 @item -cargs @var{switches}
8842 @cindex @option{-cargs} (@command{gnatmake})
8843 Compiler switches. Here @var{switches} is a list of switches
8844 that are valid switches for @command{gcc}. They will be passed on to
8845 all compile steps performed by @command{gnatmake}.
8847 @item -bargs @var{switches}
8848 @cindex @option{-bargs} (@command{gnatmake})
8849 Binder switches. Here @var{switches} is a list of switches
8850 that are valid switches for @code{gnatbind}. They will be passed on to
8851 all bind steps performed by @command{gnatmake}.
8853 @item -largs @var{switches}
8854 @cindex @option{-largs} (@command{gnatmake})
8855 Linker switches. Here @var{switches} is a list of switches
8856 that are valid switches for @command{gnatlink}. They will be passed on to
8857 all link steps performed by @command{gnatmake}.
8859 @item -margs @var{switches}
8860 @cindex @option{-margs} (@command{gnatmake})
8861 Make switches. The switches are directly interpreted by @command{gnatmake},
8862 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
8866 @node Notes on the Command Line
8867 @section Notes on the Command Line
8870 This section contains some additional useful notes on the operation
8871 of the @command{gnatmake} command.
8875 @cindex Recompilation, by @command{gnatmake}
8876 If @command{gnatmake} finds no ALI files, it recompiles the main program
8877 and all other units required by the main program.
8878 This means that @command{gnatmake}
8879 can be used for the initial compile, as well as during subsequent steps of
8880 the development cycle.
8883 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
8884 is a subunit or body of a generic unit, @command{gnatmake} recompiles
8885 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
8889 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
8890 is used to specify both source and
8891 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8892 instead if you just want to specify
8893 source paths only and @option{^-aO^/OBJECT_SEARCH^}
8894 if you want to specify library paths
8898 @command{gnatmake} will ignore any files whose ALI file is write-protected.
8899 This may conveniently be used to exclude standard libraries from
8900 consideration and in particular it means that the use of the
8901 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
8902 unless @option{^-a^/ALL_FILES^} is also specified.
8905 @command{gnatmake} has been designed to make the use of Ada libraries
8906 particularly convenient. Assume you have an Ada library organized
8907 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
8908 of your Ada compilation units,
8909 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
8910 specs of these units, but no bodies. Then to compile a unit
8911 stored in @code{main.adb}, which uses this Ada library you would just type
8915 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
8918 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
8919 /SKIP_MISSING=@i{[OBJ_DIR]} main
8924 Using @command{gnatmake} along with the
8925 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
8926 switch provides a mechanism for avoiding unnecessary rcompilations. Using
8928 you can update the comments/format of your
8929 source files without having to recompile everything. Note, however, that
8930 adding or deleting lines in a source files may render its debugging
8931 info obsolete. If the file in question is a spec, the impact is rather
8932 limited, as that debugging info will only be useful during the
8933 elaboration phase of your program. For bodies the impact can be more
8934 significant. In all events, your debugger will warn you if a source file
8935 is more recent than the corresponding object, and alert you to the fact
8936 that the debugging information may be out of date.
8939 @node How gnatmake Works
8940 @section How @command{gnatmake} Works
8943 Generally @command{gnatmake} automatically performs all necessary
8944 recompilations and you don't need to worry about how it works. However,
8945 it may be useful to have some basic understanding of the @command{gnatmake}
8946 approach and in particular to understand how it uses the results of
8947 previous compilations without incorrectly depending on them.
8949 First a definition: an object file is considered @dfn{up to date} if the
8950 corresponding ALI file exists and if all the source files listed in the
8951 dependency section of this ALI file have time stamps matching those in
8952 the ALI file. This means that neither the source file itself nor any
8953 files that it depends on have been modified, and hence there is no need
8954 to recompile this file.
8956 @command{gnatmake} works by first checking if the specified main unit is up
8957 to date. If so, no compilations are required for the main unit. If not,
8958 @command{gnatmake} compiles the main program to build a new ALI file that
8959 reflects the latest sources. Then the ALI file of the main unit is
8960 examined to find all the source files on which the main program depends,
8961 and @command{gnatmake} recursively applies the above procedure on all these
8964 This process ensures that @command{gnatmake} only trusts the dependencies
8965 in an existing ALI file if they are known to be correct. Otherwise it
8966 always recompiles to determine a new, guaranteed accurate set of
8967 dependencies. As a result the program is compiled ``upside down'' from what may
8968 be more familiar as the required order of compilation in some other Ada
8969 systems. In particular, clients are compiled before the units on which
8970 they depend. The ability of GNAT to compile in any order is critical in
8971 allowing an order of compilation to be chosen that guarantees that
8972 @command{gnatmake} will recompute a correct set of new dependencies if
8975 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
8976 imported by several of the executables, it will be recompiled at most once.
8978 Note: when using non-standard naming conventions
8979 (@pxref{Using Other File Names}), changing through a configuration pragmas
8980 file the version of a source and invoking @command{gnatmake} to recompile may
8981 have no effect, if the previous version of the source is still accessible
8982 by @command{gnatmake}. It may be necessary to use the switch
8983 ^-f^/FORCE_COMPILE^.
8985 @node Examples of gnatmake Usage
8986 @section Examples of @command{gnatmake} Usage
8989 @item gnatmake hello.adb
8990 Compile all files necessary to bind and link the main program
8991 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
8992 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
8994 @item gnatmake main1 main2 main3
8995 Compile all files necessary to bind and link the main programs
8996 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
8997 (containing unit @code{Main2}) and @file{main3.adb}
8998 (containing unit @code{Main3}) and bind and link the resulting object files
8999 to generate three executable files @file{^main1^MAIN1.EXE^},
9000 @file{^main2^MAIN2.EXE^}
9001 and @file{^main3^MAIN3.EXE^}.
9004 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9008 @item gnatmake Main_Unit /QUIET
9009 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9010 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9012 Compile all files necessary to bind and link the main program unit
9013 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9014 be done with optimization level 2 and the order of elaboration will be
9015 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9016 displaying commands it is executing.
9019 @c *************************
9020 @node Improving Performance
9021 @chapter Improving Performance
9022 @cindex Improving performance
9025 This chapter presents several topics related to program performance.
9026 It first describes some of the tradeoffs that need to be considered
9027 and some of the techniques for making your program run faster.
9028 It then documents the @command{gnatelim} tool and unused subprogram/data
9029 elimination feature, which can reduce the size of program executables.
9033 * Performance Considerations::
9034 * Reducing Size of Ada Executables with gnatelim::
9035 * Reducing Size of Executables with unused subprogram/data elimination::
9039 @c *****************************
9040 @node Performance Considerations
9041 @section Performance Considerations
9044 The GNAT system provides a number of options that allow a trade-off
9049 performance of the generated code
9052 speed of compilation
9055 minimization of dependences and recompilation
9058 the degree of run-time checking.
9062 The defaults (if no options are selected) aim at improving the speed
9063 of compilation and minimizing dependences, at the expense of performance
9064 of the generated code:
9071 no inlining of subprogram calls
9074 all run-time checks enabled except overflow and elaboration checks
9078 These options are suitable for most program development purposes. This
9079 chapter describes how you can modify these choices, and also provides
9080 some guidelines on debugging optimized code.
9083 * Controlling Run-Time Checks::
9084 * Use of Restrictions::
9085 * Optimization Levels::
9086 * Debugging Optimized Code::
9087 * Inlining of Subprograms::
9088 * Other Optimization Switches::
9089 * Optimization and Strict Aliasing::
9092 * Coverage Analysis::
9096 @node Controlling Run-Time Checks
9097 @subsection Controlling Run-Time Checks
9100 By default, GNAT generates all run-time checks, except arithmetic overflow
9101 checking for integer operations and checks for access before elaboration on
9102 subprogram calls. The latter are not required in default mode, because all
9103 necessary checking is done at compile time.
9104 @cindex @option{-gnatp} (@command{gcc})
9105 @cindex @option{-gnato} (@command{gcc})
9106 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9107 be modified. @xref{Run-Time Checks}.
9109 Our experience is that the default is suitable for most development
9112 We treat integer overflow specially because these
9113 are quite expensive and in our experience are not as important as other
9114 run-time checks in the development process. Note that division by zero
9115 is not considered an overflow check, and divide by zero checks are
9116 generated where required by default.
9118 Elaboration checks are off by default, and also not needed by default, since
9119 GNAT uses a static elaboration analysis approach that avoids the need for
9120 run-time checking. This manual contains a full chapter discussing the issue
9121 of elaboration checks, and if the default is not satisfactory for your use,
9122 you should read this chapter.
9124 For validity checks, the minimal checks required by the Ada Reference
9125 Manual (for case statements and assignments to array elements) are on
9126 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9127 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9128 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9129 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9130 are also suppressed entirely if @option{-gnatp} is used.
9132 @cindex Overflow checks
9133 @cindex Checks, overflow
9136 @cindex pragma Suppress
9137 @cindex pragma Unsuppress
9138 Note that the setting of the switches controls the default setting of
9139 the checks. They may be modified using either @code{pragma Suppress} (to
9140 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9141 checks) in the program source.
9143 @node Use of Restrictions
9144 @subsection Use of Restrictions
9147 The use of pragma Restrictions allows you to control which features are
9148 permitted in your program. Apart from the obvious point that if you avoid
9149 relatively expensive features like finalization (enforceable by the use
9150 of pragma Restrictions (No_Finalization), the use of this pragma does not
9151 affect the generated code in most cases.
9153 One notable exception to this rule is that the possibility of task abort
9154 results in some distributed overhead, particularly if finalization or
9155 exception handlers are used. The reason is that certain sections of code
9156 have to be marked as non-abortable.
9158 If you use neither the @code{abort} statement, nor asynchronous transfer
9159 of control (@code{select .. then abort}), then this distributed overhead
9160 is removed, which may have a general positive effect in improving
9161 overall performance. Especially code involving frequent use of tasking
9162 constructs and controlled types will show much improved performance.
9163 The relevant restrictions pragmas are
9165 @smallexample @c ada
9166 pragma Restrictions (No_Abort_Statements);
9167 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
9171 It is recommended that these restriction pragmas be used if possible. Note
9172 that this also means that you can write code without worrying about the
9173 possibility of an immediate abort at any point.
9175 @node Optimization Levels
9176 @subsection Optimization Levels
9177 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
9180 The default is optimization off. This results in the fastest compile
9181 times, but GNAT makes absolutely no attempt to optimize, and the
9182 generated programs are considerably larger and slower than when
9183 optimization is enabled. You can use the
9185 @option{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
9188 @code{OPTIMIZE} qualifier
9190 to @command{gcc} to control the optimization level:
9193 @item ^-O0^/OPTIMIZE=NONE^
9194 No optimization (the default);
9195 generates unoptimized code but has
9196 the fastest compilation time.
9198 Note that many other compilers do fairly extensive optimization
9199 even if "no optimization" is specified. When using gcc, it is
9200 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
9201 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
9202 really does mean no optimization at all. This difference between
9203 gcc and other compilers should be kept in mind when doing
9204 performance comparisons.
9206 @item ^-O1^/OPTIMIZE=SOME^
9207 Moderate optimization;
9208 optimizes reasonably well but does not
9209 degrade compilation time significantly.
9211 @item ^-O2^/OPTIMIZE=ALL^
9213 @itemx /OPTIMIZE=DEVELOPMENT
9216 generates highly optimized code and has
9217 the slowest compilation time.
9219 @item ^-O3^/OPTIMIZE=INLINING^
9220 Full optimization as in @option{-O2},
9221 and also attempts automatic inlining of small
9222 subprograms within a unit (@pxref{Inlining of Subprograms}).
9226 Higher optimization levels perform more global transformations on the
9227 program and apply more expensive analysis algorithms in order to generate
9228 faster and more compact code. The price in compilation time, and the
9229 resulting improvement in execution time,
9230 both depend on the particular application and the hardware environment.
9231 You should experiment to find the best level for your application.
9233 Since the precise set of optimizations done at each level will vary from
9234 release to release (and sometime from target to target), it is best to think
9235 of the optimization settings in general terms.
9236 The @cite{Using GNU GCC} manual contains details about
9237 ^the @option{-O} settings and a number of @option{-f} options that^how to^
9238 individually enable or disable specific optimizations.
9240 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
9241 been tested extensively at all optimization levels. There are some bugs
9242 which appear only with optimization turned on, but there have also been
9243 bugs which show up only in @emph{unoptimized} code. Selecting a lower
9244 level of optimization does not improve the reliability of the code
9245 generator, which in practice is highly reliable at all optimization
9248 Note regarding the use of @option{-O3}: The use of this optimization level
9249 is generally discouraged with GNAT, since it often results in larger
9250 executables which run more slowly. See further discussion of this point
9251 in @ref{Inlining of Subprograms}.
9253 @node Debugging Optimized Code
9254 @subsection Debugging Optimized Code
9255 @cindex Debugging optimized code
9256 @cindex Optimization and debugging
9259 Although it is possible to do a reasonable amount of debugging at
9261 nonzero optimization levels,
9262 the higher the level the more likely that
9265 @option{/OPTIMIZE} settings other than @code{NONE},
9266 such settings will make it more likely that
9268 source-level constructs will have been eliminated by optimization.
9269 For example, if a loop is strength-reduced, the loop
9270 control variable may be completely eliminated and thus cannot be
9271 displayed in the debugger.
9272 This can only happen at @option{-O2} or @option{-O3}.
9273 Explicit temporary variables that you code might be eliminated at
9274 ^level^setting^ @option{-O1} or higher.
9276 The use of the @option{^-g^/DEBUG^} switch,
9277 @cindex @option{^-g^/DEBUG^} (@command{gcc})
9278 which is needed for source-level debugging,
9279 affects the size of the program executable on disk,
9280 and indeed the debugging information can be quite large.
9281 However, it has no effect on the generated code (and thus does not
9282 degrade performance)
9284 Since the compiler generates debugging tables for a compilation unit before
9285 it performs optimizations, the optimizing transformations may invalidate some
9286 of the debugging data. You therefore need to anticipate certain
9287 anomalous situations that may arise while debugging optimized code.
9288 These are the most common cases:
9292 @i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next}
9294 the PC bouncing back and forth in the code. This may result from any of
9295 the following optimizations:
9299 @i{Common subexpression elimination:} using a single instance of code for a
9300 quantity that the source computes several times. As a result you
9301 may not be able to stop on what looks like a statement.
9304 @i{Invariant code motion:} moving an expression that does not change within a
9305 loop, to the beginning of the loop.
9308 @i{Instruction scheduling:} moving instructions so as to
9309 overlap loads and stores (typically) with other code, or in
9310 general to move computations of values closer to their uses. Often
9311 this causes you to pass an assignment statement without the assignment
9312 happening and then later bounce back to the statement when the
9313 value is actually needed. Placing a breakpoint on a line of code
9314 and then stepping over it may, therefore, not always cause all the
9315 expected side-effects.
9319 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
9320 two identical pieces of code are merged and the program counter suddenly
9321 jumps to a statement that is not supposed to be executed, simply because
9322 it (and the code following) translates to the same thing as the code
9323 that @emph{was} supposed to be executed. This effect is typically seen in
9324 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
9325 a @code{break} in a C @code{^switch^switch^} statement.
9328 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
9329 There are various reasons for this effect:
9333 In a subprogram prologue, a parameter may not yet have been moved to its
9337 A variable may be dead, and its register re-used. This is
9338 probably the most common cause.
9341 As mentioned above, the assignment of a value to a variable may
9345 A variable may be eliminated entirely by value propagation or
9346 other means. In this case, GCC may incorrectly generate debugging
9347 information for the variable
9351 In general, when an unexpected value appears for a local variable or parameter
9352 you should first ascertain if that value was actually computed by
9353 your program, as opposed to being incorrectly reported by the debugger.
9355 array elements in an object designated by an access value
9356 are generally less of a problem, once you have ascertained that the access
9358 Typically, this means checking variables in the preceding code and in the
9359 calling subprogram to verify that the value observed is explainable from other
9360 values (one must apply the procedure recursively to those
9361 other values); or re-running the code and stopping a little earlier
9362 (perhaps before the call) and stepping to better see how the variable obtained
9363 the value in question; or continuing to step @emph{from} the point of the
9364 strange value to see if code motion had simply moved the variable's
9369 In light of such anomalies, a recommended technique is to use @option{-O0}
9370 early in the software development cycle, when extensive debugging capabilities
9371 are most needed, and then move to @option{-O1} and later @option{-O2} as
9372 the debugger becomes less critical.
9373 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
9374 a release management issue.
9376 Note that if you use @option{-g} you can then use the @command{strip} program
9377 on the resulting executable,
9378 which removes both debugging information and global symbols.
9381 @node Inlining of Subprograms
9382 @subsection Inlining of Subprograms
9385 A call to a subprogram in the current unit is inlined if all the
9386 following conditions are met:
9390 The optimization level is at least @option{-O1}.
9393 The called subprogram is suitable for inlining: It must be small enough
9394 and not contain nested subprograms or anything else that @command{gcc}
9395 cannot support in inlined subprograms.
9398 The call occurs after the definition of the body of the subprogram.
9401 @cindex pragma Inline
9403 Either @code{pragma Inline} applies to the subprogram or it is
9404 small and automatic inlining (optimization level @option{-O3}) is
9409 Calls to subprograms in @code{with}'ed units are normally not inlined.
9410 To achieve actual inlining (that is, replacement of the call by the code
9411 in the body of the subprogram), the following conditions must all be true.
9415 The optimization level is at least @option{-O1}.
9418 The called subprogram is suitable for inlining: It must be small enough
9419 and not contain nested subprograms or anything else @command{gcc} cannot
9420 support in inlined subprograms.
9423 The call appears in a body (not in a package spec).
9426 There is a @code{pragma Inline} for the subprogram.
9429 @cindex @option{-gnatn} (@command{gcc})
9430 The @option{^-gnatn^/INLINE^} switch
9431 is used in the @command{gcc} command line
9434 Even if all these conditions are met, it may not be possible for
9435 the compiler to inline the call, due to the length of the body,
9436 or features in the body that make it impossible for the compiler
9439 Note that specifying the @option{-gnatn} switch causes additional
9440 compilation dependencies. Consider the following:
9442 @smallexample @c ada
9462 With the default behavior (no @option{-gnatn} switch specified), the
9463 compilation of the @code{Main} procedure depends only on its own source,
9464 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
9465 means that editing the body of @code{R} does not require recompiling
9468 On the other hand, the call @code{R.Q} is not inlined under these
9469 circumstances. If the @option{-gnatn} switch is present when @code{Main}
9470 is compiled, the call will be inlined if the body of @code{Q} is small
9471 enough, but now @code{Main} depends on the body of @code{R} in
9472 @file{r.adb} as well as on the spec. This means that if this body is edited,
9473 the main program must be recompiled. Note that this extra dependency
9474 occurs whether or not the call is in fact inlined by @command{gcc}.
9476 The use of front end inlining with @option{-gnatN} generates similar
9477 additional dependencies.
9479 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
9480 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
9481 can be used to prevent
9482 all inlining. This switch overrides all other conditions and ensures
9483 that no inlining occurs. The extra dependences resulting from
9484 @option{-gnatn} will still be active, even if
9485 this switch is used to suppress the resulting inlining actions.
9487 Note regarding the use of @option{-O3}: There is no difference in inlining
9488 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
9489 pragma @code{Inline} assuming the use of @option{-gnatn}
9490 or @option{-gnatN} (the switches that activate inlining). If you have used
9491 pragma @code{Inline} in appropriate cases, then it is usually much better
9492 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
9493 in this case only has the effect of inlining subprograms you did not
9494 think should be inlined. We often find that the use of @option{-O3} slows
9495 down code by performing excessive inlining, leading to increased instruction
9496 cache pressure from the increased code size. So the bottom line here is
9497 that you should not automatically assume that @option{-O3} is better than
9498 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
9499 it actually improves performance.
9501 @node Other Optimization Switches
9502 @subsection Other Optimization Switches
9503 @cindex Optimization Switches
9505 Since @code{GNAT} uses the @code{gcc} back end, all the specialized
9506 @code{gcc} optimization switches are potentially usable. These switches
9507 have not been extensively tested with GNAT but can generally be expected
9508 to work. Examples of switches in this category are
9509 @option{-funroll-loops} and
9510 the various target-specific @option{-m} options (in particular, it has been
9511 observed that @option{-march=pentium4} can significantly improve performance
9512 on appropriate machines). For full details of these switches, see the
9515 @node Optimization and Strict Aliasing
9516 @subsection Optimization and Strict Aliasing
9518 @cindex Strict Aliasing
9519 @cindex No_Strict_Aliasing
9522 The strong typing capabilities of Ada allow an optimizer to generate
9523 efficient code in situations where other languages would be forced to
9524 make worst case assumptions preventing such optimizations. Consider
9525 the following example:
9527 @smallexample @c ada
9530 type Int1 is new Integer;
9531 type Int2 is new Integer;
9532 type Int1A is access Int1;
9533 type Int2A is access Int2;
9540 for J in Data'Range loop
9541 if Data (J) = Int1V.all then
9542 Int2V.all := Int2V.all + 1;
9551 In this example, since the variable @code{Int1V} can only access objects
9552 of type @code{Int1}, and @code{Int2V} can only access objects of type
9553 @code{Int2}, there is no possibility that the assignment to
9554 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
9555 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
9556 for all iterations of the loop and avoid the extra memory reference
9557 required to dereference it each time through the loop.
9559 This kind of optimization, called strict aliasing analysis, is
9560 triggered by specifying an optimization level of @option{-O2} or
9561 higher and allows @code{GNAT} to generate more efficient code
9562 when access values are involved.
9564 However, although this optimization is always correct in terms of
9565 the formal semantics of the Ada Reference Manual, difficulties can
9566 arise if features like @code{Unchecked_Conversion} are used to break
9567 the typing system. Consider the following complete program example:
9569 @smallexample @c ada
9572 type int1 is new integer;
9573 type int2 is new integer;
9574 type a1 is access int1;
9575 type a2 is access int2;
9580 function to_a2 (Input : a1) return a2;
9583 with Unchecked_Conversion;
9585 function to_a2 (Input : a1) return a2 is
9587 new Unchecked_Conversion (a1, a2);
9589 return to_a2u (Input);
9595 with Text_IO; use Text_IO;
9597 v1 : a1 := new int1;
9598 v2 : a2 := to_a2 (v1);
9602 put_line (int1'image (v1.all));
9608 This program prints out 0 in @code{-O0} or @code{-O1}
9609 mode, but it prints out 1 in @code{-O2} mode. That's
9610 because in strict aliasing mode, the compiler can and
9611 does assume that the assignment to @code{v2.all} could not
9612 affect the value of @code{v1.all}, since different types
9615 This behavior is not a case of non-conformance with the standard, since
9616 the Ada RM specifies that an unchecked conversion where the resulting
9617 bit pattern is not a correct value of the target type can result in an
9618 abnormal value and attempting to reference an abnormal value makes the
9619 execution of a program erroneous. That's the case here since the result
9620 does not point to an object of type @code{int2}. This means that the
9621 effect is entirely unpredictable.
9623 However, although that explanation may satisfy a language
9624 lawyer, in practice an applications programmer expects an
9625 unchecked conversion involving pointers to create true
9626 aliases and the behavior of printing 1 seems plain wrong.
9627 In this case, the strict aliasing optimization is unwelcome.
9629 Indeed the compiler recognizes this possibility, and the
9630 unchecked conversion generates a warning:
9633 p2.adb:5:07: warning: possible aliasing problem with type "a2"
9634 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
9635 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
9639 Unfortunately the problem is recognized when compiling the body of
9640 package @code{p2}, but the actual "bad" code is generated while
9641 compiling the body of @code{m} and this latter compilation does not see
9642 the suspicious @code{Unchecked_Conversion}.
9644 As implied by the warning message, there are approaches you can use to
9645 avoid the unwanted strict aliasing optimization in a case like this.
9647 One possibility is to simply avoid the use of @code{-O2}, but
9648 that is a bit drastic, since it throws away a number of useful
9649 optimizations that do not involve strict aliasing assumptions.
9651 A less drastic approach is to compile the program using the
9652 option @code{-fno-strict-aliasing}. Actually it is only the
9653 unit containing the dereferencing of the suspicious pointer
9654 that needs to be compiled. So in this case, if we compile
9655 unit @code{m} with this switch, then we get the expected
9656 value of zero printed. Analyzing which units might need
9657 the switch can be painful, so a more reasonable approach
9658 is to compile the entire program with options @code{-O2}
9659 and @code{-fno-strict-aliasing}. If the performance is
9660 satisfactory with this combination of options, then the
9661 advantage is that the entire issue of possible "wrong"
9662 optimization due to strict aliasing is avoided.
9664 To avoid the use of compiler switches, the configuration
9665 pragma @code{No_Strict_Aliasing} with no parameters may be
9666 used to specify that for all access types, the strict
9667 aliasing optimization should be suppressed.
9669 However, these approaches are still overkill, in that they causes
9670 all manipulations of all access values to be deoptimized. A more
9671 refined approach is to concentrate attention on the specific
9672 access type identified as problematic.
9674 First, if a careful analysis of uses of the pointer shows
9675 that there are no possible problematic references, then
9676 the warning can be suppressed by bracketing the
9677 instantiation of @code{Unchecked_Conversion} to turn
9680 @smallexample @c ada
9681 pragma Warnings (Off);
9683 new Unchecked_Conversion (a1, a2);
9684 pragma Warnings (On);
9688 Of course that approach is not appropriate for this particular
9689 example, since indeed there is a problematic reference. In this
9690 case we can take one of two other approaches.
9692 The first possibility is to move the instantiation of unchecked
9693 conversion to the unit in which the type is declared. In
9694 this example, we would move the instantiation of
9695 @code{Unchecked_Conversion} from the body of package
9696 @code{p2} to the spec of package @code{p1}. Now the
9697 warning disappears. That's because any use of the
9698 access type knows there is a suspicious unchecked
9699 conversion, and the strict aliasing optimization
9700 is automatically suppressed for the type.
9702 If it is not practical to move the unchecked conversion to the same unit
9703 in which the destination access type is declared (perhaps because the
9704 source type is not visible in that unit), you may use pragma
9705 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
9706 same declarative sequence as the declaration of the access type:
9708 @smallexample @c ada
9709 type a2 is access int2;
9710 pragma No_Strict_Aliasing (a2);
9714 Here again, the compiler now knows that the strict aliasing optimization
9715 should be suppressed for any reference to type @code{a2} and the
9716 expected behavior is obtained.
9718 Finally, note that although the compiler can generate warnings for
9719 simple cases of unchecked conversions, there are tricker and more
9720 indirect ways of creating type incorrect aliases which the compiler
9721 cannot detect. Examples are the use of address overlays and unchecked
9722 conversions involving composite types containing access types as
9723 components. In such cases, no warnings are generated, but there can
9724 still be aliasing problems. One safe coding practice is to forbid the
9725 use of address clauses for type overlaying, and to allow unchecked
9726 conversion only for primitive types. This is not really a significant
9727 restriction since any possible desired effect can be achieved by
9728 unchecked conversion of access values.
9731 @node Coverage Analysis
9732 @subsection Coverage Analysis
9735 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
9736 the user to determine the distribution of execution time across a program,
9737 @pxref{Profiling} for details of usage.
9740 @node Reducing Size of Ada Executables with gnatelim
9741 @section Reducing Size of Ada Executables with @code{gnatelim}
9745 This section describes @command{gnatelim}, a tool which detects unused
9746 subprograms and helps the compiler to create a smaller executable for your
9751 * Running gnatelim::
9752 * Correcting the List of Eliminate Pragmas::
9753 * Making Your Executables Smaller::
9754 * Summary of the gnatelim Usage Cycle::
9757 @node About gnatelim
9758 @subsection About @code{gnatelim}
9761 When a program shares a set of Ada
9762 packages with other programs, it may happen that this program uses
9763 only a fraction of the subprograms defined in these packages. The code
9764 created for these unused subprograms increases the size of the executable.
9766 @code{gnatelim} tracks unused subprograms in an Ada program and
9767 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
9768 subprograms that are declared but never called. By placing the list of
9769 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
9770 recompiling your program, you may decrease the size of its executable,
9771 because the compiler will not generate the code for 'eliminated' subprograms.
9772 See GNAT Reference Manual for more information about this pragma.
9774 @code{gnatelim} needs as its input data the name of the main subprogram
9775 and a bind file for a main subprogram.
9777 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
9778 the main subprogram. @code{gnatelim} can work with both Ada and C
9779 bind files; when both are present, it uses the Ada bind file.
9780 The following commands will build the program and create the bind file:
9783 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
9784 $ gnatbind main_prog
9787 Note that @code{gnatelim} needs neither object nor ALI files.
9789 @node Running gnatelim
9790 @subsection Running @code{gnatelim}
9793 @code{gnatelim} has the following command-line interface:
9796 $ gnatelim [options] name
9800 @code{name} should be a name of a source file that contains the main subprogram
9801 of a program (partition).
9803 @code{gnatelim} has the following switches:
9808 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
9809 Quiet mode: by default @code{gnatelim} outputs to the standard error
9810 stream the number of program units left to be processed. This option turns
9814 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
9815 Verbose mode: @code{gnatelim} version information is printed as Ada
9816 comments to the standard output stream. Also, in addition to the number of
9817 program units left @code{gnatelim} will output the name of the current unit
9821 @cindex @option{^-a^/ALL^} (@command{gnatelim})
9822 Also look for subprograms from the GNAT run time that can be eliminated. Note
9823 that when @file{gnat.adc} is produced using this switch, the entire program
9824 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
9826 @item ^-I^/INCLUDE_DIRS=^@var{dir}
9827 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
9828 When looking for source files also look in directory @var{dir}. Specifying
9829 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
9830 sources in the current directory.
9832 @item ^-b^/BIND_FILE=^@var{bind_file}
9833 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
9834 Specifies @var{bind_file} as the bind file to process. If not set, the name
9835 of the bind file is computed from the full expanded Ada name
9836 of a main subprogram.
9838 @item ^-C^/CONFIG_FILE=^@var{config_file}
9839 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
9840 Specifies a file @var{config_file} that contains configuration pragmas. The
9841 file must be specified with full path.
9843 @item ^--GCC^/COMPILER^=@var{compiler_name}
9844 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
9845 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
9846 available on the path.
9848 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
9849 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
9850 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
9851 available on the path.
9855 @code{gnatelim} sends its output to the standard output stream, and all the
9856 tracing and debug information is sent to the standard error stream.
9857 In order to produce a proper GNAT configuration file
9858 @file{gnat.adc}, redirection must be used:
9862 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
9865 $ gnatelim main_prog.adb > gnat.adc
9874 $ gnatelim main_prog.adb >> gnat.adc
9878 in order to append the @code{gnatelim} output to the existing contents of
9882 @node Correcting the List of Eliminate Pragmas
9883 @subsection Correcting the List of Eliminate Pragmas
9886 In some rare cases @code{gnatelim} may try to eliminate
9887 subprograms that are actually called in the program. In this case, the
9888 compiler will generate an error message of the form:
9891 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
9895 You will need to manually remove the wrong @code{Eliminate} pragmas from
9896 the @file{gnat.adc} file. You should recompile your program
9897 from scratch after that, because you need a consistent @file{gnat.adc} file
9898 during the entire compilation.
9900 @node Making Your Executables Smaller
9901 @subsection Making Your Executables Smaller
9904 In order to get a smaller executable for your program you now have to
9905 recompile the program completely with the new @file{gnat.adc} file
9906 created by @code{gnatelim} in your current directory:
9909 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9913 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
9914 recompile everything
9915 with the set of pragmas @code{Eliminate} that you have obtained with
9916 @command{gnatelim}).
9918 Be aware that the set of @code{Eliminate} pragmas is specific to each
9919 program. It is not recommended to merge sets of @code{Eliminate}
9920 pragmas created for different programs in one @file{gnat.adc} file.
9922 @node Summary of the gnatelim Usage Cycle
9923 @subsection Summary of the gnatelim Usage Cycle
9926 Here is a quick summary of the steps to be taken in order to reduce
9927 the size of your executables with @code{gnatelim}. You may use
9928 other GNAT options to control the optimization level,
9929 to produce the debugging information, to set search path, etc.
9936 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
9937 $ gnatbind main_prog
9941 Generate a list of @code{Eliminate} pragmas
9944 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
9947 $ gnatelim main_prog >[>] gnat.adc
9952 Recompile the application
9955 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9960 @node Reducing Size of Executables with unused subprogram/data elimination
9961 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
9962 @findex unused subprogram/data elimination
9965 This section describes how you can eliminate unused subprograms and data from
9966 your executable just by setting options at compilation time.
9969 * About unused subprogram/data elimination::
9970 * Compilation options::
9971 * Example of unused subprogram/data elimination::
9974 @node About unused subprogram/data elimination
9975 @subsection About unused subprogram/data elimination
9978 By default, an executable contains all code and data of its composing objects
9979 (directly linked or coming from statically linked libraries), even data or code
9980 never used by this executable.
9982 This feature will allow you to eliminate such unused code from your
9983 executable, making it smaller (in disk and in memory).
9985 This functionality is available on all platforms using elf binary format and
9986 having GNU binutils version 2.16.1.
9988 @node Compilation options
9989 @subsection Compilation options
9992 The operation of eliminating the unused code and data from the final executable
9993 is directly performed by the linker.
9995 In order to do this, it has to work with objects compiled with the
9997 @option{-ffunction-sections} @option{-fdata-sections}.
9998 @cindex @option{-ffunction-sections} (@command{gcc})
9999 @cindex @option{-fdata-sections} (@command{gcc})
10000 These options are usable with C and Ada files.
10001 They will place respectively each
10002 function or data in a separate section in the resulting object file.
10004 Once the objects and static libraries are created with these options, the
10005 linker can perform the dead code elimination. You can do this by setting
10006 the @option{-Wl,--gc-sections} option to gcc command or in the
10007 @option{-largs} section of gnatmake. This will perform a garbage collection of
10008 code and data never referenced.
10010 If the linker performs a partial link (@option{-r} ld linker option), then you
10011 will need to provide one or several entry point using the
10012 @option{-e} / @option{--entry} ld option.
10014 Note that objects compiled without the @option{-ffunction-sections} and
10015 @option{-fdata-sections} options can still be linked with the executable.
10016 However, no dead code elimination will be performed on those objects (they will
10019 The GNAT static library is now compiled with -ffunction-sections and
10020 -fdata-sections on some platforms. This allows you to eliminate the unused code
10021 and data of the GNAT library from your executable.
10023 @node Example of unused subprogram/data elimination
10024 @subsection Example of unused subprogram/data elimination
10027 Here is a simple example:
10029 @smallexample @c ada
10038 Used_Data : Integer;
10039 Unused_Data : Integer;
10041 procedure Used (Data : Integer);
10042 procedure Unused (Data : Integer);
10045 package body Aux is
10046 procedure Used (Data : Integer) is
10051 procedure Unused (Data : Integer) is
10053 Unused_Data := Data;
10059 @code{Unused} and @code{Unused_Data} are never referenced in this code
10060 excerpt, and hence they may be safely removed from the final executable.
10065 $ nm test | grep used
10066 020015f0 T aux__unused
10067 02005d88 B aux__unused_data
10068 020015cc T aux__used
10069 02005d84 B aux__used_data
10071 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10072 -largs -Wl,--gc-sections
10074 $ nm test | grep used
10075 02005350 T aux__used
10076 0201ffe0 B aux__used_data
10080 It can be observed that the procedure @code{Unused} and the object
10081 @code{Unused_Data} are removed by the linker when using the
10082 appropriate options.
10084 @c ********************************
10085 @node Renaming Files Using gnatchop
10086 @chapter Renaming Files Using @code{gnatchop}
10090 This chapter discusses how to handle files with multiple units by using
10091 the @code{gnatchop} utility. This utility is also useful in renaming
10092 files to meet the standard GNAT default file naming conventions.
10095 * Handling Files with Multiple Units::
10096 * Operating gnatchop in Compilation Mode::
10097 * Command Line for gnatchop::
10098 * Switches for gnatchop::
10099 * Examples of gnatchop Usage::
10102 @node Handling Files with Multiple Units
10103 @section Handling Files with Multiple Units
10106 The basic compilation model of GNAT requires that a file submitted to the
10107 compiler have only one unit and there be a strict correspondence
10108 between the file name and the unit name.
10110 The @code{gnatchop} utility allows both of these rules to be relaxed,
10111 allowing GNAT to process files which contain multiple compilation units
10112 and files with arbitrary file names. @code{gnatchop}
10113 reads the specified file and generates one or more output files,
10114 containing one unit per file. The unit and the file name correspond,
10115 as required by GNAT.
10117 If you want to permanently restructure a set of ``foreign'' files so that
10118 they match the GNAT rules, and do the remaining development using the
10119 GNAT structure, you can simply use @command{gnatchop} once, generate the
10120 new set of files and work with them from that point on.
10122 Alternatively, if you want to keep your files in the ``foreign'' format,
10123 perhaps to maintain compatibility with some other Ada compilation
10124 system, you can set up a procedure where you use @command{gnatchop} each
10125 time you compile, regarding the source files that it writes as temporary
10126 files that you throw away.
10128 @node Operating gnatchop in Compilation Mode
10129 @section Operating gnatchop in Compilation Mode
10132 The basic function of @code{gnatchop} is to take a file with multiple units
10133 and split it into separate files. The boundary between files is reasonably
10134 clear, except for the issue of comments and pragmas. In default mode, the
10135 rule is that any pragmas between units belong to the previous unit, except
10136 that configuration pragmas always belong to the following unit. Any comments
10137 belong to the following unit. These rules
10138 almost always result in the right choice of
10139 the split point without needing to mark it explicitly and most users will
10140 find this default to be what they want. In this default mode it is incorrect to
10141 submit a file containing only configuration pragmas, or one that ends in
10142 configuration pragmas, to @code{gnatchop}.
10144 However, using a special option to activate ``compilation mode'',
10146 can perform another function, which is to provide exactly the semantics
10147 required by the RM for handling of configuration pragmas in a compilation.
10148 In the absence of configuration pragmas (at the main file level), this
10149 option has no effect, but it causes such configuration pragmas to be handled
10150 in a quite different manner.
10152 First, in compilation mode, if @code{gnatchop} is given a file that consists of
10153 only configuration pragmas, then this file is appended to the
10154 @file{gnat.adc} file in the current directory. This behavior provides
10155 the required behavior described in the RM for the actions to be taken
10156 on submitting such a file to the compiler, namely that these pragmas
10157 should apply to all subsequent compilations in the same compilation
10158 environment. Using GNAT, the current directory, possibly containing a
10159 @file{gnat.adc} file is the representation
10160 of a compilation environment. For more information on the
10161 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
10163 Second, in compilation mode, if @code{gnatchop}
10164 is given a file that starts with
10165 configuration pragmas, and contains one or more units, then these
10166 configuration pragmas are prepended to each of the chopped files. This
10167 behavior provides the required behavior described in the RM for the
10168 actions to be taken on compiling such a file, namely that the pragmas
10169 apply to all units in the compilation, but not to subsequently compiled
10172 Finally, if configuration pragmas appear between units, they are appended
10173 to the previous unit. This results in the previous unit being illegal,
10174 since the compiler does not accept configuration pragmas that follow
10175 a unit. This provides the required RM behavior that forbids configuration
10176 pragmas other than those preceding the first compilation unit of a
10179 For most purposes, @code{gnatchop} will be used in default mode. The
10180 compilation mode described above is used only if you need exactly
10181 accurate behavior with respect to compilations, and you have files
10182 that contain multiple units and configuration pragmas. In this
10183 circumstance the use of @code{gnatchop} with the compilation mode
10184 switch provides the required behavior, and is for example the mode
10185 in which GNAT processes the ACVC tests.
10187 @node Command Line for gnatchop
10188 @section Command Line for @code{gnatchop}
10191 The @code{gnatchop} command has the form:
10194 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
10199 The only required argument is the file name of the file to be chopped.
10200 There are no restrictions on the form of this file name. The file itself
10201 contains one or more Ada units, in normal GNAT format, concatenated
10202 together. As shown, more than one file may be presented to be chopped.
10204 When run in default mode, @code{gnatchop} generates one output file in
10205 the current directory for each unit in each of the files.
10207 @var{directory}, if specified, gives the name of the directory to which
10208 the output files will be written. If it is not specified, all files are
10209 written to the current directory.
10211 For example, given a
10212 file called @file{hellofiles} containing
10214 @smallexample @c ada
10219 with Text_IO; use Text_IO;
10222 Put_Line ("Hello");
10232 $ gnatchop ^hellofiles^HELLOFILES.^
10236 generates two files in the current directory, one called
10237 @file{hello.ads} containing the single line that is the procedure spec,
10238 and the other called @file{hello.adb} containing the remaining text. The
10239 original file is not affected. The generated files can be compiled in
10243 When gnatchop is invoked on a file that is empty or that contains only empty
10244 lines and/or comments, gnatchop will not fail, but will not produce any
10247 For example, given a
10248 file called @file{toto.txt} containing
10250 @smallexample @c ada
10262 $ gnatchop ^toto.txt^TOT.TXT^
10266 will not produce any new file and will result in the following warnings:
10269 toto.txt:1:01: warning: empty file, contains no compilation units
10270 no compilation units found
10271 no source files written
10274 @node Switches for gnatchop
10275 @section Switches for @code{gnatchop}
10278 @command{gnatchop} recognizes the following switches:
10283 @item ^-c^/COMPILATION^
10284 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
10285 Causes @code{gnatchop} to operate in compilation mode, in which
10286 configuration pragmas are handled according to strict RM rules. See
10287 previous section for a full description of this mode.
10291 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
10292 used to parse the given file. Not all @code{xxx} options make sense,
10293 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
10294 process a source file that uses Latin-2 coding for identifiers.
10298 Causes @code{gnatchop} to generate a brief help summary to the standard
10299 output file showing usage information.
10301 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
10302 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
10303 Limit generated file names to the specified number @code{mm}
10305 This is useful if the
10306 resulting set of files is required to be interoperable with systems
10307 which limit the length of file names.
10309 If no value is given, or
10310 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
10311 a default of 39, suitable for OpenVMS Alpha
10312 Systems, is assumed
10315 No space is allowed between the @option{-k} and the numeric value. The numeric
10316 value may be omitted in which case a default of @option{-k8},
10318 with DOS-like file systems, is used. If no @option{-k} switch
10320 there is no limit on the length of file names.
10323 @item ^-p^/PRESERVE^
10324 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
10325 Causes the file ^modification^creation^ time stamp of the input file to be
10326 preserved and used for the time stamp of the output file(s). This may be
10327 useful for preserving coherency of time stamps in an environment where
10328 @code{gnatchop} is used as part of a standard build process.
10331 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
10332 Causes output of informational messages indicating the set of generated
10333 files to be suppressed. Warnings and error messages are unaffected.
10335 @item ^-r^/REFERENCE^
10336 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
10337 @findex Source_Reference
10338 Generate @code{Source_Reference} pragmas. Use this switch if the output
10339 files are regarded as temporary and development is to be done in terms
10340 of the original unchopped file. This switch causes
10341 @code{Source_Reference} pragmas to be inserted into each of the
10342 generated files to refers back to the original file name and line number.
10343 The result is that all error messages refer back to the original
10345 In addition, the debugging information placed into the object file (when
10346 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
10348 also refers back to this original file so that tools like profilers and
10349 debuggers will give information in terms of the original unchopped file.
10351 If the original file to be chopped itself contains
10352 a @code{Source_Reference}
10353 pragma referencing a third file, then gnatchop respects
10354 this pragma, and the generated @code{Source_Reference} pragmas
10355 in the chopped file refer to the original file, with appropriate
10356 line numbers. This is particularly useful when @code{gnatchop}
10357 is used in conjunction with @code{gnatprep} to compile files that
10358 contain preprocessing statements and multiple units.
10360 @item ^-v^/VERBOSE^
10361 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
10362 Causes @code{gnatchop} to operate in verbose mode. The version
10363 number and copyright notice are output, as well as exact copies of
10364 the gnat1 commands spawned to obtain the chop control information.
10366 @item ^-w^/OVERWRITE^
10367 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
10368 Overwrite existing file names. Normally @code{gnatchop} regards it as a
10369 fatal error if there is already a file with the same name as a
10370 file it would otherwise output, in other words if the files to be
10371 chopped contain duplicated units. This switch bypasses this
10372 check, and causes all but the last instance of such duplicated
10373 units to be skipped.
10377 @cindex @option{--GCC=} (@code{gnatchop})
10378 Specify the path of the GNAT parser to be used. When this switch is used,
10379 no attempt is made to add the prefix to the GNAT parser executable.
10383 @node Examples of gnatchop Usage
10384 @section Examples of @code{gnatchop} Usage
10388 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
10391 @item gnatchop -w hello_s.ada prerelease/files
10394 Chops the source file @file{hello_s.ada}. The output files will be
10395 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
10397 files with matching names in that directory (no files in the current
10398 directory are modified).
10400 @item gnatchop ^archive^ARCHIVE.^
10401 Chops the source file @file{^archive^ARCHIVE.^}
10402 into the current directory. One
10403 useful application of @code{gnatchop} is in sending sets of sources
10404 around, for example in email messages. The required sources are simply
10405 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
10407 @code{gnatchop} is used at the other end to reconstitute the original
10410 @item gnatchop file1 file2 file3 direc
10411 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
10412 the resulting files in the directory @file{direc}. Note that if any units
10413 occur more than once anywhere within this set of files, an error message
10414 is generated, and no files are written. To override this check, use the
10415 @option{^-w^/OVERWRITE^} switch,
10416 in which case the last occurrence in the last file will
10417 be the one that is output, and earlier duplicate occurrences for a given
10418 unit will be skipped.
10421 @node Configuration Pragmas
10422 @chapter Configuration Pragmas
10423 @cindex Configuration pragmas
10424 @cindex Pragmas, configuration
10427 In Ada 95, configuration pragmas include those pragmas described as
10428 such in the Ada 95 Reference Manual, as well as
10429 implementation-dependent pragmas that are configuration pragmas. See the
10430 individual descriptions of pragmas in the GNAT Reference Manual for
10431 details on these additional GNAT-specific configuration pragmas. Most
10432 notably, the pragma @code{Source_File_Name}, which allows
10433 specifying non-default names for source files, is a configuration
10434 pragma. The following is a complete list of configuration pragmas
10435 recognized by @code{GNAT}:
10442 Component_Alignment
10448 External_Name_Casing
10449 Float_Representation
10460 Propagate_Exceptions
10463 Restricted_Run_Time
10465 Restrictions_Warnings
10470 Task_Dispatching_Policy
10479 * Handling of Configuration Pragmas::
10480 * The Configuration Pragmas Files::
10483 @node Handling of Configuration Pragmas
10484 @section Handling of Configuration Pragmas
10486 Configuration pragmas may either appear at the start of a compilation
10487 unit, in which case they apply only to that unit, or they may apply to
10488 all compilations performed in a given compilation environment.
10490 GNAT also provides the @code{gnatchop} utility to provide an automatic
10491 way to handle configuration pragmas following the semantics for
10492 compilations (that is, files with multiple units), described in the RM.
10493 See @ref{Operating gnatchop in Compilation Mode} for details.
10494 However, for most purposes, it will be more convenient to edit the
10495 @file{gnat.adc} file that contains configuration pragmas directly,
10496 as described in the following section.
10498 @node The Configuration Pragmas Files
10499 @section The Configuration Pragmas Files
10500 @cindex @file{gnat.adc}
10503 In GNAT a compilation environment is defined by the current
10504 directory at the time that a compile command is given. This current
10505 directory is searched for a file whose name is @file{gnat.adc}. If
10506 this file is present, it is expected to contain one or more
10507 configuration pragmas that will be applied to the current compilation.
10508 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
10511 Configuration pragmas may be entered into the @file{gnat.adc} file
10512 either by running @code{gnatchop} on a source file that consists only of
10513 configuration pragmas, or more conveniently by
10514 direct editing of the @file{gnat.adc} file, which is a standard format
10517 In addition to @file{gnat.adc}, one additional file containing configuration
10518 pragmas may be applied to the current compilation using the switch
10519 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
10520 contains only configuration pragmas. These configuration pragmas are
10521 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
10522 is present and switch @option{-gnatA} is not used).
10524 It is allowed to specify several switches @option{-gnatec}, however only
10525 the last one on the command line will be taken into account.
10527 If you are using project file, a separate mechanism is provided using
10528 project attributes, see @ref{Specifying Configuration Pragmas} for more
10532 Of special interest to GNAT OpenVMS Alpha is the following
10533 configuration pragma:
10535 @smallexample @c ada
10537 pragma Extend_System (Aux_DEC);
10542 In the presence of this pragma, GNAT adds to the definition of the
10543 predefined package SYSTEM all the additional types and subprograms that are
10544 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
10547 @node Handling Arbitrary File Naming Conventions Using gnatname
10548 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
10549 @cindex Arbitrary File Naming Conventions
10552 * Arbitrary File Naming Conventions::
10553 * Running gnatname::
10554 * Switches for gnatname::
10555 * Examples of gnatname Usage::
10558 @node Arbitrary File Naming Conventions
10559 @section Arbitrary File Naming Conventions
10562 The GNAT compiler must be able to know the source file name of a compilation
10563 unit. When using the standard GNAT default file naming conventions
10564 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
10565 does not need additional information.
10568 When the source file names do not follow the standard GNAT default file naming
10569 conventions, the GNAT compiler must be given additional information through
10570 a configuration pragmas file (@pxref{Configuration Pragmas})
10572 When the non standard file naming conventions are well-defined,
10573 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
10574 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
10575 if the file naming conventions are irregular or arbitrary, a number
10576 of pragma @code{Source_File_Name} for individual compilation units
10578 To help maintain the correspondence between compilation unit names and
10579 source file names within the compiler,
10580 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
10583 @node Running gnatname
10584 @section Running @code{gnatname}
10587 The usual form of the @code{gnatname} command is
10590 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
10594 All of the arguments are optional. If invoked without any argument,
10595 @code{gnatname} will display its usage.
10598 When used with at least one naming pattern, @code{gnatname} will attempt to
10599 find all the compilation units in files that follow at least one of the
10600 naming patterns. To find these compilation units,
10601 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
10605 One or several Naming Patterns may be given as arguments to @code{gnatname}.
10606 Each Naming Pattern is enclosed between double quotes.
10607 A Naming Pattern is a regular expression similar to the wildcard patterns
10608 used in file names by the Unix shells or the DOS prompt.
10611 Examples of Naming Patterns are
10620 For a more complete description of the syntax of Naming Patterns,
10621 see the second kind of regular expressions described in @file{g-regexp.ads}
10622 (the ``Glob'' regular expressions).
10625 When invoked with no switches, @code{gnatname} will create a configuration
10626 pragmas file @file{gnat.adc} in the current working directory, with pragmas
10627 @code{Source_File_Name} for each file that contains a valid Ada unit.
10629 @node Switches for gnatname
10630 @section Switches for @code{gnatname}
10633 Switches for @code{gnatname} must precede any specified Naming Pattern.
10636 You may specify any of the following switches to @code{gnatname}:
10641 @item ^-c^/CONFIG_FILE=^@file{file}
10642 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
10643 Create a configuration pragmas file @file{file} (instead of the default
10646 There may be zero, one or more space between @option{-c} and
10649 @file{file} may include directory information. @file{file} must be
10650 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
10651 When a switch @option{^-c^/CONFIG_FILE^} is
10652 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
10654 @item ^-d^/SOURCE_DIRS=^@file{dir}
10655 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
10656 Look for source files in directory @file{dir}. There may be zero, one or more
10657 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
10658 When a switch @option{^-d^/SOURCE_DIRS^}
10659 is specified, the current working directory will not be searched for source
10660 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
10661 or @option{^-D^/DIR_FILES^} switch.
10662 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
10663 If @file{dir} is a relative path, it is relative to the directory of
10664 the configuration pragmas file specified with switch
10665 @option{^-c^/CONFIG_FILE^},
10666 or to the directory of the project file specified with switch
10667 @option{^-P^/PROJECT_FILE^} or,
10668 if neither switch @option{^-c^/CONFIG_FILE^}
10669 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
10670 current working directory. The directory
10671 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
10673 @item ^-D^/DIRS_FILE=^@file{file}
10674 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
10675 Look for source files in all directories listed in text file @file{file}.
10676 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
10678 @file{file} must be an existing, readable text file.
10679 Each non empty line in @file{file} must be a directory.
10680 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
10681 switches @option{^-d^/SOURCE_DIRS^} as there are non empty lines in
10684 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
10685 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
10686 Foreign patterns. Using this switch, it is possible to add sources of languages
10687 other than Ada to the list of sources of a project file.
10688 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
10691 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
10694 will look for Ada units in all files with the @file{.ada} extension,
10695 and will add to the list of file for project @file{prj.gpr} the C files
10696 with extension ".^c^C^".
10699 @cindex @option{^-h^/HELP^} (@code{gnatname})
10700 Output usage (help) information. The output is written to @file{stdout}.
10702 @item ^-P^/PROJECT_FILE=^@file{proj}
10703 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
10704 Create or update project file @file{proj}. There may be zero, one or more space
10705 between @option{-P} and @file{proj}. @file{proj} may include directory
10706 information. @file{proj} must be writable.
10707 There may be only one switch @option{^-P^/PROJECT_FILE^}.
10708 When a switch @option{^-P^/PROJECT_FILE^} is specified,
10709 no switch @option{^-c^/CONFIG_FILE^} may be specified.
10711 @item ^-v^/VERBOSE^
10712 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
10713 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
10714 This includes name of the file written, the name of the directories to search
10715 and, for each file in those directories whose name matches at least one of
10716 the Naming Patterns, an indication of whether the file contains a unit,
10717 and if so the name of the unit.
10719 @item ^-v -v^/VERBOSE /VERBOSE^
10720 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
10721 Very Verbose mode. In addition to the output produced in verbose mode,
10722 for each file in the searched directories whose name matches none of
10723 the Naming Patterns, an indication is given that there is no match.
10725 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
10726 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
10727 Excluded patterns. Using this switch, it is possible to exclude some files
10728 that would match the name patterns. For example,
10730 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
10733 will look for Ada units in all files with the @file{.ada} extension,
10734 except those whose names end with @file{_nt.ada}.
10738 @node Examples of gnatname Usage
10739 @section Examples of @code{gnatname} Usage
10743 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
10749 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
10754 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
10755 and be writable. In addition, the directory
10756 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
10757 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
10760 Note the optional spaces after @option{-c} and @option{-d}.
10765 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
10766 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
10769 $ gnatname /PROJECT_FILE=[HOME.ME]PROJ
10770 /EXCLUDED_PATTERN=*_nt_body.ada
10771 /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
10772 /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
10776 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
10777 even in conjunction with one or several switches
10778 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
10779 are used in this example.
10781 @c *****************************************
10782 @c * G N A T P r o j e c t M a n a g e r *
10783 @c *****************************************
10784 @node GNAT Project Manager
10785 @chapter GNAT Project Manager
10789 * Examples of Project Files::
10790 * Project File Syntax::
10791 * Objects and Sources in Project Files::
10792 * Importing Projects::
10793 * Project Extension::
10794 * Project Hierarchy Extension::
10795 * External References in Project Files::
10796 * Packages in Project Files::
10797 * Variables from Imported Projects::
10799 * Library Projects::
10800 * Stand-alone Library Projects::
10801 * Switches Related to Project Files::
10802 * Tools Supporting Project Files::
10803 * An Extended Example::
10804 * Project File Complete Syntax::
10807 @c ****************
10808 @c * Introduction *
10809 @c ****************
10812 @section Introduction
10815 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
10816 you to manage complex builds involving a number of source files, directories,
10817 and compilation options for different system configurations. In particular,
10818 project files allow you to specify:
10821 The directory or set of directories containing the source files, and/or the
10822 names of the specific source files themselves
10824 The directory in which the compiler's output
10825 (@file{ALI} files, object files, tree files) is to be placed
10827 The directory in which the executable programs is to be placed
10829 ^Switch^Switch^ settings for any of the project-enabled tools
10830 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
10831 @code{gnatfind}); you can apply these settings either globally or to individual
10834 The source files containing the main subprogram(s) to be built
10836 The source programming language(s) (currently Ada and/or C)
10838 Source file naming conventions; you can specify these either globally or for
10839 individual compilation units
10846 @node Project Files
10847 @subsection Project Files
10850 Project files are written in a syntax close to that of Ada, using familiar
10851 notions such as packages, context clauses, declarations, default values,
10852 assignments, and inheritance. Finally, project files can be built
10853 hierarchically from other project files, simplifying complex system
10854 integration and project reuse.
10856 A @dfn{project} is a specific set of values for various compilation properties.
10857 The settings for a given project are described by means of
10858 a @dfn{project file}, which is a text file written in an Ada-like syntax.
10859 Property values in project files are either strings or lists of strings.
10860 Properties that are not explicitly set receive default values. A project
10861 file may interrogate the values of @dfn{external variables} (user-defined
10862 command-line switches or environment variables), and it may specify property
10863 settings conditionally, based on the value of such variables.
10865 In simple cases, a project's source files depend only on other source files
10866 in the same project, or on the predefined libraries. (@emph{Dependence} is
10868 the Ada technical sense; as in one Ada unit @code{with}ing another.) However,
10869 the Project Manager also allows more sophisticated arrangements,
10870 where the source files in one project depend on source files in other
10874 One project can @emph{import} other projects containing needed source files.
10876 You can organize GNAT projects in a hierarchy: a @emph{child} project
10877 can extend a @emph{parent} project, inheriting the parent's source files and
10878 optionally overriding any of them with alternative versions
10882 More generally, the Project Manager lets you structure large development
10883 efforts into hierarchical subsystems, where build decisions are delegated
10884 to the subsystem level, and thus different compilation environments
10885 (^switch^switch^ settings) used for different subsystems.
10887 The Project Manager is invoked through the
10888 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
10889 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
10891 There may be zero, one or more spaces between @option{-P} and
10892 @option{@emph{projectfile}}.
10894 If you want to define (on the command line) an external variable that is
10895 queried by the project file, you must use the
10896 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
10897 The Project Manager parses and interprets the project file, and drives the
10898 invoked tool based on the project settings.
10900 The Project Manager supports a wide range of development strategies,
10901 for systems of all sizes. Here are some typical practices that are
10905 Using a common set of source files, but generating object files in different
10906 directories via different ^switch^switch^ settings
10908 Using a mostly-shared set of source files, but with different versions of
10913 The destination of an executable can be controlled inside a project file
10914 using the @option{^-o^-o^}
10916 In the absence of such a ^switch^switch^ either inside
10917 the project file or on the command line, any executable files generated by
10918 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
10919 in the project file. If no @code{Exec_Dir} is specified, they will be placed
10920 in the object directory of the project.
10922 You can use project files to achieve some of the effects of a source
10923 versioning system (for example, defining separate projects for
10924 the different sets of sources that comprise different releases) but the
10925 Project Manager is independent of any source configuration management tools
10926 that might be used by the developers.
10928 The next section introduces the main features of GNAT's project facility
10929 through a sequence of examples; subsequent sections will present the syntax
10930 and semantics in more detail. A more formal description of the project
10931 facility appears in the GNAT Reference Manual.
10933 @c *****************************
10934 @c * Examples of Project Files *
10935 @c *****************************
10937 @node Examples of Project Files
10938 @section Examples of Project Files
10940 This section illustrates some of the typical uses of project files and
10941 explains their basic structure and behavior.
10944 * Common Sources with Different ^Switches^Switches^ and Directories::
10945 * Using External Variables::
10946 * Importing Other Projects::
10947 * Extending a Project::
10950 @node Common Sources with Different ^Switches^Switches^ and Directories
10951 @subsection Common Sources with Different ^Switches^Switches^ and Directories
10955 * Specifying the Object Directory::
10956 * Specifying the Exec Directory::
10957 * Project File Packages::
10958 * Specifying ^Switch^Switch^ Settings::
10959 * Main Subprograms::
10960 * Executable File Names::
10961 * Source File Naming Conventions::
10962 * Source Language(s)::
10966 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
10967 @file{proc.adb} are in the @file{/common} directory. The file
10968 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
10969 package @code{Pack}. We want to compile these source files under two sets
10970 of ^switches^switches^:
10973 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
10974 and the @option{^-gnata^-gnata^},
10975 @option{^-gnato^-gnato^},
10976 and @option{^-gnatE^-gnatE^} switches to the
10977 compiler; the compiler's output is to appear in @file{/common/debug}
10979 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
10980 to the compiler; the compiler's output is to appear in @file{/common/release}
10984 The GNAT project files shown below, respectively @file{debug.gpr} and
10985 @file{release.gpr} in the @file{/common} directory, achieve these effects.
10998 ^/common/debug^[COMMON.DEBUG]^
11003 ^/common/release^[COMMON.RELEASE]^
11008 Here are the corresponding project files:
11010 @smallexample @c projectfile
11013 for Object_Dir use "debug";
11014 for Main use ("proc");
11017 for ^Default_Switches^Default_Switches^ ("Ada")
11019 for Executable ("proc.adb") use "proc1";
11024 package Compiler is
11025 for ^Default_Switches^Default_Switches^ ("Ada")
11026 use ("-fstack-check",
11029 "^-gnatE^-gnatE^");
11035 @smallexample @c projectfile
11038 for Object_Dir use "release";
11039 for Exec_Dir use ".";
11040 for Main use ("proc");
11042 package Compiler is
11043 for ^Default_Switches^Default_Switches^ ("Ada")
11051 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
11052 insensitive), and analogously the project defined by @file{release.gpr} is
11053 @code{"Release"}. For consistency the file should have the same name as the
11054 project, and the project file's extension should be @code{"gpr"}. These
11055 conventions are not required, but a warning is issued if they are not followed.
11057 If the current directory is @file{^/temp^[TEMP]^}, then the command
11059 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
11063 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
11064 as well as the @code{^proc1^PROC1.EXE^} executable,
11065 using the ^switch^switch^ settings defined in the project file.
11067 Likewise, the command
11069 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
11073 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
11074 and the @code{^proc^PROC.EXE^}
11075 executable in @file{^/common^[COMMON]^},
11076 using the ^switch^switch^ settings from the project file.
11079 @unnumberedsubsubsec Source Files
11082 If a project file does not explicitly specify a set of source directories or
11083 a set of source files, then by default the project's source files are the
11084 Ada source files in the project file directory. Thus @file{pack.ads},
11085 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
11087 @node Specifying the Object Directory
11088 @unnumberedsubsubsec Specifying the Object Directory
11091 Several project properties are modeled by Ada-style @emph{attributes};
11092 a property is defined by supplying the equivalent of an Ada attribute
11093 definition clause in the project file.
11094 A project's object directory is another such a property; the corresponding
11095 attribute is @code{Object_Dir}, and its value is also a string expression,
11096 specified either as absolute or relative. In the later case,
11097 it is relative to the project file directory. Thus the compiler's
11098 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
11099 (for the @code{Debug} project)
11100 and to @file{^/common/release^[COMMON.RELEASE]^}
11101 (for the @code{Release} project).
11102 If @code{Object_Dir} is not specified, then the default is the project file
11105 @node Specifying the Exec Directory
11106 @unnumberedsubsubsec Specifying the Exec Directory
11109 A project's exec directory is another property; the corresponding
11110 attribute is @code{Exec_Dir}, and its value is also a string expression,
11111 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
11112 then the default is the object directory (which may also be the project file
11113 directory if attribute @code{Object_Dir} is not specified). Thus the executable
11114 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
11115 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
11116 and in @file{^/common^[COMMON]^} for the @code{Release} project.
11118 @node Project File Packages
11119 @unnumberedsubsubsec Project File Packages
11122 A GNAT tool that is integrated with the Project Manager is modeled by a
11123 corresponding package in the project file. In the example above,
11124 The @code{Debug} project defines the packages @code{Builder}
11125 (for @command{gnatmake}) and @code{Compiler};
11126 the @code{Release} project defines only the @code{Compiler} package.
11128 The Ada-like package syntax is not to be taken literally. Although packages in
11129 project files bear a surface resemblance to packages in Ada source code, the
11130 notation is simply a way to convey a grouping of properties for a named
11131 entity. Indeed, the package names permitted in project files are restricted
11132 to a predefined set, corresponding to the project-aware tools, and the contents
11133 of packages are limited to a small set of constructs.
11134 The packages in the example above contain attribute definitions.
11136 @node Specifying ^Switch^Switch^ Settings
11137 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
11140 ^Switch^Switch^ settings for a project-aware tool can be specified through
11141 attributes in the package that corresponds to the tool.
11142 The example above illustrates one of the relevant attributes,
11143 @code{^Default_Switches^Default_Switches^}, which is defined in packages
11144 in both project files.
11145 Unlike simple attributes like @code{Source_Dirs},
11146 @code{^Default_Switches^Default_Switches^} is
11147 known as an @emph{associative array}. When you define this attribute, you must
11148 supply an ``index'' (a literal string), and the effect of the attribute
11149 definition is to set the value of the array at the specified index.
11150 For the @code{^Default_Switches^Default_Switches^} attribute,
11151 the index is a programming language (in our case, Ada),
11152 and the value specified (after @code{use}) must be a list
11153 of string expressions.
11155 The attributes permitted in project files are restricted to a predefined set.
11156 Some may appear at project level, others in packages.
11157 For any attribute that is an associative array, the index must always be a
11158 literal string, but the restrictions on this string (e.g., a file name or a
11159 language name) depend on the individual attribute.
11160 Also depending on the attribute, its specified value will need to be either a
11161 string or a string list.
11163 In the @code{Debug} project, we set the switches for two tools,
11164 @command{gnatmake} and the compiler, and thus we include the two corresponding
11165 packages; each package defines the @code{^Default_Switches^Default_Switches^}
11166 attribute with index @code{"Ada"}.
11167 Note that the package corresponding to
11168 @command{gnatmake} is named @code{Builder}. The @code{Release} project is
11169 similar, but only includes the @code{Compiler} package.
11171 In project @code{Debug} above, the ^switches^switches^ starting with
11172 @option{-gnat} that are specified in package @code{Compiler}
11173 could have been placed in package @code{Builder}, since @command{gnatmake}
11174 transmits all such ^switches^switches^ to the compiler.
11176 @node Main Subprograms
11177 @unnumberedsubsubsec Main Subprograms
11180 One of the specifiable properties of a project is a list of files that contain
11181 main subprograms. This property is captured in the @code{Main} attribute,
11182 whose value is a list of strings. If a project defines the @code{Main}
11183 attribute, it is not necessary to identify the main subprogram(s) when
11184 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
11186 @node Executable File Names
11187 @unnumberedsubsubsec Executable File Names
11190 By default, the executable file name corresponding to a main source is
11191 deduced from the main source file name. Through the attributes
11192 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
11193 it is possible to change this default.
11194 In project @code{Debug} above, the executable file name
11195 for main source @file{^proc.adb^PROC.ADB^} is
11196 @file{^proc1^PROC1.EXE^}.
11197 Attribute @code{Executable_Suffix}, when specified, may change the suffix
11198 of the executable files, when no attribute @code{Executable} applies:
11199 its value replace the platform-specific executable suffix.
11200 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
11201 specify a non default executable file name when several mains are built at once
11202 in a single @command{gnatmake} command.
11204 @node Source File Naming Conventions
11205 @unnumberedsubsubsec Source File Naming Conventions
11208 Since the project files above do not specify any source file naming
11209 conventions, the GNAT defaults are used. The mechanism for defining source
11210 file naming conventions -- a package named @code{Naming} --
11211 is described below (@pxref{Naming Schemes}).
11213 @node Source Language(s)
11214 @unnumberedsubsubsec Source Language(s)
11217 Since the project files do not specify a @code{Languages} attribute, by
11218 default the GNAT tools assume that the language of the project file is Ada.
11219 More generally, a project can comprise source files
11220 in Ada, C, and/or other languages.
11222 @node Using External Variables
11223 @subsection Using External Variables
11226 Instead of supplying different project files for debug and release, we can
11227 define a single project file that queries an external variable (set either
11228 on the command line or via an ^environment variable^logical name^) in order to
11229 conditionally define the appropriate settings. Again, assume that the
11230 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
11231 located in directory @file{^/common^[COMMON]^}. The following project file,
11232 @file{build.gpr}, queries the external variable named @code{STYLE} and
11233 defines an object directory and ^switch^switch^ settings based on whether
11234 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
11235 the default is @code{"deb"}.
11237 @smallexample @c projectfile
11240 for Main use ("proc");
11242 type Style_Type is ("deb", "rel");
11243 Style : Style_Type := external ("STYLE", "deb");
11247 for Object_Dir use "debug";
11250 for Object_Dir use "release";
11251 for Exec_Dir use ".";
11260 for ^Default_Switches^Default_Switches^ ("Ada")
11262 for Executable ("proc") use "proc1";
11271 package Compiler is
11275 for ^Default_Switches^Default_Switches^ ("Ada")
11276 use ("^-gnata^-gnata^",
11278 "^-gnatE^-gnatE^");
11281 for ^Default_Switches^Default_Switches^ ("Ada")
11292 @code{Style_Type} is an example of a @emph{string type}, which is the project
11293 file analog of an Ada enumeration type but whose components are string literals
11294 rather than identifiers. @code{Style} is declared as a variable of this type.
11296 The form @code{external("STYLE", "deb")} is known as an
11297 @emph{external reference}; its first argument is the name of an
11298 @emph{external variable}, and the second argument is a default value to be
11299 used if the external variable doesn't exist. You can define an external
11300 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
11301 or you can use ^an environment variable^a logical name^
11302 as an external variable.
11304 Each @code{case} construct is expanded by the Project Manager based on the
11305 value of @code{Style}. Thus the command
11308 gnatmake -P/common/build.gpr -XSTYLE=deb
11314 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
11319 is equivalent to the @command{gnatmake} invocation using the project file
11320 @file{debug.gpr} in the earlier example. So is the command
11322 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
11326 since @code{"deb"} is the default for @code{STYLE}.
11332 gnatmake -P/common/build.gpr -XSTYLE=rel
11338 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
11343 is equivalent to the @command{gnatmake} invocation using the project file
11344 @file{release.gpr} in the earlier example.
11346 @node Importing Other Projects
11347 @subsection Importing Other Projects
11348 @cindex @code{ADA_PROJECT_PATH}
11351 A compilation unit in a source file in one project may depend on compilation
11352 units in source files in other projects. To compile this unit under
11353 control of a project file, the
11354 dependent project must @emph{import} the projects containing the needed source
11356 This effect is obtained using syntax similar to an Ada @code{with} clause,
11357 but where @code{with}ed entities are strings that denote project files.
11359 As an example, suppose that the two projects @code{GUI_Proj} and
11360 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
11361 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
11362 and @file{^/comm^[COMM]^}, respectively.
11363 Suppose that the source files for @code{GUI_Proj} are
11364 @file{gui.ads} and @file{gui.adb}, and that the source files for
11365 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
11366 files is located in its respective project file directory. Schematically:
11385 We want to develop an application in directory @file{^/app^[APP]^} that
11386 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
11387 the corresponding project files (e.g. the ^switch^switch^ settings
11388 and object directory).
11389 Skeletal code for a main procedure might be something like the following:
11391 @smallexample @c ada
11394 procedure App_Main is
11403 Here is a project file, @file{app_proj.gpr}, that achieves the desired
11406 @smallexample @c projectfile
11408 with "/gui/gui_proj", "/comm/comm_proj";
11409 project App_Proj is
11410 for Main use ("app_main");
11416 Building an executable is achieved through the command:
11418 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
11421 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
11422 in the directory where @file{app_proj.gpr} resides.
11424 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
11425 (as illustrated above) the @code{with} clause can omit the extension.
11427 Our example specified an absolute path for each imported project file.
11428 Alternatively, the directory name of an imported object can be omitted
11432 The imported project file is in the same directory as the importing project
11435 You have defined ^an environment variable^a logical name^
11436 that includes the directory containing
11437 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
11438 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
11439 directory names separated by colons (semicolons on Windows).
11443 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
11444 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
11447 @smallexample @c projectfile
11449 with "gui_proj", "comm_proj";
11450 project App_Proj is
11451 for Main use ("app_main");
11457 Importing other projects can create ambiguities.
11458 For example, the same unit might be present in different imported projects, or
11459 it might be present in both the importing project and in an imported project.
11460 Both of these conditions are errors. Note that in the current version of
11461 the Project Manager, it is illegal to have an ambiguous unit even if the
11462 unit is never referenced by the importing project. This restriction may be
11463 relaxed in a future release.
11465 @node Extending a Project
11466 @subsection Extending a Project
11469 In large software systems it is common to have multiple
11470 implementations of a common interface; in Ada terms, multiple versions of a
11471 package body for the same specification. For example, one implementation
11472 might be safe for use in tasking programs, while another might only be used
11473 in sequential applications. This can be modeled in GNAT using the concept
11474 of @emph{project extension}. If one project (the ``child'') @emph{extends}
11475 another project (the ``parent'') then by default all source files of the
11476 parent project are inherited by the child, but the child project can
11477 override any of the parent's source files with new versions, and can also
11478 add new files. This facility is the project analog of a type extension in
11479 Object-Oriented Programming. Project hierarchies are permitted (a child
11480 project may be the parent of yet another project), and a project that
11481 inherits one project can also import other projects.
11483 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
11484 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
11485 @file{pack.adb}, and @file{proc.adb}:
11498 Note that the project file can simply be empty (that is, no attribute or
11499 package is defined):
11501 @smallexample @c projectfile
11503 project Seq_Proj is
11509 implying that its source files are all the Ada source files in the project
11512 Suppose we want to supply an alternate version of @file{pack.adb}, in
11513 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
11514 @file{pack.ads} and @file{proc.adb}. We can define a project
11515 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
11519 ^/tasking^[TASKING]^
11525 project Tasking_Proj extends "/seq/seq_proj" is
11531 The version of @file{pack.adb} used in a build depends on which project file
11534 Note that we could have obtained the desired behavior using project import
11535 rather than project inheritance; a @code{base} project would contain the
11536 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
11537 import @code{base} and add @file{pack.adb}, and likewise a tasking project
11538 would import @code{base} and add a different version of @file{pack.adb}. The
11539 choice depends on whether other sources in the original project need to be
11540 overridden. If they do, then project extension is necessary, otherwise,
11541 importing is sufficient.
11544 In a project file that extends another project file, it is possible to
11545 indicate that an inherited source is not part of the sources of the extending
11546 project. This is necessary sometimes when a package spec has been overloaded
11547 and no longer requires a body: in this case, it is necessary to indicate that
11548 the inherited body is not part of the sources of the project, otherwise there
11549 will be a compilation error when compiling the spec.
11551 For that purpose, the attribute @code{Locally_Removed_Files} is used.
11552 Its value is a string list: a list of file names.
11554 @smallexample @c @projectfile
11555 project B extends "a" is
11556 for Source_Files use ("pkg.ads");
11557 -- New spec of Pkg does not need a completion
11558 for Locally_Removed_Files use ("pkg.adb");
11562 Attribute @code{Locally_Removed_Files} may also be used to check if a source
11563 is still needed: if it is possible to build using @command{gnatmake} when such
11564 a source is put in attribute @code{Locally_Removed_Files} of a project P, then
11565 it is possible to remove the source completely from a system that includes
11568 @c ***********************
11569 @c * Project File Syntax *
11570 @c ***********************
11572 @node Project File Syntax
11573 @section Project File Syntax
11582 * Associative Array Attributes::
11583 * case Constructions::
11587 This section describes the structure of project files.
11589 A project may be an @emph{independent project}, entirely defined by a single
11590 project file. Any Ada source file in an independent project depends only
11591 on the predefined library and other Ada source files in the same project.
11594 A project may also @dfn{depend on} other projects, in either or both of
11595 the following ways:
11597 @item It may import any number of projects
11598 @item It may extend at most one other project
11602 The dependence relation is a directed acyclic graph (the subgraph reflecting
11603 the ``extends'' relation is a tree).
11605 A project's @dfn{immediate sources} are the source files directly defined by
11606 that project, either implicitly by residing in the project file's directory,
11607 or explicitly through any of the source-related attributes described below.
11608 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
11609 of @var{proj} together with the immediate sources (unless overridden) of any
11610 project on which @var{proj} depends (either directly or indirectly).
11613 @subsection Basic Syntax
11616 As seen in the earlier examples, project files have an Ada-like syntax.
11617 The minimal project file is:
11618 @smallexample @c projectfile
11627 The identifier @code{Empty} is the name of the project.
11628 This project name must be present after the reserved
11629 word @code{end} at the end of the project file, followed by a semi-colon.
11631 Any name in a project file, such as the project name or a variable name,
11632 has the same syntax as an Ada identifier.
11634 The reserved words of project files are the Ada reserved words plus
11635 @code{extends}, @code{external}, and @code{project}. Note that the only Ada
11636 reserved words currently used in project file syntax are:
11664 Comments in project files have the same syntax as in Ada, two consecutives
11665 hyphens through the end of the line.
11668 @subsection Packages
11671 A project file may contain @emph{packages}. The name of a package must be one
11672 of the identifiers from the following list. A package
11673 with a given name may only appear once in a project file. Package names are
11674 case insensitive. The following package names are legal:
11690 @code{Cross_Reference}
11694 @code{Pretty_Printer}
11704 @code{Language_Processing}
11708 In its simplest form, a package may be empty:
11710 @smallexample @c projectfile
11720 A package may contain @emph{attribute declarations},
11721 @emph{variable declarations} and @emph{case constructions}, as will be
11724 When there is ambiguity between a project name and a package name,
11725 the name always designates the project. To avoid possible confusion, it is
11726 always a good idea to avoid naming a project with one of the
11727 names allowed for packages or any name that starts with @code{gnat}.
11730 @subsection Expressions
11733 An @emph{expression} is either a @emph{string expression} or a
11734 @emph{string list expression}.
11736 A @emph{string expression} is either a @emph{simple string expression} or a
11737 @emph{compound string expression}.
11739 A @emph{simple string expression} is one of the following:
11741 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
11742 @item A string-valued variable reference (@pxref{Variables})
11743 @item A string-valued attribute reference (@pxref{Attributes})
11744 @item An external reference (@pxref{External References in Project Files})
11748 A @emph{compound string expression} is a concatenation of string expressions,
11749 using the operator @code{"&"}
11751 Path & "/" & File_Name & ".ads"
11755 A @emph{string list expression} is either a
11756 @emph{simple string list expression} or a
11757 @emph{compound string list expression}.
11759 A @emph{simple string list expression} is one of the following:
11761 @item A parenthesized list of zero or more string expressions,
11762 separated by commas
11764 File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
11767 @item A string list-valued variable reference
11768 @item A string list-valued attribute reference
11772 A @emph{compound string list expression} is the concatenation (using
11773 @code{"&"}) of a simple string list expression and an expression. Note that
11774 each term in a compound string list expression, except the first, may be
11775 either a string expression or a string list expression.
11777 @smallexample @c projectfile
11779 File_Name_List := () & File_Name; -- One string in this list
11780 Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
11782 Big_List := File_Name_List & Extended_File_Name_List;
11783 -- Concatenation of two string lists: three strings
11784 Illegal_List := "gnat.adc" & Extended_File_Name_List;
11785 -- Illegal: must start with a string list
11790 @subsection String Types
11793 A @emph{string type declaration} introduces a discrete set of string literals.
11794 If a string variable is declared to have this type, its value
11795 is restricted to the given set of literals.
11797 Here is an example of a string type declaration:
11799 @smallexample @c projectfile
11800 type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
11804 Variables of a string type are called @emph{typed variables}; all other
11805 variables are called @emph{untyped variables}. Typed variables are
11806 particularly useful in @code{case} constructions, to support conditional
11807 attribute declarations.
11808 (@pxref{case Constructions}).
11810 The string literals in the list are case sensitive and must all be different.
11811 They may include any graphic characters allowed in Ada, including spaces.
11813 A string type may only be declared at the project level, not inside a package.
11815 A string type may be referenced by its name if it has been declared in the same
11816 project file, or by an expanded name whose prefix is the name of the project
11817 in which it is declared.
11820 @subsection Variables
11823 A variable may be declared at the project file level, or within a package.
11824 Here are some examples of variable declarations:
11826 @smallexample @c projectfile
11828 This_OS : OS := external ("OS"); -- a typed variable declaration
11829 That_OS := "GNU/Linux"; -- an untyped variable declaration
11834 The syntax of a @emph{typed variable declaration} is identical to the Ada
11835 syntax for an object declaration. By contrast, the syntax of an untyped
11836 variable declaration is identical to an Ada assignment statement. In fact,
11837 variable declarations in project files have some of the characteristics of
11838 an assignment, in that successive declarations for the same variable are
11839 allowed. Untyped variable declarations do establish the expected kind of the
11840 variable (string or string list), and successive declarations for it must
11841 respect the initial kind.
11844 A string variable declaration (typed or untyped) declares a variable
11845 whose value is a string. This variable may be used as a string expression.
11846 @smallexample @c projectfile
11847 File_Name := "readme.txt";
11848 Saved_File_Name := File_Name & ".saved";
11852 A string list variable declaration declares a variable whose value is a list
11853 of strings. The list may contain any number (zero or more) of strings.
11855 @smallexample @c projectfile
11857 List_With_One_Element := ("^-gnaty^-gnaty^");
11858 List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
11859 Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
11860 "pack2.ada", "util_.ada", "util.ada");
11864 The same typed variable may not be declared more than once at project level,
11865 and it may not be declared more than once in any package; it is in effect
11868 The same untyped variable may be declared several times. Declarations are
11869 elaborated in the order in which they appear, so the new value replaces
11870 the old one, and any subsequent reference to the variable uses the new value.
11871 However, as noted above, if a variable has been declared as a string, all
11873 declarations must give it a string value. Similarly, if a variable has
11874 been declared as a string list, all subsequent declarations
11875 must give it a string list value.
11877 A @emph{variable reference} may take several forms:
11880 @item The simple variable name, for a variable in the current package (if any)
11881 or in the current project
11882 @item An expanded name, whose prefix is a context name.
11886 A @emph{context} may be one of the following:
11889 @item The name of an existing package in the current project
11890 @item The name of an imported project of the current project
11891 @item The name of an ancestor project (i.e., a project extended by the current
11892 project, either directly or indirectly)
11893 @item An expanded name whose prefix is an imported/parent project name, and
11894 whose selector is a package name in that project.
11898 A variable reference may be used in an expression.
11901 @subsection Attributes
11904 A project (and its packages) may have @emph{attributes} that define
11905 the project's properties. Some attributes have values that are strings;
11906 others have values that are string lists.
11908 There are two categories of attributes: @emph{simple attributes}
11909 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
11911 Legal project attribute names, and attribute names for each legal package are
11912 listed below. Attributes names are case-insensitive.
11914 The following attributes are defined on projects (all are simple attributes):
11916 @multitable @columnfractions .4 .3
11917 @item @emph{Attribute Name}
11919 @item @code{Source_Files}
11921 @item @code{Source_Dirs}
11923 @item @code{Source_List_File}
11925 @item @code{Object_Dir}
11927 @item @code{Exec_Dir}
11929 @item @code{Locally_Removed_Files}
11931 @item @code{Languages}
11935 @item @code{Library_Dir}
11937 @item @code{Library_Name}
11939 @item @code{Library_Kind}
11941 @item @code{Library_Version}
11943 @item @code{Library_Interface}
11945 @item @code{Library_Auto_Init}
11947 @item @code{Library_Options}
11949 @item @code{Library_Src_Dir}
11951 @item @code{Library_ALI_Dir}
11953 @item @code{Library_GCC}
11955 @item @code{Library_Symbol_File}
11957 @item @code{Library_Symbol_Policy}
11959 @item @code{Library_Reference_Symbol_File}
11961 @item @code{Externally_Built}
11966 The following attributes are defined for package @code{Naming}
11967 (@pxref{Naming Schemes}):
11969 @multitable @columnfractions .4 .2 .2 .2
11970 @item Attribute Name @tab Category @tab Index @tab Value
11971 @item @code{Spec_Suffix}
11972 @tab associative array
11975 @item @code{Body_Suffix}
11976 @tab associative array
11979 @item @code{Separate_Suffix}
11980 @tab simple attribute
11983 @item @code{Casing}
11984 @tab simple attribute
11987 @item @code{Dot_Replacement}
11988 @tab simple attribute
11992 @tab associative array
11996 @tab associative array
11999 @item @code{Specification_Exceptions}
12000 @tab associative array
12003 @item @code{Implementation_Exceptions}
12004 @tab associative array
12010 The following attributes are defined for packages @code{Builder},
12011 @code{Compiler}, @code{Binder},
12012 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
12013 (@pxref{^Switches^Switches^ and Project Files}).
12015 @multitable @columnfractions .4 .2 .2 .2
12016 @item Attribute Name @tab Category @tab Index @tab Value
12017 @item @code{^Default_Switches^Default_Switches^}
12018 @tab associative array
12021 @item @code{^Switches^Switches^}
12022 @tab associative array
12028 In addition, package @code{Compiler} has a single string attribute
12029 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
12030 string attribute @code{Global_Configuration_Pragmas}.
12033 Each simple attribute has a default value: the empty string (for string-valued
12034 attributes) and the empty list (for string list-valued attributes).
12036 An attribute declaration defines a new value for an attribute.
12038 Examples of simple attribute declarations:
12040 @smallexample @c projectfile
12041 for Object_Dir use "objects";
12042 for Source_Dirs use ("units", "test/drivers");
12046 The syntax of a @dfn{simple attribute declaration} is similar to that of an
12047 attribute definition clause in Ada.
12049 Attributes references may be appear in expressions.
12050 The general form for such a reference is @code{<entity>'<attribute>}:
12051 Associative array attributes are functions. Associative
12052 array attribute references must have an argument that is a string literal.
12056 @smallexample @c projectfile
12058 Naming'Dot_Replacement
12059 Imported_Project'Source_Dirs
12060 Imported_Project.Naming'Casing
12061 Builder'^Default_Switches^Default_Switches^("Ada")
12065 The prefix of an attribute may be:
12067 @item @code{project} for an attribute of the current project
12068 @item The name of an existing package of the current project
12069 @item The name of an imported project
12070 @item The name of a parent project that is extended by the current project
12071 @item An expanded name whose prefix is imported/parent project name,
12072 and whose selector is a package name
12077 @smallexample @c projectfile
12080 for Source_Dirs use project'Source_Dirs & "units";
12081 for Source_Dirs use project'Source_Dirs & "test/drivers"
12087 In the first attribute declaration, initially the attribute @code{Source_Dirs}
12088 has the default value: an empty string list. After this declaration,
12089 @code{Source_Dirs} is a string list of one element: @code{"units"}.
12090 After the second attribute declaration @code{Source_Dirs} is a string list of
12091 two elements: @code{"units"} and @code{"test/drivers"}.
12093 Note: this example is for illustration only. In practice,
12094 the project file would contain only one attribute declaration:
12096 @smallexample @c projectfile
12097 for Source_Dirs use ("units", "test/drivers");
12100 @node Associative Array Attributes
12101 @subsection Associative Array Attributes
12104 Some attributes are defined as @emph{associative arrays}. An associative
12105 array may be regarded as a function that takes a string as a parameter
12106 and delivers a string or string list value as its result.
12108 Here are some examples of single associative array attribute associations:
12110 @smallexample @c projectfile
12111 for Body ("main") use "Main.ada";
12112 for ^Switches^Switches^ ("main.ada")
12114 "^-gnatv^-gnatv^");
12115 for ^Switches^Switches^ ("main.ada")
12116 use Builder'^Switches^Switches^ ("main.ada")
12121 Like untyped variables and simple attributes, associative array attributes
12122 may be declared several times. Each declaration supplies a new value for the
12123 attribute, and replaces the previous setting.
12126 An associative array attribute may be declared as a full associative array
12127 declaration, with the value of the same attribute in an imported or extended
12130 @smallexample @c projectfile
12132 for Default_Switches use Default.Builder'Default_Switches;
12137 In this example, @code{Default} must be either a project imported by the
12138 current project, or the project that the current project extends. If the
12139 attribute is in a package (in this case, in package @code{Builder}), the same
12140 package needs to be specified.
12143 A full associative array declaration replaces any other declaration for the
12144 attribute, including other full associative array declaration. Single
12145 associative array associations may be declare after a full associative
12146 declaration, modifying the value for a single association of the attribute.
12148 @node case Constructions
12149 @subsection @code{case} Constructions
12152 A @code{case} construction is used in a project file to effect conditional
12154 Here is a typical example:
12156 @smallexample @c projectfile
12159 type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
12161 OS : OS_Type := external ("OS", "GNU/Linux");
12165 package Compiler is
12167 when "GNU/Linux" | "Unix" =>
12168 for ^Default_Switches^Default_Switches^ ("Ada")
12169 use ("^-gnath^-gnath^");
12171 for ^Default_Switches^Default_Switches^ ("Ada")
12172 use ("^-gnatP^-gnatP^");
12181 The syntax of a @code{case} construction is based on the Ada case statement
12182 (although there is no @code{null} construction for empty alternatives).
12184 The case expression must be a typed string variable.
12185 Each alternative comprises the reserved word @code{when}, either a list of
12186 literal strings separated by the @code{"|"} character or the reserved word
12187 @code{others}, and the @code{"=>"} token.
12188 Each literal string must belong to the string type that is the type of the
12190 An @code{others} alternative, if present, must occur last.
12192 After each @code{=>}, there are zero or more constructions. The only
12193 constructions allowed in a case construction are other case constructions and
12194 attribute declarations. String type declarations, variable declarations and
12195 package declarations are not allowed.
12197 The value of the case variable is often given by an external reference
12198 (@pxref{External References in Project Files}).
12200 @c ****************************************
12201 @c * Objects and Sources in Project Files *
12202 @c ****************************************
12204 @node Objects and Sources in Project Files
12205 @section Objects and Sources in Project Files
12208 * Object Directory::
12210 * Source Directories::
12211 * Source File Names::
12215 Each project has exactly one object directory and one or more source
12216 directories. The source directories must contain at least one source file,
12217 unless the project file explicitly specifies that no source files are present
12218 (@pxref{Source File Names}).
12220 @node Object Directory
12221 @subsection Object Directory
12224 The object directory for a project is the directory containing the compiler's
12225 output (such as @file{ALI} files and object files) for the project's immediate
12228 The object directory is given by the value of the attribute @code{Object_Dir}
12229 in the project file.
12231 @smallexample @c projectfile
12232 for Object_Dir use "objects";
12236 The attribute @var{Object_Dir} has a string value, the path name of the object
12237 directory. The path name may be absolute or relative to the directory of the
12238 project file. This directory must already exist, and be readable and writable.
12240 By default, when the attribute @code{Object_Dir} is not given an explicit value
12241 or when its value is the empty string, the object directory is the same as the
12242 directory containing the project file.
12244 @node Exec Directory
12245 @subsection Exec Directory
12248 The exec directory for a project is the directory containing the executables
12249 for the project's main subprograms.
12251 The exec directory is given by the value of the attribute @code{Exec_Dir}
12252 in the project file.
12254 @smallexample @c projectfile
12255 for Exec_Dir use "executables";
12259 The attribute @var{Exec_Dir} has a string value, the path name of the exec
12260 directory. The path name may be absolute or relative to the directory of the
12261 project file. This directory must already exist, and be writable.
12263 By default, when the attribute @code{Exec_Dir} is not given an explicit value
12264 or when its value is the empty string, the exec directory is the same as the
12265 object directory of the project file.
12267 @node Source Directories
12268 @subsection Source Directories
12271 The source directories of a project are specified by the project file
12272 attribute @code{Source_Dirs}.
12274 This attribute's value is a string list. If the attribute is not given an
12275 explicit value, then there is only one source directory, the one where the
12276 project file resides.
12278 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
12281 @smallexample @c projectfile
12282 for Source_Dirs use ();
12286 indicates that the project contains no source files.
12288 Otherwise, each string in the string list designates one or more
12289 source directories.
12291 @smallexample @c projectfile
12292 for Source_Dirs use ("sources", "test/drivers");
12296 If a string in the list ends with @code{"/**"}, then the directory whose path
12297 name precedes the two asterisks, as well as all its subdirectories
12298 (recursively), are source directories.
12300 @smallexample @c projectfile
12301 for Source_Dirs use ("/system/sources/**");
12305 Here the directory @code{/system/sources} and all of its subdirectories
12306 (recursively) are source directories.
12308 To specify that the source directories are the directory of the project file
12309 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
12310 @smallexample @c projectfile
12311 for Source_Dirs use ("./**");
12315 Each of the source directories must exist and be readable.
12317 @node Source File Names
12318 @subsection Source File Names
12321 In a project that contains source files, their names may be specified by the
12322 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
12323 (a string). Source file names never include any directory information.
12325 If the attribute @code{Source_Files} is given an explicit value, then each
12326 element of the list is a source file name.
12328 @smallexample @c projectfile
12329 for Source_Files use ("main.adb");
12330 for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
12334 If the attribute @code{Source_Files} is not given an explicit value,
12335 but the attribute @code{Source_List_File} is given a string value,
12336 then the source file names are contained in the text file whose path name
12337 (absolute or relative to the directory of the project file) is the
12338 value of the attribute @code{Source_List_File}.
12340 Each line in the file that is not empty or is not a comment
12341 contains a source file name.
12343 @smallexample @c projectfile
12344 for Source_List_File use "source_list.txt";
12348 By default, if neither the attribute @code{Source_Files} nor the attribute
12349 @code{Source_List_File} is given an explicit value, then each file in the
12350 source directories that conforms to the project's naming scheme
12351 (@pxref{Naming Schemes}) is an immediate source of the project.
12353 A warning is issued if both attributes @code{Source_Files} and
12354 @code{Source_List_File} are given explicit values. In this case, the attribute
12355 @code{Source_Files} prevails.
12357 Each source file name must be the name of one existing source file
12358 in one of the source directories.
12360 A @code{Source_Files} attribute whose value is an empty list
12361 indicates that there are no source files in the project.
12363 If the order of the source directories is known statically, that is if
12364 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
12365 be several files with the same source file name. In this case, only the file
12366 in the first directory is considered as an immediate source of the project
12367 file. If the order of the source directories is not known statically, it is
12368 an error to have several files with the same source file name.
12370 Projects can be specified to have no Ada source
12371 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
12372 list, or the @code{"Ada"} may be absent from @code{Languages}:
12374 @smallexample @c projectfile
12375 for Source_Dirs use ();
12376 for Source_Files use ();
12377 for Languages use ("C", "C++");
12381 Otherwise, a project must contain at least one immediate source.
12383 Projects with no source files are useful as template packages
12384 (@pxref{Packages in Project Files}) for other projects; in particular to
12385 define a package @code{Naming} (@pxref{Naming Schemes}).
12387 @c ****************************
12388 @c * Importing Projects *
12389 @c ****************************
12391 @node Importing Projects
12392 @section Importing Projects
12393 @cindex @code{ADA_PROJECT_PATH}
12396 An immediate source of a project P may depend on source files that
12397 are neither immediate sources of P nor in the predefined library.
12398 To get this effect, P must @emph{import} the projects that contain the needed
12401 @smallexample @c projectfile
12403 with "project1", "utilities.gpr";
12404 with "/namings/apex.gpr";
12411 As can be seen in this example, the syntax for importing projects is similar
12412 to the syntax for importing compilation units in Ada. However, project files
12413 use literal strings instead of names, and the @code{with} clause identifies
12414 project files rather than packages.
12416 Each literal string is the file name or path name (absolute or relative) of a
12417 project file. If a string corresponds to a file name, with no path or a
12418 relative path, then its location is determined by the @emph{project path}. The
12419 latter can be queried using @code{gnatls -v}. It contains:
12423 In first position, the directory containing the current project file.
12425 In last position, the default project directory. This default project directory
12426 is part of the GNAT installation and is the standard place to install project
12427 files giving access to standard support libraries.
12429 @ref{Installing a library}
12433 In between, all the directories referenced in the
12434 ^environment variable^logical name^ @env{ADA_PROJECT_PATH} if it exists.
12438 If a relative pathname is used, as in
12440 @smallexample @c projectfile
12445 then the full path for the project is constructed by concatenating this
12446 relative path to those in the project path, in order, until a matching file is
12447 found. Any symbolic link will be fully resolved in the directory of the
12448 importing project file before the imported project file is examined.
12450 If the @code{with}'ed project file name does not have an extension,
12451 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
12452 then the file name as specified in the @code{with} clause (no extension) will
12453 be used. In the above example, if a file @code{project1.gpr} is found, then it
12454 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
12455 then it will be used; if neither file exists, this is an error.
12457 A warning is issued if the name of the project file does not match the
12458 name of the project; this check is case insensitive.
12460 Any source file that is an immediate source of the imported project can be
12461 used by the immediate sources of the importing project, transitively. Thus
12462 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
12463 sources of @code{A} may depend on the immediate sources of @code{C}, even if
12464 @code{A} does not import @code{C} explicitly. However, this is not recommended,
12465 because if and when @code{B} ceases to import @code{C}, some sources in
12466 @code{A} will no longer compile.
12468 A side effect of this capability is that normally cyclic dependencies are not
12469 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
12470 is not allowed to import @code{A}. However, there are cases when cyclic
12471 dependencies would be beneficial. For these cases, another form of import
12472 between projects exists, the @code{limited with}: a project @code{A} that
12473 imports a project @code{B} with a straight @code{with} may also be imported,
12474 directly or indirectly, by @code{B} on the condition that imports from @code{B}
12475 to @code{A} include at least one @code{limited with}.
12477 @smallexample @c 0projectfile
12483 limited with "../a/a.gpr";
12491 limited with "../a/a.gpr";
12497 In the above legal example, there are two project cycles:
12500 @item A -> C -> D -> A
12504 In each of these cycle there is one @code{limited with}: import of @code{A}
12505 from @code{B} and import of @code{A} from @code{D}.
12507 The difference between straight @code{with} and @code{limited with} is that
12508 the name of a project imported with a @code{limited with} cannot be used in the
12509 project that imports it. In particular, its packages cannot be renamed and
12510 its variables cannot be referred to.
12512 An exception to the above rules for @code{limited with} is that for the main
12513 project specified to @command{gnatmake} or to the @command{GNAT} driver a
12514 @code{limited with} is equivalent to a straight @code{with}. For example,
12515 in the example above, projects @code{B} and @code{D} could not be main
12516 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
12517 each have a @code{limited with} that is the only one in a cycle of importing
12520 @c *********************
12521 @c * Project Extension *
12522 @c *********************
12524 @node Project Extension
12525 @section Project Extension
12528 During development of a large system, it is sometimes necessary to use
12529 modified versions of some of the source files, without changing the original
12530 sources. This can be achieved through the @emph{project extension} facility.
12532 @smallexample @c projectfile
12533 project Modified_Utilities extends "/baseline/utilities.gpr" is ...
12537 A project extension declaration introduces an extending project
12538 (the @emph{child}) and a project being extended (the @emph{parent}).
12540 By default, a child project inherits all the sources of its parent.
12541 However, inherited sources can be overridden: a unit in a parent is hidden
12542 by a unit of the same name in the child.
12544 Inherited sources are considered to be sources (but not immediate sources)
12545 of the child project; see @ref{Project File Syntax}.
12547 An inherited source file retains any switches specified in the parent project.
12549 For example if the project @code{Utilities} contains the specification and the
12550 body of an Ada package @code{Util_IO}, then the project
12551 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
12552 The original body of @code{Util_IO} will not be considered in program builds.
12553 However, the package specification will still be found in the project
12556 A child project can have only one parent but it may import any number of other
12559 A project is not allowed to import directly or indirectly at the same time a
12560 child project and any of its ancestors.
12562 @c *******************************
12563 @c * Project Hierarchy Extension *
12564 @c *******************************
12566 @node Project Hierarchy Extension
12567 @section Project Hierarchy Extension
12570 When extending a large system spanning multiple projects, it is often
12571 inconvenient to extend every project in the hierarchy that is impacted by a
12572 small change introduced. In such cases, it is possible to create a virtual
12573 extension of entire hierarchy using @code{extends all} relationship.
12575 When the project is extended using @code{extends all} inheritance, all projects
12576 that are imported by it, both directly and indirectly, are considered virtually
12577 extended. That is, the Project Manager creates "virtual projects"
12578 that extend every project in the hierarchy; all these virtual projects have
12579 no sources of their own and have as object directory the object directory of
12580 the root of "extending all" project.
12582 It is possible to explicitly extend one or more projects in the hierarchy
12583 in order to modify the sources. These extending projects must be imported by
12584 the "extending all" project, which will replace the corresponding virtual
12585 projects with the explicit ones.
12587 When building such a project hierarchy extension, the Project Manager will
12588 ensure that both modified sources and sources in virtual extending projects
12589 that depend on them, are recompiled.
12591 By means of example, consider the following hierarchy of projects.
12595 project A, containing package P1
12597 project B importing A and containing package P2 which depends on P1
12599 project C importing B and containing package P3 which depends on P2
12603 We want to modify packages P1 and P3.
12605 This project hierarchy will need to be extended as follows:
12609 Create project A1 that extends A, placing modified P1 there:
12611 @smallexample @c 0projectfile
12612 project A1 extends "(...)/A" is
12617 Create project C1 that "extends all" C and imports A1, placing modified
12620 @smallexample @c 0projectfile
12622 project C1 extends all "(...)/C" is
12627 When you build project C1, your entire modified project space will be
12628 recompiled, including the virtual project B1 that has been impacted by the
12629 "extending all" inheritance of project C.
12631 Note that if a Library Project in the hierarchy is virtually extended,
12632 the virtual project that extends the Library Project is not a Library Project.
12634 @c ****************************************
12635 @c * External References in Project Files *
12636 @c ****************************************
12638 @node External References in Project Files
12639 @section External References in Project Files
12642 A project file may contain references to external variables; such references
12643 are called @emph{external references}.
12645 An external variable is either defined as part of the environment (an
12646 environment variable in Unix, for example) or else specified on the command
12647 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
12648 If both, then the command line value is used.
12650 The value of an external reference is obtained by means of the built-in
12651 function @code{external}, which returns a string value.
12652 This function has two forms:
12654 @item @code{external (external_variable_name)}
12655 @item @code{external (external_variable_name, default_value)}
12659 Each parameter must be a string literal. For example:
12661 @smallexample @c projectfile
12663 external ("OS", "GNU/Linux")
12667 In the form with one parameter, the function returns the value of
12668 the external variable given as parameter. If this name is not present in the
12669 environment, the function returns an empty string.
12671 In the form with two string parameters, the second argument is
12672 the value returned when the variable given as the first argument is not
12673 present in the environment. In the example above, if @code{"OS"} is not
12674 the name of ^an environment variable^a logical name^ and is not passed on
12675 the command line, then the returned value is @code{"GNU/Linux"}.
12677 An external reference may be part of a string expression or of a string
12678 list expression, and can therefore appear in a variable declaration or
12679 an attribute declaration.
12681 @smallexample @c projectfile
12683 type Mode_Type is ("Debug", "Release");
12684 Mode : Mode_Type := external ("MODE");
12691 @c *****************************
12692 @c * Packages in Project Files *
12693 @c *****************************
12695 @node Packages in Project Files
12696 @section Packages in Project Files
12699 A @emph{package} defines the settings for project-aware tools within a
12701 For each such tool one can declare a package; the names for these
12702 packages are preset (@pxref{Packages}).
12703 A package may contain variable declarations, attribute declarations, and case
12706 @smallexample @c projectfile
12709 package Builder is -- used by gnatmake
12710 for ^Default_Switches^Default_Switches^ ("Ada")
12719 The syntax of package declarations mimics that of package in Ada.
12721 Most of the packages have an attribute
12722 @code{^Default_Switches^Default_Switches^}.
12723 This attribute is an associative array, and its value is a string list.
12724 The index of the associative array is the name of a programming language (case
12725 insensitive). This attribute indicates the ^switch^switch^
12726 or ^switches^switches^ to be used
12727 with the corresponding tool.
12729 Some packages also have another attribute, @code{^Switches^Switches^},
12730 an associative array whose value is a string list.
12731 The index is the name of a source file.
12732 This attribute indicates the ^switch^switch^
12733 or ^switches^switches^ to be used by the corresponding
12734 tool when dealing with this specific file.
12736 Further information on these ^switch^switch^-related attributes is found in
12737 @ref{^Switches^Switches^ and Project Files}.
12739 A package may be declared as a @emph{renaming} of another package; e.g., from
12740 the project file for an imported project.
12742 @smallexample @c projectfile
12744 with "/global/apex.gpr";
12746 package Naming renames Apex.Naming;
12753 Packages that are renamed in other project files often come from project files
12754 that have no sources: they are just used as templates. Any modification in the
12755 template will be reflected automatically in all the project files that rename
12756 a package from the template.
12758 In addition to the tool-oriented packages, you can also declare a package
12759 named @code{Naming} to establish specialized source file naming conventions
12760 (@pxref{Naming Schemes}).
12762 @c ************************************
12763 @c * Variables from Imported Projects *
12764 @c ************************************
12766 @node Variables from Imported Projects
12767 @section Variables from Imported Projects
12770 An attribute or variable defined in an imported or parent project can
12771 be used in expressions in the importing / extending project.
12772 Such an attribute or variable is denoted by an expanded name whose prefix
12773 is either the name of the project or the expanded name of a package within
12776 @smallexample @c projectfile
12779 project Main extends "base" is
12780 Var1 := Imported.Var;
12781 Var2 := Base.Var & ".new";
12786 for ^Default_Switches^Default_Switches^ ("Ada")
12787 use Imported.Builder.Ada_^Switches^Switches^ &
12788 "^-gnatg^-gnatg^" &
12794 package Compiler is
12795 for ^Default_Switches^Default_Switches^ ("Ada")
12796 use Base.Compiler.Ada_^Switches^Switches^;
12807 The value of @code{Var1} is a copy of the variable @code{Var} defined
12808 in the project file @file{"imported.gpr"}
12810 the value of @code{Var2} is a copy of the value of variable @code{Var}
12811 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
12813 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12814 @code{Builder} is a string list that includes in its value a copy of the value
12815 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
12816 in project file @file{imported.gpr} plus two new elements:
12817 @option{"^-gnatg^-gnatg^"}
12818 and @option{"^-v^-v^"};
12820 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12821 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
12822 defined in the @code{Compiler} package in project file @file{base.gpr},
12823 the project being extended.
12826 @c ******************
12827 @c * Naming Schemes *
12828 @c ******************
12830 @node Naming Schemes
12831 @section Naming Schemes
12834 Sometimes an Ada software system is ported from a foreign compilation
12835 environment to GNAT, and the file names do not use the default GNAT
12836 conventions. Instead of changing all the file names (which for a variety
12837 of reasons might not be possible), you can define the relevant file
12838 naming scheme in the @code{Naming} package in your project file.
12841 Note that the use of pragmas described in
12842 @ref{Alternative File Naming Schemes} by mean of a configuration
12843 pragmas file is not supported when using project files. You must use
12844 the features described in this paragraph. You can however use specify
12845 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
12848 For example, the following
12849 package models the Apex file naming rules:
12851 @smallexample @c projectfile
12854 for Casing use "lowercase";
12855 for Dot_Replacement use ".";
12856 for Spec_Suffix ("Ada") use ".1.ada";
12857 for Body_Suffix ("Ada") use ".2.ada";
12864 For example, the following package models the HP Ada file naming rules:
12866 @smallexample @c projectfile
12869 for Casing use "lowercase";
12870 for Dot_Replacement use "__";
12871 for Spec_Suffix ("Ada") use "_.^ada^ada^";
12872 for Body_Suffix ("Ada") use ".^ada^ada^";
12878 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
12879 names in lower case)
12883 You can define the following attributes in package @code{Naming}:
12888 This must be a string with one of the three values @code{"lowercase"},
12889 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
12892 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
12894 @item @var{Dot_Replacement}
12895 This must be a string whose value satisfies the following conditions:
12898 @item It must not be empty
12899 @item It cannot start or end with an alphanumeric character
12900 @item It cannot be a single underscore
12901 @item It cannot start with an underscore followed by an alphanumeric
12902 @item It cannot contain a dot @code{'.'} except if the entire string
12907 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
12909 @item @var{Spec_Suffix}
12910 This is an associative array (indexed by the programming language name, case
12911 insensitive) whose value is a string that must satisfy the following
12915 @item It must not be empty
12916 @item It must include at least one dot
12919 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
12920 @code{"^.ads^.ADS^"}.
12922 @item @var{Body_Suffix}
12923 This is an associative array (indexed by the programming language name, case
12924 insensitive) whose value is a string that must satisfy the following
12928 @item It must not be empty
12929 @item It must include at least one dot
12930 @item It cannot end with the same string as @code{Spec_Suffix ("Ada")}
12933 If @code{Body_Suffix ("Ada")} is not specified, then the default is
12934 @code{"^.adb^.ADB^"}.
12936 @item @var{Separate_Suffix}
12937 This must be a string whose value satisfies the same conditions as
12938 @code{Body_Suffix}.
12941 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
12942 value as @code{Body_Suffix ("Ada")}.
12946 You can use the associative array attribute @code{Spec} to define
12947 the source file name for an individual Ada compilation unit's spec. The array
12948 index must be a string literal that identifies the Ada unit (case insensitive).
12949 The value of this attribute must be a string that identifies the file that
12950 contains this unit's spec (case sensitive or insensitive depending on the
12953 @smallexample @c projectfile
12954 for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
12959 You can use the associative array attribute @code{Body} to
12960 define the source file name for an individual Ada compilation unit's body
12961 (possibly a subunit). The array index must be a string literal that identifies
12962 the Ada unit (case insensitive). The value of this attribute must be a string
12963 that identifies the file that contains this unit's body or subunit (case
12964 sensitive or insensitive depending on the operating system).
12966 @smallexample @c projectfile
12967 for Body ("MyPack.MyChild") use "mypack.mychild.body";
12971 @c ********************
12972 @c * Library Projects *
12973 @c ********************
12975 @node Library Projects
12976 @section Library Projects
12979 @emph{Library projects} are projects whose object code is placed in a library.
12980 (Note that this facility is not yet supported on all platforms)
12982 To create a library project, you need to define in its project file
12983 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
12984 Additionally, you may define other library-related attributes such as
12985 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
12986 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
12988 The @code{Library_Name} attribute has a string value. There is no restriction
12989 on the name of a library. It is the responsibility of the developer to
12990 choose a name that will be accepted by the platform. It is recommended to
12991 choose names that could be Ada identifiers; such names are almost guaranteed
12992 to be acceptable on all platforms.
12994 The @code{Library_Dir} attribute has a string value that designates the path
12995 (absolute or relative) of the directory where the library will reside.
12996 It must designate an existing directory, and this directory must be writable,
12997 different from the project's object directory and from any source directory
12998 in the project tree.
13000 If both @code{Library_Name} and @code{Library_Dir} are specified and
13001 are legal, then the project file defines a library project. The optional
13002 library-related attributes are checked only for such project files.
13004 The @code{Library_Kind} attribute has a string value that must be one of the
13005 following (case insensitive): @code{"static"}, @code{"dynamic"} or
13006 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
13007 attribute is not specified, the library is a static library, that is
13008 an archive of object files that can be potentially linked into a
13009 static executable. Otherwise, the library may be dynamic or
13010 relocatable, that is a library that is loaded only at the start of execution.
13012 If you need to build both a static and a dynamic library, you should use two
13013 different object directories, since in some cases some extra code needs to
13014 be generated for the latter. For such cases, it is recommended to either use
13015 two different project files, or a single one which uses external variables
13016 to indicate what kind of library should be build.
13018 The @code{Library_ALI_Dir} attribute may be specified to indicate the
13019 directory where the ALI files of the library will be copied. When it is
13020 not specified, the ALI files are copied ti the directory specified in
13021 attribute @code{Library_Dir}. The directory specified by @code{Library_ALI_Dir}
13022 must be writable and different from the project's object directory and from
13023 any source directory in the project tree.
13025 The @code{Library_Version} attribute has a string value whose interpretation
13026 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
13027 used only for dynamic/relocatable libraries as the internal name of the
13028 library (the @code{"soname"}). If the library file name (built from the
13029 @code{Library_Name}) is different from the @code{Library_Version}, then the
13030 library file will be a symbolic link to the actual file whose name will be
13031 @code{Library_Version}.
13035 @smallexample @c projectfile
13041 for Library_Dir use "lib_dir";
13042 for Library_Name use "dummy";
13043 for Library_Kind use "relocatable";
13044 for Library_Version use "libdummy.so." & Version;
13051 Directory @file{lib_dir} will contain the internal library file whose name
13052 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
13053 @file{libdummy.so.1}.
13055 When @command{gnatmake} detects that a project file
13056 is a library project file, it will check all immediate sources of the project
13057 and rebuild the library if any of the sources have been recompiled.
13059 Standard project files can import library project files. In such cases,
13060 the libraries will only be rebuilt if some of its sources are recompiled
13061 because they are in the closure of some other source in an importing project.
13062 Sources of the library project files that are not in such a closure will
13063 not be checked, unless the full library is checked, because one of its sources
13064 needs to be recompiled.
13066 For instance, assume the project file @code{A} imports the library project file
13067 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
13068 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
13069 @file{l2.ads}, @file{l2.adb}.
13071 If @file{l1.adb} has been modified, then the library associated with @code{L}
13072 will be rebuilt when compiling all the immediate sources of @code{A} only
13073 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
13076 To be sure that all the sources in the library associated with @code{L} are
13077 up to date, and that all the sources of project @code{A} are also up to date,
13078 the following two commands needs to be used:
13085 When a library is built or rebuilt, an attempt is made first to delete all
13086 files in the library directory.
13087 All @file{ALI} files will also be copied from the object directory to the
13088 library directory. To build executables, @command{gnatmake} will use the
13089 library rather than the individual object files.
13092 It is also possible to create library project files for third-party libraries
13093 that are precompiled and cannot be compiled locally thanks to the
13094 @code{externally_built} attribute. (See @ref{Installing a library}).
13097 @c *******************************
13098 @c * Stand-alone Library Projects *
13099 @c *******************************
13101 @node Stand-alone Library Projects
13102 @section Stand-alone Library Projects
13105 A Stand-alone Library is a library that contains the necessary code to
13106 elaborate the Ada units that are included in the library. A Stand-alone
13107 Library is suitable to be used in an executable when the main is not
13108 in Ada. However, Stand-alone Libraries may also be used with an Ada main
13111 A Stand-alone Library Project is a Library Project where the library is
13112 a Stand-alone Library.
13114 To be a Stand-alone Library Project, in addition to the two attributes
13115 that make a project a Library Project (@code{Library_Name} and
13116 @code{Library_Dir}, see @ref{Library Projects}), the attribute
13117 @code{Library_Interface} must be defined.
13119 @smallexample @c projectfile
13121 for Library_Dir use "lib_dir";
13122 for Library_Name use "dummy";
13123 for Library_Interface use ("int1", "int1.child");
13127 Attribute @code{Library_Interface} has a non empty string list value,
13128 each string in the list designating a unit contained in an immediate source
13129 of the project file.
13131 When a Stand-alone Library is built, first the binder is invoked to build
13132 a package whose name depends on the library name
13133 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
13134 This binder-generated package includes initialization and
13135 finalization procedures whose
13136 names depend on the library name (dummyinit and dummyfinal in the example
13137 above). The object corresponding to this package is included in the library.
13139 A dynamic or relocatable Stand-alone Library is automatically initialized
13140 if automatic initialization of Stand-alone Libraries is supported on the
13141 platform and if attribute @code{Library_Auto_Init} is not specified or
13142 is specified with the value "true". A static Stand-alone Library is never
13143 automatically initialized.
13145 Single string attribute @code{Library_Auto_Init} may be specified with only
13146 two possible values: "false" or "true" (case-insensitive). Specifying
13147 "false" for attribute @code{Library_Auto_Init} will prevent automatic
13148 initialization of dynamic or relocatable libraries.
13150 When a non automatically initialized Stand-alone Library is used
13151 in an executable, its initialization procedure must be called before
13152 any service of the library is used.
13153 When the main subprogram is in Ada, it may mean that the initialization
13154 procedure has to be called during elaboration of another package.
13156 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
13157 (those that are listed in attribute @code{Library_Interface}) are copied to
13158 the Library Directory. As a consequence, only the Interface Units may be
13159 imported from Ada units outside of the library. If other units are imported,
13160 the binding phase will fail.
13162 When a Stand-Alone Library is bound, the switches that are specified in
13163 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
13164 used in the call to @command{gnatbind}.
13166 The string list attribute @code{Library_Options} may be used to specified
13167 additional switches to the call to @command{gcc} to link the library.
13169 The attribute @code{Library_Src_Dir}, may be specified for a
13170 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
13171 single string value. Its value must be the path (absolute or relative to the
13172 project directory) of an existing directory. This directory cannot be the
13173 object directory or one of the source directories, but it can be the same as
13174 the library directory. The sources of the Interface
13175 Units of the library, necessary to an Ada client of the library, will be
13176 copied to the designated directory, called Interface Copy directory.
13177 These sources includes the specs of the Interface Units, but they may also
13178 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
13179 are used, or when there is a generic units in the spec. Before the sources
13180 are copied to the Interface Copy directory, an attempt is made to delete all
13181 files in the Interface Copy directory.
13183 @c *************************************
13184 @c * Switches Related to Project Files *
13185 @c *************************************
13186 @node Switches Related to Project Files
13187 @section Switches Related to Project Files
13190 The following switches are used by GNAT tools that support project files:
13194 @item ^-P^/PROJECT_FILE=^@var{project}
13195 @cindex @option{^-P^/PROJECT_FILE^} (any tool supporting project files)
13196 Indicates the name of a project file. This project file will be parsed with
13197 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
13198 if any, and using the external references indicated
13199 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
13201 There may zero, one or more spaces between @option{-P} and @var{project}.
13205 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
13208 Since the Project Manager parses the project file only after all the switches
13209 on the command line are checked, the order of the switches
13210 @option{^-P^/PROJECT_FILE^},
13211 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
13212 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
13214 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
13215 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any tool supporting project files)
13216 Indicates that external variable @var{name} has the value @var{value}.
13217 The Project Manager will use this value for occurrences of
13218 @code{external(name)} when parsing the project file.
13222 If @var{name} or @var{value} includes a space, then @var{name=value} should be
13223 put between quotes.
13231 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
13232 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
13233 @var{name}, only the last one is used.
13236 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
13237 takes precedence over the value of the same name in the environment.
13239 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
13240 @cindex @code{^-vP^/MESSAGES_PROJECT_FILE^} (any tool supporting project files)
13241 @c Previous line uses code vs option command, to stay less than 80 chars
13242 Indicates the verbosity of the parsing of GNAT project files.
13245 @option{-vP0} means Default;
13246 @option{-vP1} means Medium;
13247 @option{-vP2} means High.
13251 There are three possible options for this qualifier: DEFAULT, MEDIUM and
13256 The default is ^Default^DEFAULT^: no output for syntactically correct
13259 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
13260 only the last one is used.
13264 @c **********************************
13265 @c * Tools Supporting Project Files *
13266 @c **********************************
13268 @node Tools Supporting Project Files
13269 @section Tools Supporting Project Files
13272 * gnatmake and Project Files::
13273 * The GNAT Driver and Project Files::
13275 * Glide and Project Files::
13279 @node gnatmake and Project Files
13280 @subsection gnatmake and Project Files
13283 This section covers several topics related to @command{gnatmake} and
13284 project files: defining ^switches^switches^ for @command{gnatmake}
13285 and for the tools that it invokes; specifying configuration pragmas;
13286 the use of the @code{Main} attribute; building and rebuilding library project
13290 * ^Switches^Switches^ and Project Files::
13291 * Specifying Configuration Pragmas::
13292 * Project Files and Main Subprograms::
13293 * Library Project Files::
13296 @node ^Switches^Switches^ and Project Files
13297 @subsubsection ^Switches^Switches^ and Project Files
13300 It is not currently possible to specify VMS style qualifiers in the project
13301 files; only Unix style ^switches^switches^ may be specified.
13305 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
13306 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
13307 attribute, a @code{^Switches^Switches^} attribute, or both;
13308 as their names imply, these ^switch^switch^-related
13309 attributes affect the ^switches^switches^ that are used for each of these GNAT
13311 @command{gnatmake} is invoked. As will be explained below, these
13312 component-specific ^switches^switches^ precede
13313 the ^switches^switches^ provided on the @command{gnatmake} command line.
13315 The @code{^Default_Switches^Default_Switches^} attribute is an associative
13316 array indexed by language name (case insensitive) whose value is a string list.
13319 @smallexample @c projectfile
13321 package Compiler is
13322 for ^Default_Switches^Default_Switches^ ("Ada")
13323 use ("^-gnaty^-gnaty^",
13330 The @code{^Switches^Switches^} attribute is also an associative array,
13331 indexed by a file name (which may or may not be case sensitive, depending
13332 on the operating system) whose value is a string list. For example:
13334 @smallexample @c projectfile
13337 for ^Switches^Switches^ ("main1.adb")
13339 for ^Switches^Switches^ ("main2.adb")
13346 For the @code{Builder} package, the file names must designate source files
13347 for main subprograms. For the @code{Binder} and @code{Linker} packages, the
13348 file names must designate @file{ALI} or source files for main subprograms.
13349 In each case just the file name without an explicit extension is acceptable.
13351 For each tool used in a program build (@command{gnatmake}, the compiler, the
13352 binder, and the linker), the corresponding package @dfn{contributes} a set of
13353 ^switches^switches^ for each file on which the tool is invoked, based on the
13354 ^switch^switch^-related attributes defined in the package.
13355 In particular, the ^switches^switches^
13356 that each of these packages contributes for a given file @var{f} comprise:
13360 the value of attribute @code{^Switches^Switches^ (@var{f})},
13361 if it is specified in the package for the given file,
13363 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
13364 if it is specified in the package.
13368 If neither of these attributes is defined in the package, then the package does
13369 not contribute any ^switches^switches^ for the given file.
13371 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
13372 two sets, in the following order: those contributed for the file
13373 by the @code{Builder} package;
13374 and the switches passed on the command line.
13376 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
13377 the ^switches^switches^ passed to the tool comprise three sets,
13378 in the following order:
13382 the applicable ^switches^switches^ contributed for the file
13383 by the @code{Builder} package in the project file supplied on the command line;
13386 those contributed for the file by the package (in the relevant project file --
13387 see below) corresponding to the tool; and
13390 the applicable switches passed on the command line.
13394 The term @emph{applicable ^switches^switches^} reflects the fact that
13395 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
13396 tools, depending on the individual ^switch^switch^.
13398 @command{gnatmake} may invoke the compiler on source files from different
13399 projects. The Project Manager will use the appropriate project file to
13400 determine the @code{Compiler} package for each source file being compiled.
13401 Likewise for the @code{Binder} and @code{Linker} packages.
13403 As an example, consider the following package in a project file:
13405 @smallexample @c projectfile
13408 package Compiler is
13409 for ^Default_Switches^Default_Switches^ ("Ada")
13411 for ^Switches^Switches^ ("a.adb")
13413 for ^Switches^Switches^ ("b.adb")
13415 "^-gnaty^-gnaty^");
13422 If @command{gnatmake} is invoked with this project file, and it needs to
13423 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
13424 @file{a.adb} will be compiled with the ^switch^switch^
13425 @option{^-O1^-O1^},
13426 @file{b.adb} with ^switches^switches^
13428 and @option{^-gnaty^-gnaty^},
13429 and @file{c.adb} with @option{^-g^-g^}.
13431 The following example illustrates the ordering of the ^switches^switches^
13432 contributed by different packages:
13434 @smallexample @c projectfile
13438 for ^Switches^Switches^ ("main.adb")
13446 package Compiler is
13447 for ^Switches^Switches^ ("main.adb")
13455 If you issue the command:
13458 gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
13462 then the compiler will be invoked on @file{main.adb} with the following
13463 sequence of ^switches^switches^
13466 ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
13469 with the last @option{^-O^-O^}
13470 ^switch^switch^ having precedence over the earlier ones;
13471 several other ^switches^switches^
13472 (such as @option{^-c^-c^}) are added implicitly.
13474 The ^switches^switches^
13476 and @option{^-O1^-O1^} are contributed by package
13477 @code{Builder}, @option{^-O2^-O2^} is contributed
13478 by the package @code{Compiler}
13479 and @option{^-O0^-O0^} comes from the command line.
13481 The @option{^-g^-g^}
13482 ^switch^switch^ will also be passed in the invocation of
13483 @command{Gnatlink.}
13485 A final example illustrates switch contributions from packages in different
13488 @smallexample @c projectfile
13491 for Source_Files use ("pack.ads", "pack.adb");
13492 package Compiler is
13493 for ^Default_Switches^Default_Switches^ ("Ada")
13494 use ("^-gnata^-gnata^");
13502 for Source_Files use ("foo_main.adb", "bar_main.adb");
13504 for ^Switches^Switches^ ("foo_main.adb")
13512 -- Ada source file:
13514 procedure Foo_Main is
13522 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
13526 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
13527 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
13528 @option{^-gnato^-gnato^} (passed on the command line).
13529 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
13530 are @option{^-g^-g^} from @code{Proj4.Builder},
13531 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
13532 and @option{^-gnato^-gnato^} from the command line.
13535 When using @command{gnatmake} with project files, some ^switches^switches^ or
13536 arguments may be expressed as relative paths. As the working directory where
13537 compilation occurs may change, these relative paths are converted to absolute
13538 paths. For the ^switches^switches^ found in a project file, the relative paths
13539 are relative to the project file directory, for the switches on the command
13540 line, they are relative to the directory where @command{gnatmake} is invoked.
13541 The ^switches^switches^ for which this occurs are:
13547 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
13549 ^-o^-o^, object files specified in package @code{Linker} or after
13550 -largs on the command line). The exception to this rule is the ^switch^switch^
13551 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
13553 @node Specifying Configuration Pragmas
13554 @subsubsection Specifying Configuration Pragmas
13556 When using @command{gnatmake} with project files, if there exists a file
13557 @file{gnat.adc} that contains configuration pragmas, this file will be
13560 Configuration pragmas can be defined by means of the following attributes in
13561 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
13562 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
13564 Both these attributes are single string attributes. Their values is the path
13565 name of a file containing configuration pragmas. If a path name is relative,
13566 then it is relative to the project directory of the project file where the
13567 attribute is defined.
13569 When compiling a source, the configuration pragmas used are, in order,
13570 those listed in the file designated by attribute
13571 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
13572 project file, if it is specified, and those listed in the file designated by
13573 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
13574 the project file of the source, if it exists.
13576 @node Project Files and Main Subprograms
13577 @subsubsection Project Files and Main Subprograms
13580 When using a project file, you can invoke @command{gnatmake}
13581 with one or several main subprograms, by specifying their source files on the
13585 gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
13589 Each of these needs to be a source file of the same project, except
13590 when the switch ^-u^/UNIQUE^ is used.
13593 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
13594 same project, one of the project in the tree rooted at the project specified
13595 on the command line. The package @code{Builder} of this common project, the
13596 "main project" is the one that is considered by @command{gnatmake}.
13599 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
13600 imported directly or indirectly by the project specified on the command line.
13601 Note that if such a source file is not part of the project specified on the
13602 command line, the ^switches^switches^ found in package @code{Builder} of the
13603 project specified on the command line, if any, that are transmitted
13604 to the compiler will still be used, not those found in the project file of
13608 When using a project file, you can also invoke @command{gnatmake} without
13609 explicitly specifying any main, and the effect depends on whether you have
13610 defined the @code{Main} attribute. This attribute has a string list value,
13611 where each element in the list is the name of a source file (the file
13612 extension is optional) that contains a unit that can be a main subprogram.
13614 If the @code{Main} attribute is defined in a project file as a non-empty
13615 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
13616 line, then invoking @command{gnatmake} with this project file but without any
13617 main on the command line is equivalent to invoking @command{gnatmake} with all
13618 the file names in the @code{Main} attribute on the command line.
13621 @smallexample @c projectfile
13624 for Main use ("main1", "main2", "main3");
13630 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
13632 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
13634 When the project attribute @code{Main} is not specified, or is specified
13635 as an empty string list, or when the switch @option{-u} is used on the command
13636 line, then invoking @command{gnatmake} with no main on the command line will
13637 result in all immediate sources of the project file being checked, and
13638 potentially recompiled. Depending on the presence of the switch @option{-u},
13639 sources from other project files on which the immediate sources of the main
13640 project file depend are also checked and potentially recompiled. In other
13641 words, the @option{-u} switch is applied to all of the immediate sources of the
13644 When no main is specified on the command line and attribute @code{Main} exists
13645 and includes several mains, or when several mains are specified on the
13646 command line, the default ^switches^switches^ in package @code{Builder} will
13647 be used for all mains, even if there are specific ^switches^switches^
13648 specified for one or several mains.
13650 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
13651 the specific ^switches^switches^ for each main, if they are specified.
13653 @node Library Project Files
13654 @subsubsection Library Project Files
13657 When @command{gnatmake} is invoked with a main project file that is a library
13658 project file, it is not allowed to specify one or more mains on the command
13662 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
13663 ^-l^/ACTION=LINK^ have special meanings.
13666 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
13667 to @command{gnatmake} that @command{gnatbind} should be invoked for the
13670 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13671 to @command{gnatmake} that the binder generated file should be compiled
13672 (in the case of a stand-alone library) and that the library should be built.
13676 @node The GNAT Driver and Project Files
13677 @subsection The GNAT Driver and Project Files
13680 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13682 @command{^gnatbind^gnatbind^},
13683 @command{^gnatfind^gnatfind^},
13684 @command{^gnatlink^gnatlink^},
13685 @command{^gnatls^gnatls^},
13686 @command{^gnatelim^gnatelim^},
13687 @command{^gnatpp^gnatpp^},
13688 @command{^gnatmetric^gnatmetric^},
13689 @command{^gnatstub^gnatstub^},
13690 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
13691 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13692 They must be invoked through the @command{gnat} driver.
13694 The @command{gnat} driver is a front-end that accepts a number of commands and
13695 call the corresponding tool. It has been designed initially for VMS to convert
13696 VMS style qualifiers to Unix style switches, but it is now available to all
13697 the GNAT supported platforms.
13699 On non VMS platforms, the @command{gnat} driver accepts the following commands
13700 (case insensitive):
13704 BIND to invoke @command{^gnatbind^gnatbind^}
13706 CHOP to invoke @command{^gnatchop^gnatchop^}
13708 CLEAN to invoke @command{^gnatclean^gnatclean^}
13710 COMP or COMPILE to invoke the compiler
13712 ELIM to invoke @command{^gnatelim^gnatelim^}
13714 FIND to invoke @command{^gnatfind^gnatfind^}
13716 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
13718 LINK to invoke @command{^gnatlink^gnatlink^}
13720 LS or LIST to invoke @command{^gnatls^gnatls^}
13722 MAKE to invoke @command{^gnatmake^gnatmake^}
13724 NAME to invoke @command{^gnatname^gnatname^}
13726 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
13728 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
13730 METRIC to invoke @command{^gnatmetric^gnatmetric^}
13732 STUB to invoke @command{^gnatstub^gnatstub^}
13734 XREF to invoke @command{^gnatxref^gnatxref^}
13738 (note that the compiler is invoked using the command
13739 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
13742 On non VMS platforms, between @command{gnat} and the command, two
13743 special switches may be used:
13747 @command{-v} to display the invocation of the tool.
13749 @command{-dn} to prevent the @command{gnat} driver from removing
13750 the temporary files it has created. These temporary files are
13751 configuration files and temporary file list files.
13755 The command may be followed by switches and arguments for the invoked
13759 gnat bind -C main.ali
13765 Switches may also be put in text files, one switch per line, and the text
13766 files may be specified with their path name preceded by '@@'.
13769 gnat bind @@args.txt main.ali
13773 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
13774 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
13775 (@option{^-P^/PROJECT_FILE^},
13776 @option{^-X^/EXTERNAL_REFERENCE^} and
13777 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
13778 the switches of the invoking tool.
13781 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
13782 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
13783 the immediate sources of the specified project file.
13786 When GNAT METRIC is used with a project file, but with no source
13787 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
13788 with all the immediate sources of the specified project file and with
13789 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
13793 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
13794 a project file, no source is specified on the command line and
13795 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
13796 the underlying tool (^gnatpp^gnatpp^ or
13797 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
13798 not only for the immediate sources of the main project.
13800 (-U stands for Universal or Union of the project files of the project tree)
13804 For each of the following commands, there is optionally a corresponding
13805 package in the main project.
13809 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
13812 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
13815 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
13818 package @code{Eliminate} for command ELIM (invoking
13819 @code{^gnatelim^gnatelim^})
13822 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
13825 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
13828 package @code{Metrics} for command METRIC
13829 (invoking @code{^gnatmetric^gnatmetric^})
13832 package @code{Pretty_Printer} for command PP or PRETTY
13833 (invoking @code{^gnatpp^gnatpp^})
13836 package @code{Gnatstub} for command STUB
13837 (invoking @code{^gnatstub^gnatstub^})
13840 package @code{Cross_Reference} for command XREF (invoking
13841 @code{^gnatxref^gnatxref^})
13846 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
13847 a simple variable with a string list value. It contains ^switches^switches^
13848 for the invocation of @code{^gnatls^gnatls^}.
13850 @smallexample @c projectfile
13854 for ^Switches^Switches^
13863 All other packages have two attribute @code{^Switches^Switches^} and
13864 @code{^Default_Switches^Default_Switches^}.
13867 @code{^Switches^Switches^} is an associated array attribute, indexed by the
13868 source file name, that has a string list value: the ^switches^switches^ to be
13869 used when the tool corresponding to the package is invoked for the specific
13873 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
13874 indexed by the programming language that has a string list value.
13875 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
13876 ^switches^switches^ for the invocation of the tool corresponding
13877 to the package, except if a specific @code{^Switches^Switches^} attribute
13878 is specified for the source file.
13880 @smallexample @c projectfile
13884 for Source_Dirs use ("./**");
13887 for ^Switches^Switches^ use
13894 package Compiler is
13895 for ^Default_Switches^Default_Switches^ ("Ada")
13896 use ("^-gnatv^-gnatv^",
13897 "^-gnatwa^-gnatwa^");
13903 for ^Default_Switches^Default_Switches^ ("Ada")
13911 for ^Default_Switches^Default_Switches^ ("Ada")
13913 for ^Switches^Switches^ ("main.adb")
13922 for ^Default_Switches^Default_Switches^ ("Ada")
13929 package Cross_Reference is
13930 for ^Default_Switches^Default_Switches^ ("Ada")
13935 end Cross_Reference;
13941 With the above project file, commands such as
13944 ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13945 ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13946 ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13947 ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13948 ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13952 will set up the environment properly and invoke the tool with the switches
13953 found in the package corresponding to the tool:
13954 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13955 except @code{^Switches^Switches^ ("main.adb")}
13956 for @code{^gnatlink^gnatlink^}.
13959 @node Glide and Project Files
13960 @subsection Glide and Project Files
13963 Glide will automatically recognize the @file{.gpr} extension for
13964 project files, and will
13965 convert them to its own internal format automatically. However, it
13966 doesn't provide a syntax-oriented editor for modifying these
13968 The project file will be loaded as text when you select the menu item
13969 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
13970 You can edit this text and save the @file{gpr} file;
13971 when you next select this project file in Glide it
13972 will be automatically reloaded.
13975 @c **********************
13976 @node An Extended Example
13977 @section An Extended Example
13980 Suppose that we have two programs, @var{prog1} and @var{prog2},
13981 whose sources are in corresponding directories. We would like
13982 to build them with a single @command{gnatmake} command, and we want to place
13983 their object files into @file{build} subdirectories of the source directories.
13984 Furthermore, we want to have to have two separate subdirectories
13985 in @file{build} -- @file{release} and @file{debug} -- which will contain
13986 the object files compiled with different set of compilation flags.
13988 In other words, we have the following structure:
14005 Here are the project files that we must place in a directory @file{main}
14006 to maintain this structure:
14010 @item We create a @code{Common} project with a package @code{Compiler} that
14011 specifies the compilation ^switches^switches^:
14016 @b{project} Common @b{is}
14018 @b{for} Source_Dirs @b{use} (); -- No source files
14022 @b{type} Build_Type @b{is} ("release", "debug");
14023 Build : Build_Type := External ("BUILD", "debug");
14026 @b{package} Compiler @b{is}
14027 @b{case} Build @b{is}
14028 @b{when} "release" =>
14029 @b{for} ^Default_Switches^Default_Switches^ ("Ada")
14030 @b{use} ("^-O2^-O2^");
14031 @b{when} "debug" =>
14032 @b{for} ^Default_Switches^Default_Switches^ ("Ada")
14033 @b{use} ("^-g^-g^");
14041 @item We create separate projects for the two programs:
14048 @b{project} Prog1 @b{is}
14050 @b{for} Source_Dirs @b{use} ("prog1");
14051 @b{for} Object_Dir @b{use} "prog1/build/" & Common.Build;
14053 @b{package} Compiler @b{renames} Common.Compiler;
14064 @b{project} Prog2 @b{is}
14066 @b{for} Source_Dirs @b{use} ("prog2");
14067 @b{for} Object_Dir @b{use} "prog2/build/" & Common.Build;
14069 @b{package} Compiler @b{renames} Common.Compiler;
14075 @item We create a wrapping project @code{Main}:
14084 @b{project} Main @b{is}
14086 @b{package} Compiler @b{renames} Common.Compiler;
14092 @item Finally we need to create a dummy procedure that @code{with}s (either
14093 explicitly or implicitly) all the sources of our two programs.
14098 Now we can build the programs using the command
14101 gnatmake ^-P^/PROJECT_FILE=^main dummy
14105 for the Debug mode, or
14109 gnatmake -Pmain -XBUILD=release
14115 GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
14120 for the Release mode.
14122 @c ********************************
14123 @c * Project File Complete Syntax *
14124 @c ********************************
14126 @node Project File Complete Syntax
14127 @section Project File Complete Syntax
14131 context_clause project_declaration
14137 @b{with} path_name @{ , path_name @} ;
14142 project_declaration ::=
14143 simple_project_declaration | project_extension
14145 simple_project_declaration ::=
14146 @b{project} <project_>simple_name @b{is}
14147 @{declarative_item@}
14148 @b{end} <project_>simple_name;
14150 project_extension ::=
14151 @b{project} <project_>simple_name @b{extends} path_name @b{is}
14152 @{declarative_item@}
14153 @b{end} <project_>simple_name;
14155 declarative_item ::=
14156 package_declaration |
14157 typed_string_declaration |
14158 other_declarative_item
14160 package_declaration ::=
14161 package_specification | package_renaming
14163 package_specification ::=
14164 @b{package} package_identifier @b{is}
14165 @{simple_declarative_item@}
14166 @b{end} package_identifier ;
14168 package_identifier ::=
14169 @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
14170 @code{Linker} | @code{Finder} | @code{Cross_Reference} |
14171 @code{^gnatls^gnatls^} | @code{IDE} | @code{Pretty_Printer}
14173 package_renaming ::==
14174 @b{package} package_identifier @b{renames}
14175 <project_>simple_name.package_identifier ;
14177 typed_string_declaration ::=
14178 @b{type} <typed_string_>_simple_name @b{is}
14179 ( string_literal @{, string_literal@} );
14181 other_declarative_item ::=
14182 attribute_declaration |
14183 typed_variable_declaration |
14184 variable_declaration |
14187 attribute_declaration ::=
14188 full_associative_array_declaration |
14189 @b{for} attribute_designator @b{use} expression ;
14191 full_associative_array_declaration ::=
14192 @b{for} <associative_array_attribute_>simple_name @b{use}
14193 <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
14195 attribute_designator ::=
14196 <simple_attribute_>simple_name |
14197 <associative_array_attribute_>simple_name ( string_literal )
14199 typed_variable_declaration ::=
14200 <typed_variable_>simple_name : <typed_string_>name := string_expression ;
14202 variable_declaration ::=
14203 <variable_>simple_name := expression;
14213 attribute_reference
14219 ( <string_>expression @{ , <string_>expression @} )
14222 @b{external} ( string_literal [, string_literal] )
14224 attribute_reference ::=
14225 attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
14227 attribute_prefix ::=
14229 <project_>simple_name | package_identifier |
14230 <project_>simple_name . package_identifier
14232 case_construction ::=
14233 @b{case} <typed_variable_>name @b{is}
14238 @b{when} discrete_choice_list =>
14239 @{case_construction | attribute_declaration@}
14241 discrete_choice_list ::=
14242 string_literal @{| string_literal@} |
14246 simple_name @{. simple_name@}
14249 identifier (same as Ada)
14253 @node The Cross-Referencing Tools gnatxref and gnatfind
14254 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
14259 The compiler generates cross-referencing information (unless
14260 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
14261 This information indicates where in the source each entity is declared and
14262 referenced. Note that entities in package Standard are not included, but
14263 entities in all other predefined units are included in the output.
14265 Before using any of these two tools, you need to compile successfully your
14266 application, so that GNAT gets a chance to generate the cross-referencing
14269 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
14270 information to provide the user with the capability to easily locate the
14271 declaration and references to an entity. These tools are quite similar,
14272 the difference being that @code{gnatfind} is intended for locating
14273 definitions and/or references to a specified entity or entities, whereas
14274 @code{gnatxref} is oriented to generating a full report of all
14277 To use these tools, you must not compile your application using the
14278 @option{-gnatx} switch on the @command{gnatmake} command line
14279 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
14280 information will not be generated.
14283 * gnatxref Switches::
14284 * gnatfind Switches::
14285 * Project Files for gnatxref and gnatfind::
14286 * Regular Expressions in gnatfind and gnatxref::
14287 * Examples of gnatxref Usage::
14288 * Examples of gnatfind Usage::
14291 @node gnatxref Switches
14292 @section @code{gnatxref} Switches
14295 The command invocation for @code{gnatxref} is:
14297 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
14304 @item sourcefile1, sourcefile2
14305 identifies the source files for which a report is to be generated. The
14306 ``with''ed units will be processed too. You must provide at least one file.
14308 These file names are considered to be regular expressions, so for instance
14309 specifying @file{source*.adb} is the same as giving every file in the current
14310 directory whose name starts with @file{source} and whose extension is
14313 You shouldn't specify any directory name, just base names. @command{gnatxref}
14314 and @command{gnatfind} will be able to locate these files by themselves using
14315 the source path. If you specify directories, no result is produced.
14320 The switches can be :
14323 @item ^-a^/ALL_FILES^
14324 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
14325 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
14326 the read-only files found in the library search path. Otherwise, these files
14327 will be ignored. This option can be used to protect Gnat sources or your own
14328 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
14329 much faster, and their output much smaller. Read-only here refers to access
14330 or permissions status in the file system for the current user.
14333 @cindex @option{-aIDIR} (@command{gnatxref})
14334 When looking for source files also look in directory DIR. The order in which
14335 source file search is undertaken is the same as for @command{gnatmake}.
14338 @cindex @option{-aODIR} (@command{gnatxref})
14339 When searching for library and object files, look in directory
14340 DIR. The order in which library files are searched is the same as for
14341 @command{gnatmake}.
14344 @cindex @option{-nostdinc} (@command{gnatxref})
14345 Do not look for sources in the system default directory.
14348 @cindex @option{-nostdlib} (@command{gnatxref})
14349 Do not look for library files in the system default directory.
14351 @item --RTS=@var{rts-path}
14352 @cindex @option{--RTS} (@command{gnatxref})
14353 Specifies the default location of the runtime library. Same meaning as the
14354 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14356 @item ^-d^/DERIVED_TYPES^
14357 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
14358 If this switch is set @code{gnatxref} will output the parent type
14359 reference for each matching derived types.
14361 @item ^-f^/FULL_PATHNAME^
14362 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
14363 If this switch is set, the output file names will be preceded by their
14364 directory (if the file was found in the search path). If this switch is
14365 not set, the directory will not be printed.
14367 @item ^-g^/IGNORE_LOCALS^
14368 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
14369 If this switch is set, information is output only for library-level
14370 entities, ignoring local entities. The use of this switch may accelerate
14371 @code{gnatfind} and @code{gnatxref}.
14374 @cindex @option{-IDIR} (@command{gnatxref})
14375 Equivalent to @samp{-aODIR -aIDIR}.
14378 @cindex @option{-pFILE} (@command{gnatxref})
14379 Specify a project file to use @xref{Project Files}. These project files are
14380 the @file{.adp} files used by Glide. If you need to use the @file{.gpr}
14381 project files, you should use gnatxref through the GNAT driver
14382 (@command{gnat xref -Pproject}).
14384 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14385 project file in the current directory.
14387 If a project file is either specified or found by the tools, then the content
14388 of the source directory and object directory lines are added as if they
14389 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
14390 and @samp{^-aO^OBJECT_SEARCH^}.
14392 Output only unused symbols. This may be really useful if you give your
14393 main compilation unit on the command line, as @code{gnatxref} will then
14394 display every unused entity and 'with'ed package.
14398 Instead of producing the default output, @code{gnatxref} will generate a
14399 @file{tags} file that can be used by vi. For examples how to use this
14400 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
14401 to the standard output, thus you will have to redirect it to a file.
14407 All these switches may be in any order on the command line, and may even
14408 appear after the file names. They need not be separated by spaces, thus
14409 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14410 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14412 @node gnatfind Switches
14413 @section @code{gnatfind} Switches
14416 The command line for @code{gnatfind} is:
14419 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
14428 An entity will be output only if it matches the regular expression found
14429 in @samp{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
14431 Omitting the pattern is equivalent to specifying @samp{*}, which
14432 will match any entity. Note that if you do not provide a pattern, you
14433 have to provide both a sourcefile and a line.
14435 Entity names are given in Latin-1, with uppercase/lowercase equivalence
14436 for matching purposes. At the current time there is no support for
14437 8-bit codes other than Latin-1, or for wide characters in identifiers.
14440 @code{gnatfind} will look for references, bodies or declarations
14441 of symbols referenced in @file{sourcefile}, at line @samp{line}
14442 and column @samp{column}. See @ref{Examples of gnatfind Usage}
14443 for syntax examples.
14446 is a decimal integer identifying the line number containing
14447 the reference to the entity (or entities) to be located.
14450 is a decimal integer identifying the exact location on the
14451 line of the first character of the identifier for the
14452 entity reference. Columns are numbered from 1.
14454 @item file1 file2 ...
14455 The search will be restricted to these source files. If none are given, then
14456 the search will be done for every library file in the search path.
14457 These file must appear only after the pattern or sourcefile.
14459 These file names are considered to be regular expressions, so for instance
14460 specifying 'source*.adb' is the same as giving every file in the current
14461 directory whose name starts with 'source' and whose extension is 'adb'.
14463 The location of the spec of the entity will always be displayed, even if it
14464 isn't in one of file1, file2,... The occurrences of the entity in the
14465 separate units of the ones given on the command line will also be displayed.
14467 Note that if you specify at least one file in this part, @code{gnatfind} may
14468 sometimes not be able to find the body of the subprograms...
14473 At least one of 'sourcefile' or 'pattern' has to be present on
14476 The following switches are available:
14480 @item ^-a^/ALL_FILES^
14481 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
14482 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
14483 the read-only files found in the library search path. Otherwise, these files
14484 will be ignored. This option can be used to protect Gnat sources or your own
14485 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
14486 much faster, and their output much smaller. Read-only here refers to access
14487 or permission status in the file system for the current user.
14490 @cindex @option{-aIDIR} (@command{gnatfind})
14491 When looking for source files also look in directory DIR. The order in which
14492 source file search is undertaken is the same as for @command{gnatmake}.
14495 @cindex @option{-aODIR} (@command{gnatfind})
14496 When searching for library and object files, look in directory
14497 DIR. The order in which library files are searched is the same as for
14498 @command{gnatmake}.
14501 @cindex @option{-nostdinc} (@command{gnatfind})
14502 Do not look for sources in the system default directory.
14505 @cindex @option{-nostdlib} (@command{gnatfind})
14506 Do not look for library files in the system default directory.
14508 @item --RTS=@var{rts-path}
14509 @cindex @option{--RTS} (@command{gnatfind})
14510 Specifies the default location of the runtime library. Same meaning as the
14511 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14513 @item ^-d^/DERIVED_TYPE_INFORMATION^
14514 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
14515 If this switch is set, then @code{gnatfind} will output the parent type
14516 reference for each matching derived types.
14518 @item ^-e^/EXPRESSIONS^
14519 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
14520 By default, @code{gnatfind} accept the simple regular expression set for
14521 @samp{pattern}. If this switch is set, then the pattern will be
14522 considered as full Unix-style regular expression.
14524 @item ^-f^/FULL_PATHNAME^
14525 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
14526 If this switch is set, the output file names will be preceded by their
14527 directory (if the file was found in the search path). If this switch is
14528 not set, the directory will not be printed.
14530 @item ^-g^/IGNORE_LOCALS^
14531 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
14532 If this switch is set, information is output only for library-level
14533 entities, ignoring local entities. The use of this switch may accelerate
14534 @code{gnatfind} and @code{gnatxref}.
14537 @cindex @option{-IDIR} (@command{gnatfind})
14538 Equivalent to @samp{-aODIR -aIDIR}.
14541 @cindex @option{-pFILE} (@command{gnatfind})
14542 Specify a project file (@pxref{Project Files}) to use.
14543 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14544 project file in the current directory.
14546 If a project file is either specified or found by the tools, then the content
14547 of the source directory and object directory lines are added as if they
14548 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
14549 @samp{^-aO^/OBJECT_SEARCH^}.
14551 @item ^-r^/REFERENCES^
14552 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
14553 By default, @code{gnatfind} will output only the information about the
14554 declaration, body or type completion of the entities. If this switch is
14555 set, the @code{gnatfind} will locate every reference to the entities in
14556 the files specified on the command line (or in every file in the search
14557 path if no file is given on the command line).
14559 @item ^-s^/PRINT_LINES^
14560 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
14561 If this switch is set, then @code{gnatfind} will output the content
14562 of the Ada source file lines were the entity was found.
14564 @item ^-t^/TYPE_HIERARCHY^
14565 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
14566 If this switch is set, then @code{gnatfind} will output the type hierarchy for
14567 the specified type. It act like -d option but recursively from parent
14568 type to parent type. When this switch is set it is not possible to
14569 specify more than one file.
14574 All these switches may be in any order on the command line, and may even
14575 appear after the file names. They need not be separated by spaces, thus
14576 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14577 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14579 As stated previously, gnatfind will search in every directory in the
14580 search path. You can force it to look only in the current directory if
14581 you specify @code{*} at the end of the command line.
14583 @node Project Files for gnatxref and gnatfind
14584 @section Project Files for @command{gnatxref} and @command{gnatfind}
14587 Project files allow a programmer to specify how to compile its
14588 application, where to find sources, etc. These files are used
14590 primarily by the Glide Ada mode, but they can also be used
14593 @code{gnatxref} and @code{gnatfind}.
14595 A project file name must end with @file{.gpr}. If a single one is
14596 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
14597 extract the information from it. If multiple project files are found, none of
14598 them is read, and you have to use the @samp{-p} switch to specify the one
14601 The following lines can be included, even though most of them have default
14602 values which can be used in most cases.
14603 The lines can be entered in any order in the file.
14604 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
14605 each line. If you have multiple instances, only the last one is taken into
14610 [default: @code{"^./^[]^"}]
14611 specifies a directory where to look for source files. Multiple @code{src_dir}
14612 lines can be specified and they will be searched in the order they
14616 [default: @code{"^./^[]^"}]
14617 specifies a directory where to look for object and library files. Multiple
14618 @code{obj_dir} lines can be specified, and they will be searched in the order
14621 @item comp_opt=SWITCHES
14622 [default: @code{""}]
14623 creates a variable which can be referred to subsequently by using
14624 the @code{$@{comp_opt@}} notation. This is intended to store the default
14625 switches given to @command{gnatmake} and @command{gcc}.
14627 @item bind_opt=SWITCHES
14628 [default: @code{""}]
14629 creates a variable which can be referred to subsequently by using
14630 the @samp{$@{bind_opt@}} notation. This is intended to store the default
14631 switches given to @command{gnatbind}.
14633 @item link_opt=SWITCHES
14634 [default: @code{""}]
14635 creates a variable which can be referred to subsequently by using
14636 the @samp{$@{link_opt@}} notation. This is intended to store the default
14637 switches given to @command{gnatlink}.
14639 @item main=EXECUTABLE
14640 [default: @code{""}]
14641 specifies the name of the executable for the application. This variable can
14642 be referred to in the following lines by using the @samp{$@{main@}} notation.
14645 @item comp_cmd=COMMAND
14646 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
14649 @item comp_cmd=COMMAND
14650 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
14652 specifies the command used to compile a single file in the application.
14655 @item make_cmd=COMMAND
14656 [default: @code{"GNAT MAKE $@{main@}
14657 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
14658 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
14659 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
14662 @item make_cmd=COMMAND
14663 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
14664 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
14665 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
14667 specifies the command used to recompile the whole application.
14669 @item run_cmd=COMMAND
14670 [default: @code{"$@{main@}"}]
14671 specifies the command used to run the application.
14673 @item debug_cmd=COMMAND
14674 [default: @code{"gdb $@{main@}"}]
14675 specifies the command used to debug the application
14680 @command{gnatxref} and @command{gnatfind} only take into account the
14681 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
14683 @node Regular Expressions in gnatfind and gnatxref
14684 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
14687 As specified in the section about @command{gnatfind}, the pattern can be a
14688 regular expression. Actually, there are to set of regular expressions
14689 which are recognized by the program :
14692 @item globbing patterns
14693 These are the most usual regular expression. They are the same that you
14694 generally used in a Unix shell command line, or in a DOS session.
14696 Here is a more formal grammar :
14703 term ::= elmt -- matches elmt
14704 term ::= elmt elmt -- concatenation (elmt then elmt)
14705 term ::= * -- any string of 0 or more characters
14706 term ::= ? -- matches any character
14707 term ::= [char @{char@}] -- matches any character listed
14708 term ::= [char - char] -- matches any character in range
14712 @item full regular expression
14713 The second set of regular expressions is much more powerful. This is the
14714 type of regular expressions recognized by utilities such a @file{grep}.
14716 The following is the form of a regular expression, expressed in Ada
14717 reference manual style BNF is as follows
14724 regexp ::= term @{| term@} -- alternation (term or term ...)
14726 term ::= item @{item@} -- concatenation (item then item)
14728 item ::= elmt -- match elmt
14729 item ::= elmt * -- zero or more elmt's
14730 item ::= elmt + -- one or more elmt's
14731 item ::= elmt ? -- matches elmt or nothing
14734 elmt ::= nschar -- matches given character
14735 elmt ::= [nschar @{nschar@}] -- matches any character listed
14736 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
14737 elmt ::= [char - char] -- matches chars in given range
14738 elmt ::= \ char -- matches given character
14739 elmt ::= . -- matches any single character
14740 elmt ::= ( regexp ) -- parens used for grouping
14742 char ::= any character, including special characters
14743 nschar ::= any character except ()[].*+?^^^
14747 Following are a few examples :
14751 will match any of the two strings 'abcde' and 'fghi'.
14754 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
14757 will match any string which has only lowercase characters in it (and at
14758 least one character
14763 @node Examples of gnatxref Usage
14764 @section Examples of @code{gnatxref} Usage
14766 @subsection General Usage
14769 For the following examples, we will consider the following units :
14771 @smallexample @c ada
14777 3: procedure Foo (B : in Integer);
14784 1: package body Main is
14785 2: procedure Foo (B : in Integer) is
14796 2: procedure Print (B : Integer);
14805 The first thing to do is to recompile your application (for instance, in
14806 that case just by doing a @samp{gnatmake main}, so that GNAT generates
14807 the cross-referencing information.
14808 You can then issue any of the following commands:
14810 @item gnatxref main.adb
14811 @code{gnatxref} generates cross-reference information for main.adb
14812 and every unit 'with'ed by main.adb.
14814 The output would be:
14822 Decl: main.ads 3:20
14823 Body: main.adb 2:20
14824 Ref: main.adb 4:13 5:13 6:19
14827 Ref: main.adb 6:8 7:8
14837 Decl: main.ads 3:15
14838 Body: main.adb 2:15
14841 Body: main.adb 1:14
14844 Ref: main.adb 6:12 7:12
14848 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
14849 its body is in main.adb, line 1, column 14 and is not referenced any where.
14851 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
14852 it referenced in main.adb, line 6 column 12 and line 7 column 12.
14854 @item gnatxref package1.adb package2.ads
14855 @code{gnatxref} will generates cross-reference information for
14856 package1.adb, package2.ads and any other package 'with'ed by any
14862 @subsection Using gnatxref with vi
14864 @code{gnatxref} can generate a tags file output, which can be used
14865 directly from @file{vi}. Note that the standard version of @file{vi}
14866 will not work properly with overloaded symbols. Consider using another
14867 free implementation of @file{vi}, such as @file{vim}.
14870 $ gnatxref -v gnatfind.adb > tags
14874 will generate the tags file for @code{gnatfind} itself (if the sources
14875 are in the search path!).
14877 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
14878 (replacing @i{entity} by whatever you are looking for), and vi will
14879 display a new file with the corresponding declaration of entity.
14882 @node Examples of gnatfind Usage
14883 @section Examples of @code{gnatfind} Usage
14887 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
14888 Find declarations for all entities xyz referenced at least once in
14889 main.adb. The references are search in every library file in the search
14892 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
14895 The output will look like:
14897 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14898 ^directory/^[directory]^main.adb:24:10: xyz <= body
14899 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14903 that is to say, one of the entities xyz found in main.adb is declared at
14904 line 12 of main.ads (and its body is in main.adb), and another one is
14905 declared at line 45 of foo.ads
14907 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
14908 This is the same command as the previous one, instead @code{gnatfind} will
14909 display the content of the Ada source file lines.
14911 The output will look like:
14914 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14916 ^directory/^[directory]^main.adb:24:10: xyz <= body
14918 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14923 This can make it easier to find exactly the location your are looking
14926 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14927 Find references to all entities containing an x that are
14928 referenced on line 123 of main.ads.
14929 The references will be searched only in main.ads and foo.adb.
14931 @item gnatfind main.ads:123
14932 Find declarations and bodies for all entities that are referenced on
14933 line 123 of main.ads.
14935 This is the same as @code{gnatfind "*":main.adb:123}.
14937 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
14938 Find the declaration for the entity referenced at column 45 in
14939 line 123 of file main.adb in directory mydir. Note that it
14940 is usual to omit the identifier name when the column is given,
14941 since the column position identifies a unique reference.
14943 The column has to be the beginning of the identifier, and should not
14944 point to any character in the middle of the identifier.
14948 @c *********************************
14949 @node The GNAT Pretty-Printer gnatpp
14950 @chapter The GNAT Pretty-Printer @command{gnatpp}
14952 @cindex Pretty-Printer
14955 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
14956 for source reformatting / pretty-printing.
14957 It takes an Ada source file as input and generates a reformatted
14959 You can specify various style directives via switches; e.g.,
14960 identifier case conventions, rules of indentation, and comment layout.
14962 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
14963 tree for the input source and thus requires the input to be syntactically and
14964 semantically legal.
14965 If this condition is not met, @command{gnatpp} will terminate with an
14966 error message; no output file will be generated.
14968 If the compilation unit
14969 contained in the input source depends semantically upon units located
14970 outside the current directory, you have to provide the source search path
14971 when invoking @command{gnatpp}, if these units are contained in files with
14972 names that do not follow the GNAT file naming rules, you have to provide
14973 the configuration file describing the corresponding naming scheme;
14974 see the description of the @command{gnatpp}
14975 switches below. Another possibility is to use a project file and to
14976 call @command{gnatpp} through the @command{gnat} driver
14978 The @command{gnatpp} command has the form
14981 $ gnatpp [@var{switches}] @var{filename}
14988 @var{switches} is an optional sequence of switches defining such properties as
14989 the formatting rules, the source search path, and the destination for the
14993 @var{filename} is the name (including the extension) of the source file to
14994 reformat; ``wildcards'' or several file names on the same gnatpp command are
14995 allowed. The file name may contain path information; it does not have to
14996 follow the GNAT file naming rules
15000 * Switches for gnatpp::
15001 * Formatting Rules::
15004 @node Switches for gnatpp
15005 @section Switches for @command{gnatpp}
15008 The following subsections describe the various switches accepted by
15009 @command{gnatpp}, organized by category.
15012 You specify a switch by supplying a name and generally also a value.
15013 In many cases the values for a switch with a given name are incompatible with
15015 (for example the switch that controls the casing of a reserved word may have
15016 exactly one value: upper case, lower case, or
15017 mixed case) and thus exactly one such switch can be in effect for an
15018 invocation of @command{gnatpp}.
15019 If more than one is supplied, the last one is used.
15020 However, some values for the same switch are mutually compatible.
15021 You may supply several such switches to @command{gnatpp}, but then
15022 each must be specified in full, with both the name and the value.
15023 Abbreviated forms (the name appearing once, followed by each value) are
15025 For example, to set
15026 the alignment of the assignment delimiter both in declarations and in
15027 assignment statements, you must write @option{-A2A3}
15028 (or @option{-A2 -A3}), but not @option{-A23}.
15032 In many cases the set of options for a given qualifier are incompatible with
15033 each other (for example the qualifier that controls the casing of a reserved
15034 word may have exactly one option, which specifies either upper case, lower
15035 case, or mixed case), and thus exactly one such option can be in effect for
15036 an invocation of @command{gnatpp}.
15037 If more than one is supplied, the last one is used.
15038 However, some qualifiers have options that are mutually compatible,
15039 and then you may then supply several such options when invoking
15043 In most cases, it is obvious whether or not the
15044 ^values for a switch with a given name^options for a given qualifier^
15045 are compatible with each other.
15046 When the semantics might not be evident, the summaries below explicitly
15047 indicate the effect.
15050 * Alignment Control::
15052 * Construct Layout Control::
15053 * General Text Layout Control::
15054 * Other Formatting Options::
15055 * Setting the Source Search Path::
15056 * Output File Control::
15057 * Other gnatpp Switches::
15060 @node Alignment Control
15061 @subsection Alignment Control
15062 @cindex Alignment control in @command{gnatpp}
15065 Programs can be easier to read if certain constructs are vertically aligned.
15066 By default all alignments are set ON.
15067 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
15068 OFF, and then use one or more of the other
15069 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
15070 to activate alignment for specific constructs.
15073 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
15077 Set all alignments to ON
15080 @item ^-A0^/ALIGN=OFF^
15081 Set all alignments to OFF
15083 @item ^-A1^/ALIGN=COLONS^
15084 Align @code{:} in declarations
15086 @item ^-A2^/ALIGN=DECLARATIONS^
15087 Align @code{:=} in initializations in declarations
15089 @item ^-A3^/ALIGN=STATEMENTS^
15090 Align @code{:=} in assignment statements
15092 @item ^-A4^/ALIGN=ARROWS^
15093 Align @code{=>} in associations
15095 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
15096 Align @code{at} keywords in the component clauses in record
15097 representation clauses
15101 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
15104 @node Casing Control
15105 @subsection Casing Control
15106 @cindex Casing control in @command{gnatpp}
15109 @command{gnatpp} allows you to specify the casing for reserved words,
15110 pragma names, attribute designators and identifiers.
15111 For identifiers you may define a
15112 general rule for name casing but also override this rule
15113 via a set of dictionary files.
15115 Three types of casing are supported: lower case, upper case, and mixed case.
15116 Lower and upper case are self-explanatory (but since some letters in
15117 Latin1 and other GNAT-supported character sets
15118 exist only in lower-case form, an upper case conversion will have no
15120 ``Mixed case'' means that the first letter, and also each letter immediately
15121 following an underscore, are converted to their uppercase forms;
15122 all the other letters are converted to their lowercase forms.
15125 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
15126 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
15127 Attribute designators are lower case
15129 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
15130 Attribute designators are upper case
15132 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
15133 Attribute designators are mixed case (this is the default)
15135 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
15136 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
15137 Keywords (technically, these are known in Ada as @emph{reserved words}) are
15138 lower case (this is the default)
15140 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
15141 Keywords are upper case
15143 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
15144 @item ^-nD^/NAME_CASING=AS_DECLARED^
15145 Name casing for defining occurrences are as they appear in the source file
15146 (this is the default)
15148 @item ^-nU^/NAME_CASING=UPPER_CASE^
15149 Names are in upper case
15151 @item ^-nL^/NAME_CASING=LOWER_CASE^
15152 Names are in lower case
15154 @item ^-nM^/NAME_CASING=MIXED_CASE^
15155 Names are in mixed case
15157 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
15158 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
15159 Pragma names are lower case
15161 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
15162 Pragma names are upper case
15164 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
15165 Pragma names are mixed case (this is the default)
15167 @item ^-D@var{file}^/DICTIONARY=@var{file}^
15168 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
15169 Use @var{file} as a @emph{dictionary file} that defines
15170 the casing for a set of specified names,
15171 thereby overriding the effect on these names by
15172 any explicit or implicit
15173 ^-n^/NAME_CASING^ switch.
15174 To supply more than one dictionary file,
15175 use ^several @option{-D} switches^a list of files as options^.
15178 @option{gnatpp} implicitly uses a @emph{default dictionary file}
15179 to define the casing for the Ada predefined names and
15180 the names declared in the GNAT libraries.
15182 @item ^-D-^/SPECIFIC_CASING^
15183 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
15184 Do not use the default dictionary file;
15185 instead, use the casing
15186 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
15191 The structure of a dictionary file, and details on the conventions
15192 used in the default dictionary file, are defined in @ref{Name Casing}.
15194 The @option{^-D-^/SPECIFIC_CASING^} and
15195 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
15198 @node Construct Layout Control
15199 @subsection Construct Layout Control
15200 @cindex Layout control in @command{gnatpp}
15203 This group of @command{gnatpp} switches controls the layout of comments and
15204 complex syntactic constructs. See @ref{Formatting Comments} for details
15208 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
15209 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
15210 All the comments remain unchanged
15212 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
15213 GNAT-style comment line indentation (this is the default).
15215 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
15216 Reference-manual comment line indentation.
15218 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
15219 GNAT-style comment beginning
15221 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
15222 Reformat comment blocks
15224 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
15225 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
15226 GNAT-style layout (this is the default)
15228 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
15231 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
15234 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
15236 All the VT characters are removed from the comment text. All the HT characters
15237 are expanded with the sequences of space characters to get to the next tab
15240 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
15241 @item ^--no-separate-is^/NO_SEPARATE_IS^
15242 Do not place the keyword @code{is} on a separate line in a subprogram body in
15243 case if the specification occupies more then one line.
15249 The @option{-c1} and @option{-c2} switches are incompatible.
15250 The @option{-c3} and @option{-c4} switches are compatible with each other and
15251 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
15252 the other comment formatting switches.
15254 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
15259 For the @option{/COMMENTS_LAYOUT} qualifier:
15262 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
15264 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
15265 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
15269 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
15270 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
15273 @node General Text Layout Control
15274 @subsection General Text Layout Control
15277 These switches allow control over line length and indentation.
15280 @item ^-M@i{nnn}^/LINE_LENGTH_MAX=@i{nnn}^
15281 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
15282 Maximum line length, @i{nnn} from 32 ..256, the default value is 79
15284 @item ^-i@i{nnn}^/INDENTATION_LEVEL=@i{nnn}^
15285 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
15286 Indentation level, @i{nnn} from 1 .. 9, the default value is 3
15288 @item ^-cl@i{nnn}^/CONTINUATION_INDENT=@i{nnn}^
15289 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
15290 Indentation level for continuation lines (relative to the line being
15291 continued), @i{nnn} from 1 .. 9.
15293 value is one less then the (normal) indentation level, unless the
15294 indentation is set to 1 (in which case the default value for continuation
15295 line indentation is also 1)
15298 @node Other Formatting Options
15299 @subsection Other Formatting Options
15302 These switches control the inclusion of missing end/exit labels, and
15303 the indentation level in @b{case} statements.
15306 @item ^-e^/NO_MISSED_LABELS^
15307 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
15308 Do not insert missing end/exit labels. An end label is the name of
15309 a construct that may optionally be repeated at the end of the
15310 construct's declaration;
15311 e.g., the names of packages, subprograms, and tasks.
15312 An exit label is the name of a loop that may appear as target
15313 of an exit statement within the loop.
15314 By default, @command{gnatpp} inserts these end/exit labels when
15315 they are absent from the original source. This option suppresses such
15316 insertion, so that the formatted source reflects the original.
15318 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
15319 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
15320 Insert a Form Feed character after a pragma Page.
15322 @item ^-T@i{nnn}^/MAX_INDENT=@i{nnn}^
15323 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
15324 Do not use an additional indentation level for @b{case} alternatives
15325 and variants if there are @i{nnn} or more (the default
15327 If @i{nnn} is 0, an additional indentation level is
15328 used for @b{case} alternatives and variants regardless of their number.
15331 @node Setting the Source Search Path
15332 @subsection Setting the Source Search Path
15335 To define the search path for the input source file, @command{gnatpp}
15336 uses the same switches as the GNAT compiler, with the same effects.
15339 @item ^-I^/SEARCH=^@var{dir}
15340 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
15341 The same as the corresponding gcc switch
15343 @item ^-I-^/NOCURRENT_DIRECTORY^
15344 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
15345 The same as the corresponding gcc switch
15347 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
15348 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
15349 The same as the corresponding gcc switch
15351 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
15352 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
15353 The same as the corresponding gcc switch
15357 @node Output File Control
15358 @subsection Output File Control
15361 By default the output is sent to the file whose name is obtained by appending
15362 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
15363 (if the file with this name already exists, it is unconditionally overwritten).
15364 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
15365 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
15367 The output may be redirected by the following switches:
15370 @item ^-pipe^/STANDARD_OUTPUT^
15371 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
15372 Send the output to @code{Standard_Output}
15374 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
15375 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
15376 Write the output into @var{output_file}.
15377 If @var{output_file} already exists, @command{gnatpp} terminates without
15378 reading or processing the input file.
15380 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
15381 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
15382 Write the output into @var{output_file}, overwriting the existing file
15383 (if one is present).
15385 @item ^-r^/REPLACE^
15386 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
15387 Replace the input source file with the reformatted output, and copy the
15388 original input source into the file whose name is obtained by appending the
15389 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
15390 If a file with this name already exists, @command{gnatpp} terminates without
15391 reading or processing the input file.
15393 @item ^-rf^/OVERRIDING_REPLACE^
15394 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
15395 Like @option{^-r^/REPLACE^} except that if the file with the specified name
15396 already exists, it is overwritten.
15398 @item ^-rnb^/NO_BACKUP^
15399 @cindex @option{^-rnb^/NO_BACKUP^} (@code{gnatpp})
15400 Replace the input source file with the reformatted output without
15401 creating any backup copy of the input source.
15403 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
15404 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
15405 Specifies the format of the reformatted output file. The @var{xxx}
15406 ^string specified with the switch^option^ may be either
15408 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
15409 @item ``@option{^crlf^CRLF^}''
15410 the same as @option{^crlf^CRLF^}
15411 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
15412 @item ``@option{^lf^LF^}''
15413 the same as @option{^unix^UNIX^}
15419 Options @option{^-pipe^/STANDARD_OUTPUT^},
15420 @option{^-o^/OUTPUT^} and
15421 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
15422 contains only one file to reformat.
15424 @option{^--eol^/END_OF_LINE^}
15425 cannot be used together
15426 with @option{^-pipe^/STANDARD_OUTPUT^} option.
15428 @node Other gnatpp Switches
15429 @subsection Other @code{gnatpp} Switches
15432 The additional @command{gnatpp} switches are defined in this subsection.
15435 @item ^-files @var{filename}^/FILES=@var{output_file}^
15436 @cindex @option{^-files^/FILES^} (@code{gnatpp})
15437 Take the argument source files from the specified file. This file should be an
15438 ordinary textual file containing file names separated by spaces or
15439 line breaks. You can use this switch more then once in the same call to
15440 @command{gnatpp}. You also can combine this switch with explicit list of
15443 @item ^-v^/VERBOSE^
15444 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
15446 @command{gnatpp} generates version information and then
15447 a trace of the actions it takes to produce or obtain the ASIS tree.
15449 @item ^-w^/WARNINGS^
15450 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
15452 @command{gnatpp} generates a warning whenever it cannot provide
15453 a required layout in the result source.
15456 @node Formatting Rules
15457 @section Formatting Rules
15460 The following subsections show how @command{gnatpp} treats ``white space'',
15461 comments, program layout, and name casing.
15462 They provide the detailed descriptions of the switches shown above.
15465 * White Space and Empty Lines::
15466 * Formatting Comments::
15467 * Construct Layout::
15471 @node White Space and Empty Lines
15472 @subsection White Space and Empty Lines
15475 @command{gnatpp} does not have an option to control space characters.
15476 It will add or remove spaces according to the style illustrated by the
15477 examples in the @cite{Ada Reference Manual}.
15479 The only format effectors
15480 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
15481 that will appear in the output file are platform-specific line breaks,
15482 and also format effectors within (but not at the end of) comments.
15483 In particular, each horizontal tab character that is not inside
15484 a comment will be treated as a space and thus will appear in the
15485 output file as zero or more spaces depending on
15486 the reformatting of the line in which it appears.
15487 The only exception is a Form Feed character, which is inserted after a
15488 pragma @code{Page} when @option{-ff} is set.
15490 The output file will contain no lines with trailing ``white space'' (spaces,
15493 Empty lines in the original source are preserved
15494 only if they separate declarations or statements.
15495 In such contexts, a
15496 sequence of two or more empty lines is replaced by exactly one empty line.
15497 Note that a blank line will be removed if it separates two ``comment blocks''
15498 (a comment block is a sequence of whole-line comments).
15499 In order to preserve a visual separation between comment blocks, use an
15500 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
15501 Likewise, if for some reason you wish to have a sequence of empty lines,
15502 use a sequence of empty comments instead.
15504 @node Formatting Comments
15505 @subsection Formatting Comments
15508 Comments in Ada code are of two kinds:
15511 a @emph{whole-line comment}, which appears by itself (possibly preceded by
15512 ``white space'') on a line
15515 an @emph{end-of-line comment}, which follows some other Ada lexical element
15520 The indentation of a whole-line comment is that of either
15521 the preceding or following line in
15522 the formatted source, depending on switch settings as will be described below.
15524 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
15525 between the end of the preceding Ada lexical element and the beginning
15526 of the comment as appear in the original source,
15527 unless either the comment has to be split to
15528 satisfy the line length limitation, or else the next line contains a
15529 whole line comment that is considered a continuation of this end-of-line
15530 comment (because it starts at the same position).
15532 cases, the start of the end-of-line comment is moved right to the nearest
15533 multiple of the indentation level.
15534 This may result in a ``line overflow'' (the right-shifted comment extending
15535 beyond the maximum line length), in which case the comment is split as
15538 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
15539 (GNAT-style comment line indentation)
15540 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
15541 (reference-manual comment line indentation).
15542 With reference-manual style, a whole-line comment is indented as if it
15543 were a declaration or statement at the same place
15544 (i.e., according to the indentation of the preceding line(s)).
15545 With GNAT style, a whole-line comment that is immediately followed by an
15546 @b{if} or @b{case} statement alternative, a record variant, or the reserved
15547 word @b{begin}, is indented based on the construct that follows it.
15550 @smallexample @c ada
15562 Reference-manual indentation produces:
15564 @smallexample @c ada
15576 while GNAT-style indentation produces:
15578 @smallexample @c ada
15590 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
15591 (GNAT style comment beginning) has the following
15596 For each whole-line comment that does not end with two hyphens,
15597 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
15598 to ensure that there are at least two spaces between these hyphens and the
15599 first non-blank character of the comment.
15603 For an end-of-line comment, if in the original source the next line is a
15604 whole-line comment that starts at the same position
15605 as the end-of-line comment,
15606 then the whole-line comment (and all whole-line comments
15607 that follow it and that start at the same position)
15608 will start at this position in the output file.
15611 That is, if in the original source we have:
15613 @smallexample @c ada
15616 A := B + C; -- B must be in the range Low1..High1
15617 -- C must be in the range Low2..High2
15618 --B+C will be in the range Low1+Low2..High1+High2
15624 Then in the formatted source we get
15626 @smallexample @c ada
15629 A := B + C; -- B must be in the range Low1..High1
15630 -- C must be in the range Low2..High2
15631 -- B+C will be in the range Low1+Low2..High1+High2
15637 A comment that exceeds the line length limit will be split.
15639 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
15640 the line belongs to a reformattable block, splitting the line generates a
15641 @command{gnatpp} warning.
15642 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
15643 comments may be reformatted in typical
15644 word processor style (that is, moving words between lines and putting as
15645 many words in a line as possible).
15647 @node Construct Layout
15648 @subsection Construct Layout
15651 In several cases the suggested layout in the Ada Reference Manual includes
15652 an extra level of indentation that many programmers prefer to avoid. The
15653 affected cases include:
15657 @item Record type declaration (RM 3.8)
15659 @item Record representation clause (RM 13.5.1)
15661 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
15663 @item Block statement in case if a block has a statement identifier (RM 5.6)
15667 In compact mode (when GNAT style layout or compact layout is set),
15668 the pretty printer uses one level of indentation instead
15669 of two. This is achieved in the record definition and record representation
15670 clause cases by putting the @code{record} keyword on the same line as the
15671 start of the declaration or representation clause, and in the block and loop
15672 case by putting the block or loop header on the same line as the statement
15676 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
15677 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
15678 layout on the one hand, and uncompact layout
15679 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
15680 can be illustrated by the following examples:
15684 @multitable @columnfractions .5 .5
15685 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
15688 @smallexample @c ada
15695 @smallexample @c ada
15704 @smallexample @c ada
15706 a at 0 range 0 .. 31;
15707 b at 4 range 0 .. 31;
15711 @smallexample @c ada
15714 a at 0 range 0 .. 31;
15715 b at 4 range 0 .. 31;
15720 @smallexample @c ada
15728 @smallexample @c ada
15738 @smallexample @c ada
15739 Clear : for J in 1 .. 10 loop
15744 @smallexample @c ada
15746 for J in 1 .. 10 loop
15757 GNAT style, compact layout Uncompact layout
15759 type q is record type q is
15760 a : integer; record
15761 b : integer; a : integer;
15762 end record; b : integer;
15765 for q use record for q use
15766 a at 0 range 0 .. 31; record
15767 b at 4 range 0 .. 31; a at 0 range 0 .. 31;
15768 end record; b at 4 range 0 .. 31;
15771 Block : declare Block :
15772 A : Integer := 3; declare
15773 begin A : Integer := 3;
15775 end Block; Proc (A, A);
15778 Clear : for J in 1 .. 10 loop Clear :
15779 A (J) := 0; for J in 1 .. 10 loop
15780 end loop Clear; A (J) := 0;
15787 A further difference between GNAT style layout and compact layout is that
15788 GNAT style layout inserts empty lines as separation for
15789 compound statements, return statements and bodies.
15792 @subsection Name Casing
15795 @command{gnatpp} always converts the usage occurrence of a (simple) name to
15796 the same casing as the corresponding defining identifier.
15798 You control the casing for defining occurrences via the
15799 @option{^-n^/NAME_CASING^} switch.
15801 With @option{-nD} (``as declared'', which is the default),
15804 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
15806 defining occurrences appear exactly as in the source file
15807 where they are declared.
15808 The other ^values for this switch^options for this qualifier^ ---
15809 @option{^-nU^UPPER_CASE^},
15810 @option{^-nL^LOWER_CASE^},
15811 @option{^-nM^MIXED_CASE^} ---
15813 ^upper, lower, or mixed case, respectively^the corresponding casing^.
15814 If @command{gnatpp} changes the casing of a defining
15815 occurrence, it analogously changes the casing of all the
15816 usage occurrences of this name.
15818 If the defining occurrence of a name is not in the source compilation unit
15819 currently being processed by @command{gnatpp}, the casing of each reference to
15820 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
15821 switch (subject to the dictionary file mechanism described below).
15822 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
15824 casing for the defining occurrence of the name.
15826 Some names may need to be spelled with casing conventions that are not
15827 covered by the upper-, lower-, and mixed-case transformations.
15828 You can arrange correct casing by placing such names in a
15829 @emph{dictionary file},
15830 and then supplying a @option{^-D^/DICTIONARY^} switch.
15831 The casing of names from dictionary files overrides
15832 any @option{^-n^/NAME_CASING^} switch.
15834 To handle the casing of Ada predefined names and the names from GNAT libraries,
15835 @command{gnatpp} assumes a default dictionary file.
15836 The name of each predefined entity is spelled with the same casing as is used
15837 for the entity in the @cite{Ada Reference Manual}.
15838 The name of each entity in the GNAT libraries is spelled with the same casing
15839 as is used in the declaration of that entity.
15841 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
15842 default dictionary file.
15843 Instead, the casing for predefined and GNAT-defined names will be established
15844 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
15845 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
15846 will appear as just shown,
15847 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
15848 To ensure that even such names are rendered in uppercase,
15849 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
15850 (or else, less conveniently, place these names in upper case in a dictionary
15853 A dictionary file is
15854 a plain text file; each line in this file can be either a blank line
15855 (containing only space characters and ASCII.HT characters), an Ada comment
15856 line, or the specification of exactly one @emph{casing schema}.
15858 A casing schema is a string that has the following syntax:
15862 @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
15864 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
15869 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
15870 @var{identifier} lexical element and the @var{letter_or_digit} category.)
15872 The casing schema string can be followed by white space and/or an Ada-style
15873 comment; any amount of white space is allowed before the string.
15875 If a dictionary file is passed as
15877 the value of a @option{-D@var{file}} switch
15880 an option to the @option{/DICTIONARY} qualifier
15883 simple name and every identifier, @command{gnatpp} checks if the dictionary
15884 defines the casing for the name or for some of its parts (the term ``subword''
15885 is used below to denote the part of a name which is delimited by ``_'' or by
15886 the beginning or end of the word and which does not contain any ``_'' inside):
15890 if the whole name is in the dictionary, @command{gnatpp} uses for this name
15891 the casing defined by the dictionary; no subwords are checked for this word
15894 for every subword @command{gnatpp} checks if the dictionary contains the
15895 corresponding string of the form @code{*@var{simple_identifier}*},
15896 and if it does, the casing of this @var{simple_identifier} is used
15900 if the whole name does not contain any ``_'' inside, and if for this name
15901 the dictionary contains two entries - one of the form @var{identifier},
15902 and another - of the form *@var{simple_identifier}*, then the first one
15903 is applied to define the casing of this name
15906 if more than one dictionary file is passed as @command{gnatpp} switches, each
15907 dictionary adds new casing exceptions and overrides all the existing casing
15908 exceptions set by the previous dictionaries
15911 when @command{gnatpp} checks if the word or subword is in the dictionary,
15912 this check is not case sensitive
15916 For example, suppose we have the following source to reformat:
15918 @smallexample @c ada
15921 name1 : integer := 1;
15922 name4_name3_name2 : integer := 2;
15923 name2_name3_name4 : Boolean;
15926 name2_name3_name4 := name4_name3_name2 > name1;
15932 And suppose we have two dictionaries:
15949 If @command{gnatpp} is called with the following switches:
15953 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
15956 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
15961 then we will get the following name casing in the @command{gnatpp} output:
15963 @smallexample @c ada
15966 NAME1 : Integer := 1;
15967 Name4_NAME3_Name2 : Integer := 2;
15968 Name2_NAME3_Name4 : Boolean;
15971 Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
15976 @c *********************************
15977 @node The GNAT Metric Tool gnatmetric
15978 @chapter The GNAT Metric Tool @command{gnatmetric}
15980 @cindex Metric tool
15983 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
15984 for computing various program metrics.
15985 It takes an Ada source file as input and generates a file containing the
15986 metrics data as output. Various switches control which
15987 metrics are computed and output.
15989 @command{gnatmetric} generates and uses the ASIS
15990 tree for the input source and thus requires the input to be syntactically and
15991 semantically legal.
15992 If this condition is not met, @command{gnatmetric} will generate
15993 an error message; no metric information for this file will be
15994 computed and reported.
15996 If the compilation unit contained in the input source depends semantically
15997 upon units in files located outside the current directory, you have to provide
15998 the source search path when invoking @command{gnatmetric}.
15999 If it depends semantically upon units that are contained
16000 in files with names that do not follow the GNAT file naming rules, you have to
16001 provide the configuration file describing the corresponding naming scheme (see
16002 the description of the @command{gnatmetric} switches below.)
16003 Alternatively, you may use a project file and invoke @command{gnatmetric}
16004 through the @command{gnat} driver.
16006 The @command{gnatmetric} command has the form
16009 $ gnatmetric [@i{switches}] @{@i{filename}@} [@i{-cargs gcc_switches}]
16016 @i{switches} specify the metrics to compute and define the destination for
16020 Each @i{filename} is the name (including the extension) of a source
16021 file to process. ``Wildcards'' are allowed, and
16022 the file name may contain path information.
16023 If no @i{filename} is supplied, then the @i{switches} list must contain
16025 @option{-files} switch (@pxref{Other gnatmetric Switches}).
16026 Including both a @option{-files} switch and one or more
16027 @i{filename} arguments is permitted.
16030 @i{-cargs gcc_switches} is a list of switches for
16031 @command{gcc}. They will be passed on to all compiler invocations made by
16032 @command{gnatmetric} to generate the ASIS trees. Here you can provide
16033 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
16034 and use the @option{-gnatec} switch to set the configuration file.
16038 * Switches for gnatmetric::
16041 @node Switches for gnatmetric
16042 @section Switches for @command{gnatmetric}
16045 The following subsections describe the various switches accepted by
16046 @command{gnatmetric}, organized by category.
16049 * Output Files Control::
16050 * Disable Metrics For Local Units::
16051 * Line Metrics Control::
16052 * Syntax Metrics Control::
16053 * Complexity Metrics Control::
16054 * Other gnatmetric Switches::
16057 @node Output Files Control
16058 @subsection Output File Control
16059 @cindex Output file control in @command{gnatmetric}
16062 @command{gnatmetric} has two output formats. It can generate a
16063 textual (human-readable) form, and also XML. By default only textual
16064 output is generated.
16066 When generating the output in textual form, @command{gnatmetric} creates
16067 for each Ada source file a corresponding text file
16068 containing the computed metrics. By default, this file
16069 is placed in the same directory as where the source file is located, and
16070 its name is obtained
16071 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
16074 All the output information generated in XML format is placed in a single
16075 file. By default this file is placed in the current directory and has the
16076 name ^@file{metrix.xml}^@file{METRIX$XML}^.
16078 Some of the computed metrics are summed over the units passed to
16079 @command{gnatmetric}; for example, the total number of lines of code.
16080 By default this information is sent to @file{stdout}, but a file
16081 can be specified with the @option{-og} switch.
16083 The following switches control the @command{gnatmetric} output:
16086 @cindex @option{^-x^/XML^} (@command{gnatmetric})
16088 Generate the XML output
16090 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
16091 @item ^-nt^/NO_TEXT^
16092 Do not generate the output in text form (implies @option{^-x^/XML^})
16094 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
16095 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
16096 Put textual files with detailed metrics into @var{output_dir}
16098 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
16099 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
16100 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
16101 in the name of the output file.
16103 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
16104 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
16105 Put global metrics into @var{file_name}
16107 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
16108 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
16109 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
16111 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
16112 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
16113 Use ``short'' source file names in the output. (The @command{gnatmetric}
16114 output includes the name(s) of the Ada source file(s) from which the metrics
16115 are computed. By default each name includes the absolute path. The
16116 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
16117 to exclude all directory information from the file names that are output.)
16121 @node Disable Metrics For Local Units
16122 @subsection Disable Metrics For Local Units
16123 @cindex Disable Metrics For Local Units in @command{gnatmetric}
16126 @command{gnatmetric} relies on the GNAT compilation model @minus{}
16128 unit per one source file. It computes line metrics for the whole source
16129 file, and it also computes syntax
16130 and complexity metrics for the file's outermost unit.
16132 By default, @command{gnatmetric} will also compute all metrics for certain
16133 kinds of locally declared program units:
16137 subprogram (and generic subprogram) bodies;
16140 package (and generic package) specifications and bodies;
16143 task object and type specifications and bodies;
16146 protected object and type specifications and bodies.
16150 These kinds of entities will be referred to as
16151 @emph{eligible local program units}, or simply @emph{eligible local units},
16152 @cindex Eligible local unit (for @command{gnatmetric})
16153 in the discussion below.
16155 Note that a subprogram declaration, generic instantiation,
16156 or renaming declaration only receives metrics
16157 computation when it appear as the outermost entity
16160 Suppression of metrics computation for eligible local units can be
16161 obtained via the following switch:
16164 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
16165 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
16166 Do not compute detailed metrics for eligible local program units
16170 @node Line Metrics Control
16171 @subsection Line Metrics Control
16172 @cindex Line metrics control in @command{gnatmetric}
16175 For any (legal) source file, and for each of its
16176 eligible local program units, @command{gnatmetric} computes the following
16181 the total number of lines;
16184 the total number of code lines (i.e., non-blank lines that are not comments)
16187 the number of comment lines
16190 the number of code lines containing end-of-line comments;
16193 the number of empty lines and lines containing only space characters and/or
16194 format effectors (blank lines)
16198 If @command{gnatmetric} is invoked on more than one source file, it sums the
16199 values of the line metrics for all the files being processed and then
16200 generates the cumulative results.
16202 By default, all the line metrics are computed and reported. You can use the
16203 following switches to select the specific line metrics to be computed and
16204 reported (if any of these parameters is set, only explicitly specified line
16205 metrics are computed).
16208 @cindex @option{^-la^/LINES_ALL^} (@command{gnatmetric})
16209 @item ^-la^/LINES_ALL^
16210 The number of all lines
16212 @cindex @option{^-lcode^/CODE_LINES^} (@command{gnatmetric})
16213 @item ^-lcode^/CODE_LINES^
16214 The number of code lines
16216 @cindex @option{^-lcomm^/COMMENT_LINES^} (@command{gnatmetric})
16217 @item ^-lcomm^/COMENT_LINES^
16218 The number of comment lines
16220 @cindex @option{^-leol^/MIXED_CODE_COMMENTS^} (@command{gnatmetric})
16221 @item ^-leol^/MIXED_CODE_COMMENTS^
16222 The number of code lines containing
16223 end-of-line comments
16225 @cindex @option{^-lb^/BLANK_LINES^} (@command{gnatmetric})
16226 @item ^-lb^/BLANK_LINES^
16227 The number of blank lines
16231 @node Syntax Metrics Control
16232 @subsection Syntax Metrics Control
16233 @cindex Syntax metrics control in @command{gnatmetric}
16236 @command{gnatmetric} computes various syntactic metrics for the
16237 outermost unit and for each eligible local unit:
16240 @item LSLOC (``Logical Source Lines Of Code'')
16241 The total number of declarations and the total number of statements
16243 @item Maximal static nesting level of inner program units
16245 @cite{Ada 95 Language Reference Manual}, 10.1(1), ``A program unit is either a
16246 package, a task unit, a protected unit, a
16247 protected entry, a generic unit, or an explicitly declared subprogram other
16248 than an enumeration literal.''
16250 @item Maximal nesting level of composite syntactic constructs
16251 This corresponds to the notion of the
16252 maximum nesting level in the GNAT built-in style checks
16253 (@pxref{Style Checking})
16257 For the outermost unit in the file, @command{gnatmetric} additionally computes
16258 the following metrics:
16261 @item Public subprograms
16262 This metric is computed for package specifications. It is the
16263 number of subprograms and generic subprograms declared in the visible
16264 part (including in nested packages, protected objects, and
16267 @item All subprograms
16268 This metric is computed for bodies and subunits. The
16269 metric is equal to a total number of subprogram bodies in the compilation
16271 Neither generic instantiations nor renamings-as-a-body nor body stubs
16272 are counted. Any subprogram body is counted, independently of its nesting
16273 level and enclosing constructs. Generic bodies and bodies of protected
16274 subprograms are counted in the same way as ``usual'' subprogram bodies.
16277 This metric is computed for package specifications and
16278 generic package declarations. It is the total number of types
16279 that can be referenced from outside this compilation unit, plus the
16280 number of types from all the visible parts of all the visible generic packages.
16281 Generic formal types are not counted. Only types, not subtypes,
16285 Along with the total number of public types, the following
16286 types are counted and reported separately:
16293 Root tagged types (abstract, non-abstract, private, non-private). Type
16294 extensions are @emph{not} counted
16297 Private types (including private extensions)
16308 This metric is computed for any compilation unit. It is equal to the total
16309 number of the declarations of different types given in the compilation unit.
16310 The private and the corresponding full type declaration are counted as one
16311 type declaration. Incomplete type declarations and generic formal types
16313 No distinction is made among different kinds of types (abstract,
16314 private etc.); the total number of types is computed and reported.
16319 By default, all the syntax metrics are computed and reported. You can use the
16320 following switches to select specific syntax metrics;
16321 if any of these is set, only the explicitly specified metrics are computed.
16324 @cindex @option{^-ed^/DECLARATION_TOTAL^} (@command{gnatmetric})
16325 @item ^-ed^/DECLARATION_TOTAL^
16326 The total number of declarations
16328 @cindex @option{^-es^/STATEMENT_TOTAL^} (@command{gnatmetric})
16329 @item ^-es^/STATEMENT_TOTAL^
16330 The total number of statements
16332 @cindex @option{^-eps^/^} (@command{gnatmetric})
16333 @item ^-eps^/INT_SUBPROGRAMS^
16334 The number of public subprograms in a compilation unit
16336 @cindex @option{^-eas^/SUBPROGRAMS_ALL^} (@command{gnatmetric})
16337 @item ^-eas^/SUBPROGRAMS_ALL^
16338 The number of all the subprograms in a compilation unit
16340 @cindex @option{^-ept^/INT_TYPES^} (@command{gnatmetric})
16341 @item ^-ept^/INT_TYPES^
16342 The number of public types in a compilation unit
16344 @cindex @option{^-eat^/TYPES_ALL^} (@command{gnatmetric})
16345 @item ^-eat^/TYPES_ALL^
16346 The number of all the types in a compilation unit
16348 @cindex @option{^-enu^/PROGRAM_NESTING_MAX^} (@command{gnatmetric})
16349 @item ^-enu^/PROGRAM_NESTING_MAX^
16350 The maximal program unit nesting level
16352 @cindex @option{^-ec^/CONSTRUCT_NESTING_MAX^} (@command{gnatmetric})
16353 @item ^-ec^/CONSTRUCT_NESTING_MAX^
16354 The maximal construct nesting level
16358 @node Complexity Metrics Control
16359 @subsection Complexity Metrics Control
16360 @cindex Complexity metrics control in @command{gnatmetric}
16363 For a program unit that is an executable body (a subprogram body (including
16364 generic bodies), task body, entry body or a package body containing
16365 its own statement sequence ) @command{gnatmetric} computes the following
16366 complexity metrics:
16370 McCabe cyclomatic complexity;
16373 McCabe essential complexity;
16376 maximal loop nesting level
16381 The McCabe complexity metrics are defined
16382 in @url{www.mccabe.com/pdf/nist235r.pdf}
16384 According to McCabe, both control statements and short-circuit control forms
16385 should be taken into account when computing cyclomatic complexity. For each
16386 body, we compute three metric values:
16390 the complexity introduced by control
16391 statements only, without taking into account short-circuit forms,
16394 the complexity introduced by short-circuit control forms only, and
16398 cyclomatic complexity, which is the sum of these two values.
16402 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
16403 the code in the exception handlers and in all the nested program units.
16405 By default, all the complexity metrics are computed and reported.
16406 For more finely-grained control you can use
16407 the following switches:
16410 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
16412 @item ^-nocc^/SUPPRESS=CYCLOMATIC_COMPLEXITY^
16413 Do not compute the McCabe Cyclomatic Complexity
16415 @item ^-noec^/SUPPRESS=ESSENTIAL_COMPLEXITY^
16416 Do not compute the Essential Complexity
16418 @item ^-nonl^/SUPPRESS=MAXIMAL_LOOP_NESTING^
16419 Do not compute maximal loop nesting level
16421 @item ^-ne^/SUPPRESS=EXITS_AS_GOTOS^
16422 Do not consider @code{exit} statements as @code{goto}s when
16423 computing Essential Complexity
16427 @node Other gnatmetric Switches
16428 @subsection Other @code{gnatmetric} Switches
16431 Additional @command{gnatmetric} switches are as follows:
16434 @item ^-files @var{filename}^/FILES=@var{filename}^
16435 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
16436 Take the argument source files from the specified file. This file should be an
16437 ordinary textual file containing file names separated by spaces or
16438 line breaks. You can use this switch more then once in the same call to
16439 @command{gnatmetric}. You also can combine this switch with
16440 an explicit list of files.
16442 @item ^-v^/VERBOSE^
16443 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
16445 @command{gnatmetric} generates version information and then
16446 a trace of sources being processed.
16448 @item ^-dv^/DEBUG_OUTPUT^
16449 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
16451 @command{gnatmetric} generates various messages useful to understand what
16452 happens during the metrics computation
16455 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
16459 @c ***********************************
16460 @node File Name Krunching Using gnatkr
16461 @chapter File Name Krunching Using @code{gnatkr}
16465 This chapter discusses the method used by the compiler to shorten
16466 the default file names chosen for Ada units so that they do not
16467 exceed the maximum length permitted. It also describes the
16468 @code{gnatkr} utility that can be used to determine the result of
16469 applying this shortening.
16473 * Krunching Method::
16474 * Examples of gnatkr Usage::
16478 @section About @code{gnatkr}
16481 The default file naming rule in GNAT
16482 is that the file name must be derived from
16483 the unit name. The exact default rule is as follows:
16486 Take the unit name and replace all dots by hyphens.
16488 If such a replacement occurs in the
16489 second character position of a name, and the first character is
16490 ^a, g, s, or i^A, G, S, or I^ then replace the dot by the character
16491 ^~ (tilde)^$ (dollar sign)^
16492 instead of a minus.
16494 The reason for this exception is to avoid clashes
16495 with the standard names for children of System, Ada, Interfaces,
16496 and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^
16499 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
16500 switch of the compiler activates a ``krunching''
16501 circuit that limits file names to nn characters (where nn is a decimal
16502 integer). For example, using OpenVMS,
16503 where the maximum file name length is
16504 39, the value of nn is usually set to 39, but if you want to generate
16505 a set of files that would be usable if ported to a system with some
16506 different maximum file length, then a different value can be specified.
16507 The default value of 39 for OpenVMS need not be specified.
16509 The @code{gnatkr} utility can be used to determine the krunched name for
16510 a given file, when krunched to a specified maximum length.
16513 @section Using @code{gnatkr}
16516 The @code{gnatkr} command has the form
16520 $ gnatkr @var{name} [@var{length}]
16526 $ gnatkr @var{name} /COUNT=nn
16531 @var{name} is the uncrunched file name, derived from the name of the unit
16532 in the standard manner described in the previous section (i.e. in particular
16533 all dots are replaced by hyphens). The file name may or may not have an
16534 extension (defined as a suffix of the form period followed by arbitrary
16535 characters other than period). If an extension is present then it will
16536 be preserved in the output. For example, when krunching @file{hellofile.ads}
16537 to eight characters, the result will be hellofil.ads.
16539 Note: for compatibility with previous versions of @code{gnatkr} dots may
16540 appear in the name instead of hyphens, but the last dot will always be
16541 taken as the start of an extension. So if @code{gnatkr} is given an argument
16542 such as @file{Hello.World.adb} it will be treated exactly as if the first
16543 period had been a hyphen, and for example krunching to eight characters
16544 gives the result @file{hellworl.adb}.
16546 Note that the result is always all lower case (except on OpenVMS where it is
16547 all upper case). Characters of the other case are folded as required.
16549 @var{length} represents the length of the krunched name. The default
16550 when no argument is given is ^8^39^ characters. A length of zero stands for
16551 unlimited, in other words do not chop except for system files where the
16552 implied crunching length is always eight characters.
16555 The output is the krunched name. The output has an extension only if the
16556 original argument was a file name with an extension.
16558 @node Krunching Method
16559 @section Krunching Method
16562 The initial file name is determined by the name of the unit that the file
16563 contains. The name is formed by taking the full expanded name of the
16564 unit and replacing the separating dots with hyphens and
16565 using ^lowercase^uppercase^
16566 for all letters, except that a hyphen in the second character position is
16567 replaced by a ^tilde^dollar sign^ if the first character is
16568 ^a, i, g, or s^A, I, G, or S^.
16569 The extension is @code{.ads} for a
16570 specification and @code{.adb} for a body.
16571 Krunching does not affect the extension, but the file name is shortened to
16572 the specified length by following these rules:
16576 The name is divided into segments separated by hyphens, tildes or
16577 underscores and all hyphens, tildes, and underscores are
16578 eliminated. If this leaves the name short enough, we are done.
16581 If the name is too long, the longest segment is located (left-most
16582 if there are two of equal length), and shortened by dropping
16583 its last character. This is repeated until the name is short enough.
16585 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16586 to fit the name into 8 characters as required by some operating systems.
16589 our-strings-wide_fixed 22
16590 our strings wide fixed 19
16591 our string wide fixed 18
16592 our strin wide fixed 17
16593 our stri wide fixed 16
16594 our stri wide fixe 15
16595 our str wide fixe 14
16596 our str wid fixe 13
16602 Final file name: oustwifi.adb
16606 The file names for all predefined units are always krunched to eight
16607 characters. The krunching of these predefined units uses the following
16608 special prefix replacements:
16612 replaced by @file{^a^A^-}
16615 replaced by @file{^g^G^-}
16618 replaced by @file{^i^I^-}
16621 replaced by @file{^s^S^-}
16624 These system files have a hyphen in the second character position. That
16625 is why normal user files replace such a character with a
16626 ^tilde^dollar sign^, to
16627 avoid confusion with system file names.
16629 As an example of this special rule, consider
16630 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16633 ada-strings-wide_fixed 22
16634 a- strings wide fixed 18
16635 a- string wide fixed 17
16636 a- strin wide fixed 16
16637 a- stri wide fixed 15
16638 a- stri wide fixe 14
16639 a- str wide fixe 13
16645 Final file name: a-stwifi.adb
16649 Of course no file shortening algorithm can guarantee uniqueness over all
16650 possible unit names, and if file name krunching is used then it is your
16651 responsibility to ensure that no name clashes occur. The utility
16652 program @code{gnatkr} is supplied for conveniently determining the
16653 krunched name of a file.
16655 @node Examples of gnatkr Usage
16656 @section Examples of @code{gnatkr} Usage
16663 $ gnatkr very_long_unit_name.ads --> velounna.ads
16664 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
16665 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16666 $ gnatkr grandparent-parent-child --> grparchi
16668 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16669 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16672 @node Preprocessing Using gnatprep
16673 @chapter Preprocessing Using @code{gnatprep}
16677 The @code{gnatprep} utility provides
16678 a simple preprocessing capability for Ada programs.
16679 It is designed for use with GNAT, but is not dependent on any special
16684 * Switches for gnatprep::
16685 * Form of Definitions File::
16686 * Form of Input Text for gnatprep::
16689 @node Using gnatprep
16690 @section Using @code{gnatprep}
16693 To call @code{gnatprep} use
16696 $ gnatprep [switches] infile outfile [deffile]
16703 is an optional sequence of switches as described in the next section.
16706 is the full name of the input file, which is an Ada source
16707 file containing preprocessor directives.
16710 is the full name of the output file, which is an Ada source
16711 in standard Ada form. When used with GNAT, this file name will
16712 normally have an ads or adb suffix.
16715 is the full name of a text file containing definitions of
16716 symbols to be referenced by the preprocessor. This argument is
16717 optional, and can be replaced by the use of the @option{-D} switch.
16721 @node Switches for gnatprep
16722 @section Switches for @code{gnatprep}
16727 @item ^-b^/BLANK_LINES^
16728 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
16729 Causes both preprocessor lines and the lines deleted by
16730 preprocessing to be replaced by blank lines in the output source file,
16731 preserving line numbers in the output file.
16733 @item ^-c^/COMMENTS^
16734 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
16735 Causes both preprocessor lines and the lines deleted
16736 by preprocessing to be retained in the output source as comments marked
16737 with the special string @code{"--! "}. This option will result in line numbers
16738 being preserved in the output file.
16740 @item ^-C^/REPLACE_IN_COMMENTS^
16741 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
16742 Causes comments to be scanned. Normally comments are ignored by gnatprep.
16743 If this option is specified, then comments are scanned and any $symbol
16744 substitutions performed as in program text. This is particularly useful
16745 when structured comments are used (e.g. when writing programs in the
16746 SPARK dialect of Ada). Note that this switch is not available when
16747 doing integrated preprocessing (it would be useless in this context
16748 since comments are ignored by the compiler in any case).
16750 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
16751 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
16752 Defines a new symbol, associated with value. If no value is given on the
16753 command line, then symbol is considered to be @code{True}. This switch
16754 can be used in place of a definition file.
16758 @cindex @option{/REMOVE} (@command{gnatprep})
16759 This is the default setting which causes lines deleted by preprocessing
16760 to be entirely removed from the output file.
16763 @item ^-r^/REFERENCE^
16764 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
16765 Causes a @code{Source_Reference} pragma to be generated that
16766 references the original input file, so that error messages will use
16767 the file name of this original file. The use of this switch implies
16768 that preprocessor lines are not to be removed from the file, so its
16769 use will force @option{^-b^/BLANK_LINES^} mode if
16770 @option{^-c^/COMMENTS^}
16771 has not been specified explicitly.
16773 Note that if the file to be preprocessed contains multiple units, then
16774 it will be necessary to @code{gnatchop} the output file from
16775 @code{gnatprep}. If a @code{Source_Reference} pragma is present
16776 in the preprocessed file, it will be respected by
16777 @code{gnatchop ^-r^/REFERENCE^}
16778 so that the final chopped files will correctly refer to the original
16779 input source file for @code{gnatprep}.
16781 @item ^-s^/SYMBOLS^
16782 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
16783 Causes a sorted list of symbol names and values to be
16784 listed on the standard output file.
16786 @item ^-u^/UNDEFINED^
16787 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
16788 Causes undefined symbols to be treated as having the value FALSE in the context
16789 of a preprocessor test. In the absence of this option, an undefined symbol in
16790 a @code{#if} or @code{#elsif} test will be treated as an error.
16796 Note: if neither @option{-b} nor @option{-c} is present,
16797 then preprocessor lines and
16798 deleted lines are completely removed from the output, unless -r is
16799 specified, in which case -b is assumed.
16802 @node Form of Definitions File
16803 @section Form of Definitions File
16806 The definitions file contains lines of the form
16813 where symbol is an identifier, following normal Ada (case-insensitive)
16814 rules for its syntax, and value is one of the following:
16818 Empty, corresponding to a null substitution
16820 A string literal using normal Ada syntax
16822 Any sequence of characters from the set
16823 (letters, digits, period, underline).
16827 Comment lines may also appear in the definitions file, starting with
16828 the usual @code{--},
16829 and comments may be added to the definitions lines.
16831 @node Form of Input Text for gnatprep
16832 @section Form of Input Text for @code{gnatprep}
16835 The input text may contain preprocessor conditional inclusion lines,
16836 as well as general symbol substitution sequences.
16838 The preprocessor conditional inclusion commands have the form
16843 #if @i{expression} [then]
16845 #elsif @i{expression} [then]
16847 #elsif @i{expression} [then]
16858 In this example, @i{expression} is defined by the following grammar:
16860 @i{expression} ::= <symbol>
16861 @i{expression} ::= <symbol> = "<value>"
16862 @i{expression} ::= <symbol> = <symbol>
16863 @i{expression} ::= <symbol> 'Defined
16864 @i{expression} ::= not @i{expression}
16865 @i{expression} ::= @i{expression} and @i{expression}
16866 @i{expression} ::= @i{expression} or @i{expression}
16867 @i{expression} ::= @i{expression} and then @i{expression}
16868 @i{expression} ::= @i{expression} or else @i{expression}
16869 @i{expression} ::= ( @i{expression} )
16873 For the first test (@i{expression} ::= <symbol>) the symbol must have
16874 either the value true or false, that is to say the right-hand of the
16875 symbol definition must be one of the (case-insensitive) literals
16876 @code{True} or @code{False}. If the value is true, then the
16877 corresponding lines are included, and if the value is false, they are
16880 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
16881 the symbol has been defined in the definition file or by a @option{-D}
16882 switch on the command line. Otherwise, the test is false.
16884 The equality tests are case insensitive, as are all the preprocessor lines.
16886 If the symbol referenced is not defined in the symbol definitions file,
16887 then the effect depends on whether or not switch @option{-u}
16888 is specified. If so, then the symbol is treated as if it had the value
16889 false and the test fails. If this switch is not specified, then
16890 it is an error to reference an undefined symbol. It is also an error to
16891 reference a symbol that is defined with a value other than @code{True}
16894 The use of the @code{not} operator inverts the sense of this logical test, so
16895 that the lines are included only if the symbol is not defined.
16896 The @code{then} keyword is optional as shown
16898 The @code{#} must be the first non-blank character on a line, but
16899 otherwise the format is free form. Spaces or tabs may appear between
16900 the @code{#} and the keyword. The keywords and the symbols are case
16901 insensitive as in normal Ada code. Comments may be used on a
16902 preprocessor line, but other than that, no other tokens may appear on a
16903 preprocessor line. Any number of @code{elsif} clauses can be present,
16904 including none at all. The @code{else} is optional, as in Ada.
16906 The @code{#} marking the start of a preprocessor line must be the first
16907 non-blank character on the line, i.e. it must be preceded only by
16908 spaces or horizontal tabs.
16910 Symbol substitution outside of preprocessor lines is obtained by using
16918 anywhere within a source line, except in a comment or within a
16919 string literal. The identifier
16920 following the @code{$} must match one of the symbols defined in the symbol
16921 definition file, and the result is to substitute the value of the
16922 symbol in place of @code{$symbol} in the output file.
16924 Note that although the substitution of strings within a string literal
16925 is not possible, it is possible to have a symbol whose defined value is
16926 a string literal. So instead of setting XYZ to @code{hello} and writing:
16929 Header : String := "$XYZ";
16933 you should set XYZ to @code{"hello"} and write:
16936 Header : String := $XYZ;
16940 and then the substitution will occur as desired.
16943 @node The GNAT Run-Time Library Builder gnatlbr
16944 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
16946 @cindex Library builder
16949 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
16950 supplied configuration pragmas.
16953 * Running gnatlbr::
16954 * Switches for gnatlbr::
16955 * Examples of gnatlbr Usage::
16958 @node Running gnatlbr
16959 @section Running @code{gnatlbr}
16962 The @code{gnatlbr} command has the form
16965 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
16968 @node Switches for gnatlbr
16969 @section Switches for @code{gnatlbr}
16972 @code{gnatlbr} recognizes the following switches:
16976 @item /CREATE=directory
16977 @cindex @code{/CREATE} (@code{gnatlbr})
16978 Create the new run-time library in the specified directory.
16980 @item /SET=directory
16981 @cindex @code{/SET} (@code{gnatlbr})
16982 Make the library in the specified directory the current run-time
16985 @item /DELETE=directory
16986 @cindex @code{/DELETE} (@code{gnatlbr})
16987 Delete the run-time library in the specified directory.
16990 @cindex @code{/CONFIG} (@code{gnatlbr})
16992 Use the configuration pragmas in the specified file when building
16996 Use the configuration pragmas in the specified file when compiling.
17000 @node Examples of gnatlbr Usage
17001 @section Example of @code{gnatlbr} Usage
17004 Contents of VAXFLOAT.ADC:
17005 pragma Float_Representation (VAX_Float);
17007 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
17009 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
17014 @node The GNAT Library Browser gnatls
17015 @chapter The GNAT Library Browser @code{gnatls}
17017 @cindex Library browser
17020 @code{gnatls} is a tool that outputs information about compiled
17021 units. It gives the relationship between objects, unit names and source
17022 files. It can also be used to check the source dependencies of a unit
17023 as well as various characteristics.
17027 * Switches for gnatls::
17028 * Examples of gnatls Usage::
17031 @node Running gnatls
17032 @section Running @code{gnatls}
17035 The @code{gnatls} command has the form
17038 $ gnatls switches @var{object_or_ali_file}
17042 The main argument is the list of object or @file{ali} files
17043 (@pxref{The Ada Library Information Files})
17044 for which information is requested.
17046 In normal mode, without additional option, @code{gnatls} produces a
17047 four-column listing. Each line represents information for a specific
17048 object. The first column gives the full path of the object, the second
17049 column gives the name of the principal unit in this object, the third
17050 column gives the status of the source and the fourth column gives the
17051 full path of the source representing this unit.
17052 Here is a simple example of use:
17056 ^./^[]^demo1.o demo1 DIF demo1.adb
17057 ^./^[]^demo2.o demo2 OK demo2.adb
17058 ^./^[]^hello.o h1 OK hello.adb
17059 ^./^[]^instr-child.o instr.child MOK instr-child.adb
17060 ^./^[]^instr.o instr OK instr.adb
17061 ^./^[]^tef.o tef DIF tef.adb
17062 ^./^[]^text_io_example.o text_io_example OK text_io_example.adb
17063 ^./^[]^tgef.o tgef DIF tgef.adb
17067 The first line can be interpreted as follows: the main unit which is
17069 object file @file{demo1.o} is demo1, whose main source is in
17070 @file{demo1.adb}. Furthermore, the version of the source used for the
17071 compilation of demo1 has been modified (DIF). Each source file has a status
17072 qualifier which can be:
17075 @item OK (unchanged)
17076 The version of the source file used for the compilation of the
17077 specified unit corresponds exactly to the actual source file.
17079 @item MOK (slightly modified)
17080 The version of the source file used for the compilation of the
17081 specified unit differs from the actual source file but not enough to
17082 require recompilation. If you use gnatmake with the qualifier
17083 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
17084 MOK will not be recompiled.
17086 @item DIF (modified)
17087 No version of the source found on the path corresponds to the source
17088 used to build this object.
17090 @item ??? (file not found)
17091 No source file was found for this unit.
17093 @item HID (hidden, unchanged version not first on PATH)
17094 The version of the source that corresponds exactly to the source used
17095 for compilation has been found on the path but it is hidden by another
17096 version of the same source that has been modified.
17100 @node Switches for gnatls
17101 @section Switches for @code{gnatls}
17104 @code{gnatls} recognizes the following switches:
17108 @item ^-a^/ALL_UNITS^
17109 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
17110 Consider all units, including those of the predefined Ada library.
17111 Especially useful with @option{^-d^/DEPENDENCIES^}.
17113 @item ^-d^/DEPENDENCIES^
17114 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
17115 List sources from which specified units depend on.
17117 @item ^-h^/OUTPUT=OPTIONS^
17118 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
17119 Output the list of options.
17121 @item ^-o^/OUTPUT=OBJECTS^
17122 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
17123 Only output information about object files.
17125 @item ^-s^/OUTPUT=SOURCES^
17126 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
17127 Only output information about source files.
17129 @item ^-u^/OUTPUT=UNITS^
17130 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
17131 Only output information about compilation units.
17133 @item ^-files^/FILES^=@var{file}
17134 @cindex @option{^-files^/FILES^} (@code{gnatls})
17135 Take as arguments the files listed in text file @var{file}.
17136 Text file @var{file} may contain empty lines that are ignored.
17137 Each non empty line should contain the name of an existing file.
17138 Several such switches may be specified simultaneously.
17140 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17141 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
17142 @itemx ^-I^/SEARCH=^@var{dir}
17143 @itemx ^-I-^/NOCURRENT_DIRECTORY^
17145 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
17146 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
17147 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
17148 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
17149 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
17150 flags (@pxref{Switches for gnatmake}).
17152 @item --RTS=@var{rts-path}
17153 @cindex @option{--RTS} (@code{gnatls})
17154 Specifies the default location of the runtime library. Same meaning as the
17155 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
17157 @item ^-v^/OUTPUT=VERBOSE^
17158 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
17159 Verbose mode. Output the complete source, object and project paths. Do not use
17160 the default column layout but instead use long format giving as much as
17161 information possible on each requested units, including special
17162 characteristics such as:
17165 @item Preelaborable
17166 The unit is preelaborable in the Ada 95 sense.
17169 No elaboration code has been produced by the compiler for this unit.
17172 The unit is pure in the Ada 95 sense.
17174 @item Elaborate_Body
17175 The unit contains a pragma Elaborate_Body.
17178 The unit contains a pragma Remote_Types.
17180 @item Shared_Passive
17181 The unit contains a pragma Shared_Passive.
17184 This unit is part of the predefined environment and cannot be modified
17187 @item Remote_Call_Interface
17188 The unit contains a pragma Remote_Call_Interface.
17194 @node Examples of gnatls Usage
17195 @section Example of @code{gnatls} Usage
17199 Example of using the verbose switch. Note how the source and
17200 object paths are affected by the -I switch.
17203 $ gnatls -v -I.. demo1.o
17205 GNATLS 5.03w (20041123-34)
17206 Copyright 1997-2004 Free Software Foundation, Inc.
17208 Source Search Path:
17209 <Current_Directory>
17211 /home/comar/local/adainclude/
17213 Object Search Path:
17214 <Current_Directory>
17216 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
17218 Project Search Path:
17219 <Current_Directory>
17220 /home/comar/local/lib/gnat/
17225 Kind => subprogram body
17226 Flags => No_Elab_Code
17227 Source => demo1.adb modified
17231 The following is an example of use of the dependency list.
17232 Note the use of the -s switch
17233 which gives a straight list of source files. This can be useful for
17234 building specialized scripts.
17237 $ gnatls -d demo2.o
17238 ./demo2.o demo2 OK demo2.adb
17244 $ gnatls -d -s -a demo1.o
17246 /home/comar/local/adainclude/ada.ads
17247 /home/comar/local/adainclude/a-finali.ads
17248 /home/comar/local/adainclude/a-filico.ads
17249 /home/comar/local/adainclude/a-stream.ads
17250 /home/comar/local/adainclude/a-tags.ads
17253 /home/comar/local/adainclude/gnat.ads
17254 /home/comar/local/adainclude/g-io.ads
17256 /home/comar/local/adainclude/system.ads
17257 /home/comar/local/adainclude/s-exctab.ads
17258 /home/comar/local/adainclude/s-finimp.ads
17259 /home/comar/local/adainclude/s-finroo.ads
17260 /home/comar/local/adainclude/s-secsta.ads
17261 /home/comar/local/adainclude/s-stalib.ads
17262 /home/comar/local/adainclude/s-stoele.ads
17263 /home/comar/local/adainclude/s-stratt.ads
17264 /home/comar/local/adainclude/s-tasoli.ads
17265 /home/comar/local/adainclude/s-unstyp.ads
17266 /home/comar/local/adainclude/unchconv.ads
17272 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
17274 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
17275 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
17276 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
17277 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
17278 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
17282 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
17283 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
17285 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
17286 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
17287 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
17288 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
17289 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
17290 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
17291 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
17292 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
17293 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
17294 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
17295 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
17299 @node Cleaning Up Using gnatclean
17300 @chapter Cleaning Up Using @code{gnatclean}
17302 @cindex Cleaning tool
17305 @code{gnatclean} is a tool that allows the deletion of files produced by the
17306 compiler, binder and linker, including ALI files, object files, tree files,
17307 expanded source files, library files, interface copy source files, binder
17308 generated files and executable files.
17311 * Running gnatclean::
17312 * Switches for gnatclean::
17313 @c * Examples of gnatclean Usage::
17316 @node Running gnatclean
17317 @section Running @code{gnatclean}
17320 The @code{gnatclean} command has the form:
17323 $ gnatclean switches @var{names}
17327 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
17328 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
17329 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
17332 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17333 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
17334 the linker. In informative-only mode, specified by switch
17335 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
17336 normal mode is listed, but no file is actually deleted.
17338 @node Switches for gnatclean
17339 @section Switches for @code{gnatclean}
17342 @code{gnatclean} recognizes the following switches:
17346 @item ^-c^/COMPILER_FILES_ONLY^
17347 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
17348 Only attempt to delete the files produced by the compiler, not those produced
17349 by the binder or the linker. The files that are not to be deleted are library
17350 files, interface copy files, binder generated files and executable files.
17352 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
17353 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
17354 Indicate that ALI and object files should normally be found in directory
17357 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
17358 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
17359 When using project files, if some errors or warnings are detected during
17360 parsing and verbose mode is not in effect (no use of switch
17361 ^-v^/VERBOSE^), then error lines start with the full path name of the project
17362 file, rather than its simple file name.
17365 @cindex @option{^-h^/HELP^} (@code{gnatclean})
17366 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
17368 @item ^-n^/NODELETE^
17369 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
17370 Informative-only mode. Do not delete any files. Output the list of the files
17371 that would have been deleted if this switch was not specified.
17373 @item ^-P^/PROJECT_FILE=^@var{project}
17374 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
17375 Use project file @var{project}. Only one such switch can be used.
17376 When cleaning a project file, the files produced by the compilation of the
17377 immediate sources or inherited sources of the project files are to be
17378 deleted. This is not depending on the presence or not of executable names
17379 on the command line.
17382 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
17383 Quiet output. If there are no errors, do not output anything, except in
17384 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
17385 (switch ^-n^/NODELETE^).
17387 @item ^-r^/RECURSIVE^
17388 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
17389 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
17390 clean all imported and extended project files, recursively. If this switch
17391 is not specified, only the files related to the main project file are to be
17392 deleted. This switch has no effect if no project file is specified.
17394 @item ^-v^/VERBOSE^
17395 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
17398 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
17399 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
17400 Indicates the verbosity of the parsing of GNAT project files.
17401 @xref{Switches Related to Project Files}.
17403 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
17404 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
17405 Indicates that external variable @var{name} has the value @var{value}.
17406 The Project Manager will use this value for occurrences of
17407 @code{external(name)} when parsing the project file.
17408 @xref{Switches Related to Project Files}.
17410 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17411 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
17412 When searching for ALI and object files, look in directory
17415 @item ^-I^/SEARCH=^@var{dir}
17416 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
17417 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
17419 @item ^-I-^/NOCURRENT_DIRECTORY^
17420 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
17421 @cindex Source files, suppressing search
17422 Do not look for ALI or object files in the directory
17423 where @code{gnatclean} was invoked.
17427 @c @node Examples of gnatclean Usage
17428 @c @section Examples of @code{gnatclean} Usage
17431 @node GNAT and Libraries
17432 @chapter GNAT and Libraries
17433 @cindex Library, building, installing, using
17436 This chapter describes how to build and use libraries with GNAT, and also shows
17437 how to recompile the GNAT run-time library. You should be familiar with the
17438 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
17442 * Introduction to Libraries in GNAT::
17443 * General Ada Libraries::
17444 * Stand-alone Ada Libraries::
17445 * Rebuilding the GNAT Run-Time Library::
17448 @node Introduction to Libraries in GNAT
17449 @section Introduction to Libraries in GNAT
17452 A library is, conceptually, a collection of objects which does not have its
17453 own main thread of execution, but rather provides certain services to the
17454 applications that use it. A library can be either statically linked with the
17455 application, in which case its code is directly included in the application,
17456 or, on platforms that support it, be dynamically linked, in which case
17457 its code is shared by all applications making use of this library.
17459 GNAT supports both types of libraries.
17460 In the static case, the compiled code can be provided in different ways. The
17461 simplest approach is to provide directly the set of objects resulting from
17462 compilation of the library source files. Alternatively, you can group the
17463 objects into an archive using whatever commands are provided by the operating
17464 system. For the latter case, the objects are grouped into a shared library.
17466 In the GNAT environment, a library has three types of components:
17472 @xref{The Ada Library Information Files}.
17474 Object files, an archive or a shared library.
17478 A GNAT library may expose all its source files, which is useful for
17479 documentation purposes. Alternatively, it may expose only the units needed by
17480 an external user to make use of the library. That is to say, the specs
17481 reflecting the library services along with all the units needed to compile
17482 those specs, which can include generic bodies or any body implementing an
17483 inlined routine. In the case of @emph{stand-alone libraries} those exposed
17484 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
17486 All compilation units comprising an application, including those in a library,
17487 need to be elaborated in an order partially defined by Ada's semantics. GNAT
17488 computes the elaboration order from the @file{ALI} files and this is why they
17489 constitute a mandatory part of GNAT libraries. Except in the case of
17490 @emph{stand-alone libraries}, where a specific library elaboration routine is
17491 produced independently of the application(s) using the library.
17493 @node General Ada Libraries
17494 @section General Ada Libraries
17497 * Building a library::
17498 * Installing a library::
17499 * Using a library::
17502 @node Building a library
17503 @subsection Building a library
17506 The easiest way to build a library is to use the Project Manager,
17507 which supports a special type of project called a @emph{Library Project}
17508 (@pxref{Library Projects}).
17510 A project is considered a library project, when two project-level attributes
17511 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
17512 control different aspects of library configuration, additional optional
17513 project-level attributes can be specified:
17516 This attribute controls whether the library is to be static or dynamic
17518 @item Library_Version
17519 This attribute specifies the library version; this value is used
17520 during dynamic linking of shared libraries to determine if the currently
17521 installed versions of the binaries are compatible.
17523 @item Library_Options
17525 These attributes specify additional low-level options to be used during
17526 library generation, and redefine the actual application used to generate
17531 The GNAT Project Manager takes full care of the library maintenance task,
17532 including recompilation of the source files for which objects do not exist
17533 or are not up to date, assembly of the library archive, and installation of
17534 the library (i.e., copying associated source, object and @file{ALI} files
17535 to the specified location).
17537 Here is a simple library project file:
17538 @smallexample @c ada
17540 for Source_Dirs use ("src1", "src2");
17541 for Object_Dir use "obj";
17542 for Library_Name use "mylib";
17543 for Library_Dir use "lib";
17544 for Library_Kind use "dynamic";
17549 and the compilation command to build and install the library:
17551 @smallexample @c ada
17552 $ gnatmake -Pmy_lib
17556 It is not entirely trivial to perform manually all the steps required to
17557 produce a library. We recommend that you use the GNAT Project Manager
17558 for this task. In special cases where this is not desired, the necessary
17559 steps are discussed below.
17561 There are various possibilities for compiling the units that make up the
17562 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
17563 with a conventional script. For simple libraries, it is also possible to create
17564 a dummy main program which depends upon all the packages that comprise the
17565 interface of the library. This dummy main program can then be given to
17566 @command{gnatmake}, which will ensure that all necessary objects are built.
17568 After this task is accomplished, you should follow the standard procedure
17569 of the underlying operating system to produce the static or shared library.
17571 Here is an example of such a dummy program:
17572 @smallexample @c ada
17574 with My_Lib.Service1;
17575 with My_Lib.Service2;
17576 with My_Lib.Service3;
17577 procedure My_Lib_Dummy is
17585 Here are the generic commands that will build an archive or a shared library.
17588 # compiling the library
17589 $ gnatmake -c my_lib_dummy.adb
17591 # we don't need the dummy object itself
17592 $ rm my_lib_dummy.o my_lib_dummy.ali
17594 # create an archive with the remaining objects
17595 $ ar rc libmy_lib.a *.o
17596 # some systems may require "ranlib" to be run as well
17598 # or create a shared library
17599 $ gcc -shared -o libmy_lib.so *.o
17600 # some systems may require the code to have been compiled with -fPIC
17602 # remove the object files that are now in the library
17605 # Make the ALI files read-only so that gnatmake will not try to
17606 # regenerate the objects that are in the library
17611 Please note that the library must have a name of the form @file{libxxx.a} or
17612 @file{libxxx.so} (or @file{libxxx.dll} on Windows) in order to be accessed by
17613 the directive @option{-lxxx} at link time.
17615 @node Installing a library
17616 @subsection Installing a library
17617 @cindex @code{ADA_PROJECT_PATH}
17620 If you use project files, library installation is part of the library build
17621 process. Thus no further action is needed in order to make use of the
17622 libraries that are built as part of the general application build. A usable
17623 version of the library is installed in the directory specified by the
17624 @code{Library_Dir} attribute of the library project file.
17626 You may want to install a library in a context different from where the library
17627 is built. This situation arises with third party suppliers, who may want
17628 to distribute a library in binary form where the user is not expected to be
17629 able to recompile the library. The simplest option in this case is to provide
17630 a project file slightly different from the one used to build the library, by
17631 using the @code{externally_built} attribute. For instance, the project
17632 file used to build the library in the previous section can be changed into the
17633 following one when the library is installed:
17635 @smallexample @c projectfile
17637 for Source_Dirs use ("src1", "src2");
17638 for Library_Name use "mylib";
17639 for Library_Dir use "lib";
17640 for Library_Kind use "dynamic";
17641 for Externally_Built use "true";
17646 This project file assumes that the directories @file{src1},
17647 @file{src2}, and @file{lib} exist in
17648 the directory containing the project file. The @code{externally_built}
17649 attribute makes it clear to the GNAT builder that it should not attempt to
17650 recompile any of the units from this library. It allows the library provider to
17651 restrict the source set to the minimum necessary for clients to make use of the
17652 library as described in the first section of this chapter. It is the
17653 responsibility of the library provider to install the necessary sources, ALI
17654 files and libraries in the directories mentioned in the project file. For
17655 convenience, the user's library project file should be installed in a location
17656 that will be searched automatically by the GNAT
17657 builder. These are the directories referenced in the @code{ADA_PROJECT_PATH}
17658 environment variable (@pxref{Importing Projects}), and also the default GNAT
17659 library location that can be queried with @command{gnatls -v} and is usually of
17660 the form $gnat_install_root/lib/gnat.
17662 When project files are not an option, it is also possible, but not recommended,
17663 to install the library so that the sources needed to use the library are on the
17664 Ada source path and the ALI files & libraries be on the Ada Object path (see
17665 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
17666 administrator can place general-purpose libraries in the default compiler
17667 paths, by specifying the libraries' location in the configuration files
17668 @file{ada_source_path} and @file{ada_object_path}. These configuration files
17669 must be located in the GNAT installation tree at the same place as the gcc spec
17670 file. The location of the gcc spec file can be determined as follows:
17676 The configuration files mentioned above have a simple format: each line
17677 must contain one unique directory name.
17678 Those names are added to the corresponding path
17679 in their order of appearance in the file. The names can be either absolute
17680 or relative; in the latter case, they are relative to where theses files
17683 The files @file{ada_source_path} and @file{ada_object_path} might not be
17685 GNAT installation, in which case, GNAT will look for its run-time library in
17686 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17687 objects and @file{ALI} files). When the files exist, the compiler does not
17688 look in @file{adainclude} and @file{adalib}, and thus the
17689 @file{ada_source_path} file
17690 must contain the location for the GNAT run-time sources (which can simply
17691 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17692 contain the location for the GNAT run-time objects (which can simply
17695 You can also specify a new default path to the run-time library at compilation
17696 time with the switch @option{--RTS=rts-path}. You can thus choose / change
17697 the run-time library you want your program to be compiled with. This switch is
17698 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17699 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17701 It is possible to install a library before or after the standard GNAT
17702 library, by reordering the lines in the configuration files. In general, a
17703 library must be installed before the GNAT library if it redefines
17706 @node Using a library
17707 @subsection Using a library
17709 @noindent Once again, the project facility greatly simplifies the use of
17710 libraries. In this context, using a library is just a matter of adding a
17711 @code{with} clause in the user project. For instance, to make use of the
17712 library @code{My_Lib} shown in examples in earlier sections, you can
17715 @smallexample @c projectfile
17722 Even if you have a third-party, non-Ada library, you can still use GNAT's
17723 Project Manager facility to provide a wrapper for it. For example, the
17724 following project, when @code{with}ed by your main project, will link with the
17725 third-party library @file{liba.a}:
17727 @smallexample @c projectfile
17730 for Externally_Built use "true";
17731 for Library_Dir use "lib";
17732 for Library_Name use "a";
17733 for Library_Kind use "static";
17737 This is an alternative to the use of @code{pragma Linker_Options}. It is
17738 especially interesting in the context of systems with several interdependent
17739 static libraries where finding a proper linker order is not easy and best be
17740 left to the tools having visibility over project dependence information.
17743 In order to use an Ada library manually, you need to make sure that this
17744 library is on both your source and object path
17745 (see @ref{Search Paths and the Run-Time Library (RTL)}
17746 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17747 in an archive or a shared library, you need to specify the desired
17748 library at link time.
17750 For example, you can use the library @file{mylib} installed in
17751 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17754 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17759 This can be expressed more simply:
17764 when the following conditions are met:
17767 @file{/dir/my_lib_src} has been added by the user to the environment
17768 variable @code{ADA_INCLUDE_PATH}, or by the administrator to the file
17769 @file{ada_source_path}
17771 @file{/dir/my_lib_obj} has been added by the user to the environment
17772 variable @code{ADA_OBJECTS_PATH}, or by the administrator to the file
17773 @file{ada_object_path}
17775 a pragma @code{Linker_Options} has been added to one of the sources.
17778 @smallexample @c ada
17779 pragma Linker_Options ("-lmy_lib");
17783 @node Stand-alone Ada Libraries
17784 @section Stand-alone Ada Libraries
17785 @cindex Stand-alone library, building, using
17788 * Introduction to Stand-alone Libraries::
17789 * Building a Stand-alone Library::
17790 * Creating a Stand-alone Library to be used in a non-Ada context::
17791 * Restrictions in Stand-alone Libraries::
17794 @node Introduction to Stand-alone Libraries
17795 @subsection Introduction to Stand-alone Libraries
17798 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
17800 elaborate the Ada units that are included in the library. In contrast with
17801 an ordinary library, which consists of all sources, objects and @file{ALI}
17803 library, a SAL may specify a restricted subset of compilation units
17804 to serve as a library interface. In this case, the fully
17805 self-sufficient set of files will normally consist of an objects
17806 archive, the sources of interface units' specs, and the @file{ALI}
17807 files of interface units.
17808 If an interface spec contains a generic unit or an inlined subprogram,
17810 source must also be provided; if the units that must be provided in the source
17811 form depend on other units, the source and @file{ALI} files of those must
17814 The main purpose of a SAL is to minimize the recompilation overhead of client
17815 applications when a new version of the library is installed. Specifically,
17816 if the interface sources have not changed, client applications do not need to
17817 be recompiled. If, furthermore, a SAL is provided in the shared form and its
17818 version, controlled by @code{Library_Version} attribute, is not changed,
17819 then the clients do not need to be relinked.
17821 SALs also allow the library providers to minimize the amount of library source
17822 text exposed to the clients. Such ``information hiding'' might be useful or
17823 necessary for various reasons.
17825 Stand-alone libraries are also well suited to be used in an executable whose
17826 main routine is not written in Ada.
17828 @node Building a Stand-alone Library
17829 @subsection Building a Stand-alone Library
17832 GNAT's Project facility provides a simple way of building and installing
17833 stand-alone libraries; see @ref{Stand-alone Library Projects}.
17834 To be a Stand-alone Library Project, in addition to the two attributes
17835 that make a project a Library Project (@code{Library_Name} and
17836 @code{Library_Dir}; see @ref{Library Projects}), the attribute
17837 @code{Library_Interface} must be defined. For example:
17839 @smallexample @c projectfile
17841 for Library_Dir use "lib_dir";
17842 for Library_Name use "dummy";
17843 for Library_Interface use ("int1", "int1.child");
17848 Attribute @code{Library_Interface} has a non-empty string list value,
17849 each string in the list designating a unit contained in an immediate source
17850 of the project file.
17852 When a Stand-alone Library is built, first the binder is invoked to build
17853 a package whose name depends on the library name
17854 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
17855 This binder-generated package includes initialization and
17856 finalization procedures whose
17857 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
17859 above). The object corresponding to this package is included in the library.
17861 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
17862 calling of these procedures if a static SAL is built, or if a shared SAL
17864 with the project-level attribute @code{Library_Auto_Init} set to
17867 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
17868 (those that are listed in attribute @code{Library_Interface}) are copied to
17869 the Library Directory. As a consequence, only the Interface Units may be
17870 imported from Ada units outside of the library. If other units are imported,
17871 the binding phase will fail.
17873 The attribute @code{Library_Src_Dir} may be specified for a
17874 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
17875 single string value. Its value must be the path (absolute or relative to the
17876 project directory) of an existing directory. This directory cannot be the
17877 object directory or one of the source directories, but it can be the same as
17878 the library directory. The sources of the Interface
17879 Units of the library that are needed by an Ada client of the library will be
17880 copied to the designated directory, called the Interface Copy directory.
17881 These sources include the specs of the Interface Units, but they may also
17882 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
17883 are used, or when there is a generic unit in the spec. Before the sources
17884 are copied to the Interface Copy directory, an attempt is made to delete all
17885 files in the Interface Copy directory.
17887 Building stand-alone libraries by hand is somewhat tedious, but for those
17888 occasions when it is necessary here are the steps that you need to perform:
17891 Compile all library sources.
17894 Invoke the binder with the switch @option{-n} (No Ada main program),
17895 with all the @file{ALI} files of the interfaces, and
17896 with the switch @option{-L} to give specific names to the @code{init}
17897 and @code{final} procedures. For example:
17899 gnatbind -n int1.ali int2.ali -Lsal1
17903 Compile the binder generated file:
17909 Link the dynamic library with all the necessary object files,
17910 indicating to the linker the names of the @code{init} (and possibly
17911 @code{final}) procedures for automatic initialization (and finalization).
17912 The built library should be placed in a directory different from
17913 the object directory.
17916 Copy the @code{ALI} files of the interface to the library directory,
17917 add in this copy an indication that it is an interface to a SAL
17918 (i.e. add a word @option{SL} on the line in the @file{ALI} file that starts
17919 with letter ``P'') and make the modified copy of the @file{ALI} file
17924 Using SALs is not different from using other libraries
17925 (see @ref{Using a library}).
17927 @node Creating a Stand-alone Library to be used in a non-Ada context
17928 @subsection Creating a Stand-alone Library to be used in a non-Ada context
17931 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
17934 The only extra step required is to ensure that library interface subprograms
17935 are compatible with the main program, by means of @code{pragma Export}
17936 or @code{pragma Convention}.
17938 Here is an example of simple library interface for use with C main program:
17940 @smallexample @c ada
17941 package Interface is
17943 procedure Do_Something;
17944 pragma Export (C, Do_Something, "do_something");
17946 procedure Do_Something_Else;
17947 pragma Export (C, Do_Something_Else, "do_something_else");
17953 On the foreign language side, you must provide a ``foreign'' view of the
17954 library interface; remember that it should contain elaboration routines in
17955 addition to interface subprograms.
17957 The example below shows the content of @code{mylib_interface.h} (note
17958 that there is no rule for the naming of this file, any name can be used)
17960 /* the library elaboration procedure */
17961 extern void mylibinit (void);
17963 /* the library finalization procedure */
17964 extern void mylibfinal (void);
17966 /* the interface exported by the library */
17967 extern void do_something (void);
17968 extern void do_something_else (void);
17972 Libraries built as explained above can be used from any program, provided
17973 that the elaboration procedures (named @code{mylibinit} in the previous
17974 example) are called before the library services are used. Any number of
17975 libraries can be used simultaneously, as long as the elaboration
17976 procedure of each library is called.
17978 Below is an example of a C program that uses the @code{mylib} library.
17981 #include "mylib_interface.h"
17986 /* First, elaborate the library before using it */
17989 /* Main program, using the library exported entities */
17991 do_something_else ();
17993 /* Library finalization at the end of the program */
18000 Note that invoking any library finalization procedure generated by
18001 @code{gnatbind} shuts down the Ada run-time environment.
18003 finalization of all Ada libraries must be performed at the end of the program.
18004 No call to these libraries or to the Ada run-time library should be made
18005 after the finalization phase.
18007 @node Restrictions in Stand-alone Libraries
18008 @subsection Restrictions in Stand-alone Libraries
18011 The pragmas listed below should be used with caution inside libraries,
18012 as they can create incompatibilities with other Ada libraries:
18014 @item pragma @code{Locking_Policy}
18015 @item pragma @code{Queuing_Policy}
18016 @item pragma @code{Task_Dispatching_Policy}
18017 @item pragma @code{Unreserve_All_Interrupts}
18021 When using a library that contains such pragmas, the user must make sure
18022 that all libraries use the same pragmas with the same values. Otherwise,
18023 @code{Program_Error} will
18024 be raised during the elaboration of the conflicting
18025 libraries. The usage of these pragmas and its consequences for the user
18026 should therefore be well documented.
18028 Similarly, the traceback in the exception occurrence mechanism should be
18029 enabled or disabled in a consistent manner across all libraries.
18030 Otherwise, Program_Error will be raised during the elaboration of the
18031 conflicting libraries.
18033 If the @code{Version} or @code{Body_Version}
18034 attributes are used inside a library, then you need to
18035 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
18036 libraries, so that version identifiers can be properly computed.
18037 In practice these attributes are rarely used, so this is unlikely
18038 to be a consideration.
18040 @node Rebuilding the GNAT Run-Time Library
18041 @section Rebuilding the GNAT Run-Time Library
18042 @cindex GNAT Run-Time Library, rebuilding
18043 @cindex Building the GNAT Run-Time Library
18044 @cindex Rebuilding the GNAT Run-Time Library
18045 @cindex Run-Time Library, rebuilding
18048 It may be useful to recompile the GNAT library in various contexts, the
18049 most important one being the use of partition-wide configuration pragmas
18050 such as @code{Normalize_Scalars}. A special Makefile called
18051 @code{Makefile.adalib} is provided to that effect and can be found in
18052 the directory containing the GNAT library. The location of this
18053 directory depends on the way the GNAT environment has been installed and can
18054 be determined by means of the command:
18061 The last entry in the object search path usually contains the
18062 gnat library. This Makefile contains its own documentation and in
18063 particular the set of instructions needed to rebuild a new library and
18066 @node Using the GNU make Utility
18067 @chapter Using the GNU @code{make} Utility
18071 This chapter offers some examples of makefiles that solve specific
18072 problems. It does not explain how to write a makefile (see the GNU make
18073 documentation), nor does it try to replace the @command{gnatmake} utility
18074 (@pxref{The GNAT Make Program gnatmake}).
18076 All the examples in this section are specific to the GNU version of
18077 make. Although @code{make} is a standard utility, and the basic language
18078 is the same, these examples use some advanced features found only in
18082 * Using gnatmake in a Makefile::
18083 * Automatically Creating a List of Directories::
18084 * Generating the Command Line Switches::
18085 * Overcoming Command Line Length Limits::
18088 @node Using gnatmake in a Makefile
18089 @section Using gnatmake in a Makefile
18094 Complex project organizations can be handled in a very powerful way by
18095 using GNU make combined with gnatmake. For instance, here is a Makefile
18096 which allows you to build each subsystem of a big project into a separate
18097 shared library. Such a makefile allows you to significantly reduce the link
18098 time of very big applications while maintaining full coherence at
18099 each step of the build process.
18101 The list of dependencies are handled automatically by
18102 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
18103 the appropriate directories.
18105 Note that you should also read the example on how to automatically
18106 create the list of directories
18107 (@pxref{Automatically Creating a List of Directories})
18108 which might help you in case your project has a lot of subdirectories.
18113 @font@heightrm=cmr8
18116 ## This Makefile is intended to be used with the following directory
18118 ## - The sources are split into a series of csc (computer software components)
18119 ## Each of these csc is put in its own directory.
18120 ## Their name are referenced by the directory names.
18121 ## They will be compiled into shared library (although this would also work
18122 ## with static libraries
18123 ## - The main program (and possibly other packages that do not belong to any
18124 ## csc is put in the top level directory (where the Makefile is).
18125 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
18126 ## \_ second_csc (sources) __ lib (will contain the library)
18128 ## Although this Makefile is build for shared library, it is easy to modify
18129 ## to build partial link objects instead (modify the lines with -shared and
18132 ## With this makefile, you can change any file in the system or add any new
18133 ## file, and everything will be recompiled correctly (only the relevant shared
18134 ## objects will be recompiled, and the main program will be re-linked).
18136 # The list of computer software component for your project. This might be
18137 # generated automatically.
18140 # Name of the main program (no extension)
18143 # If we need to build objects with -fPIC, uncomment the following line
18146 # The following variable should give the directory containing libgnat.so
18147 # You can get this directory through 'gnatls -v'. This is usually the last
18148 # directory in the Object_Path.
18151 # The directories for the libraries
18152 # (This macro expands the list of CSC to the list of shared libraries, you
18153 # could simply use the expanded form :
18154 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
18155 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
18157 $@{MAIN@}: objects $@{LIB_DIR@}
18158 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
18159 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
18162 # recompile the sources
18163 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
18165 # Note: In a future version of GNAT, the following commands will be simplified
18166 # by a new tool, gnatmlib
18168 mkdir -p $@{dir $@@ @}
18169 cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
18170 cd $@{dir $@@ @}; cp -f ../*.ali .
18172 # The dependencies for the modules
18173 # Note that we have to force the expansion of *.o, since in some cases
18174 # make won't be able to do it itself.
18175 aa/lib/libaa.so: $@{wildcard aa/*.o@}
18176 bb/lib/libbb.so: $@{wildcard bb/*.o@}
18177 cc/lib/libcc.so: $@{wildcard cc/*.o@}
18179 # Make sure all of the shared libraries are in the path before starting the
18182 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
18185 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
18186 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
18187 $@{RM@} $@{CSC_LIST:%=%/*.o@}
18188 $@{RM@} *.o *.ali $@{MAIN@}
18191 @node Automatically Creating a List of Directories
18192 @section Automatically Creating a List of Directories
18195 In most makefiles, you will have to specify a list of directories, and
18196 store it in a variable. For small projects, it is often easier to
18197 specify each of them by hand, since you then have full control over what
18198 is the proper order for these directories, which ones should be
18201 However, in larger projects, which might involve hundreds of
18202 subdirectories, it might be more convenient to generate this list
18205 The example below presents two methods. The first one, although less
18206 general, gives you more control over the list. It involves wildcard
18207 characters, that are automatically expanded by @code{make}. Its
18208 shortcoming is that you need to explicitly specify some of the
18209 organization of your project, such as for instance the directory tree
18210 depth, whether some directories are found in a separate tree,...
18212 The second method is the most general one. It requires an external
18213 program, called @code{find}, which is standard on all Unix systems. All
18214 the directories found under a given root directory will be added to the
18220 @font@heightrm=cmr8
18223 # The examples below are based on the following directory hierarchy:
18224 # All the directories can contain any number of files
18225 # ROOT_DIRECTORY -> a -> aa -> aaa
18228 # -> b -> ba -> baa
18231 # This Makefile creates a variable called DIRS, that can be reused any time
18232 # you need this list (see the other examples in this section)
18234 # The root of your project's directory hierarchy
18238 # First method: specify explicitly the list of directories
18239 # This allows you to specify any subset of all the directories you need.
18242 DIRS := a/aa/ a/ab/ b/ba/
18245 # Second method: use wildcards
18246 # Note that the argument(s) to wildcard below should end with a '/'.
18247 # Since wildcards also return file names, we have to filter them out
18248 # to avoid duplicate directory names.
18249 # We thus use make's @code{dir} and @code{sort} functions.
18250 # It sets DIRs to the following value (note that the directories aaa and baa
18251 # are not given, unless you change the arguments to wildcard).
18252 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
18255 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
18256 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
18259 # Third method: use an external program
18260 # This command is much faster if run on local disks, avoiding NFS slowdowns.
18261 # This is the most complete command: it sets DIRs to the following value:
18262 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
18265 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
18269 @node Generating the Command Line Switches
18270 @section Generating the Command Line Switches
18273 Once you have created the list of directories as explained in the
18274 previous section (@pxref{Automatically Creating a List of Directories}),
18275 you can easily generate the command line arguments to pass to gnatmake.
18277 For the sake of completeness, this example assumes that the source path
18278 is not the same as the object path, and that you have two separate lists
18282 # see "Automatically creating a list of directories" to create
18287 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
18288 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
18291 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
18294 @node Overcoming Command Line Length Limits
18295 @section Overcoming Command Line Length Limits
18298 One problem that might be encountered on big projects is that many
18299 operating systems limit the length of the command line. It is thus hard to give
18300 gnatmake the list of source and object directories.
18302 This example shows how you can set up environment variables, which will
18303 make @command{gnatmake} behave exactly as if the directories had been
18304 specified on the command line, but have a much higher length limit (or
18305 even none on most systems).
18307 It assumes that you have created a list of directories in your Makefile,
18308 using one of the methods presented in
18309 @ref{Automatically Creating a List of Directories}.
18310 For the sake of completeness, we assume that the object
18311 path (where the ALI files are found) is different from the sources patch.
18313 Note a small trick in the Makefile below: for efficiency reasons, we
18314 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
18315 expanded immediately by @code{make}. This way we overcome the standard
18316 make behavior which is to expand the variables only when they are
18319 On Windows, if you are using the standard Windows command shell, you must
18320 replace colons with semicolons in the assignments to these variables.
18325 @font@heightrm=cmr8
18328 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
18329 # This is the same thing as putting the -I arguments on the command line.
18330 # (the equivalent of using -aI on the command line would be to define
18331 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
18332 # You can of course have different values for these variables.
18334 # Note also that we need to keep the previous values of these variables, since
18335 # they might have been set before running 'make' to specify where the GNAT
18336 # library is installed.
18338 # see "Automatically creating a list of directories" to create these
18344 space:=$@{empty@} $@{empty@}
18345 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
18346 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
18347 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
18348 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
18349 export ADA_INCLUDE_PATH
18350 export ADA_OBJECT_PATH
18357 @node Memory Management Issues
18358 @chapter Memory Management Issues
18361 This chapter describes some useful memory pools provided in the GNAT library
18362 and in particular the GNAT Debug Pool facility, which can be used to detect
18363 incorrect uses of access values (including ``dangling references'').
18365 It also describes the @command{gnatmem} tool, which can be used to track down
18370 * Some Useful Memory Pools::
18371 * The GNAT Debug Pool Facility::
18373 * The gnatmem Tool::
18377 @node Some Useful Memory Pools
18378 @section Some Useful Memory Pools
18379 @findex Memory Pool
18380 @cindex storage, pool
18383 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
18384 storage pool. Allocations use the standard system call @code{malloc} while
18385 deallocations use the standard system call @code{free}. No reclamation is
18386 performed when the pool goes out of scope. For performance reasons, the
18387 standard default Ada allocators/deallocators do not use any explicit storage
18388 pools but if they did, they could use this storage pool without any change in
18389 behavior. That is why this storage pool is used when the user
18390 manages to make the default implicit allocator explicit as in this example:
18391 @smallexample @c ada
18392 type T1 is access Something;
18393 -- no Storage pool is defined for T2
18394 type T2 is access Something_Else;
18395 for T2'Storage_Pool use T1'Storage_Pool;
18396 -- the above is equivalent to
18397 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
18401 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
18402 pool. The allocation strategy is similar to @code{Pool_Local}'s
18403 except that the all
18404 storage allocated with this pool is reclaimed when the pool object goes out of
18405 scope. This pool provides a explicit mechanism similar to the implicit one
18406 provided by several Ada 83 compilers for allocations performed through a local
18407 access type and whose purpose was to reclaim memory when exiting the
18408 scope of a given local access. As an example, the following program does not
18409 leak memory even though it does not perform explicit deallocation:
18411 @smallexample @c ada
18412 with System.Pool_Local;
18413 procedure Pooloc1 is
18414 procedure Internal is
18415 type A is access Integer;
18416 X : System.Pool_Local.Unbounded_Reclaim_Pool;
18417 for A'Storage_Pool use X;
18420 for I in 1 .. 50 loop
18425 for I in 1 .. 100 loop
18432 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
18433 @code{Storage_Size} is specified for an access type.
18434 The whole storage for the pool is
18435 allocated at once, usually on the stack at the point where the access type is
18436 elaborated. It is automatically reclaimed when exiting the scope where the
18437 access type is defined. This package is not intended to be used directly by the
18438 user and it is implicitly used for each such declaration:
18440 @smallexample @c ada
18441 type T1 is access Something;
18442 for T1'Storage_Size use 10_000;
18445 @node The GNAT Debug Pool Facility
18446 @section The GNAT Debug Pool Facility
18448 @cindex storage, pool, memory corruption
18451 The use of unchecked deallocation and unchecked conversion can easily
18452 lead to incorrect memory references. The problems generated by such
18453 references are usually difficult to tackle because the symptoms can be
18454 very remote from the origin of the problem. In such cases, it is
18455 very helpful to detect the problem as early as possible. This is the
18456 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
18458 In order to use the GNAT specific debugging pool, the user must
18459 associate a debug pool object with each of the access types that may be
18460 related to suspected memory problems. See Ada Reference Manual 13.11.
18461 @smallexample @c ada
18462 type Ptr is access Some_Type;
18463 Pool : GNAT.Debug_Pools.Debug_Pool;
18464 for Ptr'Storage_Pool use Pool;
18468 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
18469 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
18470 allow the user to redefine allocation and deallocation strategies. They
18471 also provide a checkpoint for each dereference, through the use of
18472 the primitive operation @code{Dereference} which is implicitly called at
18473 each dereference of an access value.
18475 Once an access type has been associated with a debug pool, operations on
18476 values of the type may raise four distinct exceptions,
18477 which correspond to four potential kinds of memory corruption:
18480 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
18482 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
18484 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
18486 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
18490 For types associated with a Debug_Pool, dynamic allocation is performed using
18491 the standard GNAT allocation routine. References to all allocated chunks of
18492 memory are kept in an internal dictionary. Several deallocation strategies are
18493 provided, whereupon the user can choose to release the memory to the system,
18494 keep it allocated for further invalid access checks, or fill it with an easily
18495 recognizable pattern for debug sessions. The memory pattern is the old IBM
18496 hexadecimal convention: @code{16#DEADBEEF#}.
18498 See the documentation in the file g-debpoo.ads for more information on the
18499 various strategies.
18501 Upon each dereference, a check is made that the access value denotes a
18502 properly allocated memory location. Here is a complete example of use of
18503 @code{Debug_Pools}, that includes typical instances of memory corruption:
18504 @smallexample @c ada
18508 with Gnat.Io; use Gnat.Io;
18509 with Unchecked_Deallocation;
18510 with Unchecked_Conversion;
18511 with GNAT.Debug_Pools;
18512 with System.Storage_Elements;
18513 with Ada.Exceptions; use Ada.Exceptions;
18514 procedure Debug_Pool_Test is
18516 type T is access Integer;
18517 type U is access all T;
18519 P : GNAT.Debug_Pools.Debug_Pool;
18520 for T'Storage_Pool use P;
18522 procedure Free is new Unchecked_Deallocation (Integer, T);
18523 function UC is new Unchecked_Conversion (U, T);
18526 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
18536 Put_Line (Integer'Image(B.all));
18538 when E : others => Put_Line ("raised: " & Exception_Name (E));
18543 when E : others => Put_Line ("raised: " & Exception_Name (E));
18547 Put_Line (Integer'Image(B.all));
18549 when E : others => Put_Line ("raised: " & Exception_Name (E));
18554 when E : others => Put_Line ("raised: " & Exception_Name (E));
18557 end Debug_Pool_Test;
18561 The debug pool mechanism provides the following precise diagnostics on the
18562 execution of this erroneous program:
18565 Total allocated bytes : 0
18566 Total deallocated bytes : 0
18567 Current Water Mark: 0
18571 Total allocated bytes : 8
18572 Total deallocated bytes : 0
18573 Current Water Mark: 8
18576 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18577 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18578 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18579 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18581 Total allocated bytes : 8
18582 Total deallocated bytes : 4
18583 Current Water Mark: 4
18588 @node The gnatmem Tool
18589 @section The @command{gnatmem} Tool
18593 The @code{gnatmem} utility monitors dynamic allocation and
18594 deallocation activity in a program, and displays information about
18595 incorrect deallocations and possible sources of memory leaks.
18596 It provides three type of information:
18599 General information concerning memory management, such as the total
18600 number of allocations and deallocations, the amount of allocated
18601 memory and the high water mark, i.e. the largest amount of allocated
18602 memory in the course of program execution.
18605 Backtraces for all incorrect deallocations, that is to say deallocations
18606 which do not correspond to a valid allocation.
18609 Information on each allocation that is potentially the origin of a memory
18614 * Running gnatmem::
18615 * Switches for gnatmem::
18616 * Example of gnatmem Usage::
18619 @node Running gnatmem
18620 @subsection Running @code{gnatmem}
18623 @code{gnatmem} makes use of the output created by the special version of
18624 allocation and deallocation routines that record call information. This
18625 allows to obtain accurate dynamic memory usage history at a minimal cost to
18626 the execution speed. Note however, that @code{gnatmem} is not supported on
18627 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux x86,
18628 32-bit Solaris (sparc and x86) and Windows NT/2000/XP (x86).
18631 The @code{gnatmem} command has the form
18634 $ gnatmem [switches] user_program
18638 The program must have been linked with the instrumented version of the
18639 allocation and deallocation routines. This is done by linking with the
18640 @file{libgmem.a} library. For correct symbolic backtrace information,
18641 the user program should be compiled with debugging options
18642 (see @ref{Switches for gcc}). For example to build @file{my_program}:
18645 $ gnatmake -g my_program -largs -lgmem
18649 As library @file{libgmem.a} contains an alternate body for package
18650 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
18651 when an executable is linked with library @file{libgmem.a}. It is then not
18652 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
18655 When @file{my_program} is executed, the file @file{gmem.out} is produced.
18656 This file contains information about all allocations and deallocations
18657 performed by the program. It is produced by the instrumented allocations and
18658 deallocations routines and will be used by @code{gnatmem}.
18660 In order to produce symbolic backtrace information for allocations and
18661 deallocations performed by the GNAT run-time library, you need to use a
18662 version of that library that has been compiled with the @option{-g} switch
18663 (see @ref{Rebuilding the GNAT Run-Time Library}).
18665 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18666 examine. If the location of @file{gmem.out} file was not explicitly supplied by
18667 @code{-i} switch, gnatmem will assume that this file can be found in the
18668 current directory. For example, after you have executed @file{my_program},
18669 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18672 $ gnatmem my_program
18676 This will produce the output with the following format:
18678 *************** debut cc
18680 $ gnatmem my_program
18684 Total number of allocations : 45
18685 Total number of deallocations : 6
18686 Final Water Mark (non freed mem) : 11.29 Kilobytes
18687 High Water Mark : 11.40 Kilobytes
18692 Allocation Root # 2
18693 -------------------
18694 Number of non freed allocations : 11
18695 Final Water Mark (non freed mem) : 1.16 Kilobytes
18696 High Water Mark : 1.27 Kilobytes
18698 my_program.adb:23 my_program.alloc
18704 The first block of output gives general information. In this case, the
18705 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18706 Unchecked_Deallocation routine occurred.
18709 Subsequent paragraphs display information on all allocation roots.
18710 An allocation root is a specific point in the execution of the program
18711 that generates some dynamic allocation, such as a ``@code{@b{new}}''
18712 construct. This root is represented by an execution backtrace (or subprogram
18713 call stack). By default the backtrace depth for allocations roots is 1, so
18714 that a root corresponds exactly to a source location. The backtrace can
18715 be made deeper, to make the root more specific.
18717 @node Switches for gnatmem
18718 @subsection Switches for @code{gnatmem}
18721 @code{gnatmem} recognizes the following switches:
18726 @cindex @option{-q} (@code{gnatmem})
18727 Quiet. Gives the minimum output needed to identify the origin of the
18728 memory leaks. Omits statistical information.
18731 @cindex @var{N} (@code{gnatmem})
18732 N is an integer literal (usually between 1 and 10) which controls the
18733 depth of the backtraces defining allocation root. The default value for
18734 N is 1. The deeper the backtrace, the more precise the localization of
18735 the root. Note that the total number of roots can depend on this
18736 parameter. This parameter must be specified @emph{before} the name of the
18737 executable to be analyzed, to avoid ambiguity.
18740 @cindex @option{-b} (@code{gnatmem})
18741 This switch has the same effect as just depth parameter.
18743 @item -i @var{file}
18744 @cindex @option{-i} (@code{gnatmem})
18745 Do the @code{gnatmem} processing starting from @file{file}, rather than
18746 @file{gmem.out} in the current directory.
18749 @cindex @option{-m} (@code{gnatmem})
18750 This switch causes @code{gnatmem} to mask the allocation roots that have less
18751 than n leaks. The default value is 1. Specifying the value of 0 will allow to
18752 examine even the roots that didn't result in leaks.
18755 @cindex @option{-s} (@code{gnatmem})
18756 This switch causes @code{gnatmem} to sort the allocation roots according to the
18757 specified order of sort criteria, each identified by a single letter. The
18758 currently supported criteria are @code{n, h, w} standing respectively for
18759 number of unfreed allocations, high watermark, and final watermark
18760 corresponding to a specific root. The default order is @code{nwh}.
18764 @node Example of gnatmem Usage
18765 @subsection Example of @code{gnatmem} Usage
18768 The following example shows the use of @code{gnatmem}
18769 on a simple memory-leaking program.
18770 Suppose that we have the following Ada program:
18772 @smallexample @c ada
18775 with Unchecked_Deallocation;
18776 procedure Test_Gm is
18778 type T is array (1..1000) of Integer;
18779 type Ptr is access T;
18780 procedure Free is new Unchecked_Deallocation (T, Ptr);
18783 procedure My_Alloc is
18788 procedure My_DeAlloc is
18796 for I in 1 .. 5 loop
18797 for J in I .. 5 loop
18808 The program needs to be compiled with debugging option and linked with
18809 @code{gmem} library:
18812 $ gnatmake -g test_gm -largs -lgmem
18816 Then we execute the program as usual:
18823 Then @code{gnatmem} is invoked simply with
18829 which produces the following output (result may vary on different platforms):
18834 Total number of allocations : 18
18835 Total number of deallocations : 5
18836 Final Water Mark (non freed mem) : 53.00 Kilobytes
18837 High Water Mark : 56.90 Kilobytes
18839 Allocation Root # 1
18840 -------------------
18841 Number of non freed allocations : 11
18842 Final Water Mark (non freed mem) : 42.97 Kilobytes
18843 High Water Mark : 46.88 Kilobytes
18845 test_gm.adb:11 test_gm.my_alloc
18847 Allocation Root # 2
18848 -------------------
18849 Number of non freed allocations : 1
18850 Final Water Mark (non freed mem) : 10.02 Kilobytes
18851 High Water Mark : 10.02 Kilobytes
18853 s-secsta.adb:81 system.secondary_stack.ss_init
18855 Allocation Root # 3
18856 -------------------
18857 Number of non freed allocations : 1
18858 Final Water Mark (non freed mem) : 12 Bytes
18859 High Water Mark : 12 Bytes
18861 s-secsta.adb:181 system.secondary_stack.ss_init
18865 Note that the GNAT run time contains itself a certain number of
18866 allocations that have no corresponding deallocation,
18867 as shown here for root #2 and root
18868 #3. This is a normal behavior when the number of non freed allocations
18869 is one, it allocates dynamic data structures that the run time needs for
18870 the complete lifetime of the program. Note also that there is only one
18871 allocation root in the user program with a single line back trace:
18872 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
18873 program shows that 'My_Alloc' is called at 2 different points in the
18874 source (line 21 and line 24). If those two allocation roots need to be
18875 distinguished, the backtrace depth parameter can be used:
18878 $ gnatmem 3 test_gm
18882 which will give the following output:
18887 Total number of allocations : 18
18888 Total number of deallocations : 5
18889 Final Water Mark (non freed mem) : 53.00 Kilobytes
18890 High Water Mark : 56.90 Kilobytes
18892 Allocation Root # 1
18893 -------------------
18894 Number of non freed allocations : 10
18895 Final Water Mark (non freed mem) : 39.06 Kilobytes
18896 High Water Mark : 42.97 Kilobytes
18898 test_gm.adb:11 test_gm.my_alloc
18899 test_gm.adb:24 test_gm
18900 b_test_gm.c:52 main
18902 Allocation Root # 2
18903 -------------------
18904 Number of non freed allocations : 1
18905 Final Water Mark (non freed mem) : 10.02 Kilobytes
18906 High Water Mark : 10.02 Kilobytes
18908 s-secsta.adb:81 system.secondary_stack.ss_init
18909 s-secsta.adb:283 <system__secondary_stack___elabb>
18910 b_test_gm.c:33 adainit
18912 Allocation Root # 3
18913 -------------------
18914 Number of non freed allocations : 1
18915 Final Water Mark (non freed mem) : 3.91 Kilobytes
18916 High Water Mark : 3.91 Kilobytes
18918 test_gm.adb:11 test_gm.my_alloc
18919 test_gm.adb:21 test_gm
18920 b_test_gm.c:52 main
18922 Allocation Root # 4
18923 -------------------
18924 Number of non freed allocations : 1
18925 Final Water Mark (non freed mem) : 12 Bytes
18926 High Water Mark : 12 Bytes
18928 s-secsta.adb:181 system.secondary_stack.ss_init
18929 s-secsta.adb:283 <system__secondary_stack___elabb>
18930 b_test_gm.c:33 adainit
18934 The allocation root #1 of the first example has been split in 2 roots #1
18935 and #3 thanks to the more precise associated backtrace.
18939 @node Stack Related Facilities
18940 @chapter Stack Related Facilities
18943 This chapter describes some useful tools associated with stack
18944 checking and analysis. In
18945 particular, it deals with dynamic and static stack usage measurements.
18948 * Stack Overflow Checking::
18949 * Static Stack Usage Analysis::
18950 * Dynamic Stack Usage Analysis::
18953 @node Stack Overflow Checking
18954 @section Stack Overflow Checking
18955 @cindex Stack Overflow Checking
18956 @cindex -fstack-check
18959 For most operating systems, @command{gcc} does not perform stack overflow
18960 checking by default. This means that if the main environment task or
18961 some other task exceeds the available stack space, then unpredictable
18962 behavior will occur. Most native systems offer some level of protection by
18963 adding a guard page at the end of each task stack. This mechanism is usually
18964 not enough for dealing properly with stack overflow situations because
18965 a large local variable could ``jump'' above the guard page.
18966 Furthermore, when the
18967 guard page is hit, there may not be any space left on the stack for executing
18968 the exception propagation code. Enabling stack checking avoids
18971 To activate stack checking, compile all units with the gcc option
18972 @option{-fstack-check}. For example:
18975 gcc -c -fstack-check package1.adb
18979 Units compiled with this option will generate extra instructions to check
18980 that any use of the stack (for procedure calls or for declaring local
18981 variables in declare blocks) does not exceed the available stack space.
18982 If the space is exceeded, then a @code{Storage_Error} exception is raised.
18984 For declared tasks, the stack size is controlled by the size
18985 given in an applicable @code{Storage_Size} pragma or by the value specified
18986 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
18987 the default size as defined in the GNAT runtime otherwise.
18989 For the environment task, the stack size depends on
18990 system defaults and is unknown to the compiler. Stack checking
18991 may still work correctly if a fixed
18992 size stack is allocated, but this cannot be guaranteed.
18993 To ensure that a clean exception is signalled for stack
18994 overflow, set the environment variable
18995 @code{GNAT_STACK_LIMIT} to indicate the maximum
18996 stack area that can be used, as in:
18997 @cindex GNAT_STACK_LIMIT
19000 SET GNAT_STACK_LIMIT 1600
19004 The limit is given in kilobytes, so the above declaration would
19005 set the stack limit of the environment task to 1.6 megabytes.
19006 Note that the only purpose of this usage is to limit the amount
19007 of stack used by the environment task. If it is necessary to
19008 increase the amount of stack for the environment task, then this
19009 is an operating systems issue, and must be addressed with the
19010 appropriate operating systems commands.
19012 @node Static Stack Usage Analysis
19013 @section Static Stack Usage Analysis
19014 @cindex Static Stack Usage Analysis
19015 @cindex -fstack-usage
19018 A unit compiled with @option{-fstack-usage} will generate an extra file
19020 the maximum amount of stack used, on a per-function basis.
19021 The file has the same
19022 basename as the target object file with a @file{.su} extension.
19023 Each line of this file is made up of three fields:
19027 The name of the function.
19031 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
19034 The second field corresponds to the size of the known part of the function
19037 The qualifier @code{static} means that the function frame size
19039 It usually means that all local variables have a static size.
19040 In this case, the second field is a reliable measure of the function stack
19043 The qualifier @code{dynamic} means that the function frame size is not static.
19044 It happens mainly when some local variables have a dynamic size. When this
19045 qualifier appears alone, the second field is not a reliable measure
19046 of the function stack analysis. When it is qualified with @code{bounded}, it
19047 means that the second field is a reliable maximum of the function stack
19050 @node Dynamic Stack Usage Analysis
19051 @section Dynamic Stack Usage Analysis
19054 It is possible to measure the maximum amount of stack used by a task, by
19055 adding a switch to @command{gnatbind}, as:
19058 $ gnatbind -u0 file
19062 With this option, at each task termination, its stack usage is output on
19064 It is not always convenient to output the stack usage when the program
19065 is still running. Hence, it is possible to delay this output until program
19066 termination. for a given number of tasks specified as the argument of the
19067 @code{-u} option. For instance:
19070 $ gnatbind -u100 file
19074 will buffer the stack usage information of the first 100 tasks to terminate and
19075 output this info at program termination. Results are displayed in four
19079 Index | Task Name | Stack Size | Actual Use
19086 is a number associated with each task.
19089 is the name of the task analyzed.
19092 is the maximum size for the stack. In order to prevent overflow,
19093 the real stack limit is slightly larger than the Stack Size in order to allow
19097 is the measure done by the stack analyzer.
19102 The environment task stack, e.g. the stack that contains the main unit, is
19103 only processed when the environment variable GNAT_STACK_LIMIT is set.
19105 @c *********************************
19106 @node Verifying properties using gnatcheck
19107 @chapter Verifying properties using @command{gnatcheck}
19111 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
19112 of Ada source files according to a given set of semantic rules.
19114 In order to check compliance with a given rule, @command{gnatcheck} has to
19115 semantically analyze the Ada sources.
19116 Therefore, checks can only be performed on
19117 legal Ada units. Moreover, when a unit depends semantically upon units located
19118 outside the current directory, the source search path has to be provided when
19119 calling @command{gnatcheck}, either through a specified project file or
19120 through @command{gnatcheck} switches as described below.
19122 The project support for @command{gnatcheck} is provided by the @command{gnat}
19125 Several rules are already implemented in @command{gnatcheck}. The list of such
19126 rules can be obtained with option @option{^-h^/HELP^} as described in the next
19127 section. A user can add new rules by modifying the @command{gnatcheck} code and
19128 rebuilding the tool. For adding a simple rule making some local checks, a small
19129 amount of straightforward ASIS-based programming is usually needed.
19132 @command{gnatcheck} has the command-line interface of the form
19135 $ gnatcheck [@i{switches}] @{@i{filename}@}
19136 [@i{^-files^/FILES^=@{arg_list_filename@}}]
19137 [@i{-cargs gcc_switches}] [@i{-rules rule_options}]
19144 @i{switches} specify the general tool options
19147 Each @i{filename} is the name (including the extension) of a source
19148 file to process. ``Wildcards'' are allowed, and
19149 the file name may contain path information.
19152 Each @i{arg_list_filename} is the name (including the extension) of a text
19153 file containing the names of the source files to process, separated by spaces
19157 @i{-cargs gcc_switches} is a list of switches for
19158 @command{gcc}. They will be passed on to all compiler invocations made by
19159 @command{gnatcheck} to generate the ASIS trees. Here you can provide
19160 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19161 and use the @option{-gnatec} switch to set the configuration file.
19164 @i{-rules rule_options} is a list of options for controlling a set of
19165 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options})
19169 Either a @i{filename} or an @i{arg_list_filename} needs to be supplied.
19172 * Format of the Report File::
19173 * General gnatcheck Switches::
19174 * gnatcheck Rule Options::
19175 * Add the Results of Compiler Checks to gnatcheck Output::
19178 @node Format of the Report File
19179 @section Format of the Report File
19182 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
19184 It also creates, in the current
19185 directory, a text file named @file{^gnatcheck.out^GNATCHECK.OUT^} that
19186 contains the complete report of the last gnatcheck run. This report contains:
19188 @item a list of the Ada source files being checked,
19189 @item a list of enabled and disabled rules,
19190 @item a list of the diagnostic messages, ordered in three different ways
19191 and collected in three separate
19192 sections. Section 1 contains the raw list of diagnostic messages. It
19193 corresponds to the output going to @file{stdout}. Section 2 contains
19194 messages ordered by rules.
19195 Section 3 contains messages ordered by source files.
19198 @node General gnatcheck Switches
19199 @section General @command{gnatcheck} Switches
19202 The following switches control the general @command{gnatcheck} behavior
19205 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
19207 Process all units including those with read-only ALI files such as
19208 those from GNAT Run-Time library.
19210 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
19212 Print out the list of the currently implemented rules. For more details see
19213 the README file in the @command{gnatcheck} sources.
19215 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
19217 Use full source locations references in the report file. For a construct from
19218 a generic instantiation a full source location is a chain from the location
19219 of this construct in the generic unit to the place where this unit is
19222 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
19224 Quiet mode. All the diagnoses about rule violations are placed in the
19225 @command{gnatcheck} report file only, without duplicating in @file{stdout}.
19227 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
19229 Short format of the report file (no version information, no list of applied
19230 rules, no list of checked sources is included)
19232 @cindex @option{^-s1^/COMPILER_STYLE^} (@command{gnatcheck})
19233 @item ^-s1^/COMPILER_STYLE^
19234 Include the compiler-style section in the report file
19236 @cindex @option{^-s2^/BY_RULES^} (@command{gnatcheck})
19237 @item ^-s2^/BY_RULES^
19238 Include the section containing diagnoses ordered by rules in the report file
19240 @cindex @option{^-s3^/BY_FILES_BY_RULES^} (@command{gnatcheck})
19241 @item ^-s3^/BY_FILES_BY_RULES^
19242 Include the section containing diagnoses ordered by files and then by rules
19245 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
19246 @item ^-v^/VERBOSE^
19247 Verbose mode; @command{gnatcheck} generates version information and then
19248 a trace of sources being processed.
19253 Note, that if either of the options @option{^-s1^/COMPILER_STYLE^},
19254 @option{^-s2^/BY_RULES^} or
19255 @option{^-s3^/BY_FILES_BY_RULES^} is specified,
19256 then the @command{gnatcheck} report file will contain only sections
19257 explicitly stated by these options.
19259 @node gnatcheck Rule Options
19260 @section @command{gnatcheck} Rule Options
19263 The following options control the processing performed by
19264 @command{gnatcheck}.
19267 @cindex @option{+ALL} (@command{gnatcheck})
19269 Turn all the rule checks ON
19271 @cindex @option{-ALL} (@command{gnatcheck})
19273 Turn all the rule checks OFF
19275 @cindex @option{+R} (@command{gnatcheck})
19276 @item +R@i{rule_id[:param]}
19277 Turn on the check for a specified rule with the specified parameter, if any.
19278 @i{rule_id} should be the identifier of one of the currently implemented rules
19279 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
19280 are not case-sensitive. The @i{:param} item should
19281 be a string representing a valid parameter(s) for the specified rule.
19282 If it contains any space characters then this string must be enclosed in
19285 @cindex @option{-R} (@command{gnatcheck})
19286 @item -R@i{rule_id}
19287 Turn off the check for a specified rule
19291 @node Add the Results of Compiler Checks to gnatcheck Output
19292 @section Add the Results of Compiler Checks to @command{gnatcheck} Output
19295 The @command{gnatcheck} tool can include in the generated diagnostic messages
19297 the report file the results of the checks performed by the compiler. Though
19298 disabled by default, this effect may be obtained by using @option{+R} with
19299 the following rule identifiers and parameters:
19303 To record restrictions violations (that are performed by the compiler if the
19304 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
19306 @i{Restrictions} with the same parameters as pragma
19307 @code{Restrictions} or @code{Restriction_Warnings}
19310 To record compiler style checks, use the rule named
19311 @i{Style_Checks}. A parameter of this rule can be either @i{All_Checks}, that
19312 turns ON all the style checks, or a string that has exactly the same structure
19313 and semantics as @code{string_LITERAL} parameter of GNAT pragma
19314 @code{Style_Checks}.
19317 To record compiler warnings (@pxref{Warning Message Control}), use the rule
19318 named @i{Warnings} with a parameter that is a valid
19319 @code{static_string_expression} argument of GNAT pragma @code{Warnings}.
19323 @c *********************************
19324 @node Creating Sample Bodies Using gnatstub
19325 @chapter Creating Sample Bodies Using @command{gnatstub}
19329 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
19330 for library unit declarations.
19332 To create a body stub, @command{gnatstub} has to compile the library
19333 unit declaration. Therefore, bodies can be created only for legal
19334 library units. Moreover, if a library unit depends semantically upon
19335 units located outside the current directory, you have to provide
19336 the source search path when calling @command{gnatstub}, see the description
19337 of @command{gnatstub} switches below.
19340 * Running gnatstub::
19341 * Switches for gnatstub::
19344 @node Running gnatstub
19345 @section Running @command{gnatstub}
19348 @command{gnatstub} has the command-line interface of the form
19351 $ gnatstub [switches] filename [directory]
19358 is the name of the source file that contains a library unit declaration
19359 for which a body must be created. The file name may contain the path
19361 The file name does not have to follow the GNAT file name conventions. If the
19363 does not follow GNAT file naming conventions, the name of the body file must
19365 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
19366 If the file name follows the GNAT file naming
19367 conventions and the name of the body file is not provided,
19370 of the body file from the argument file name by replacing the @file{.ads}
19372 with the @file{.adb} suffix.
19375 indicates the directory in which the body stub is to be placed (the default
19380 is an optional sequence of switches as described in the next section
19383 @node Switches for gnatstub
19384 @section Switches for @command{gnatstub}
19390 @cindex @option{^-f^/FULL^} (@command{gnatstub})
19391 If the destination directory already contains a file with the name of the
19393 for the argument spec file, replace it with the generated body stub.
19395 @item ^-hs^/HEADER=SPEC^
19396 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
19397 Put the comment header (i.e., all the comments preceding the
19398 compilation unit) from the source of the library unit declaration
19399 into the body stub.
19401 @item ^-hg^/HEADER=GENERAL^
19402 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
19403 Put a sample comment header into the body stub.
19407 @cindex @option{-IDIR} (@command{gnatstub})
19409 @cindex @option{-I-} (@command{gnatstub})
19412 @item /NOCURRENT_DIRECTORY
19413 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
19415 ^These switches have ^This switch has^ the same meaning as in calls to
19417 ^They define ^It defines ^ the source search path in the call to
19418 @command{gcc} issued
19419 by @command{gnatstub} to compile an argument source file.
19421 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
19422 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
19423 This switch has the same meaning as in calls to @command{gcc}.
19424 It defines the additional configuration file to be passed to the call to
19425 @command{gcc} issued
19426 by @command{gnatstub} to compile an argument source file.
19428 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
19429 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
19430 (@var{n} is a non-negative integer). Set the maximum line length in the
19431 body stub to @var{n}; the default is 79. The maximum value that can be
19432 specified is 32767. Note that in the special case of configuration
19433 pragma files, the maximum is always 32767 regardless of whether or
19434 not this switch appears.
19436 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
19437 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
19438 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
19439 the generated body sample to @var{n}.
19440 The default indentation is 3.
19442 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
19443 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
19444 Order local bodies alphabetically. (By default local bodies are ordered
19445 in the same way as the corresponding local specs in the argument spec file.)
19447 @item ^-i^/INDENTATION=^@var{n}
19448 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
19449 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
19451 @item ^-k^/TREE_FILE=SAVE^
19452 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
19453 Do not remove the tree file (i.e., the snapshot of the compiler internal
19454 structures used by @command{gnatstub}) after creating the body stub.
19456 @item ^-l^/LINE_LENGTH=^@var{n}
19457 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
19458 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
19460 @item ^-o^/BODY=^@var{body-name}
19461 @cindex @option{^-o^/BODY^} (@command{gnatstub})
19462 Body file name. This should be set if the argument file name does not
19464 the GNAT file naming
19465 conventions. If this switch is omitted the default name for the body will be
19467 from the argument file name according to the GNAT file naming conventions.
19470 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
19471 Quiet mode: do not generate a confirmation when a body is
19472 successfully created, and do not generate a message when a body is not
19476 @item ^-r^/TREE_FILE=REUSE^
19477 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
19478 Reuse the tree file (if it exists) instead of creating it. Instead of
19479 creating the tree file for the library unit declaration, @command{gnatstub}
19480 tries to find it in the current directory and use it for creating
19481 a body. If the tree file is not found, no body is created. This option
19482 also implies @option{^-k^/SAVE^}, whether or not
19483 the latter is set explicitly.
19485 @item ^-t^/TREE_FILE=OVERWRITE^
19486 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
19487 Overwrite the existing tree file. If the current directory already
19488 contains the file which, according to the GNAT file naming rules should
19489 be considered as a tree file for the argument source file,
19491 will refuse to create the tree file needed to create a sample body
19492 unless this option is set.
19494 @item ^-v^/VERBOSE^
19495 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
19496 Verbose mode: generate version information.
19500 @node Other Utility Programs
19501 @chapter Other Utility Programs
19504 This chapter discusses some other utility programs available in the Ada
19508 * Using Other Utility Programs with GNAT::
19509 * The External Symbol Naming Scheme of GNAT::
19511 * Ada Mode for Glide::
19513 * Converting Ada Files to html with gnathtml::
19514 * Installing gnathtml::
19521 @node Using Other Utility Programs with GNAT
19522 @section Using Other Utility Programs with GNAT
19525 The object files generated by GNAT are in standard system format and in
19526 particular the debugging information uses this format. This means
19527 programs generated by GNAT can be used with existing utilities that
19528 depend on these formats.
19531 In general, any utility program that works with C will also often work with
19532 Ada programs generated by GNAT. This includes software utilities such as
19533 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
19537 @node The External Symbol Naming Scheme of GNAT
19538 @section The External Symbol Naming Scheme of GNAT
19541 In order to interpret the output from GNAT, when using tools that are
19542 originally intended for use with other languages, it is useful to
19543 understand the conventions used to generate link names from the Ada
19546 All link names are in all lowercase letters. With the exception of library
19547 procedure names, the mechanism used is simply to use the full expanded
19548 Ada name with dots replaced by double underscores. For example, suppose
19549 we have the following package spec:
19551 @smallexample @c ada
19562 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
19563 the corresponding link name is @code{qrs__mn}.
19565 Of course if a @code{pragma Export} is used this may be overridden:
19567 @smallexample @c ada
19572 pragma Export (Var1, C, External_Name => "var1_name");
19574 pragma Export (Var2, C, Link_Name => "var2_link_name");
19581 In this case, the link name for @var{Var1} is whatever link name the
19582 C compiler would assign for the C function @var{var1_name}. This typically
19583 would be either @var{var1_name} or @var{_var1_name}, depending on operating
19584 system conventions, but other possibilities exist. The link name for
19585 @var{Var2} is @var{var2_link_name}, and this is not operating system
19589 One exception occurs for library level procedures. A potential ambiguity
19590 arises between the required name @code{_main} for the C main program,
19591 and the name we would otherwise assign to an Ada library level procedure
19592 called @code{Main} (which might well not be the main program).
19594 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
19595 names. So if we have a library level procedure such as
19597 @smallexample @c ada
19600 procedure Hello (S : String);
19606 the external name of this procedure will be @var{_ada_hello}.
19609 @node Ada Mode for Glide
19610 @section Ada Mode for @code{Glide}
19611 @cindex Ada mode (for Glide)
19614 The Glide mode for programming in Ada (both Ada83 and Ada95) helps the
19615 user to understand and navigate existing code, and facilitates writing
19616 new code. It furthermore provides some utility functions for easier
19617 integration of standard Emacs features when programming in Ada.
19619 Its general features include:
19623 An Integrated Development Environment with functionality such as the
19628 ``Project files'' for configuration-specific aspects
19629 (e.g. directories and compilation options)
19632 Compiling and stepping through error messages.
19635 Running and debugging an applications within Glide.
19642 User configurability
19645 Some of the specific Ada mode features are:
19649 Functions for easy and quick stepping through Ada code
19652 Getting cross reference information for identifiers (e.g., finding a
19653 defining occurrence)
19656 Displaying an index menu of types and subprograms, allowing
19657 direct selection for browsing
19660 Automatic color highlighting of the various Ada entities
19663 Glide directly supports writing Ada code, via several facilities:
19667 Switching between spec and body files with possible
19668 autogeneration of body files
19671 Automatic formating of subprogram parameter lists
19674 Automatic indentation according to Ada syntax
19677 Automatic completion of identifiers
19680 Automatic (and configurable) casing of identifiers, keywords, and attributes
19683 Insertion of syntactic templates
19686 Block commenting / uncommenting
19690 For more information, please refer to the online documentation
19691 available in the @code{Glide} @result{} @code{Help} menu.
19694 @node Converting Ada Files to html with gnathtml
19695 @section Converting Ada Files to HTML with @code{gnathtml}
19698 This @code{Perl} script allows Ada source files to be browsed using
19699 standard Web browsers. For installation procedure, see the section
19700 @xref{Installing gnathtml}.
19702 Ada reserved keywords are highlighted in a bold font and Ada comments in
19703 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
19704 switch to suppress the generation of cross-referencing information, user
19705 defined variables and types will appear in a different color; you will
19706 be able to click on any identifier and go to its declaration.
19708 The command line is as follow:
19710 $ perl gnathtml.pl [^switches^options^] ada-files
19714 You can pass it as many Ada files as you want. @code{gnathtml} will generate
19715 an html file for every ada file, and a global file called @file{index.htm}.
19716 This file is an index of every identifier defined in the files.
19718 The available ^switches^options^ are the following ones :
19722 @cindex @option{-83} (@code{gnathtml})
19723 Only the subset on the Ada 83 keywords will be highlighted, not the full
19724 Ada 95 keywords set.
19726 @item -cc @var{color}
19727 @cindex @option{-cc} (@code{gnathtml})
19728 This option allows you to change the color used for comments. The default
19729 value is green. The color argument can be any name accepted by html.
19732 @cindex @option{-d} (@code{gnathtml})
19733 If the Ada files depend on some other files (for instance through
19734 @code{with} clauses, the latter files will also be converted to html.
19735 Only the files in the user project will be converted to html, not the files
19736 in the run-time library itself.
19739 @cindex @option{-D} (@code{gnathtml})
19740 This command is the same as @option{-d} above, but @command{gnathtml} will
19741 also look for files in the run-time library, and generate html files for them.
19743 @item -ext @var{extension}
19744 @cindex @option{-ext} (@code{gnathtml})
19745 This option allows you to change the extension of the generated HTML files.
19746 If you do not specify an extension, it will default to @file{htm}.
19749 @cindex @option{-f} (@code{gnathtml})
19750 By default, gnathtml will generate html links only for global entities
19751 ('with'ed units, global variables and types,...). If you specify
19752 @option{-f} on the command line, then links will be generated for local
19755 @item -l @var{number}
19756 @cindex @option{-l} (@code{gnathtml})
19757 If this ^switch^option^ is provided and @var{number} is not 0, then
19758 @code{gnathtml} will number the html files every @var{number} line.
19761 @cindex @option{-I} (@code{gnathtml})
19762 Specify a directory to search for library files (@file{.ALI} files) and
19763 source files. You can provide several -I switches on the command line,
19764 and the directories will be parsed in the order of the command line.
19767 @cindex @option{-o} (@code{gnathtml})
19768 Specify the output directory for html files. By default, gnathtml will
19769 saved the generated html files in a subdirectory named @file{html/}.
19771 @item -p @var{file}
19772 @cindex @option{-p} (@code{gnathtml})
19773 If you are using Emacs and the most recent Emacs Ada mode, which provides
19774 a full Integrated Development Environment for compiling, checking,
19775 running and debugging applications, you may use @file{.gpr} files
19776 to give the directories where Emacs can find sources and object files.
19778 Using this ^switch^option^, you can tell gnathtml to use these files.
19779 This allows you to get an html version of your application, even if it
19780 is spread over multiple directories.
19782 @item -sc @var{color}
19783 @cindex @option{-sc} (@code{gnathtml})
19784 This ^switch^option^ allows you to change the color used for symbol
19786 The default value is red. The color argument can be any name accepted by html.
19788 @item -t @var{file}
19789 @cindex @option{-t} (@code{gnathtml})
19790 This ^switch^option^ provides the name of a file. This file contains a list of
19791 file names to be converted, and the effect is exactly as though they had
19792 appeared explicitly on the command line. This
19793 is the recommended way to work around the command line length limit on some
19798 @node Installing gnathtml
19799 @section Installing @code{gnathtml}
19802 @code{Perl} needs to be installed on your machine to run this script.
19803 @code{Perl} is freely available for almost every architecture and
19804 Operating System via the Internet.
19806 On Unix systems, you may want to modify the first line of the script
19807 @code{gnathtml}, to explicitly tell the Operating system where Perl
19808 is. The syntax of this line is :
19810 #!full_path_name_to_perl
19814 Alternatively, you may run the script using the following command line:
19817 $ perl gnathtml.pl [switches] files
19826 The GNAT distribution provides an Ada 95 template for the HP Language
19827 Sensitive Editor (LSE), a component of DECset. In order to
19828 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
19835 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
19836 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
19837 the collection phase with the /DEBUG qualifier.
19840 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
19841 $ DEFINE LIB$DEBUG PCA$COLLECTOR
19842 $ RUN/DEBUG <PROGRAM_NAME>
19847 @node Running and Debugging Ada Programs
19848 @chapter Running and Debugging Ada Programs
19852 This chapter discusses how to debug Ada programs.
19854 It applies to the Alpha OpenVMS platform;
19855 the debugger for I64 OpenVMS is scheduled for a subsequent release.
19858 An incorrect Ada program may be handled in three ways by the GNAT compiler:
19862 The illegality may be a violation of the static semantics of Ada. In
19863 that case GNAT diagnoses the constructs in the program that are illegal.
19864 It is then a straightforward matter for the user to modify those parts of
19868 The illegality may be a violation of the dynamic semantics of Ada. In
19869 that case the program compiles and executes, but may generate incorrect
19870 results, or may terminate abnormally with some exception.
19873 When presented with a program that contains convoluted errors, GNAT
19874 itself may terminate abnormally without providing full diagnostics on
19875 the incorrect user program.
19879 * The GNAT Debugger GDB::
19881 * Introduction to GDB Commands::
19882 * Using Ada Expressions::
19883 * Calling User-Defined Subprograms::
19884 * Using the Next Command in a Function::
19887 * Debugging Generic Units::
19888 * GNAT Abnormal Termination or Failure to Terminate::
19889 * Naming Conventions for GNAT Source Files::
19890 * Getting Internal Debugging Information::
19891 * Stack Traceback::
19897 @node The GNAT Debugger GDB
19898 @section The GNAT Debugger GDB
19901 @code{GDB} is a general purpose, platform-independent debugger that
19902 can be used to debug mixed-language programs compiled with @command{gcc},
19903 and in particular is capable of debugging Ada programs compiled with
19904 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
19905 complex Ada data structures.
19907 The manual @cite{Debugging with GDB}
19909 , located in the GNU:[DOCS] directory,
19911 contains full details on the usage of @code{GDB}, including a section on
19912 its usage on programs. This manual should be consulted for full
19913 details. The section that follows is a brief introduction to the
19914 philosophy and use of @code{GDB}.
19916 When GNAT programs are compiled, the compiler optionally writes debugging
19917 information into the generated object file, including information on
19918 line numbers, and on declared types and variables. This information is
19919 separate from the generated code. It makes the object files considerably
19920 larger, but it does not add to the size of the actual executable that
19921 will be loaded into memory, and has no impact on run-time performance. The
19922 generation of debug information is triggered by the use of the
19923 ^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out
19924 the compilations. It is important to emphasize that the use of these
19925 options does not change the generated code.
19927 The debugging information is written in standard system formats that
19928 are used by many tools, including debuggers and profilers. The format
19929 of the information is typically designed to describe C types and
19930 semantics, but GNAT implements a translation scheme which allows full
19931 details about Ada types and variables to be encoded into these
19932 standard C formats. Details of this encoding scheme may be found in
19933 the file exp_dbug.ads in the GNAT source distribution. However, the
19934 details of this encoding are, in general, of no interest to a user,
19935 since @code{GDB} automatically performs the necessary decoding.
19937 When a program is bound and linked, the debugging information is
19938 collected from the object files, and stored in the executable image of
19939 the program. Again, this process significantly increases the size of
19940 the generated executable file, but it does not increase the size of
19941 the executable program itself. Furthermore, if this program is run in
19942 the normal manner, it runs exactly as if the debug information were
19943 not present, and takes no more actual memory.
19945 However, if the program is run under control of @code{GDB}, the
19946 debugger is activated. The image of the program is loaded, at which
19947 point it is ready to run. If a run command is given, then the program
19948 will run exactly as it would have if @code{GDB} were not present. This
19949 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
19950 entirely non-intrusive until a breakpoint is encountered. If no
19951 breakpoint is ever hit, the program will run exactly as it would if no
19952 debugger were present. When a breakpoint is hit, @code{GDB} accesses
19953 the debugging information and can respond to user commands to inspect
19954 variables, and more generally to report on the state of execution.
19958 @section Running GDB
19961 The debugger can be launched directly and simply from @code{glide} or
19962 through its graphical interface: @code{gvd}. It can also be used
19963 directly in text mode. Here is described the basic use of @code{GDB}
19964 in text mode. All the commands described below can be used in the
19965 @code{gvd} console window even though there is usually other more
19966 graphical ways to achieve the same goals.
19970 The command to run the graphical interface of the debugger is
19977 The command to run @code{GDB} in text mode is
19980 $ ^gdb program^$ GDB PROGRAM^
19984 where @code{^program^PROGRAM^} is the name of the executable file. This
19985 activates the debugger and results in a prompt for debugger commands.
19986 The simplest command is simply @code{run}, which causes the program to run
19987 exactly as if the debugger were not present. The following section
19988 describes some of the additional commands that can be given to @code{GDB}.
19990 @c *******************************
19991 @node Introduction to GDB Commands
19992 @section Introduction to GDB Commands
19995 @code{GDB} contains a large repertoire of commands. The manual
19996 @cite{Debugging with GDB}
19998 , located in the GNU:[DOCS] directory,
20000 includes extensive documentation on the use
20001 of these commands, together with examples of their use. Furthermore,
20002 the command @var{help} invoked from within @code{GDB} activates a simple help
20003 facility which summarizes the available commands and their options.
20004 In this section we summarize a few of the most commonly
20005 used commands to give an idea of what @code{GDB} is about. You should create
20006 a simple program with debugging information and experiment with the use of
20007 these @code{GDB} commands on the program as you read through the
20011 @item set args @var{arguments}
20012 The @var{arguments} list above is a list of arguments to be passed to
20013 the program on a subsequent run command, just as though the arguments
20014 had been entered on a normal invocation of the program. The @code{set args}
20015 command is not needed if the program does not require arguments.
20018 The @code{run} command causes execution of the program to start from
20019 the beginning. If the program is already running, that is to say if
20020 you are currently positioned at a breakpoint, then a prompt will ask
20021 for confirmation that you want to abandon the current execution and
20024 @item breakpoint @var{location}
20025 The breakpoint command sets a breakpoint, that is to say a point at which
20026 execution will halt and @code{GDB} will await further
20027 commands. @var{location} is
20028 either a line number within a file, given in the format @code{file:linenumber},
20029 or it is the name of a subprogram. If you request that a breakpoint be set on
20030 a subprogram that is overloaded, a prompt will ask you to specify on which of
20031 those subprograms you want to breakpoint. You can also
20032 specify that all of them should be breakpointed. If the program is run
20033 and execution encounters the breakpoint, then the program
20034 stops and @code{GDB} signals that the breakpoint was encountered by
20035 printing the line of code before which the program is halted.
20037 @item breakpoint exception @var{name}
20038 A special form of the breakpoint command which breakpoints whenever
20039 exception @var{name} is raised.
20040 If @var{name} is omitted,
20041 then a breakpoint will occur when any exception is raised.
20043 @item print @var{expression}
20044 This will print the value of the given expression. Most simple
20045 Ada expression formats are properly handled by @code{GDB}, so the expression
20046 can contain function calls, variables, operators, and attribute references.
20049 Continues execution following a breakpoint, until the next breakpoint or the
20050 termination of the program.
20053 Executes a single line after a breakpoint. If the next statement
20054 is a subprogram call, execution continues into (the first statement of)
20055 the called subprogram.
20058 Executes a single line. If this line is a subprogram call, executes and
20059 returns from the call.
20062 Lists a few lines around the current source location. In practice, it
20063 is usually more convenient to have a separate edit window open with the
20064 relevant source file displayed. Successive applications of this command
20065 print subsequent lines. The command can be given an argument which is a
20066 line number, in which case it displays a few lines around the specified one.
20069 Displays a backtrace of the call chain. This command is typically
20070 used after a breakpoint has occurred, to examine the sequence of calls that
20071 leads to the current breakpoint. The display includes one line for each
20072 activation record (frame) corresponding to an active subprogram.
20075 At a breakpoint, @code{GDB} can display the values of variables local
20076 to the current frame. The command @code{up} can be used to
20077 examine the contents of other active frames, by moving the focus up
20078 the stack, that is to say from callee to caller, one frame at a time.
20081 Moves the focus of @code{GDB} down from the frame currently being
20082 examined to the frame of its callee (the reverse of the previous command),
20084 @item frame @var{n}
20085 Inspect the frame with the given number. The value 0 denotes the frame
20086 of the current breakpoint, that is to say the top of the call stack.
20090 The above list is a very short introduction to the commands that
20091 @code{GDB} provides. Important additional capabilities, including conditional
20092 breakpoints, the ability to execute command sequences on a breakpoint,
20093 the ability to debug at the machine instruction level and many other
20094 features are described in detail in @cite{Debugging with GDB}.
20095 Note that most commands can be abbreviated
20096 (for example, c for continue, bt for backtrace).
20098 @node Using Ada Expressions
20099 @section Using Ada Expressions
20100 @cindex Ada expressions
20103 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
20104 extensions. The philosophy behind the design of this subset is
20108 That @code{GDB} should provide basic literals and access to operations for
20109 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
20110 leaving more sophisticated computations to subprograms written into the
20111 program (which therefore may be called from @code{GDB}).
20114 That type safety and strict adherence to Ada language restrictions
20115 are not particularly important to the @code{GDB} user.
20118 That brevity is important to the @code{GDB} user.
20121 Thus, for brevity, the debugger acts as if there were
20122 implicit @code{with} and @code{use} clauses in effect for all user-written
20123 packages, thus making it unnecessary to fully qualify most names with
20124 their packages, regardless of context. Where this causes ambiguity,
20125 @code{GDB} asks the user's intent.
20127 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
20129 @node Calling User-Defined Subprograms
20130 @section Calling User-Defined Subprograms
20133 An important capability of @code{GDB} is the ability to call user-defined
20134 subprograms while debugging. This is achieved simply by entering
20135 a subprogram call statement in the form:
20138 call subprogram-name (parameters)
20142 The keyword @code{call} can be omitted in the normal case where the
20143 @code{subprogram-name} does not coincide with any of the predefined
20144 @code{GDB} commands.
20146 The effect is to invoke the given subprogram, passing it the
20147 list of parameters that is supplied. The parameters can be expressions and
20148 can include variables from the program being debugged. The
20149 subprogram must be defined
20150 at the library level within your program, and @code{GDB} will call the
20151 subprogram within the environment of your program execution (which
20152 means that the subprogram is free to access or even modify variables
20153 within your program).
20155 The most important use of this facility is in allowing the inclusion of
20156 debugging routines that are tailored to particular data structures
20157 in your program. Such debugging routines can be written to provide a suitably
20158 high-level description of an abstract type, rather than a low-level dump
20159 of its physical layout. After all, the standard
20160 @code{GDB print} command only knows the physical layout of your
20161 types, not their abstract meaning. Debugging routines can provide information
20162 at the desired semantic level and are thus enormously useful.
20164 For example, when debugging GNAT itself, it is crucial to have access to
20165 the contents of the tree nodes used to represent the program internally.
20166 But tree nodes are represented simply by an integer value (which in turn
20167 is an index into a table of nodes).
20168 Using the @code{print} command on a tree node would simply print this integer
20169 value, which is not very useful. But the PN routine (defined in file
20170 treepr.adb in the GNAT sources) takes a tree node as input, and displays
20171 a useful high level representation of the tree node, which includes the
20172 syntactic category of the node, its position in the source, the integers
20173 that denote descendant nodes and parent node, as well as varied
20174 semantic information. To study this example in more detail, you might want to
20175 look at the body of the PN procedure in the stated file.
20177 @node Using the Next Command in a Function
20178 @section Using the Next Command in a Function
20181 When you use the @code{next} command in a function, the current source
20182 location will advance to the next statement as usual. A special case
20183 arises in the case of a @code{return} statement.
20185 Part of the code for a return statement is the ``epilog'' of the function.
20186 This is the code that returns to the caller. There is only one copy of
20187 this epilog code, and it is typically associated with the last return
20188 statement in the function if there is more than one return. In some
20189 implementations, this epilog is associated with the first statement
20192 The result is that if you use the @code{next} command from a return
20193 statement that is not the last return statement of the function you
20194 may see a strange apparent jump to the last return statement or to
20195 the start of the function. You should simply ignore this odd jump.
20196 The value returned is always that from the first return statement
20197 that was stepped through.
20199 @node Ada Exceptions
20200 @section Breaking on Ada Exceptions
20204 You can set breakpoints that trip when your program raises
20205 selected exceptions.
20208 @item break exception
20209 Set a breakpoint that trips whenever (any task in the) program raises
20212 @item break exception @var{name}
20213 Set a breakpoint that trips whenever (any task in the) program raises
20214 the exception @var{name}.
20216 @item break exception unhandled
20217 Set a breakpoint that trips whenever (any task in the) program raises an
20218 exception for which there is no handler.
20220 @item info exceptions
20221 @itemx info exceptions @var{regexp}
20222 The @code{info exceptions} command permits the user to examine all defined
20223 exceptions within Ada programs. With a regular expression, @var{regexp}, as
20224 argument, prints out only those exceptions whose name matches @var{regexp}.
20232 @code{GDB} allows the following task-related commands:
20236 This command shows a list of current Ada tasks, as in the following example:
20243 ID TID P-ID Thread Pri State Name
20244 1 8088000 0 807e000 15 Child Activation Wait main_task
20245 2 80a4000 1 80ae000 15 Accept/Select Wait b
20246 3 809a800 1 80a4800 15 Child Activation Wait a
20247 * 4 80ae800 3 80b8000 15 Running c
20251 In this listing, the asterisk before the first task indicates it to be the
20252 currently running task. The first column lists the task ID that is used
20253 to refer to tasks in the following commands.
20255 @item break @var{linespec} task @var{taskid}
20256 @itemx break @var{linespec} task @var{taskid} if @dots{}
20257 @cindex Breakpoints and tasks
20258 These commands are like the @code{break @dots{} thread @dots{}}.
20259 @var{linespec} specifies source lines.
20261 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
20262 to specify that you only want @code{GDB} to stop the program when a
20263 particular Ada task reaches this breakpoint. @var{taskid} is one of the
20264 numeric task identifiers assigned by @code{GDB}, shown in the first
20265 column of the @samp{info tasks} display.
20267 If you do not specify @samp{task @var{taskid}} when you set a
20268 breakpoint, the breakpoint applies to @emph{all} tasks of your
20271 You can use the @code{task} qualifier on conditional breakpoints as
20272 well; in this case, place @samp{task @var{taskid}} before the
20273 breakpoint condition (before the @code{if}).
20275 @item task @var{taskno}
20276 @cindex Task switching
20278 This command allows to switch to the task referred by @var{taskno}. In
20279 particular, This allows to browse the backtrace of the specified
20280 task. It is advised to switch back to the original task before
20281 continuing execution otherwise the scheduling of the program may be
20286 For more detailed information on the tasking support,
20287 see @cite{Debugging with GDB}.
20289 @node Debugging Generic Units
20290 @section Debugging Generic Units
20291 @cindex Debugging Generic Units
20295 GNAT always uses code expansion for generic instantiation. This means that
20296 each time an instantiation occurs, a complete copy of the original code is
20297 made, with appropriate substitutions of formals by actuals.
20299 It is not possible to refer to the original generic entities in
20300 @code{GDB}, but it is always possible to debug a particular instance of
20301 a generic, by using the appropriate expanded names. For example, if we have
20303 @smallexample @c ada
20308 generic package k is
20309 procedure kp (v1 : in out integer);
20313 procedure kp (v1 : in out integer) is
20319 package k1 is new k;
20320 package k2 is new k;
20322 var : integer := 1;
20335 Then to break on a call to procedure kp in the k2 instance, simply
20339 (gdb) break g.k2.kp
20343 When the breakpoint occurs, you can step through the code of the
20344 instance in the normal manner and examine the values of local variables, as for
20347 @node GNAT Abnormal Termination or Failure to Terminate
20348 @section GNAT Abnormal Termination or Failure to Terminate
20349 @cindex GNAT Abnormal Termination or Failure to Terminate
20352 When presented with programs that contain serious errors in syntax
20354 GNAT may on rare occasions experience problems in operation, such
20356 segmentation fault or illegal memory access, raising an internal
20357 exception, terminating abnormally, or failing to terminate at all.
20358 In such cases, you can activate
20359 various features of GNAT that can help you pinpoint the construct in your
20360 program that is the likely source of the problem.
20362 The following strategies are presented in increasing order of
20363 difficulty, corresponding to your experience in using GNAT and your
20364 familiarity with compiler internals.
20368 Run @command{gcc} with the @option{-gnatf}. This first
20369 switch causes all errors on a given line to be reported. In its absence,
20370 only the first error on a line is displayed.
20372 The @option{-gnatdO} switch causes errors to be displayed as soon as they
20373 are encountered, rather than after compilation is terminated. If GNAT
20374 terminates prematurely or goes into an infinite loop, the last error
20375 message displayed may help to pinpoint the culprit.
20378 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
20379 mode, @command{gcc} produces ongoing information about the progress of the
20380 compilation and provides the name of each procedure as code is
20381 generated. This switch allows you to find which Ada procedure was being
20382 compiled when it encountered a code generation problem.
20385 @cindex @option{-gnatdc} switch
20386 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
20387 switch that does for the front-end what @option{^-v^VERBOSE^} does
20388 for the back end. The system prints the name of each unit,
20389 either a compilation unit or nested unit, as it is being analyzed.
20391 Finally, you can start
20392 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
20393 front-end of GNAT, and can be run independently (normally it is just
20394 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
20395 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
20396 @code{where} command is the first line of attack; the variable
20397 @code{lineno} (seen by @code{print lineno}), used by the second phase of
20398 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
20399 which the execution stopped, and @code{input_file name} indicates the name of
20403 @node Naming Conventions for GNAT Source Files
20404 @section Naming Conventions for GNAT Source Files
20407 In order to examine the workings of the GNAT system, the following
20408 brief description of its organization may be helpful:
20412 Files with prefix @file{^sc^SC^} contain the lexical scanner.
20415 All files prefixed with @file{^par^PAR^} are components of the parser. The
20416 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
20417 parsing of select statements can be found in @file{par-ch9.adb}.
20420 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
20421 numbers correspond to chapters of the Ada standard. For example, all
20422 issues involving context clauses can be found in @file{sem_ch10.adb}. In
20423 addition, some features of the language require sufficient special processing
20424 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
20425 dynamic dispatching, etc.
20428 All files prefixed with @file{^exp^EXP^} perform normalization and
20429 expansion of the intermediate representation (abstract syntax tree, or AST).
20430 these files use the same numbering scheme as the parser and semantics files.
20431 For example, the construction of record initialization procedures is done in
20432 @file{exp_ch3.adb}.
20435 The files prefixed with @file{^bind^BIND^} implement the binder, which
20436 verifies the consistency of the compilation, determines an order of
20437 elaboration, and generates the bind file.
20440 The files @file{atree.ads} and @file{atree.adb} detail the low-level
20441 data structures used by the front-end.
20444 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
20445 the abstract syntax tree as produced by the parser.
20448 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
20449 all entities, computed during semantic analysis.
20452 Library management issues are dealt with in files with prefix
20458 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
20459 defined in Annex A.
20464 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
20465 defined in Annex B.
20469 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
20470 both language-defined children and GNAT run-time routines.
20474 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
20475 general-purpose packages, fully documented in their specifications. All
20476 the other @file{.c} files are modifications of common @command{gcc} files.
20479 @node Getting Internal Debugging Information
20480 @section Getting Internal Debugging Information
20483 Most compilers have internal debugging switches and modes. GNAT
20484 does also, except GNAT internal debugging switches and modes are not
20485 secret. A summary and full description of all the compiler and binder
20486 debug flags are in the file @file{debug.adb}. You must obtain the
20487 sources of the compiler to see the full detailed effects of these flags.
20489 The switches that print the source of the program (reconstructed from
20490 the internal tree) are of general interest for user programs, as are the
20492 the full internal tree, and the entity table (the symbol table
20493 information). The reconstructed source provides a readable version of the
20494 program after the front-end has completed analysis and expansion,
20495 and is useful when studying the performance of specific constructs.
20496 For example, constraint checks are indicated, complex aggregates
20497 are replaced with loops and assignments, and tasking primitives
20498 are replaced with run-time calls.
20500 @node Stack Traceback
20501 @section Stack Traceback
20503 @cindex stack traceback
20504 @cindex stack unwinding
20507 Traceback is a mechanism to display the sequence of subprogram calls that
20508 leads to a specified execution point in a program. Often (but not always)
20509 the execution point is an instruction at which an exception has been raised.
20510 This mechanism is also known as @i{stack unwinding} because it obtains
20511 its information by scanning the run-time stack and recovering the activation
20512 records of all active subprograms. Stack unwinding is one of the most
20513 important tools for program debugging.
20515 The first entry stored in traceback corresponds to the deepest calling level,
20516 that is to say the subprogram currently executing the instruction
20517 from which we want to obtain the traceback.
20519 Note that there is no runtime performance penalty when stack traceback
20520 is enabled, and no exception is raised during program execution.
20523 * Non-Symbolic Traceback::
20524 * Symbolic Traceback::
20527 @node Non-Symbolic Traceback
20528 @subsection Non-Symbolic Traceback
20529 @cindex traceback, non-symbolic
20532 Note: this feature is not supported on all platforms. See
20533 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
20537 * Tracebacks From an Unhandled Exception::
20538 * Tracebacks From Exception Occurrences (non-symbolic)::
20539 * Tracebacks From Anywhere in a Program (non-symbolic)::
20542 @node Tracebacks From an Unhandled Exception
20543 @subsubsection Tracebacks From an Unhandled Exception
20546 A runtime non-symbolic traceback is a list of addresses of call instructions.
20547 To enable this feature you must use the @option{-E}
20548 @code{gnatbind}'s option. With this option a stack traceback is stored as part
20549 of exception information. You can retrieve this information using the
20550 @code{addr2line} tool.
20552 Here is a simple example:
20554 @smallexample @c ada
20560 raise Constraint_Error;
20575 $ gnatmake stb -bargs -E
20578 Execution terminated by unhandled exception
20579 Exception name: CONSTRAINT_ERROR
20581 Call stack traceback locations:
20582 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
20586 As we see the traceback lists a sequence of addresses for the unhandled
20587 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
20588 guess that this exception come from procedure P1. To translate these
20589 addresses into the source lines where the calls appear, the
20590 @code{addr2line} tool, described below, is invaluable. The use of this tool
20591 requires the program to be compiled with debug information.
20594 $ gnatmake -g stb -bargs -E
20597 Execution terminated by unhandled exception
20598 Exception name: CONSTRAINT_ERROR
20600 Call stack traceback locations:
20601 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
20603 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
20604 0x4011f1 0x77e892a4
20606 00401373 at d:/stb/stb.adb:5
20607 0040138B at d:/stb/stb.adb:10
20608 0040139C at d:/stb/stb.adb:14
20609 00401335 at d:/stb/b~stb.adb:104
20610 004011C4 at /build/.../crt1.c:200
20611 004011F1 at /build/.../crt1.c:222
20612 77E892A4 in ?? at ??:0
20616 The @code{addr2line} tool has several other useful options:
20620 to get the function name corresponding to any location
20622 @item --demangle=gnat
20623 to use the gnat decoding mode for the function names. Note that
20624 for binutils version 2.9.x the option is simply @option{--demangle}.
20628 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
20629 0x40139c 0x401335 0x4011c4 0x4011f1
20631 00401373 in stb.p1 at d:/stb/stb.adb:5
20632 0040138B in stb.p2 at d:/stb/stb.adb:10
20633 0040139C in stb at d:/stb/stb.adb:14
20634 00401335 in main at d:/stb/b~stb.adb:104
20635 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
20636 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
20640 From this traceback we can see that the exception was raised in
20641 @file{stb.adb} at line 5, which was reached from a procedure call in
20642 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
20643 which contains the call to the main program.
20644 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
20645 and the output will vary from platform to platform.
20647 It is also possible to use @code{GDB} with these traceback addresses to debug
20648 the program. For example, we can break at a given code location, as reported
20649 in the stack traceback:
20655 Furthermore, this feature is not implemented inside Windows DLL. Only
20656 the non-symbolic traceback is reported in this case.
20659 (gdb) break *0x401373
20660 Breakpoint 1 at 0x401373: file stb.adb, line 5.
20664 It is important to note that the stack traceback addresses
20665 do not change when debug information is included. This is particularly useful
20666 because it makes it possible to release software without debug information (to
20667 minimize object size), get a field report that includes a stack traceback
20668 whenever an internal bug occurs, and then be able to retrieve the sequence
20669 of calls with the same program compiled with debug information.
20671 @node Tracebacks From Exception Occurrences (non-symbolic)
20672 @subsubsection Tracebacks From Exception Occurrences
20675 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
20676 The stack traceback is attached to the exception information string, and can
20677 be retrieved in an exception handler within the Ada program, by means of the
20678 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
20680 @smallexample @c ada
20682 with Ada.Exceptions;
20687 use Ada.Exceptions;
20695 Text_IO.Put_Line (Exception_Information (E));
20709 This program will output:
20714 Exception name: CONSTRAINT_ERROR
20715 Message: stb.adb:12
20716 Call stack traceback locations:
20717 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
20720 @node Tracebacks From Anywhere in a Program (non-symbolic)
20721 @subsubsection Tracebacks From Anywhere in a Program
20724 It is also possible to retrieve a stack traceback from anywhere in a
20725 program. For this you need to
20726 use the @code{GNAT.Traceback} API. This package includes a procedure called
20727 @code{Call_Chain} that computes a complete stack traceback, as well as useful
20728 display procedures described below. It is not necessary to use the
20729 @option{-E gnatbind} option in this case, because the stack traceback mechanism
20730 is invoked explicitly.
20733 In the following example we compute a traceback at a specific location in
20734 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
20735 convert addresses to strings:
20737 @smallexample @c ada
20739 with GNAT.Traceback;
20740 with GNAT.Debug_Utilities;
20746 use GNAT.Traceback;
20749 TB : Tracebacks_Array (1 .. 10);
20750 -- We are asking for a maximum of 10 stack frames.
20752 -- Len will receive the actual number of stack frames returned.
20754 Call_Chain (TB, Len);
20756 Text_IO.Put ("In STB.P1 : ");
20758 for K in 1 .. Len loop
20759 Text_IO.Put (Debug_Utilities.Image (TB (K)));
20780 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
20781 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
20785 You can then get further information by invoking the @code{addr2line}
20786 tool as described earlier (note that the hexadecimal addresses
20787 need to be specified in C format, with a leading ``0x'').
20789 @node Symbolic Traceback
20790 @subsection Symbolic Traceback
20791 @cindex traceback, symbolic
20794 A symbolic traceback is a stack traceback in which procedure names are
20795 associated with each code location.
20798 Note that this feature is not supported on all platforms. See
20799 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
20800 list of currently supported platforms.
20803 Note that the symbolic traceback requires that the program be compiled
20804 with debug information. If it is not compiled with debug information
20805 only the non-symbolic information will be valid.
20808 * Tracebacks From Exception Occurrences (symbolic)::
20809 * Tracebacks From Anywhere in a Program (symbolic)::
20812 @node Tracebacks From Exception Occurrences (symbolic)
20813 @subsubsection Tracebacks From Exception Occurrences
20815 @smallexample @c ada
20817 with GNAT.Traceback.Symbolic;
20823 raise Constraint_Error;
20840 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
20845 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
20848 0040149F in stb.p1 at stb.adb:8
20849 004014B7 in stb.p2 at stb.adb:13
20850 004014CF in stb.p3 at stb.adb:18
20851 004015DD in ada.stb at stb.adb:22
20852 00401461 in main at b~stb.adb:168
20853 004011C4 in __mingw_CRTStartup at crt1.c:200
20854 004011F1 in mainCRTStartup at crt1.c:222
20855 77E892A4 in ?? at ??:0
20859 In the above example the ``.\'' syntax in the @command{gnatmake} command
20860 is currently required by @command{addr2line} for files that are in
20861 the current working directory.
20862 Moreover, the exact sequence of linker options may vary from platform
20864 The above @option{-largs} section is for Windows platforms. By contrast,
20865 under Unix there is no need for the @option{-largs} section.
20866 Differences across platforms are due to details of linker implementation.
20868 @node Tracebacks From Anywhere in a Program (symbolic)
20869 @subsubsection Tracebacks From Anywhere in a Program
20872 It is possible to get a symbolic stack traceback
20873 from anywhere in a program, just as for non-symbolic tracebacks.
20874 The first step is to obtain a non-symbolic
20875 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
20876 information. Here is an example:
20878 @smallexample @c ada
20880 with GNAT.Traceback;
20881 with GNAT.Traceback.Symbolic;
20886 use GNAT.Traceback;
20887 use GNAT.Traceback.Symbolic;
20890 TB : Tracebacks_Array (1 .. 10);
20891 -- We are asking for a maximum of 10 stack frames.
20893 -- Len will receive the actual number of stack frames returned.
20895 Call_Chain (TB, Len);
20896 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20909 @c ******************************
20911 @node Compatibility with HP Ada
20912 @chapter Compatibility with HP Ada
20913 @cindex Compatibility
20918 @cindex Compatibility between GNAT and HP Ada
20919 This chapter compares HP Ada (formerly known as ``DEC Ada'')
20920 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
20921 GNAT is highly compatible
20922 with HP Ada, and it should generally be straightforward to port code
20923 from the HP Ada environment to GNAT. However, there are a few language
20924 and implementation differences of which the user must be aware. These
20925 differences are discussed in this chapter. In
20926 addition, the operating environment and command structure for the
20927 compiler are different, and these differences are also discussed.
20929 For further details on these and other compatibility issues,
20930 see Appendix E of the HP publication
20931 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
20933 Except where otherwise indicated, the description of GNAT for OpenVMS
20934 applies to both the Alpha and I64 platforms.
20936 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
20937 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
20939 The discussion in this chapter addresses specifically the implementation
20940 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
20941 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
20942 GNAT always follows the Alpha implementation.
20944 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
20945 attributes are recognized, although only a subset of them can sensibly
20946 be implemented. The description of pragmas in the
20947 @cite{GNAT Reference Manual} indicates whether or not they are applicable
20948 to non-VMS systems.
20951 * Ada 95 Compatibility::
20952 * Differences in the Definition of Package System::
20953 * Language-Related Features::
20954 * The Package STANDARD::
20955 * The Package SYSTEM::
20956 * Tasking and Task-Related Features::
20957 * Pragmas and Pragma-Related Features::
20958 * Library of Predefined Units::
20960 * Main Program Definition::
20961 * Implementation-Defined Attributes::
20962 * Compiler and Run-Time Interfacing::
20963 * Program Compilation and Library Management::
20965 * Implementation Limits::
20966 * Tools and Utilities::
20969 @node Ada 95 Compatibility
20970 @section Ada 95 Compatibility
20973 GNAT is an Ada 95 compiler, and HP Ada is an Ada 83
20974 compiler. Ada 95 is almost completely upwards compatible
20975 with Ada 83, and therefore Ada 83 programs will compile
20976 and run under GNAT with
20977 no changes or only minor changes. The Ada 95 Reference
20978 Manual provides details on specific incompatibilities.
20980 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
20981 as well as the pragma @code{ADA_83}, to force the compiler to
20982 operate in Ada 83 mode. This mode does not guarantee complete
20983 conformance to Ada 83, but in practice is sufficient to
20984 eliminate most sources of incompatibilities.
20985 In particular, it eliminates the recognition of the
20986 additional Ada 95 keywords, so that their use as identifiers
20987 in Ada 83 programs is legal, and handles the cases of packages
20988 with optional bodies, and generics that instantiate unconstrained
20989 types without the use of @code{(<>)}.
20991 @node Differences in the Definition of Package System
20992 @section Differences in the Definition of Package @code{System}
20995 Both Ada 95 and Ada 83 permit a compiler to add
20996 implementation-dependent declarations to package @code{System}.
20998 GNAT does not take advantage of this permission, and the version of
20999 @code{System} provided by GNAT exactly matches that in Ada 95.
21001 However, HP Ada adds an extensive set of declarations to package
21003 as fully documented in the HP Ada manuals. To minimize changes required
21004 for programs that make use of these extensions, GNAT provides the pragma
21005 @code{Extend_System} for extending the definition of package System. By using:
21006 @cindex pragma @code{Extend_System}
21007 @cindex @code{Extend_System} pragma
21009 @smallexample @c ada
21012 pragma Extend_System (Aux_DEC);
21018 the set of definitions in @code{System} is extended to include those in
21019 package @code{System.Aux_DEC}.
21020 @cindex @code{System.Aux_DEC} package
21021 @cindex @code{Aux_DEC} package (child of @code{System})
21022 These definitions are incorporated directly into package @code{System},
21023 as though they had been declared there. For a
21024 list of the declarations added, see the specification of this package,
21025 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
21026 @cindex @file{s-auxdec.ads} file
21027 The pragma @code{Extend_System} is a configuration pragma, which means that
21028 it can be placed in the file @file{gnat.adc}, so that it will automatically
21029 apply to all subsequent compilations. See @ref{Configuration Pragmas},
21030 for further details.
21032 An alternative approach that avoids the use of the non-standard
21033 @code{Extend_System} pragma is to add a context clause to the unit that
21034 references these facilities:
21036 @smallexample @c ada
21038 with System.Aux_DEC;
21039 use System.Aux_DEC;
21044 The effect is not quite semantically identical to incorporating
21045 the declarations directly into package @code{System},
21046 but most programs will not notice a difference
21047 unless they use prefix notation (e.g. @code{System.Integer_8})
21048 to reference the entities directly in package @code{System}.
21049 For units containing such references,
21050 the prefixes must either be removed, or the pragma @code{Extend_System}
21053 @node Language-Related Features
21054 @section Language-Related Features
21057 The following sections highlight differences in types,
21058 representations of types, operations, alignment, and
21062 * Integer Types and Representations::
21063 * Floating-Point Types and Representations::
21064 * Pragmas Float_Representation and Long_Float::
21065 * Fixed-Point Types and Representations::
21066 * Record and Array Component Alignment::
21067 * Address Clauses::
21068 * Other Representation Clauses::
21071 @node Integer Types and Representations
21072 @subsection Integer Types and Representations
21075 The set of predefined integer types is identical in HP Ada and GNAT.
21076 Furthermore the representation of these integer types is also identical,
21077 including the capability of size clauses forcing biased representation.
21080 HP Ada for OpenVMS Alpha systems has defined the
21081 following additional integer types in package @code{System}:
21098 @code{LARGEST_INTEGER}
21102 In GNAT, the first four of these types may be obtained from the
21103 standard Ada 95 package @code{Interfaces}.
21104 Alternatively, by use of the pragma @code{Extend_System}, identical
21105 declarations can be referenced directly in package @code{System}.
21106 On both GNAT and HP Ada, the maximum integer size is 64 bits.
21108 @node Floating-Point Types and Representations
21109 @subsection Floating-Point Types and Representations
21110 @cindex Floating-Point types
21113 The set of predefined floating-point types is identical in HP Ada and GNAT.
21114 Furthermore the representation of these floating-point
21115 types is also identical. One important difference is that the default
21116 representation for HP Ada is @code{VAX_Float}, but the default representation
21119 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
21120 pragma @code{Float_Representation} as described in the HP Ada
21122 For example, the declarations:
21124 @smallexample @c ada
21126 type F_Float is digits 6;
21127 pragma Float_Representation (VAX_Float, F_Float);
21132 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
21134 This set of declarations actually appears in @code{System.Aux_DEC},
21136 the full set of additional floating-point declarations provided in
21137 the HP Ada version of package @code{System}.
21138 This and similar declarations may be accessed in a user program
21139 by using pragma @code{Extend_System}. The use of this
21140 pragma, and the related pragma @code{Long_Float} is described in further
21141 detail in the following section.
21143 @node Pragmas Float_Representation and Long_Float
21144 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
21147 HP Ada provides the pragma @code{Float_Representation}, which
21148 acts as a program library switch to allow control over
21149 the internal representation chosen for the predefined
21150 floating-point types declared in the package @code{Standard}.
21151 The format of this pragma is as follows:
21153 @smallexample @c ada
21155 pragma Float_Representation(VAX_Float | IEEE_Float);
21160 This pragma controls the representation of floating-point
21165 @code{VAX_Float} specifies that floating-point
21166 types are represented by default with the VAX system hardware types
21167 @code{F-floating}, @code{D-floating}, @code{G-floating}.
21168 Note that the @code{H-floating}
21169 type was available only on VAX systems, and is not available
21170 in either HP Ada or GNAT.
21173 @code{IEEE_Float} specifies that floating-point
21174 types are represented by default with the IEEE single and
21175 double floating-point types.
21179 GNAT provides an identical implementation of the pragma
21180 @code{Float_Representation}, except that it functions as a
21181 configuration pragma. Note that the
21182 notion of configuration pragma corresponds closely to the
21183 HP Ada notion of a program library switch.
21185 When no pragma is used in GNAT, the default is @code{IEEE_Float},
21187 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
21188 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
21189 advisable to change the format of numbers passed to standard library
21190 routines, and if necessary explicit type conversions may be needed.
21192 The use of @code{IEEE_Float} is recommended in GNAT since it is more
21193 efficient, and (given that it conforms to an international standard)
21194 potentially more portable.
21195 The situation in which @code{VAX_Float} may be useful is in interfacing
21196 to existing code and data that expect the use of @code{VAX_Float}.
21197 In such a situation use the predefined @code{VAX_Float}
21198 types in package @code{System}, as extended by
21199 @code{Extend_System}. For example, use @code{System.F_Float}
21200 to specify the 32-bit @code{F-Float} format.
21203 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
21204 to allow control over the internal representation chosen
21205 for the predefined type @code{Long_Float} and for floating-point
21206 type declarations with digits specified in the range 7 .. 15.
21207 The format of this pragma is as follows:
21209 @smallexample @c ada
21211 pragma Long_Float (D_FLOAT | G_FLOAT);
21215 @node Fixed-Point Types and Representations
21216 @subsection Fixed-Point Types and Representations
21219 On HP Ada for OpenVMS Alpha systems, rounding is
21220 away from zero for both positive and negative numbers.
21221 Therefore, @code{+0.5} rounds to @code{1},
21222 and @code{-0.5} rounds to @code{-1}.
21224 On GNAT the results of operations
21225 on fixed-point types are in accordance with the Ada 95
21226 rules. In particular, results of operations on decimal
21227 fixed-point types are truncated.
21229 @node Record and Array Component Alignment
21230 @subsection Record and Array Component Alignment
21233 On HP Ada for OpenVMS Alpha, all non composite components
21234 are aligned on natural boundaries. For example, 1-byte
21235 components are aligned on byte boundaries, 2-byte
21236 components on 2-byte boundaries, 4-byte components on 4-byte
21237 byte boundaries, and so on. The OpenVMS Alpha hardware
21238 runs more efficiently with naturally aligned data.
21240 On GNAT, alignment rules are compatible
21241 with HP Ada for OpenVMS Alpha.
21243 @node Address Clauses
21244 @subsection Address Clauses
21247 In HP Ada and GNAT, address clauses are supported for
21248 objects and imported subprograms.
21249 The predefined type @code{System.Address} is a private type
21250 in both compilers on Alpha OpenVMS, with the same representation
21251 (it is simply a machine pointer). Addition, subtraction, and comparison
21252 operations are available in the standard Ada 95 package
21253 @code{System.Storage_Elements}, or in package @code{System}
21254 if it is extended to include @code{System.Aux_DEC} using a
21255 pragma @code{Extend_System} as previously described.
21257 Note that code that @code{with}'s both this extended package @code{System}
21258 and the package @code{System.Storage_Elements} should not @code{use}
21259 both packages, or ambiguities will result. In general it is better
21260 not to mix these two sets of facilities. The Ada 95 package was
21261 designed specifically to provide the kind of features that HP Ada
21262 adds directly to package @code{System}.
21264 The type @code{System.Address} is a 64-bit integer type in GNAT for
21265 I64 OpenVMS. For more information,
21266 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
21268 GNAT is compatible with HP Ada in its handling of address
21269 clauses, except for some limitations in
21270 the form of address clauses for composite objects with
21271 initialization. Such address clauses are easily replaced
21272 by the use of an explicitly-defined constant as described
21273 in the Ada 95 Reference Manual (13.1(22)). For example, the sequence
21276 @smallexample @c ada
21278 X, Y : Integer := Init_Func;
21279 Q : String (X .. Y) := "abc";
21281 for Q'Address use Compute_Address;
21286 will be rejected by GNAT, since the address cannot be computed at the time
21287 that @code{Q} is declared. To achieve the intended effect, write instead:
21289 @smallexample @c ada
21292 X, Y : Integer := Init_Func;
21293 Q_Address : constant Address := Compute_Address;
21294 Q : String (X .. Y) := "abc";
21296 for Q'Address use Q_Address;
21302 which will be accepted by GNAT (and other Ada 95 compilers), and is also
21303 compatible with Ada 83. A fuller description of the restrictions
21304 on address specifications is found in the @cite{GNAT Reference Manual}.
21306 @node Other Representation Clauses
21307 @subsection Other Representation Clauses
21310 GNAT implements in a compatible manner all the representation
21311 clauses supported by HP Ada. In addition, GNAT
21312 implements the representation clause forms that were introduced in Ada 95,
21313 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
21315 @node The Package STANDARD
21316 @section The Package @code{STANDARD}
21319 The package @code{STANDARD}, as implemented by HP Ada, is fully
21320 described in the Ada 95 Reference Manual and in the HP Ada
21321 Language Reference Manual. As implemented by GNAT, the
21322 package @code{STANDARD} is described in the Ada 95 Reference
21325 In addition, HP Ada supports the Latin-1 character set in
21326 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
21327 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
21328 the type @code{WIDE_CHARACTER}.
21330 The floating-point types supported by GNAT are those
21331 supported by HP Ada, but the defaults are different, and are controlled by
21332 pragmas. See @ref{Floating-Point Types and Representations}, for details.
21334 @node The Package SYSTEM
21335 @section The Package @code{SYSTEM}
21338 HP Ada provides a specific version of the package
21339 @code{SYSTEM} for each platform on which the language is implemented.
21340 For the complete specification of the package @code{SYSTEM}, see
21341 Appendix F of the @cite{HP Ada Language Reference Manual}.
21343 On HP Ada, the package @code{SYSTEM} includes the following conversion
21346 @item @code{TO_ADDRESS(INTEGER)}
21348 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
21350 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
21352 @item @code{TO_INTEGER(ADDRESS)}
21354 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
21356 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
21357 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
21361 By default, GNAT supplies a version of @code{SYSTEM} that matches
21362 the definition given in the Ada 95 Reference Manual.
21364 is a subset of the HP system definitions, which is as
21365 close as possible to the original definitions. The only difference
21366 is that the definition of @code{SYSTEM_NAME} is different:
21368 @smallexample @c ada
21370 type Name is (SYSTEM_NAME_GNAT);
21371 System_Name : constant Name := SYSTEM_NAME_GNAT;
21376 Also, GNAT adds the new Ada 95 declarations for
21377 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
21379 However, the use of the following pragma causes GNAT
21380 to extend the definition of package @code{SYSTEM} so that it
21381 encompasses the full set of HP-specific extensions,
21382 including the functions listed above:
21384 @smallexample @c ada
21386 pragma Extend_System (Aux_DEC);
21391 The pragma @code{Extend_System} is a configuration pragma that
21392 is most conveniently placed in the @file{gnat.adc} file. See the
21393 @cite{GNAT Reference Manual} for further details.
21395 HP Ada does not allow the recompilation of the package
21396 @code{SYSTEM}. Instead HP Ada provides several pragmas
21397 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
21398 to modify values in the package @code{SYSTEM}.
21399 On OpenVMS Alpha systems, the pragma
21400 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
21401 its single argument.
21403 GNAT does permit the recompilation of package @code{SYSTEM} using
21404 the special switch @option{-gnatg}, and this switch can be used if
21405 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
21406 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
21407 or @code{MEMORY_SIZE} by any other means.
21409 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
21410 enumeration literal @code{SYSTEM_NAME_GNAT}.
21412 The definitions provided by the use of
21414 @smallexample @c ada
21415 pragma Extend_System (AUX_Dec);
21419 are virtually identical to those provided by the HP Ada 83 package
21420 @code{SYSTEM}. One important difference is that the name of the
21422 function for type @code{UNSIGNED_LONGWORD} is changed to
21423 @code{TO_ADDRESS_LONG}.
21424 See the @cite{GNAT Reference Manual} for a discussion of why this change was
21428 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
21430 an extension to Ada 83 not strictly compatible with the reference manual.
21431 GNAT, in order to be exactly compatible with the standard,
21432 does not provide this capability. In HP Ada 83, the
21433 point of this definition is to deal with a call like:
21435 @smallexample @c ada
21436 TO_ADDRESS (16#12777#);
21440 Normally, according to Ada 83 semantics, one would expect this to be
21441 ambiguous, since it matches both the @code{INTEGER} and
21442 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
21443 However, in HP Ada 83, there is no ambiguity, since the
21444 definition using @i{universal_integer} takes precedence.
21446 In GNAT, since the version with @i{universal_integer} cannot be supplied,
21448 not possible to be 100% compatible. Since there are many programs using
21449 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
21451 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
21452 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
21454 @smallexample @c ada
21455 function To_Address (X : Integer) return Address;
21456 pragma Pure_Function (To_Address);
21458 function To_Address_Long (X : Unsigned_Longword) return Address;
21459 pragma Pure_Function (To_Address_Long);
21463 This means that programs using @code{TO_ADDRESS} for
21464 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
21466 @node Tasking and Task-Related Features
21467 @section Tasking and Task-Related Features
21470 This section compares the treatment of tasking in GNAT
21471 and in HP Ada for OpenVMS Alpha.
21472 The GNAT description applies to both Alpha and I64 OpenVMS.
21473 For detailed information on tasking in
21474 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
21475 relevant run-time reference manual.
21478 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
21479 * Assigning Task IDs::
21480 * Task IDs and Delays::
21481 * Task-Related Pragmas::
21482 * Scheduling and Task Priority::
21484 * External Interrupts::
21487 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
21488 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
21491 On OpenVMS Alpha systems, each Ada task (except a passive
21492 task) is implemented as a single stream of execution
21493 that is created and managed by the kernel. On these
21494 systems, HP Ada tasking support is based on DECthreads,
21495 an implementation of the POSIX standard for threads.
21497 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
21498 code that calls DECthreads routines can be used together.
21499 The interaction between Ada tasks and DECthreads routines
21500 can have some benefits. For example when on OpenVMS Alpha,
21501 HP Ada can call C code that is already threaded.
21503 GNAT uses the facilities of DECthreads,
21504 and Ada tasks are mapped to threads.
21506 @node Assigning Task IDs
21507 @subsection Assigning Task IDs
21510 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
21511 the environment task that executes the main program. On
21512 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
21513 that have been created but are not yet activated.
21515 On OpenVMS Alpha systems, task IDs are assigned at
21516 activation. On GNAT systems, task IDs are also assigned at
21517 task creation but do not have the same form or values as
21518 task ID values in HP Ada. There is no null task, and the
21519 environment task does not have a specific task ID value.
21521 @node Task IDs and Delays
21522 @subsection Task IDs and Delays
21525 On OpenVMS Alpha systems, tasking delays are implemented
21526 using Timer System Services. The Task ID is used for the
21527 identification of the timer request (the @code{REQIDT} parameter).
21528 If Timers are used in the application take care not to use
21529 @code{0} for the identification, because cancelling such a timer
21530 will cancel all timers and may lead to unpredictable results.
21532 @node Task-Related Pragmas
21533 @subsection Task-Related Pragmas
21536 Ada supplies the pragma @code{TASK_STORAGE}, which allows
21537 specification of the size of the guard area for a task
21538 stack. (The guard area forms an area of memory that has no
21539 read or write access and thus helps in the detection of
21540 stack overflow.) On OpenVMS Alpha systems, if the pragma
21541 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
21542 area is created. In the absence of a pragma @code{TASK_STORAGE},
21543 a default guard area is created.
21545 GNAT supplies the following task-related pragmas:
21548 @item @code{TASK_INFO}
21550 This pragma appears within a task definition and
21551 applies to the task in which it appears. The argument
21552 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
21554 @item @code{TASK_STORAGE}
21556 GNAT implements pragma @code{TASK_STORAGE} in the same way as
21558 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
21559 @code{SUPPRESS}, and @code{VOLATILE}.
21561 @node Scheduling and Task Priority
21562 @subsection Scheduling and Task Priority
21565 HP Ada implements the Ada language requirement that
21566 when two tasks are eligible for execution and they have
21567 different priorities, the lower priority task does not
21568 execute while the higher priority task is waiting. The HP
21569 Ada Run-Time Library keeps a task running until either the
21570 task is suspended or a higher priority task becomes ready.
21572 On OpenVMS Alpha systems, the default strategy is round-
21573 robin with preemption. Tasks of equal priority take turns
21574 at the processor. A task is run for a certain period of
21575 time and then placed at the tail of the ready queue for
21576 its priority level.
21578 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
21579 which can be used to enable or disable round-robin
21580 scheduling of tasks with the same priority.
21581 See the relevant HP Ada run-time reference manual for
21582 information on using the pragmas to control HP Ada task
21585 GNAT follows the scheduling rules of Annex D (Real-Time
21586 Annex) of the Ada 95 Reference Manual. In general, this
21587 scheduling strategy is fully compatible with HP Ada
21588 although it provides some additional constraints (as
21589 fully documented in Annex D).
21590 GNAT implements time slicing control in a manner compatible with
21591 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
21592 are identical to the HP Ada 83 pragma of the same name.
21593 Note that it is not possible to mix GNAT tasking and
21594 HP Ada 83 tasking in the same program, since the two run-time
21595 libraries are not compatible.
21597 @node The Task Stack
21598 @subsection The Task Stack
21601 In HP Ada, a task stack is allocated each time a
21602 non-passive task is activated. As soon as the task is
21603 terminated, the storage for the task stack is deallocated.
21604 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
21605 a default stack size is used. Also, regardless of the size
21606 specified, some additional space is allocated for task
21607 management purposes. On OpenVMS Alpha systems, at least
21608 one page is allocated.
21610 GNAT handles task stacks in a similar manner. In accordance with
21611 the Ada 95 rules, it provides the pragma @code{STORAGE_SIZE} as
21612 an alternative method for controlling the task stack size.
21613 The specification of the attribute @code{T'STORAGE_SIZE} is also
21614 supported in a manner compatible with HP Ada.
21616 @node External Interrupts
21617 @subsection External Interrupts
21620 On HP Ada, external interrupts can be associated with task entries.
21621 GNAT is compatible with HP Ada in its handling of external interrupts.
21623 @node Pragmas and Pragma-Related Features
21624 @section Pragmas and Pragma-Related Features
21627 Both HP Ada and GNAT supply all language-defined pragmas
21628 as specified by the Ada 83 standard. GNAT also supplies all
21629 language-defined pragmas specified in the Ada 95 Reference Manual.
21630 In addition, GNAT implements the implementation-defined pragmas
21634 @item @code{AST_ENTRY}
21636 @item @code{COMMON_OBJECT}
21638 @item @code{COMPONENT_ALIGNMENT}
21640 @item @code{EXPORT_EXCEPTION}
21642 @item @code{EXPORT_FUNCTION}
21644 @item @code{EXPORT_OBJECT}
21646 @item @code{EXPORT_PROCEDURE}
21648 @item @code{EXPORT_VALUED_PROCEDURE}
21650 @item @code{FLOAT_REPRESENTATION}
21654 @item @code{IMPORT_EXCEPTION}
21656 @item @code{IMPORT_FUNCTION}
21658 @item @code{IMPORT_OBJECT}
21660 @item @code{IMPORT_PROCEDURE}
21662 @item @code{IMPORT_VALUED_PROCEDURE}
21664 @item @code{INLINE_GENERIC}
21666 @item @code{INTERFACE_NAME}
21668 @item @code{LONG_FLOAT}
21670 @item @code{MAIN_STORAGE}
21672 @item @code{PASSIVE}
21674 @item @code{PSET_OBJECT}
21676 @item @code{SHARE_GENERIC}
21678 @item @code{SUPPRESS_ALL}
21680 @item @code{TASK_STORAGE}
21682 @item @code{TIME_SLICE}
21688 These pragmas are all fully implemented, with the exception of @code{TITLE},
21689 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
21690 recognized, but which have no
21691 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
21692 use of protected objects in Ada 95. In GNAT, all generics are inlined.
21694 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
21695 a separate subprogram specification which must appear before the
21698 GNAT also supplies a number of implementation-defined pragmas as follows:
21700 @item @code{ABORT_DEFER}
21702 @item @code{ADA_83}
21704 @item @code{ADA_95}
21706 @item @code{ADA_05}
21708 @item @code{ANNOTATE}
21710 @item @code{ASSERT}
21712 @item @code{C_PASS_BY_COPY}
21714 @item @code{CPP_CLASS}
21716 @item @code{CPP_CONSTRUCTOR}
21718 @item @code{CPP_DESTRUCTOR}
21720 @item @code{CPP_VIRTUAL}
21722 @item @code{CPP_VTABLE}
21726 @item @code{EXTEND_SYSTEM}
21728 @item @code{LINKER_ALIAS}
21730 @item @code{LINKER_SECTION}
21732 @item @code{MACHINE_ATTRIBUTE}
21734 @item @code{NO_RETURN}
21736 @item @code{PURE_FUNCTION}
21738 @item @code{SOURCE_FILE_NAME}
21740 @item @code{SOURCE_REFERENCE}
21742 @item @code{TASK_INFO}
21744 @item @code{UNCHECKED_UNION}
21746 @item @code{UNIMPLEMENTED_UNIT}
21748 @item @code{UNIVERSAL_DATA}
21750 @item @code{UNSUPPRESS}
21752 @item @code{WARNINGS}
21754 @item @code{WEAK_EXTERNAL}
21758 For full details on these GNAT implementation-defined pragmas, see
21759 the GNAT Reference Manual.
21762 * Restrictions on the Pragma INLINE::
21763 * Restrictions on the Pragma INTERFACE::
21764 * Restrictions on the Pragma SYSTEM_NAME::
21767 @node Restrictions on the Pragma INLINE
21768 @subsection Restrictions on Pragma @code{INLINE}
21771 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
21773 @item Parameters cannot have a task type.
21775 @item Function results cannot be task types, unconstrained
21776 array types, or unconstrained types with discriminants.
21778 @item Bodies cannot declare the following:
21780 @item Subprogram body or stub (imported subprogram is allowed)
21784 @item Generic declarations
21786 @item Instantiations
21790 @item Access types (types derived from access types allowed)
21792 @item Array or record types
21794 @item Dependent tasks
21796 @item Direct recursive calls of subprogram or containing
21797 subprogram, directly or via a renaming
21803 In GNAT, the only restriction on pragma @code{INLINE} is that the
21804 body must occur before the call if both are in the same
21805 unit, and the size must be appropriately small. There are
21806 no other specific restrictions which cause subprograms to
21807 be incapable of being inlined.
21809 @node Restrictions on the Pragma INTERFACE
21810 @subsection Restrictions on Pragma @code{INTERFACE}
21813 The following restrictions on pragma @code{INTERFACE}
21814 are enforced by both HP Ada and GNAT:
21816 @item Languages accepted: Ada, Bliss, C, Fortran, Default.
21817 Default is the default on OpenVMS Alpha systems.
21819 @item Parameter passing: Language specifies default
21820 mechanisms but can be overridden with an @code{EXPORT} pragma.
21823 @item Ada: Use internal Ada rules.
21825 @item Bliss, C: Parameters must be mode @code{in}; cannot be
21826 record or task type. Result cannot be a string, an
21827 array, or a record.
21829 @item Fortran: Parameters cannot have a task type. Result cannot
21830 be a string, an array, or a record.
21835 GNAT is entirely upwards compatible with HP Ada, and in addition allows
21836 record parameters for all languages.
21838 @node Restrictions on the Pragma SYSTEM_NAME
21839 @subsection Restrictions on Pragma @code{SYSTEM_NAME}
21842 For HP Ada for OpenVMS Alpha, the enumeration literal
21843 for the type @code{NAME} is @code{OPENVMS_AXP}.
21844 In GNAT, the enumeration
21845 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
21847 @node Library of Predefined Units
21848 @section Library of Predefined Units
21851 A library of predefined units is provided as part of the
21852 HP Ada and GNAT implementations. HP Ada does not provide
21853 the package @code{MACHINE_CODE} but instead recommends importing
21856 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
21857 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
21859 The HP Ada Predefined Library units are modified to remove Ada 95
21860 incompatibilities and to make them interoperable with GNAT
21861 (@pxref{Changes to DECLIB}, for details).
21862 The units are located in the @file{DECLIB} directory.
21864 The GNAT RTL is contained in
21865 the @file{ADALIB} directory, and
21866 the default search path is set up to find @code{DECLIB} units in preference
21867 to @code{ADALIB} units with the same name (@code{TEXT_IO},
21868 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
21871 * Changes to DECLIB::
21874 @node Changes to DECLIB
21875 @subsection Changes to @code{DECLIB}
21878 The changes made to the HP Ada predefined library for GNAT and Ada 95
21879 compatibility are minor and include the following:
21882 @item Adjusting the location of pragmas and record representation
21883 clauses to obey Ada 95 rules
21885 @item Adding the proper notation to generic formal parameters
21886 that take unconstrained types in instantiation
21888 @item Adding pragma @code{ELABORATE_BODY} to package specifications
21889 that have package bodies not otherwise allowed
21891 @item Replacing occurrences of the identifier ``@code{PROTECTED}'' by
21892 ``@code{PROTECTD}''.
21893 Currently these are found only in the @code{STARLET} package spec.
21895 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
21896 where the address size is constrained to 32 bits.
21900 None of the above changes is visible to users.
21906 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
21909 @item Command Language Interpreter (CLI interface)
21911 @item DECtalk Run-Time Library (DTK interface)
21913 @item Librarian utility routines (LBR interface)
21915 @item General Purpose Run-Time Library (LIB interface)
21917 @item Math Run-Time Library (MTH interface)
21919 @item National Character Set Run-Time Library (NCS interface)
21921 @item Compiled Code Support Run-Time Library (OTS interface)
21923 @item Parallel Processing Run-Time Library (PPL interface)
21925 @item Screen Management Run-Time Library (SMG interface)
21927 @item Sort Run-Time Library (SOR interface)
21929 @item String Run-Time Library (STR interface)
21931 @item STARLET System Library
21934 @item X Window System Version 11R4 and 11R5 (X, XLIB interface)
21936 @item X Windows Toolkit (XT interface)
21938 @item X/Motif Version 1.1.3 and 1.2 (XM interface)
21942 GNAT provides implementations of these HP bindings in the @code{DECLIB}
21945 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
21947 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
21948 A pragma @code{Linker_Options} has been added to packages @code{Xm},
21949 @code{Xt}, and @code{X_Lib}
21950 causing the default X/Motif sharable image libraries to be linked in. This
21951 is done via options files named @file{xm.opt}, @file{xt.opt}, and
21952 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
21954 It may be necessary to edit these options files to update or correct the
21955 library names if, for example, the newer X/Motif bindings from
21956 @file{ADA$EXAMPLES}
21957 had been (previous to installing GNAT) copied and renamed to supersede the
21958 default @file{ADA$PREDEFINED} versions.
21961 * Shared Libraries and Options Files::
21962 * Interfaces to C::
21965 @node Shared Libraries and Options Files
21966 @subsection Shared Libraries and Options Files
21969 When using the HP Ada
21970 predefined X and Motif bindings, the linking with their sharable images is
21971 done automatically by @command{GNAT LINK}.
21972 When using other X and Motif bindings, you need
21973 to add the corresponding sharable images to the command line for
21974 @code{GNAT LINK}. When linking with shared libraries, or with
21975 @file{.OPT} files, you must
21976 also add them to the command line for @command{GNAT LINK}.
21978 A shared library to be used with GNAT is built in the same way as other
21979 libraries under VMS. The VMS Link command can be used in standard fashion.
21981 @node Interfaces to C
21982 @subsection Interfaces to C
21986 provides the following Ada types and operations:
21989 @item C types package (@code{C_TYPES})
21991 @item C strings (@code{C_TYPES.NULL_TERMINATED})
21993 @item Other_types (@code{SHORT_INT})
21997 Interfacing to C with GNAT, you can use the above approach
21998 described for HP Ada or the facilities of Annex B of
21999 the Ada 95 Reference Manual (packages @code{INTERFACES.C},
22000 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
22001 information, see the section ``Interfacing to C'' in the
22002 @cite{GNAT Reference Manual}.
22004 The @option{-gnatF} qualifier forces default and explicit
22005 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
22006 to be uppercased for compatibility with the default behavior
22007 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
22009 @node Main Program Definition
22010 @section Main Program Definition
22013 The following section discusses differences in the
22014 definition of main programs on HP Ada and GNAT.
22015 On HP Ada, main programs are defined to meet the
22016 following conditions:
22018 @item Procedure with no formal parameters (returns @code{0} upon
22021 @item Procedure with no formal parameters (returns @code{42} when
22022 an unhandled exception is raised)
22024 @item Function with no formal parameters whose returned value
22025 is of a discrete type
22027 @item Procedure with one @code{out} formal of a discrete type for
22028 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE}
22034 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
22035 a main function or main procedure returns a discrete
22036 value whose size is less than 64 bits (32 on VAX systems),
22037 the value is zero- or sign-extended as appropriate.
22038 On GNAT, main programs are defined as follows:
22040 @item Must be a non-generic, parameterless subprogram that
22041 is either a procedure or function returning an Ada
22042 @code{STANDARD.INTEGER} (the predefined type)
22044 @item Cannot be a generic subprogram or an instantiation of a
22048 @node Implementation-Defined Attributes
22049 @section Implementation-Defined Attributes
22052 GNAT provides all HP Ada implementation-defined
22055 @node Compiler and Run-Time Interfacing
22056 @section Compiler and Run-Time Interfacing
22059 HP Ada provides the following qualifiers to pass options to the linker
22062 @item @option{/WAIT} and @option{/SUBMIT}
22064 @item @option{/COMMAND}
22066 @item @option{/[NO]MAP}
22068 @item @option{/OUTPUT=@i{file-spec}}
22070 @item @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK}
22074 To pass options to the linker, GNAT provides the following
22078 @item @option{/EXECUTABLE=@i{exec-name}}
22080 @item @option{/VERBOSE}
22082 @item @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK}
22086 For more information on these switches, see
22087 @ref{Switches for gnatlink}.
22088 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
22089 to control optimization. HP Ada also supplies the
22092 @item @code{OPTIMIZE}
22094 @item @code{INLINE}
22096 @item @code{INLINE_GENERIC}
22098 @item @code{SUPPRESS_ALL}
22100 @item @code{PASSIVE}
22104 In GNAT, optimization is controlled strictly by command
22105 line parameters, as described in the corresponding section of this guide.
22106 The HP pragmas for control of optimization are
22107 recognized but ignored.
22109 Note that in GNAT, the default is optimization off, whereas in HP Ada
22110 the default is that optimization is turned on.
22112 @node Program Compilation and Library Management
22113 @section Program Compilation and Library Management
22116 HP Ada and GNAT provide a comparable set of commands to
22117 build programs. HP Ada also provides a program library,
22118 which is a concept that does not exist on GNAT. Instead,
22119 GNAT provides directories of sources that are compiled as
22122 The following table summarizes
22123 the HP Ada commands and provides
22124 equivalent GNAT commands. In this table, some GNAT
22125 equivalents reflect the fact that GNAT does not use the
22126 concept of a program library. Instead, it uses a model
22127 in which collections of source and object files are used
22128 in a manner consistent with other languages like C and
22129 Fortran. Therefore, standard system file commands are used
22130 to manipulate these elements. Those GNAT commands are marked with
22132 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
22135 @multitable @columnfractions .35 .65
22137 @item @emph{HP Ada Command}
22138 @tab @emph{GNAT Equivalent / Description}
22140 @item @command{ADA}
22141 @tab @command{GNAT COMPILE}@*
22142 Invokes the compiler to compile one or more Ada source files.
22144 @item @command{ACS ATTACH}@*
22145 @tab [No equivalent]@*
22146 Switches control of terminal from current process running the program
22149 @item @command{ACS CHECK}
22150 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
22151 Forms the execution closure of one
22152 or more compiled units and checks completeness and currency.
22154 @item @command{ACS COMPILE}
22155 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
22156 Forms the execution closure of one or
22157 more specified units, checks completeness and currency,
22158 identifies units that have revised source files, compiles same,
22159 and recompiles units that are or will become obsolete.
22160 Also completes incomplete generic instantiations.
22162 @item @command{ACS COPY FOREIGN}
22164 Copies a foreign object file into the program library as a
22167 @item @command{ACS COPY UNIT}
22169 Copies a compiled unit from one program library to another.
22171 @item @command{ACS CREATE LIBRARY}
22172 @tab Create /directory (*)@*
22173 Creates a program library.
22175 @item @command{ACS CREATE SUBLIBRARY}
22176 @tab Create /directory (*)@*
22177 Creates a program sublibrary.
22179 @item @command{ACS DELETE LIBRARY}
22181 Deletes a program library and its contents.
22183 @item @command{ACS DELETE SUBLIBRARY}
22185 Deletes a program sublibrary and its contents.
22187 @item @command{ACS DELETE UNIT}
22188 @tab Delete file (*)@*
22189 On OpenVMS systems, deletes one or more compiled units from
22190 the current program library.
22192 @item @command{ACS DIRECTORY}
22193 @tab Directory (*)@*
22194 On OpenVMS systems, lists units contained in the current
22197 @item @command{ACS ENTER FOREIGN}
22199 Allows the import of a foreign body as an Ada library
22200 specification and enters a reference to a pointer.
22202 @item @command{ACS ENTER UNIT}
22204 Enters a reference (pointer) from the current program library to
22205 a unit compiled into another program library.
22207 @item @command{ACS EXIT}
22208 @tab [No equivalent]@*
22209 Exits from the program library manager.
22211 @item @command{ACS EXPORT}
22213 Creates an object file that contains system-specific object code
22214 for one or more units. With GNAT, object files can simply be copied
22215 into the desired directory.
22217 @item @command{ACS EXTRACT SOURCE}
22219 Allows access to the copied source file for each Ada compilation unit
22221 @item @command{ACS HELP}
22222 @tab @command{HELP GNAT}@*
22223 Provides online help.
22225 @item @command{ACS LINK}
22226 @tab @command{GNAT LINK}@*
22227 Links an object file containing Ada units into an executable file.
22229 @item @command{ACS LOAD}
22231 Loads (partially compiles) Ada units into the program library.
22232 Allows loading a program from a collection of files into a library
22233 without knowing the relationship among units.
22235 @item @command{ACS MERGE}
22237 Merges into the current program library, one or more units from
22238 another library where they were modified.
22240 @item @command{ACS RECOMPILE}
22241 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
22242 Recompiles from external or copied source files any obsolete
22243 unit in the closure. Also, completes any incomplete generic
22246 @item @command{ACS REENTER}
22247 @tab @command{GNAT MAKE}@*
22248 Reenters current references to units compiled after last entered
22249 with the @command{ACS ENTER UNIT} command.
22251 @item @command{ACS SET LIBRARY}
22252 @tab Set default (*)@*
22253 Defines a program library to be the compilation context as well
22254 as the target library for compiler output and commands in general.
22256 @item @command{ACS SET PRAGMA}
22257 @tab Edit @file{gnat.adc} (*)@*
22258 Redefines specified values of the library characteristics
22259 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
22260 and @code{Float_Representation}.
22262 @item @command{ACS SET SOURCE}
22263 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
22264 Defines the source file search list for the @command{ACS COMPILE} command.
22266 @item @command{ACS SHOW LIBRARY}
22267 @tab Directory (*)@*
22268 Lists information about one or more program libraries.
22270 @item @command{ACS SHOW PROGRAM}
22271 @tab [No equivalent]@*
22272 Lists information about the execution closure of one or
22273 more units in the program library.
22275 @item @command{ACS SHOW SOURCE}
22276 @tab Show logical @code{ADA_INCLUDE_PATH}@*
22277 Shows the source file search used when compiling units.
22279 @item @command{ACS SHOW VERSION}
22280 @tab Compile with @option{VERBOSE} option
22281 Displays the version number of the compiler and program library
22284 @item @command{ACS SPAWN}
22285 @tab [No equivalent]@*
22286 Creates a subprocess of the current process (same as @command{DCL SPAWN}
22289 @item @command{ACS VERIFY}
22290 @tab [No equivalent]@*
22291 Performs a series of consistency checks on a program library to
22292 determine whether the library structure and library files are in
22299 @section Input-Output
22302 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
22303 Management Services (RMS) to perform operations on
22307 HP Ada and GNAT predefine an identical set of input-
22308 output packages. To make the use of the
22309 generic @code{TEXT_IO} operations more convenient, HP Ada
22310 provides predefined library packages that instantiate the
22311 integer and floating-point operations for the predefined
22312 integer and floating-point types as shown in the following table.
22314 @multitable @columnfractions .45 .55
22315 @item @emph{Package Name} @tab Instantiation
22317 @item @code{INTEGER_TEXT_IO}
22318 @tab @code{INTEGER_IO(INTEGER)}
22320 @item @code{SHORT_INTEGER_TEXT_IO}
22321 @tab @code{INTEGER_IO(SHORT_INTEGER)}
22323 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
22324 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
22326 @item @code{FLOAT_TEXT_IO}
22327 @tab @code{FLOAT_IO(FLOAT)}
22329 @item @code{LONG_FLOAT_TEXT_IO}
22330 @tab @code{FLOAT_IO(LONG_FLOAT)}
22334 The HP Ada predefined packages and their operations
22335 are implemented using OpenVMS Alpha files and input-output
22336 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
22337 Familiarity with the following is recommended:
22339 @item RMS file organizations and access methods
22341 @item OpenVMS file specifications and directories
22343 @item OpenVMS File Definition Language (FDL)
22347 GNAT provides I/O facilities that are completely
22348 compatible with HP Ada. The distribution includes the
22349 standard HP Ada versions of all I/O packages, operating
22350 in a manner compatible with HP Ada. In particular, the
22351 following packages are by default the HP Ada (Ada 83)
22352 versions of these packages rather than the renamings
22353 suggested in Annex J of the Ada 95 Reference Manual:
22355 @item @code{TEXT_IO}
22357 @item @code{SEQUENTIAL_IO}
22359 @item @code{DIRECT_IO}
22363 The use of the standard Ada 95 syntax for child packages (for
22364 example, @code{ADA.TEXT_IO}) retrieves the Ada 95 versions of these
22365 packages, as defined in the Ada 95 Reference Manual.
22366 GNAT provides HP-compatible predefined instantiations
22367 of the @code{TEXT_IO} packages, and also
22368 provides the standard predefined instantiations required
22369 by the Ada 95 Reference Manual.
22371 For further information on how GNAT interfaces to the file
22372 system or how I/O is implemented in programs written in
22373 mixed languages, see the chapter ``Implementation of the
22374 Standard I/O'' in the @cite{GNAT Reference Manual}.
22375 This chapter covers the following:
22377 @item Standard I/O packages
22379 @item @code{FORM} strings
22381 @item @code{ADA.DIRECT_IO}
22383 @item @code{ADA.SEQUENTIAL_IO}
22385 @item @code{ADA.TEXT_IO}
22387 @item Stream pointer positioning
22389 @item Reading and writing non-regular files
22391 @item @code{GET_IMMEDIATE}
22393 @item Treating @code{TEXT_IO} files as streams
22400 @node Implementation Limits
22401 @section Implementation Limits
22404 The following table lists implementation limits for HP Ada
22406 @multitable @columnfractions .60 .20 .20
22408 @item @emph{Compilation Parameter}
22413 @item In a subprogram or entry declaration, maximum number of
22414 formal parameters that are of an unconstrained record type
22419 @item Maximum identifier length (number of characters)
22424 @item Maximum number of characters in a source line
22429 @item Maximum collection size (number of bytes)
22434 @item Maximum number of discriminants for a record type
22439 @item Maximum number of formal parameters in an entry or
22440 subprogram declaration
22445 @item Maximum number of dimensions in an array type
22450 @item Maximum number of library units and subunits in a compilation.
22455 @item Maximum number of library units and subunits in an execution.
22460 @item Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
22461 or @code{PSECT_OBJECT}
22466 @item Maximum number of enumeration literals in an enumeration type
22472 @item Maximum number of lines in a source file
22477 @item Maximum number of bits in any object
22482 @item Maximum size of the static portion of a stack frame (approximate)
22487 @node Tools and Utilities
22488 @section Tools and Utilities
22491 The following table lists some of the OpenVMS development tools
22492 available for HP Ada, and the corresponding tools for
22493 use with @value{EDITION} on Alpha and I64 platforms.
22494 Aside from the debugger, all the OpenVMS tools identified are part
22495 of the DECset package.
22498 @c Specify table in TeX since Texinfo does a poor job
22502 \settabs\+Language-Sensitive Editor\quad
22503 &Product with HP Ada\quad
22506 &\it Product with HP Ada
22507 & \it Product with GNAT Pro\cr
22509 \+Code Management System
22513 \+Language-Sensitive Editor
22515 & emacs or HP LSE (Alpha)\cr
22525 & OpenVMS Debug (I64)\cr
22527 \+Source Code Analyzer /
22544 \+Coverage Analyzer
22548 \+Module Management
22550 & Not applicable\cr
22560 @c This is the Texinfo version of the table. It renders poorly in pdf, hence
22561 @c the TeX version above for the printed version
22563 @c @multitable @columnfractions .3 .4 .4
22564 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
22566 @tab @i{Tool with HP Ada}
22567 @tab @i{Tool with @value{EDITION}}
22568 @item Code Management@*System
22571 @item Language-Sensitive@*Editor
22573 @tab emacs or HP LSE (Alpha)
22582 @tab OpenVMS Debug (I64)
22583 @item Source Code Analyzer /@*Cross Referencer
22587 @tab HP Digital Test@*Manager (DTM)
22589 @item Performance and@*Coverage Analyzer
22592 @item Module Management@*System
22594 @tab Not applicable
22601 @c **************************************
22602 @node Platform-Specific Information for the Run-Time Libraries
22603 @appendix Platform-Specific Information for the Run-Time Libraries
22604 @cindex Tasking and threads libraries
22605 @cindex Threads libraries and tasking
22606 @cindex Run-time libraries (platform-specific information)
22609 The GNAT run-time implementation may vary with respect to both the
22610 underlying threads library and the exception handling scheme.
22611 For threads support, one or more of the following are supplied:
22613 @item @b{native threads library}, a binding to the thread package from
22614 the underlying operating system
22616 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
22617 POSIX thread package
22621 For exception handling, either or both of two models are supplied:
22623 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
22624 Most programs should experience a substantial speed improvement by
22625 being compiled with a ZCX run-time.
22626 This is especially true for
22627 tasking applications or applications with many exception handlers.}
22628 @cindex Zero-Cost Exceptions
22629 @cindex ZCX (Zero-Cost Exceptions)
22630 which uses binder-generated tables that
22631 are interrogated at run time to locate a handler
22633 @item @b{setjmp / longjmp} (``SJLJ''),
22634 @cindex setjmp/longjmp Exception Model
22635 @cindex SJLJ (setjmp/longjmp Exception Model)
22636 which uses dynamically-set data to establish
22637 the set of handlers
22641 This appendix summarizes which combinations of threads and exception support
22642 are supplied on various GNAT platforms.
22643 It then shows how to select a particular library either
22644 permanently or temporarily,
22645 explains the properties of (and tradeoffs among) the various threads
22646 libraries, and provides some additional
22647 information about several specific platforms.
22650 * Summary of Run-Time Configurations::
22651 * Specifying a Run-Time Library::
22652 * Choosing the Scheduling Policy::
22653 * Solaris-Specific Considerations::
22654 * Linux-Specific Considerations::
22655 * AIX-Specific Considerations::
22658 @node Summary of Run-Time Configurations
22659 @section Summary of Run-Time Configurations
22661 @multitable @columnfractions .30 .70
22662 @item @b{alpha-openvms}
22663 @item @code{@ @ }@i{rts-native (default)}
22664 @item @code{@ @ @ @ }Tasking @tab native VMS threads
22665 @item @code{@ @ @ @ }Exceptions @tab ZCX
22667 @item @b{alpha-tru64}
22668 @item @code{@ @ }@i{rts-native (default)}
22669 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
22670 @item @code{@ @ @ @ }Exceptions @tab ZCX
22672 @item @code{@ @ }@i{rts-sjlj}
22673 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
22674 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22676 @item @b{ia64-hp_linux}
22677 @item @code{@ @ }@i{rts-native (default)}
22678 @item @code{@ @ @ @ }Tasking @tab pthread library
22679 @item @code{@ @ @ @ }Exceptions @tab ZCX
22681 @item @b{ia64-hpux}
22682 @item @code{@ @ }@i{rts-native (default)}
22683 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
22684 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22686 @item @b{ia64-openvms}
22687 @item @code{@ @ }@i{rts-native (default)}
22688 @item @code{@ @ @ @ }Tasking @tab native VMS threads
22689 @item @code{@ @ @ @ }Exceptions @tab ZCX
22691 @item @b{ia64-sgi_linux}
22692 @item @code{@ @ }@i{rts-native (default)}
22693 @item @code{@ @ @ @ }Tasking @tab pthread library
22694 @item @code{@ @ @ @ }Exceptions @tab ZCX
22696 @item @b{mips-irix}
22697 @item @code{@ @ }@i{rts-native (default)}
22698 @item @code{@ @ @ @ }Tasking @tab native IRIX threads
22699 @item @code{@ @ @ @ }Exceptions @tab ZCX
22702 @item @code{@ @ }@i{rts-native (default)}
22703 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
22704 @item @code{@ @ @ @ }Exceptions @tab ZCX
22706 @item @code{@ @ }@i{rts-sjlj}
22707 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
22708 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22711 @item @code{@ @ }@i{rts-native (default)}
22712 @item @code{@ @ @ @ }Tasking @tab native AIX threads
22713 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22715 @item @b{ppc-darwin}
22716 @item @code{@ @ }@i{rts-native (default)}
22717 @item @code{@ @ @ @ }Tasking @tab native MacOS threads
22718 @item @code{@ @ @ @ }Exceptions @tab ZCX
22720 @item @b{sparc-solaris} @tab
22721 @item @code{@ @ }@i{rts-native (default)}
22722 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
22723 @item @code{@ @ @ @ }Exceptions @tab ZCX
22725 @item @code{@ @ }@i{rts-m64}
22726 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
22727 @item @code{@ @ @ @ }Exceptions @tab ZCX
22728 @item @code{@ @ @ @ }Constraints @tab Use only when compiling in 64-bit mode;
22729 @item @tab Use only on Solaris 8 or later.
22730 @item @tab @xref{Building and Debugging 64-bit Applications}, for details.
22732 @item @code{@ @ }@i{rts-pthread}
22733 @item @code{@ @ @ @ }Tasking @tab pthread library
22734 @item @code{@ @ @ @ }Exceptions @tab ZCX
22736 @item @code{@ @ }@i{rts-sjlj}
22737 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
22738 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22740 @item @b{x86-linux}
22741 @item @code{@ @ }@i{rts-native (default)}
22742 @item @code{@ @ @ @ }Tasking @tab pthread library
22743 @item @code{@ @ @ @ }Exceptions @tab ZCX
22745 @item @code{@ @ }@i{rts-sjlj}
22746 @item @code{@ @ @ @ }Tasking @tab pthread library
22747 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22750 @item @code{@ @ }@i{rts-native (default)}
22751 @item @code{@ @ @ @ }Tasking @tab native LynxOS threads
22752 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22754 @item @b{x86-windows}
22755 @item @code{@ @ }@i{rts-native (default)}
22756 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
22757 @item @code{@ @ @ @ }Exceptions @tab ZCX
22759 @item @code{@ @ }@i{rts-sjlj (default)}
22760 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
22761 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22763 @item @b{x86_64-linux}
22764 @item @code{@ @ }@i{rts-native (default)}
22765 @item @code{@ @ @ @ }Tasking @tab pthread library
22766 @item @code{@ @ @ @ }Exceptions @tab ZCX
22768 @item @code{@ @ }@i{rts-sjlj}
22769 @item @code{@ @ @ @ }Tasking @tab pthread library
22770 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22774 @node Specifying a Run-Time Library
22775 @section Specifying a Run-Time Library
22778 The @file{adainclude} subdirectory containing the sources of the GNAT
22779 run-time library, and the @file{adalib} subdirectory containing the
22780 @file{ALI} files and the static and/or shared GNAT library, are located
22781 in the gcc target-dependent area:
22784 target=$prefix/lib/gcc-lib/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
22788 As indicated above, on some platforms several run-time libraries are supplied.
22789 These libraries are installed in the target dependent area and
22790 contain a complete source and binary subdirectory. The detailed description
22791 below explains the differences between the different libraries in terms of
22792 their thread support.
22794 The default run-time library (when GNAT is installed) is @emph{rts-native}.
22795 This default run time is selected by the means of soft links.
22796 For example on x86-linux:
22802 +--- adainclude----------+
22804 +--- adalib-----------+ |
22806 +--- rts-native | |
22808 | +--- adainclude <---+
22810 | +--- adalib <----+
22821 If the @i{rts-sjlj} library is to be selected on a permanent basis,
22822 these soft links can be modified with the following commands:
22826 $ rm -f adainclude adalib
22827 $ ln -s rts-sjlj/adainclude adainclude
22828 $ ln -s rts-sjlj/adalib adalib
22832 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
22833 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
22834 @file{$target/ada_object_path}.
22836 Selecting another run-time library temporarily can be
22837 achieved by the regular mechanism for GNAT object or source path selection:
22841 Set the environment variables:
22844 $ ADA_INCLUDE_PATH=$target/rts-sjlj/adainclude:$ADA_INCLUDE_PATH
22845 $ ADA_OBJECTS_PATH=$target/rts-sjlj/adalib:$ADA_OBJECTS_PATH
22846 $ export ADA_INCLUDE_PATH ADA_OBJECTS_PATH
22850 Use @option{-aI$target/rts-sjlj/adainclude}
22851 and @option{-aO$target/rts-sjlj/adalib}
22852 on the @command{gnatmake} command line
22855 Use the switch @option{--RTS}; e.g., @option{--RTS=sjlj}
22856 @cindex @option{--RTS} option
22859 @node Choosing the Scheduling Policy
22860 @section Choosing the Scheduling Policy
22863 When using a POSIX threads implementation, you have a choice of several
22864 scheduling policies: @code{SCHED_FIFO},
22865 @cindex @code{SCHED_FIFO} scheduling policy
22867 @cindex @code{SCHED_RR} scheduling policy
22868 and @code{SCHED_OTHER}.
22869 @cindex @code{SCHED_OTHER} scheduling policy
22870 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
22871 or @code{SCHED_RR} requires special (e.g., root) privileges.
22873 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
22875 @cindex @code{SCHED_FIFO} scheduling policy
22876 you can use one of the following:
22880 @code{pragma Time_Slice (0.0)}
22881 @cindex pragma Time_Slice
22883 the corresponding binder option @option{-T0}
22884 @cindex @option{-T0} option
22886 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22887 @cindex pragma Task_Dispatching_Policy
22891 To specify @code{SCHED_RR},
22892 @cindex @code{SCHED_RR} scheduling policy
22893 you should use @code{pragma Time_Slice} with a
22894 value greater than @code{0.0}, or else use the corresponding @option{-T}
22897 @node Solaris-Specific Considerations
22898 @section Solaris-Specific Considerations
22899 @cindex Solaris Sparc threads libraries
22902 This section addresses some topics related to the various threads libraries
22903 on Sparc Solaris and then provides some information on building and
22904 debugging 64-bit applications.
22907 * Solaris Threads Issues::
22908 * Building and Debugging 64-bit Applications::
22911 @node Solaris Threads Issues
22912 @subsection Solaris Threads Issues
22915 GNAT under Solaris comes with an alternate tasking run-time library
22916 based on POSIX threads --- @emph{rts-pthread}.
22917 @cindex rts-pthread threads library
22918 This run-time library has the advantage of being mostly shared across all
22919 POSIX-compliant thread implementations, and it also provides under
22920 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
22921 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
22922 and @code{PTHREAD_PRIO_PROTECT}
22923 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
22924 semantics that can be selected using the predefined pragma
22925 @code{Locking_Policy}
22926 @cindex pragma Locking_Policy (under rts-pthread)
22928 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
22929 @cindex @code{Inheritance_Locking} (under rts-pthread)
22930 @cindex @code{Ceiling_Locking} (under rts-pthread)
22932 As explained above, the native run-time library is based on the Solaris thread
22933 library (@code{libthread}) and is the default library.
22935 When the Solaris threads library is used (this is the default), programs
22936 compiled with GNAT can automatically take advantage of
22937 and can thus execute on multiple processors.
22938 The user can alternatively specify a processor on which the program should run
22939 to emulate a single-processor system. The multiprocessor / uniprocessor choice
22941 setting the environment variable @code{GNAT_PROCESSOR}
22942 @cindex @code{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
22943 to one of the following:
22947 Use the default configuration (run the program on all
22948 available processors) - this is the same as having
22949 @code{GNAT_PROCESSOR} unset
22952 Let the run-time implementation choose one processor and run the program on
22955 @item 0 .. Last_Proc
22956 Run the program on the specified processor.
22957 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
22958 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
22961 @node Building and Debugging 64-bit Applications
22962 @subsection Building and Debugging 64-bit Applications
22965 In a 64-bit application, all the sources involved must be compiled with the
22966 @option{-m64} command-line option, and a specific GNAT library (compiled with
22967 this option) is required.
22968 The easiest way to build a 64bit application is to add
22969 @option{-m64 --RTS=m64} to the @command{gnatmake} flags.
22971 To debug these applications, a special version of gdb called @command{gdb64}
22974 To summarize, building and debugging a ``Hello World'' program in 64-bit mode
22978 $ gnatmake -m64 -g --RTS=m64 hello.adb
22982 @node Linux-Specific Considerations
22983 @section Linux-Specific Considerations
22984 @cindex Linux threads libraries
22987 On GNU/Linux without NPTL support (usually system with GNU C Library
22988 older than 2.3), the signal model is not POSIX compliant, which means
22989 that to send a signal to the process, you need to send the signal to all
22990 threads, e.g. by using @code{killpg()}.
22992 @node AIX-Specific Considerations
22993 @section AIX-Specific Considerations
22994 @cindex AIX resolver library
22997 On AIX, the resolver library initializes some internal structure on
22998 the first call to @code{get*by*} functions, which are used to implement
22999 @code{GNAT.Sockets.Get_Host_By_Name} and
23000 @code{GNAT.Sockets.Get_Host_By_Addrss}.
23001 If such initialization occurs within an Ada task, and the stack size for
23002 the task is the default size, a stack overflow may occur.
23004 To avoid this overflow, the user should either ensure that the first call
23005 to @code{GNAT.Sockets.Get_Host_By_Name} or
23006 @code{GNAT.Sockets.Get_Host_By_Addrss}
23007 occurs in the environment task, or use @code{pragma Storage_Size} to
23008 specify a sufficiently large size for the stack of the task that contains
23011 @c *******************************
23012 @node Example of Binder Output File
23013 @appendix Example of Binder Output File
23016 This Appendix displays the source code for @command{gnatbind}'s output
23017 file generated for a simple ``Hello World'' program.
23018 Comments have been added for clarification purposes.
23020 @smallexample @c adanocomment
23024 -- The package is called Ada_Main unless this name is actually used
23025 -- as a unit name in the partition, in which case some other unique
23029 package ada_main is
23031 Elab_Final_Code : Integer;
23032 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
23034 -- The main program saves the parameters (argument count,
23035 -- argument values, environment pointer) in global variables
23036 -- for later access by other units including
23037 -- Ada.Command_Line.
23039 gnat_argc : Integer;
23040 gnat_argv : System.Address;
23041 gnat_envp : System.Address;
23043 -- The actual variables are stored in a library routine. This
23044 -- is useful for some shared library situations, where there
23045 -- are problems if variables are not in the library.
23047 pragma Import (C, gnat_argc);
23048 pragma Import (C, gnat_argv);
23049 pragma Import (C, gnat_envp);
23051 -- The exit status is similarly an external location
23053 gnat_exit_status : Integer;
23054 pragma Import (C, gnat_exit_status);
23056 GNAT_Version : constant String :=
23057 "GNAT Version: 3.15w (20010315)";
23058 pragma Export (C, GNAT_Version, "__gnat_version");
23060 -- This is the generated adafinal routine that performs
23061 -- finalization at the end of execution. In the case where
23062 -- Ada is the main program, this main program makes a call
23063 -- to adafinal at program termination.
23065 procedure adafinal;
23066 pragma Export (C, adafinal, "adafinal");
23068 -- This is the generated adainit routine that performs
23069 -- initialization at the start of execution. In the case
23070 -- where Ada is the main program, this main program makes
23071 -- a call to adainit at program startup.
23074 pragma Export (C, adainit, "adainit");
23076 -- This routine is called at the start of execution. It is
23077 -- a dummy routine that is used by the debugger to breakpoint
23078 -- at the start of execution.
23080 procedure Break_Start;
23081 pragma Import (C, Break_Start, "__gnat_break_start");
23083 -- This is the actual generated main program (it would be
23084 -- suppressed if the no main program switch were used). As
23085 -- required by standard system conventions, this program has
23086 -- the external name main.
23090 argv : System.Address;
23091 envp : System.Address)
23093 pragma Export (C, main, "main");
23095 -- The following set of constants give the version
23096 -- identification values for every unit in the bound
23097 -- partition. This identification is computed from all
23098 -- dependent semantic units, and corresponds to the
23099 -- string that would be returned by use of the
23100 -- Body_Version or Version attributes.
23102 type Version_32 is mod 2 ** 32;
23103 u00001 : constant Version_32 := 16#7880BEB3#;
23104 u00002 : constant Version_32 := 16#0D24CBD0#;
23105 u00003 : constant Version_32 := 16#3283DBEB#;
23106 u00004 : constant Version_32 := 16#2359F9ED#;
23107 u00005 : constant Version_32 := 16#664FB847#;
23108 u00006 : constant Version_32 := 16#68E803DF#;
23109 u00007 : constant Version_32 := 16#5572E604#;
23110 u00008 : constant Version_32 := 16#46B173D8#;
23111 u00009 : constant Version_32 := 16#156A40CF#;
23112 u00010 : constant Version_32 := 16#033DABE0#;
23113 u00011 : constant Version_32 := 16#6AB38FEA#;
23114 u00012 : constant Version_32 := 16#22B6217D#;
23115 u00013 : constant Version_32 := 16#68A22947#;
23116 u00014 : constant Version_32 := 16#18CC4A56#;
23117 u00015 : constant Version_32 := 16#08258E1B#;
23118 u00016 : constant Version_32 := 16#367D5222#;
23119 u00017 : constant Version_32 := 16#20C9ECA4#;
23120 u00018 : constant Version_32 := 16#50D32CB6#;
23121 u00019 : constant Version_32 := 16#39A8BB77#;
23122 u00020 : constant Version_32 := 16#5CF8FA2B#;
23123 u00021 : constant Version_32 := 16#2F1EB794#;
23124 u00022 : constant Version_32 := 16#31AB6444#;
23125 u00023 : constant Version_32 := 16#1574B6E9#;
23126 u00024 : constant Version_32 := 16#5109C189#;
23127 u00025 : constant Version_32 := 16#56D770CD#;
23128 u00026 : constant Version_32 := 16#02F9DE3D#;
23129 u00027 : constant Version_32 := 16#08AB6B2C#;
23130 u00028 : constant Version_32 := 16#3FA37670#;
23131 u00029 : constant Version_32 := 16#476457A0#;
23132 u00030 : constant Version_32 := 16#731E1B6E#;
23133 u00031 : constant Version_32 := 16#23C2E789#;
23134 u00032 : constant Version_32 := 16#0F1BD6A1#;
23135 u00033 : constant Version_32 := 16#7C25DE96#;
23136 u00034 : constant Version_32 := 16#39ADFFA2#;
23137 u00035 : constant Version_32 := 16#571DE3E7#;
23138 u00036 : constant Version_32 := 16#5EB646AB#;
23139 u00037 : constant Version_32 := 16#4249379B#;
23140 u00038 : constant Version_32 := 16#0357E00A#;
23141 u00039 : constant Version_32 := 16#3784FB72#;
23142 u00040 : constant Version_32 := 16#2E723019#;
23143 u00041 : constant Version_32 := 16#623358EA#;
23144 u00042 : constant Version_32 := 16#107F9465#;
23145 u00043 : constant Version_32 := 16#6843F68A#;
23146 u00044 : constant Version_32 := 16#63305874#;
23147 u00045 : constant Version_32 := 16#31E56CE1#;
23148 u00046 : constant Version_32 := 16#02917970#;
23149 u00047 : constant Version_32 := 16#6CCBA70E#;
23150 u00048 : constant Version_32 := 16#41CD4204#;
23151 u00049 : constant Version_32 := 16#572E3F58#;
23152 u00050 : constant Version_32 := 16#20729FF5#;
23153 u00051 : constant Version_32 := 16#1D4F93E8#;
23154 u00052 : constant Version_32 := 16#30B2EC3D#;
23155 u00053 : constant Version_32 := 16#34054F96#;
23156 u00054 : constant Version_32 := 16#5A199860#;
23157 u00055 : constant Version_32 := 16#0E7F912B#;
23158 u00056 : constant Version_32 := 16#5760634A#;
23159 u00057 : constant Version_32 := 16#5D851835#;
23161 -- The following Export pragmas export the version numbers
23162 -- with symbolic names ending in B (for body) or S
23163 -- (for spec) so that they can be located in a link. The
23164 -- information provided here is sufficient to track down
23165 -- the exact versions of units used in a given build.
23167 pragma Export (C, u00001, "helloB");
23168 pragma Export (C, u00002, "system__standard_libraryB");
23169 pragma Export (C, u00003, "system__standard_libraryS");
23170 pragma Export (C, u00004, "adaS");
23171 pragma Export (C, u00005, "ada__text_ioB");
23172 pragma Export (C, u00006, "ada__text_ioS");
23173 pragma Export (C, u00007, "ada__exceptionsB");
23174 pragma Export (C, u00008, "ada__exceptionsS");
23175 pragma Export (C, u00009, "gnatS");
23176 pragma Export (C, u00010, "gnat__heap_sort_aB");
23177 pragma Export (C, u00011, "gnat__heap_sort_aS");
23178 pragma Export (C, u00012, "systemS");
23179 pragma Export (C, u00013, "system__exception_tableB");
23180 pragma Export (C, u00014, "system__exception_tableS");
23181 pragma Export (C, u00015, "gnat__htableB");
23182 pragma Export (C, u00016, "gnat__htableS");
23183 pragma Export (C, u00017, "system__exceptionsS");
23184 pragma Export (C, u00018, "system__machine_state_operationsB");
23185 pragma Export (C, u00019, "system__machine_state_operationsS");
23186 pragma Export (C, u00020, "system__machine_codeS");
23187 pragma Export (C, u00021, "system__storage_elementsB");
23188 pragma Export (C, u00022, "system__storage_elementsS");
23189 pragma Export (C, u00023, "system__secondary_stackB");
23190 pragma Export (C, u00024, "system__secondary_stackS");
23191 pragma Export (C, u00025, "system__parametersB");
23192 pragma Export (C, u00026, "system__parametersS");
23193 pragma Export (C, u00027, "system__soft_linksB");
23194 pragma Export (C, u00028, "system__soft_linksS");
23195 pragma Export (C, u00029, "system__stack_checkingB");
23196 pragma Export (C, u00030, "system__stack_checkingS");
23197 pragma Export (C, u00031, "system__tracebackB");
23198 pragma Export (C, u00032, "system__tracebackS");
23199 pragma Export (C, u00033, "ada__streamsS");
23200 pragma Export (C, u00034, "ada__tagsB");
23201 pragma Export (C, u00035, "ada__tagsS");
23202 pragma Export (C, u00036, "system__string_opsB");
23203 pragma Export (C, u00037, "system__string_opsS");
23204 pragma Export (C, u00038, "interfacesS");
23205 pragma Export (C, u00039, "interfaces__c_streamsB");
23206 pragma Export (C, u00040, "interfaces__c_streamsS");
23207 pragma Export (C, u00041, "system__file_ioB");
23208 pragma Export (C, u00042, "system__file_ioS");
23209 pragma Export (C, u00043, "ada__finalizationB");
23210 pragma Export (C, u00044, "ada__finalizationS");
23211 pragma Export (C, u00045, "system__finalization_rootB");
23212 pragma Export (C, u00046, "system__finalization_rootS");
23213 pragma Export (C, u00047, "system__finalization_implementationB");
23214 pragma Export (C, u00048, "system__finalization_implementationS");
23215 pragma Export (C, u00049, "system__string_ops_concat_3B");
23216 pragma Export (C, u00050, "system__string_ops_concat_3S");
23217 pragma Export (C, u00051, "system__stream_attributesB");
23218 pragma Export (C, u00052, "system__stream_attributesS");
23219 pragma Export (C, u00053, "ada__io_exceptionsS");
23220 pragma Export (C, u00054, "system__unsigned_typesS");
23221 pragma Export (C, u00055, "system__file_control_blockS");
23222 pragma Export (C, u00056, "ada__finalization__list_controllerB");
23223 pragma Export (C, u00057, "ada__finalization__list_controllerS");
23225 -- BEGIN ELABORATION ORDER
23228 -- gnat.heap_sort_a (spec)
23229 -- gnat.heap_sort_a (body)
23230 -- gnat.htable (spec)
23231 -- gnat.htable (body)
23232 -- interfaces (spec)
23234 -- system.machine_code (spec)
23235 -- system.parameters (spec)
23236 -- system.parameters (body)
23237 -- interfaces.c_streams (spec)
23238 -- interfaces.c_streams (body)
23239 -- system.standard_library (spec)
23240 -- ada.exceptions (spec)
23241 -- system.exception_table (spec)
23242 -- system.exception_table (body)
23243 -- ada.io_exceptions (spec)
23244 -- system.exceptions (spec)
23245 -- system.storage_elements (spec)
23246 -- system.storage_elements (body)
23247 -- system.machine_state_operations (spec)
23248 -- system.machine_state_operations (body)
23249 -- system.secondary_stack (spec)
23250 -- system.stack_checking (spec)
23251 -- system.soft_links (spec)
23252 -- system.soft_links (body)
23253 -- system.stack_checking (body)
23254 -- system.secondary_stack (body)
23255 -- system.standard_library (body)
23256 -- system.string_ops (spec)
23257 -- system.string_ops (body)
23260 -- ada.streams (spec)
23261 -- system.finalization_root (spec)
23262 -- system.finalization_root (body)
23263 -- system.string_ops_concat_3 (spec)
23264 -- system.string_ops_concat_3 (body)
23265 -- system.traceback (spec)
23266 -- system.traceback (body)
23267 -- ada.exceptions (body)
23268 -- system.unsigned_types (spec)
23269 -- system.stream_attributes (spec)
23270 -- system.stream_attributes (body)
23271 -- system.finalization_implementation (spec)
23272 -- system.finalization_implementation (body)
23273 -- ada.finalization (spec)
23274 -- ada.finalization (body)
23275 -- ada.finalization.list_controller (spec)
23276 -- ada.finalization.list_controller (body)
23277 -- system.file_control_block (spec)
23278 -- system.file_io (spec)
23279 -- system.file_io (body)
23280 -- ada.text_io (spec)
23281 -- ada.text_io (body)
23283 -- END ELABORATION ORDER
23287 -- The following source file name pragmas allow the generated file
23288 -- names to be unique for different main programs. They are needed
23289 -- since the package name will always be Ada_Main.
23291 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
23292 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
23294 -- Generated package body for Ada_Main starts here
23296 package body ada_main is
23298 -- The actual finalization is performed by calling the
23299 -- library routine in System.Standard_Library.Adafinal
23301 procedure Do_Finalize;
23302 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
23309 procedure adainit is
23311 -- These booleans are set to True once the associated unit has
23312 -- been elaborated. It is also used to avoid elaborating the
23313 -- same unit twice.
23316 pragma Import (Ada, E040, "interfaces__c_streams_E");
23319 pragma Import (Ada, E008, "ada__exceptions_E");
23322 pragma Import (Ada, E014, "system__exception_table_E");
23325 pragma Import (Ada, E053, "ada__io_exceptions_E");
23328 pragma Import (Ada, E017, "system__exceptions_E");
23331 pragma Import (Ada, E024, "system__secondary_stack_E");
23334 pragma Import (Ada, E030, "system__stack_checking_E");
23337 pragma Import (Ada, E028, "system__soft_links_E");
23340 pragma Import (Ada, E035, "ada__tags_E");
23343 pragma Import (Ada, E033, "ada__streams_E");
23346 pragma Import (Ada, E046, "system__finalization_root_E");
23349 pragma Import (Ada, E048, "system__finalization_implementation_E");
23352 pragma Import (Ada, E044, "ada__finalization_E");
23355 pragma Import (Ada, E057, "ada__finalization__list_controller_E");
23358 pragma Import (Ada, E055, "system__file_control_block_E");
23361 pragma Import (Ada, E042, "system__file_io_E");
23364 pragma Import (Ada, E006, "ada__text_io_E");
23366 -- Set_Globals is a library routine that stores away the
23367 -- value of the indicated set of global values in global
23368 -- variables within the library.
23370 procedure Set_Globals
23371 (Main_Priority : Integer;
23372 Time_Slice_Value : Integer;
23373 WC_Encoding : Character;
23374 Locking_Policy : Character;
23375 Queuing_Policy : Character;
23376 Task_Dispatching_Policy : Character;
23377 Adafinal : System.Address;
23378 Unreserve_All_Interrupts : Integer;
23379 Exception_Tracebacks : Integer);
23380 @findex __gnat_set_globals
23381 pragma Import (C, Set_Globals, "__gnat_set_globals");
23383 -- SDP_Table_Build is a library routine used to build the
23384 -- exception tables. See unit Ada.Exceptions in files
23385 -- a-except.ads/adb for full details of how zero cost
23386 -- exception handling works. This procedure, the call to
23387 -- it, and the two following tables are all omitted if the
23388 -- build is in longjmp/setjump exception mode.
23390 @findex SDP_Table_Build
23391 @findex Zero Cost Exceptions
23392 procedure SDP_Table_Build
23393 (SDP_Addresses : System.Address;
23394 SDP_Count : Natural;
23395 Elab_Addresses : System.Address;
23396 Elab_Addr_Count : Natural);
23397 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
23399 -- Table of Unit_Exception_Table addresses. Used for zero
23400 -- cost exception handling to build the top level table.
23402 ST : aliased constant array (1 .. 23) of System.Address := (
23404 Ada.Text_Io'UET_Address,
23405 Ada.Exceptions'UET_Address,
23406 Gnat.Heap_Sort_A'UET_Address,
23407 System.Exception_Table'UET_Address,
23408 System.Machine_State_Operations'UET_Address,
23409 System.Secondary_Stack'UET_Address,
23410 System.Parameters'UET_Address,
23411 System.Soft_Links'UET_Address,
23412 System.Stack_Checking'UET_Address,
23413 System.Traceback'UET_Address,
23414 Ada.Streams'UET_Address,
23415 Ada.Tags'UET_Address,
23416 System.String_Ops'UET_Address,
23417 Interfaces.C_Streams'UET_Address,
23418 System.File_Io'UET_Address,
23419 Ada.Finalization'UET_Address,
23420 System.Finalization_Root'UET_Address,
23421 System.Finalization_Implementation'UET_Address,
23422 System.String_Ops_Concat_3'UET_Address,
23423 System.Stream_Attributes'UET_Address,
23424 System.File_Control_Block'UET_Address,
23425 Ada.Finalization.List_Controller'UET_Address);
23427 -- Table of addresses of elaboration routines. Used for
23428 -- zero cost exception handling to make sure these
23429 -- addresses are included in the top level procedure
23432 EA : aliased constant array (1 .. 23) of System.Address := (
23433 adainit'Code_Address,
23434 Do_Finalize'Code_Address,
23435 Ada.Exceptions'Elab_Spec'Address,
23436 System.Exceptions'Elab_Spec'Address,
23437 Interfaces.C_Streams'Elab_Spec'Address,
23438 System.Exception_Table'Elab_Body'Address,
23439 Ada.Io_Exceptions'Elab_Spec'Address,
23440 System.Stack_Checking'Elab_Spec'Address,
23441 System.Soft_Links'Elab_Body'Address,
23442 System.Secondary_Stack'Elab_Body'Address,
23443 Ada.Tags'Elab_Spec'Address,
23444 Ada.Tags'Elab_Body'Address,
23445 Ada.Streams'Elab_Spec'Address,
23446 System.Finalization_Root'Elab_Spec'Address,
23447 Ada.Exceptions'Elab_Body'Address,
23448 System.Finalization_Implementation'Elab_Spec'Address,
23449 System.Finalization_Implementation'Elab_Body'Address,
23450 Ada.Finalization'Elab_Spec'Address,
23451 Ada.Finalization.List_Controller'Elab_Spec'Address,
23452 System.File_Control_Block'Elab_Spec'Address,
23453 System.File_Io'Elab_Body'Address,
23454 Ada.Text_Io'Elab_Spec'Address,
23455 Ada.Text_Io'Elab_Body'Address);
23457 -- Start of processing for adainit
23461 -- Call SDP_Table_Build to build the top level procedure
23462 -- table for zero cost exception handling (omitted in
23463 -- longjmp/setjump mode).
23465 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
23467 -- Call Set_Globals to record various information for
23468 -- this partition. The values are derived by the binder
23469 -- from information stored in the ali files by the compiler.
23471 @findex __gnat_set_globals
23473 (Main_Priority => -1,
23474 -- Priority of main program, -1 if no pragma Priority used
23476 Time_Slice_Value => -1,
23477 -- Time slice from Time_Slice pragma, -1 if none used
23479 WC_Encoding => 'b',
23480 -- Wide_Character encoding used, default is brackets
23482 Locking_Policy => ' ',
23483 -- Locking_Policy used, default of space means not
23484 -- specified, otherwise it is the first character of
23485 -- the policy name.
23487 Queuing_Policy => ' ',
23488 -- Queuing_Policy used, default of space means not
23489 -- specified, otherwise it is the first character of
23490 -- the policy name.
23492 Task_Dispatching_Policy => ' ',
23493 -- Task_Dispatching_Policy used, default of space means
23494 -- not specified, otherwise first character of the
23497 Adafinal => System.Null_Address,
23498 -- Address of Adafinal routine, not used anymore
23500 Unreserve_All_Interrupts => 0,
23501 -- Set true if pragma Unreserve_All_Interrupts was used
23503 Exception_Tracebacks => 0);
23504 -- Indicates if exception tracebacks are enabled
23506 Elab_Final_Code := 1;
23508 -- Now we have the elaboration calls for all units in the partition.
23509 -- The Elab_Spec and Elab_Body attributes generate references to the
23510 -- implicit elaboration procedures generated by the compiler for
23511 -- each unit that requires elaboration.
23514 Interfaces.C_Streams'Elab_Spec;
23518 Ada.Exceptions'Elab_Spec;
23521 System.Exception_Table'Elab_Body;
23525 Ada.Io_Exceptions'Elab_Spec;
23529 System.Exceptions'Elab_Spec;
23533 System.Stack_Checking'Elab_Spec;
23536 System.Soft_Links'Elab_Body;
23541 System.Secondary_Stack'Elab_Body;
23545 Ada.Tags'Elab_Spec;
23548 Ada.Tags'Elab_Body;
23552 Ada.Streams'Elab_Spec;
23556 System.Finalization_Root'Elab_Spec;
23560 Ada.Exceptions'Elab_Body;
23564 System.Finalization_Implementation'Elab_Spec;
23567 System.Finalization_Implementation'Elab_Body;
23571 Ada.Finalization'Elab_Spec;
23575 Ada.Finalization.List_Controller'Elab_Spec;
23579 System.File_Control_Block'Elab_Spec;
23583 System.File_Io'Elab_Body;
23587 Ada.Text_Io'Elab_Spec;
23590 Ada.Text_Io'Elab_Body;
23594 Elab_Final_Code := 0;
23602 procedure adafinal is
23611 -- main is actually a function, as in the ANSI C standard,
23612 -- defined to return the exit status. The three parameters
23613 -- are the argument count, argument values and environment
23616 @findex Main Program
23619 argv : System.Address;
23620 envp : System.Address)
23623 -- The initialize routine performs low level system
23624 -- initialization using a standard library routine which
23625 -- sets up signal handling and performs any other
23626 -- required setup. The routine can be found in file
23629 @findex __gnat_initialize
23630 procedure initialize;
23631 pragma Import (C, initialize, "__gnat_initialize");
23633 -- The finalize routine performs low level system
23634 -- finalization using a standard library routine. The
23635 -- routine is found in file a-final.c and in the standard
23636 -- distribution is a dummy routine that does nothing, so
23637 -- really this is a hook for special user finalization.
23639 @findex __gnat_finalize
23640 procedure finalize;
23641 pragma Import (C, finalize, "__gnat_finalize");
23643 -- We get to the main program of the partition by using
23644 -- pragma Import because if we try to with the unit and
23645 -- call it Ada style, then not only do we waste time
23646 -- recompiling it, but also, we don't really know the right
23647 -- switches (e.g. identifier character set) to be used
23650 procedure Ada_Main_Program;
23651 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
23653 -- Start of processing for main
23656 -- Save global variables
23662 -- Call low level system initialization
23666 -- Call our generated Ada initialization routine
23670 -- This is the point at which we want the debugger to get
23675 -- Now we call the main program of the partition
23679 -- Perform Ada finalization
23683 -- Perform low level system finalization
23687 -- Return the proper exit status
23688 return (gnat_exit_status);
23691 -- This section is entirely comments, so it has no effect on the
23692 -- compilation of the Ada_Main package. It provides the list of
23693 -- object files and linker options, as well as some standard
23694 -- libraries needed for the link. The gnatlink utility parses
23695 -- this b~hello.adb file to read these comment lines to generate
23696 -- the appropriate command line arguments for the call to the
23697 -- system linker. The BEGIN/END lines are used for sentinels for
23698 -- this parsing operation.
23700 -- The exact file names will of course depend on the environment,
23701 -- host/target and location of files on the host system.
23703 @findex Object file list
23704 -- BEGIN Object file/option list
23707 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
23708 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
23709 -- END Object file/option list
23715 The Ada code in the above example is exactly what is generated by the
23716 binder. We have added comments to more clearly indicate the function
23717 of each part of the generated @code{Ada_Main} package.
23719 The code is standard Ada in all respects, and can be processed by any
23720 tools that handle Ada. In particular, it is possible to use the debugger
23721 in Ada mode to debug the generated @code{Ada_Main} package. For example,
23722 suppose that for reasons that you do not understand, your program is crashing
23723 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
23724 you can place a breakpoint on the call:
23726 @smallexample @c ada
23727 Ada.Text_Io'Elab_Body;
23731 and trace the elaboration routine for this package to find out where
23732 the problem might be (more usually of course you would be debugging
23733 elaboration code in your own application).
23735 @node Elaboration Order Handling in GNAT
23736 @appendix Elaboration Order Handling in GNAT
23737 @cindex Order of elaboration
23738 @cindex Elaboration control
23741 * Elaboration Code in Ada 95::
23742 * Checking the Elaboration Order in Ada 95::
23743 * Controlling the Elaboration Order in Ada 95::
23744 * Controlling Elaboration in GNAT - Internal Calls::
23745 * Controlling Elaboration in GNAT - External Calls::
23746 * Default Behavior in GNAT - Ensuring Safety::
23747 * Treatment of Pragma Elaborate::
23748 * Elaboration Issues for Library Tasks::
23749 * Mixing Elaboration Models::
23750 * What to Do If the Default Elaboration Behavior Fails::
23751 * Elaboration for Access-to-Subprogram Values::
23752 * Summary of Procedures for Elaboration Control::
23753 * Other Elaboration Order Considerations::
23757 This chapter describes the handling of elaboration code in Ada 95 and
23758 in GNAT, and discusses how the order of elaboration of program units can
23759 be controlled in GNAT, either automatically or with explicit programming
23762 @node Elaboration Code in Ada 95
23763 @section Elaboration Code in Ada 95
23766 Ada 95 provides rather general mechanisms for executing code at elaboration
23767 time, that is to say before the main program starts executing. Such code arises
23771 @item Initializers for variables.
23772 Variables declared at the library level, in package specs or bodies, can
23773 require initialization that is performed at elaboration time, as in:
23774 @smallexample @c ada
23776 Sqrt_Half : Float := Sqrt (0.5);
23780 @item Package initialization code
23781 Code in a @code{BEGIN-END} section at the outer level of a package body is
23782 executed as part of the package body elaboration code.
23784 @item Library level task allocators
23785 Tasks that are declared using task allocators at the library level
23786 start executing immediately and hence can execute at elaboration time.
23790 Subprogram calls are possible in any of these contexts, which means that
23791 any arbitrary part of the program may be executed as part of the elaboration
23792 code. It is even possible to write a program which does all its work at
23793 elaboration time, with a null main program, although stylistically this
23794 would usually be considered an inappropriate way to structure
23797 An important concern arises in the context of elaboration code:
23798 we have to be sure that it is executed in an appropriate order. What we
23799 have is a series of elaboration code sections, potentially one section
23800 for each unit in the program. It is important that these execute
23801 in the correct order. Correctness here means that, taking the above
23802 example of the declaration of @code{Sqrt_Half},
23803 if some other piece of
23804 elaboration code references @code{Sqrt_Half},
23805 then it must run after the
23806 section of elaboration code that contains the declaration of
23809 There would never be any order of elaboration problem if we made a rule
23810 that whenever you @code{with} a unit, you must elaborate both the spec and body
23811 of that unit before elaborating the unit doing the @code{with}'ing:
23813 @smallexample @c ada
23817 package Unit_2 is ...
23823 would require that both the body and spec of @code{Unit_1} be elaborated
23824 before the spec of @code{Unit_2}. However, a rule like that would be far too
23825 restrictive. In particular, it would make it impossible to have routines
23826 in separate packages that were mutually recursive.
23828 You might think that a clever enough compiler could look at the actual
23829 elaboration code and determine an appropriate correct order of elaboration,
23830 but in the general case, this is not possible. Consider the following
23833 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
23835 the variable @code{Sqrt_1}, which is declared in the elaboration code
23836 of the body of @code{Unit_1}:
23838 @smallexample @c ada
23840 Sqrt_1 : Float := Sqrt (0.1);
23845 The elaboration code of the body of @code{Unit_1} also contains:
23847 @smallexample @c ada
23850 if expression_1 = 1 then
23851 Q := Unit_2.Func_2;
23858 @code{Unit_2} is exactly parallel,
23859 it has a procedure @code{Func_2} that references
23860 the variable @code{Sqrt_2}, which is declared in the elaboration code of
23861 the body @code{Unit_2}:
23863 @smallexample @c ada
23865 Sqrt_2 : Float := Sqrt (0.1);
23870 The elaboration code of the body of @code{Unit_2} also contains:
23872 @smallexample @c ada
23875 if expression_2 = 2 then
23876 Q := Unit_1.Func_1;
23883 Now the question is, which of the following orders of elaboration is
23908 If you carefully analyze the flow here, you will see that you cannot tell
23909 at compile time the answer to this question.
23910 If @code{expression_1} is not equal to 1,
23911 and @code{expression_2} is not equal to 2,
23912 then either order is acceptable, because neither of the function calls is
23913 executed. If both tests evaluate to true, then neither order is acceptable
23914 and in fact there is no correct order.
23916 If one of the two expressions is true, and the other is false, then one
23917 of the above orders is correct, and the other is incorrect. For example,
23918 if @code{expression_1} = 1 and @code{expression_2} /= 2,
23919 then the call to @code{Func_2}
23920 will occur, but not the call to @code{Func_1.}
23921 This means that it is essential
23922 to elaborate the body of @code{Unit_1} before
23923 the body of @code{Unit_2}, so the first
23924 order of elaboration is correct and the second is wrong.
23926 By making @code{expression_1} and @code{expression_2}
23927 depend on input data, or perhaps
23928 the time of day, we can make it impossible for the compiler or binder
23929 to figure out which of these expressions will be true, and hence it
23930 is impossible to guarantee a safe order of elaboration at run time.
23932 @node Checking the Elaboration Order in Ada 95
23933 @section Checking the Elaboration Order in Ada 95
23936 In some languages that involve the same kind of elaboration problems,
23937 e.g. Java and C++, the programmer is expected to worry about these
23938 ordering problems himself, and it is common to
23939 write a program in which an incorrect elaboration order gives
23940 surprising results, because it references variables before they
23942 Ada 95 is designed to be a safe language, and a programmer-beware approach is
23943 clearly not sufficient. Consequently, the language provides three lines
23947 @item Standard rules
23948 Some standard rules restrict the possible choice of elaboration
23949 order. In particular, if you @code{with} a unit, then its spec is always
23950 elaborated before the unit doing the @code{with}. Similarly, a parent
23951 spec is always elaborated before the child spec, and finally
23952 a spec is always elaborated before its corresponding body.
23954 @item Dynamic elaboration checks
23955 @cindex Elaboration checks
23956 @cindex Checks, elaboration
23957 Dynamic checks are made at run time, so that if some entity is accessed
23958 before it is elaborated (typically by means of a subprogram call)
23959 then the exception (@code{Program_Error}) is raised.
23961 @item Elaboration control
23962 Facilities are provided for the programmer to specify the desired order
23966 Let's look at these facilities in more detail. First, the rules for
23967 dynamic checking. One possible rule would be simply to say that the
23968 exception is raised if you access a variable which has not yet been
23969 elaborated. The trouble with this approach is that it could require
23970 expensive checks on every variable reference. Instead Ada 95 has two
23971 rules which are a little more restrictive, but easier to check, and
23975 @item Restrictions on calls
23976 A subprogram can only be called at elaboration time if its body
23977 has been elaborated. The rules for elaboration given above guarantee
23978 that the spec of the subprogram has been elaborated before the
23979 call, but not the body. If this rule is violated, then the
23980 exception @code{Program_Error} is raised.
23982 @item Restrictions on instantiations
23983 A generic unit can only be instantiated if the body of the generic
23984 unit has been elaborated. Again, the rules for elaboration given above
23985 guarantee that the spec of the generic unit has been elaborated
23986 before the instantiation, but not the body. If this rule is
23987 violated, then the exception @code{Program_Error} is raised.
23991 The idea is that if the body has been elaborated, then any variables
23992 it references must have been elaborated; by checking for the body being
23993 elaborated we guarantee that none of its references causes any
23994 trouble. As we noted above, this is a little too restrictive, because a
23995 subprogram that has no non-local references in its body may in fact be safe
23996 to call. However, it really would be unsafe to rely on this, because
23997 it would mean that the caller was aware of details of the implementation
23998 in the body. This goes against the basic tenets of Ada.
24000 A plausible implementation can be described as follows.
24001 A Boolean variable is associated with each subprogram
24002 and each generic unit. This variable is initialized to False, and is set to
24003 True at the point body is elaborated. Every call or instantiation checks the
24004 variable, and raises @code{Program_Error} if the variable is False.
24006 Note that one might think that it would be good enough to have one Boolean
24007 variable for each package, but that would not deal with cases of trying
24008 to call a body in the same package as the call
24009 that has not been elaborated yet.
24010 Of course a compiler may be able to do enough analysis to optimize away
24011 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
24012 does such optimizations, but still the easiest conceptual model is to
24013 think of there being one variable per subprogram.
24015 @node Controlling the Elaboration Order in Ada 95
24016 @section Controlling the Elaboration Order in Ada 95
24019 In the previous section we discussed the rules in Ada 95 which ensure
24020 that @code{Program_Error} is raised if an incorrect elaboration order is
24021 chosen. This prevents erroneous executions, but we need mechanisms to
24022 specify a correct execution and avoid the exception altogether.
24023 To achieve this, Ada 95 provides a number of features for controlling
24024 the order of elaboration. We discuss these features in this section.
24026 First, there are several ways of indicating to the compiler that a given
24027 unit has no elaboration problems:
24030 @item packages that do not require a body
24031 In Ada 95, a library package that does not require a body does not permit
24032 a body. This means that if we have a such a package, as in:
24034 @smallexample @c ada
24037 package Definitions is
24039 type m is new integer;
24041 type a is array (1 .. 10) of m;
24042 type b is array (1 .. 20) of m;
24050 A package that @code{with}'s @code{Definitions} may safely instantiate
24051 @code{Definitions.Subp} because the compiler can determine that there
24052 definitely is no package body to worry about in this case
24055 @cindex pragma Pure
24057 Places sufficient restrictions on a unit to guarantee that
24058 no call to any subprogram in the unit can result in an
24059 elaboration problem. This means that the compiler does not need
24060 to worry about the point of elaboration of such units, and in
24061 particular, does not need to check any calls to any subprograms
24064 @item pragma Preelaborate
24065 @findex Preelaborate
24066 @cindex pragma Preelaborate
24067 This pragma places slightly less stringent restrictions on a unit than
24069 but these restrictions are still sufficient to ensure that there
24070 are no elaboration problems with any calls to the unit.
24072 @item pragma Elaborate_Body
24073 @findex Elaborate_Body
24074 @cindex pragma Elaborate_Body
24075 This pragma requires that the body of a unit be elaborated immediately
24076 after its spec. Suppose a unit @code{A} has such a pragma,
24077 and unit @code{B} does
24078 a @code{with} of unit @code{A}. Recall that the standard rules require
24079 the spec of unit @code{A}
24080 to be elaborated before the @code{with}'ing unit; given the pragma in
24081 @code{A}, we also know that the body of @code{A}
24082 will be elaborated before @code{B}, so
24083 that calls to @code{A} are safe and do not need a check.
24088 unlike pragma @code{Pure} and pragma @code{Preelaborate},
24090 @code{Elaborate_Body} does not guarantee that the program is
24091 free of elaboration problems, because it may not be possible
24092 to satisfy the requested elaboration order.
24093 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
24095 marks @code{Unit_1} as @code{Elaborate_Body},
24096 and not @code{Unit_2,} then the order of
24097 elaboration will be:
24109 Now that means that the call to @code{Func_1} in @code{Unit_2}
24110 need not be checked,
24111 it must be safe. But the call to @code{Func_2} in
24112 @code{Unit_1} may still fail if
24113 @code{Expression_1} is equal to 1,
24114 and the programmer must still take
24115 responsibility for this not being the case.
24117 If all units carry a pragma @code{Elaborate_Body}, then all problems are
24118 eliminated, except for calls entirely within a body, which are
24119 in any case fully under programmer control. However, using the pragma
24120 everywhere is not always possible.
24121 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
24122 we marked both of them as having pragma @code{Elaborate_Body}, then
24123 clearly there would be no possible elaboration order.
24125 The above pragmas allow a server to guarantee safe use by clients, and
24126 clearly this is the preferable approach. Consequently a good rule in
24127 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
24128 and if this is not possible,
24129 mark them as @code{Elaborate_Body} if possible.
24130 As we have seen, there are situations where neither of these
24131 three pragmas can be used.
24132 So we also provide methods for clients to control the
24133 order of elaboration of the servers on which they depend:
24136 @item pragma Elaborate (unit)
24138 @cindex pragma Elaborate
24139 This pragma is placed in the context clause, after a @code{with} clause,
24140 and it requires that the body of the named unit be elaborated before
24141 the unit in which the pragma occurs. The idea is to use this pragma
24142 if the current unit calls at elaboration time, directly or indirectly,
24143 some subprogram in the named unit.
24145 @item pragma Elaborate_All (unit)
24146 @findex Elaborate_All
24147 @cindex pragma Elaborate_All
24148 This is a stronger version of the Elaborate pragma. Consider the
24152 Unit A @code{with}'s unit B and calls B.Func in elab code
24153 Unit B @code{with}'s unit C, and B.Func calls C.Func
24157 Now if we put a pragma @code{Elaborate (B)}
24158 in unit @code{A}, this ensures that the
24159 body of @code{B} is elaborated before the call, but not the
24160 body of @code{C}, so
24161 the call to @code{C.Func} could still cause @code{Program_Error} to
24164 The effect of a pragma @code{Elaborate_All} is stronger, it requires
24165 not only that the body of the named unit be elaborated before the
24166 unit doing the @code{with}, but also the bodies of all units that the
24167 named unit uses, following @code{with} links transitively. For example,
24168 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
24170 not only that the body of @code{B} be elaborated before @code{A},
24172 body of @code{C}, because @code{B} @code{with}'s @code{C}.
24176 We are now in a position to give a usage rule in Ada 95 for avoiding
24177 elaboration problems, at least if dynamic dispatching and access to
24178 subprogram values are not used. We will handle these cases separately
24181 The rule is simple. If a unit has elaboration code that can directly or
24182 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
24183 a generic package in a @code{with}'ed unit,
24184 then if the @code{with}'ed unit does not have
24185 pragma @code{Pure} or @code{Preelaborate}, then the client should have
24186 a pragma @code{Elaborate_All}
24187 for the @code{with}'ed unit. By following this rule a client is
24188 assured that calls can be made without risk of an exception.
24190 For generic subprogram instantiations, the rule can be relaxed to
24191 require only a pragma @code{Elaborate} since elaborating the body
24192 of a subprogram cannot cause any transitive elaboration (we are
24193 not calling the subprogram in this case, just elaborating its
24196 If this rule is not followed, then a program may be in one of four
24200 @item No order exists
24201 No order of elaboration exists which follows the rules, taking into
24202 account any @code{Elaborate}, @code{Elaborate_All},
24203 or @code{Elaborate_Body} pragmas. In
24204 this case, an Ada 95 compiler must diagnose the situation at bind
24205 time, and refuse to build an executable program.
24207 @item One or more orders exist, all incorrect
24208 One or more acceptable elaboration orders exists, and all of them
24209 generate an elaboration order problem. In this case, the binder
24210 can build an executable program, but @code{Program_Error} will be raised
24211 when the program is run.
24213 @item Several orders exist, some right, some incorrect
24214 One or more acceptable elaboration orders exists, and some of them
24215 work, and some do not. The programmer has not controlled
24216 the order of elaboration, so the binder may or may not pick one of
24217 the correct orders, and the program may or may not raise an
24218 exception when it is run. This is the worst case, because it means
24219 that the program may fail when moved to another compiler, or even
24220 another version of the same compiler.
24222 @item One or more orders exists, all correct
24223 One ore more acceptable elaboration orders exist, and all of them
24224 work. In this case the program runs successfully. This state of
24225 affairs can be guaranteed by following the rule we gave above, but
24226 may be true even if the rule is not followed.
24230 Note that one additional advantage of following our rules on the use
24231 of @code{Elaborate} and @code{Elaborate_All}
24232 is that the program continues to stay in the ideal (all orders OK) state
24233 even if maintenance
24234 changes some bodies of some units. Conversely, if a program that does
24235 not follow this rule happens to be safe at some point, this state of affairs
24236 may deteriorate silently as a result of maintenance changes.
24238 You may have noticed that the above discussion did not mention
24239 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
24240 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
24241 code in the body makes calls to some other unit, so it is still necessary
24242 to use @code{Elaborate_All} on such units.
24244 @node Controlling Elaboration in GNAT - Internal Calls
24245 @section Controlling Elaboration in GNAT - Internal Calls
24248 In the case of internal calls, i.e. calls within a single package, the
24249 programmer has full control over the order of elaboration, and it is up
24250 to the programmer to elaborate declarations in an appropriate order. For
24253 @smallexample @c ada
24256 function One return Float;
24260 function One return Float is
24269 will obviously raise @code{Program_Error} at run time, because function
24270 One will be called before its body is elaborated. In this case GNAT will
24271 generate a warning that the call will raise @code{Program_Error}:
24277 2. function One return Float;
24279 4. Q : Float := One;
24281 >>> warning: cannot call "One" before body is elaborated
24282 >>> warning: Program_Error will be raised at run time
24285 6. function One return Float is
24298 Note that in this particular case, it is likely that the call is safe, because
24299 the function @code{One} does not access any global variables.
24300 Nevertheless in Ada 95, we do not want the validity of the check to depend on
24301 the contents of the body (think about the separate compilation case), so this
24302 is still wrong, as we discussed in the previous sections.
24304 The error is easily corrected by rearranging the declarations so that the
24305 body of One appears before the declaration containing the call
24306 (note that in Ada 95,
24307 declarations can appear in any order, so there is no restriction that
24308 would prevent this reordering, and if we write:
24310 @smallexample @c ada
24313 function One return Float;
24315 function One return Float is
24326 then all is well, no warning is generated, and no
24327 @code{Program_Error} exception
24329 Things are more complicated when a chain of subprograms is executed:
24331 @smallexample @c ada
24334 function A return Integer;
24335 function B return Integer;
24336 function C return Integer;
24338 function B return Integer is begin return A; end;
24339 function C return Integer is begin return B; end;
24343 function A return Integer is begin return 1; end;
24349 Now the call to @code{C}
24350 at elaboration time in the declaration of @code{X} is correct, because
24351 the body of @code{C} is already elaborated,
24352 and the call to @code{B} within the body of
24353 @code{C} is correct, but the call
24354 to @code{A} within the body of @code{B} is incorrect, because the body
24355 of @code{A} has not been elaborated, so @code{Program_Error}
24356 will be raised on the call to @code{A}.
24357 In this case GNAT will generate a
24358 warning that @code{Program_Error} may be
24359 raised at the point of the call. Let's look at the warning:
24365 2. function A return Integer;
24366 3. function B return Integer;
24367 4. function C return Integer;
24369 6. function B return Integer is begin return A; end;
24371 >>> warning: call to "A" before body is elaborated may
24372 raise Program_Error
24373 >>> warning: "B" called at line 7
24374 >>> warning: "C" called at line 9
24376 7. function C return Integer is begin return B; end;
24378 9. X : Integer := C;
24380 11. function A return Integer is begin return 1; end;
24390 Note that the message here says ``may raise'', instead of the direct case,
24391 where the message says ``will be raised''. That's because whether
24393 actually called depends in general on run-time flow of control.
24394 For example, if the body of @code{B} said
24396 @smallexample @c ada
24399 function B return Integer is
24401 if some-condition-depending-on-input-data then
24412 then we could not know until run time whether the incorrect call to A would
24413 actually occur, so @code{Program_Error} might
24414 or might not be raised. It is possible for a compiler to
24415 do a better job of analyzing bodies, to
24416 determine whether or not @code{Program_Error}
24417 might be raised, but it certainly
24418 couldn't do a perfect job (that would require solving the halting problem
24419 and is provably impossible), and because this is a warning anyway, it does
24420 not seem worth the effort to do the analysis. Cases in which it
24421 would be relevant are rare.
24423 In practice, warnings of either of the forms given
24424 above will usually correspond to
24425 real errors, and should be examined carefully and eliminated.
24426 In the rare case where a warning is bogus, it can be suppressed by any of
24427 the following methods:
24431 Compile with the @option{-gnatws} switch set
24434 Suppress @code{Elaboration_Check} for the called subprogram
24437 Use pragma @code{Warnings_Off} to turn warnings off for the call
24441 For the internal elaboration check case,
24442 GNAT by default generates the
24443 necessary run-time checks to ensure
24444 that @code{Program_Error} is raised if any
24445 call fails an elaboration check. Of course this can only happen if a
24446 warning has been issued as described above. The use of pragma
24447 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
24448 some of these checks, meaning that it may be possible (but is not
24449 guaranteed) for a program to be able to call a subprogram whose body
24450 is not yet elaborated, without raising a @code{Program_Error} exception.
24452 @node Controlling Elaboration in GNAT - External Calls
24453 @section Controlling Elaboration in GNAT - External Calls
24456 The previous section discussed the case in which the execution of a
24457 particular thread of elaboration code occurred entirely within a
24458 single unit. This is the easy case to handle, because a programmer
24459 has direct and total control over the order of elaboration, and
24460 furthermore, checks need only be generated in cases which are rare
24461 and which the compiler can easily detect.
24462 The situation is more complex when separate compilation is taken into account.
24463 Consider the following:
24465 @smallexample @c ada
24469 function Sqrt (Arg : Float) return Float;
24472 package body Math is
24473 function Sqrt (Arg : Float) return Float is
24482 X : Float := Math.Sqrt (0.5);
24495 where @code{Main} is the main program. When this program is executed, the
24496 elaboration code must first be executed, and one of the jobs of the
24497 binder is to determine the order in which the units of a program are
24498 to be elaborated. In this case we have four units: the spec and body
24500 the spec of @code{Stuff} and the body of @code{Main}).
24501 In what order should the four separate sections of elaboration code
24504 There are some restrictions in the order of elaboration that the binder
24505 can choose. In particular, if unit U has a @code{with}
24506 for a package @code{X}, then you
24507 are assured that the spec of @code{X}
24508 is elaborated before U , but you are
24509 not assured that the body of @code{X}
24510 is elaborated before U.
24511 This means that in the above case, the binder is allowed to choose the
24522 but that's not good, because now the call to @code{Math.Sqrt}
24523 that happens during
24524 the elaboration of the @code{Stuff}
24525 spec happens before the body of @code{Math.Sqrt} is
24526 elaborated, and hence causes @code{Program_Error} exception to be raised.
24527 At first glance, one might say that the binder is misbehaving, because
24528 obviously you want to elaborate the body of something you @code{with}
24530 that is not a general rule that can be followed in all cases. Consider
24532 @smallexample @c ada
24540 package body Y is ...
24543 package body X is ...
24549 This is a common arrangement, and, apart from the order of elaboration
24550 problems that might arise in connection with elaboration code, this works fine.
24551 A rule that says that you must first elaborate the body of anything you
24552 @code{with} cannot work in this case:
24553 the body of @code{X} @code{with}'s @code{Y},
24554 which means you would have to
24555 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
24557 you have to elaborate the body of @code{X} first, but ... and we have a
24558 loop that cannot be broken.
24560 It is true that the binder can in many cases guess an order of elaboration
24561 that is unlikely to cause a @code{Program_Error}
24562 exception to be raised, and it tries to do so (in the
24563 above example of @code{Math/Stuff/Spec}, the GNAT binder will
24565 elaborate the body of @code{Math} right after its spec, so all will be well).
24567 However, a program that blindly relies on the binder to be helpful can
24568 get into trouble, as we discussed in the previous sections, so
24570 provides a number of facilities for assisting the programmer in
24571 developing programs that are robust with respect to elaboration order.
24573 @node Default Behavior in GNAT - Ensuring Safety
24574 @section Default Behavior in GNAT - Ensuring Safety
24577 The default behavior in GNAT ensures elaboration safety. In its
24578 default mode GNAT implements the
24579 rule we previously described as the right approach. Let's restate it:
24583 @emph{If a unit has elaboration code that can directly or indirectly make a
24584 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
24585 package in a @code{with}'ed unit, then if the @code{with}'ed unit
24586 does not have pragma @code{Pure} or
24587 @code{Preelaborate}, then the client should have an
24588 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
24590 @emph{In the case of instantiating a generic subprogram, it is always
24591 sufficient to have only an @code{Elaborate} pragma for the
24592 @code{with}'ed unit.}
24596 By following this rule a client is assured that calls and instantiations
24597 can be made without risk of an exception.
24599 In this mode GNAT traces all calls that are potentially made from
24600 elaboration code, and puts in any missing implicit @code{Elaborate}
24601 and @code{Elaborate_All} pragmas.
24602 The advantage of this approach is that no elaboration problems
24603 are possible if the binder can find an elaboration order that is
24604 consistent with these implicit @code{Elaborate} and
24605 @code{Elaborate_All} pragmas. The
24606 disadvantage of this approach is that no such order may exist.
24608 If the binder does not generate any diagnostics, then it means that it has
24609 found an elaboration order that is guaranteed to be safe. However, the binder
24610 may still be relying on implicitly generated @code{Elaborate} and
24611 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
24614 If it is important to guarantee portability, then the compilations should
24617 (warn on elaboration problems) switch. This will cause warning messages
24618 to be generated indicating the missing @code{Elaborate} and
24619 @code{Elaborate_All} pragmas.
24620 Consider the following source program:
24622 @smallexample @c ada
24627 m : integer := k.r;
24634 where it is clear that there
24635 should be a pragma @code{Elaborate_All}
24636 for unit @code{k}. An implicit pragma will be generated, and it is
24637 likely that the binder will be able to honor it. However, if you want
24638 to port this program to some other Ada compiler than GNAT.
24639 it is safer to include the pragma explicitly in the source. If this
24640 unit is compiled with the
24642 switch, then the compiler outputs a warning:
24649 3. m : integer := k.r;
24651 >>> warning: call to "r" may raise Program_Error
24652 >>> warning: missing pragma Elaborate_All for "k"
24660 and these warnings can be used as a guide for supplying manually
24661 the missing pragmas. It is usually a bad idea to use this warning
24662 option during development. That's because it will warn you when
24663 you need to put in a pragma, but cannot warn you when it is time
24664 to take it out. So the use of pragma @code{Elaborate_All} may lead to
24665 unnecessary dependencies and even false circularities.
24667 This default mode is more restrictive than the Ada Reference
24668 Manual, and it is possible to construct programs which will compile
24669 using the dynamic model described there, but will run into a
24670 circularity using the safer static model we have described.
24672 Of course any Ada compiler must be able to operate in a mode
24673 consistent with the requirements of the Ada Reference Manual,
24674 and in particular must have the capability of implementing the
24675 standard dynamic model of elaboration with run-time checks.
24677 In GNAT, this standard mode can be achieved either by the use of
24678 the @option{-gnatE} switch on the compiler (@command{gcc} or
24679 @command{gnatmake}) command, or by the use of the configuration pragma:
24681 @smallexample @c ada
24682 pragma Elaboration_Checks (RM);
24686 Either approach will cause the unit affected to be compiled using the
24687 standard dynamic run-time elaboration checks described in the Ada
24688 Reference Manual. The static model is generally preferable, since it
24689 is clearly safer to rely on compile and link time checks rather than
24690 run-time checks. However, in the case of legacy code, it may be
24691 difficult to meet the requirements of the static model. This
24692 issue is further discussed in
24693 @ref{What to Do If the Default Elaboration Behavior Fails}.
24695 Note that the static model provides a strict subset of the allowed
24696 behavior and programs of the Ada Reference Manual, so if you do
24697 adhere to the static model and no circularities exist,
24698 then you are assured that your program will
24699 work using the dynamic model, providing that you remove any
24700 pragma Elaborate statements from the source.
24702 @node Treatment of Pragma Elaborate
24703 @section Treatment of Pragma Elaborate
24704 @cindex Pragma Elaborate
24707 The use of @code{pragma Elaborate}
24708 should generally be avoided in Ada 95 programs.
24709 The reason for this is that there is no guarantee that transitive calls
24710 will be properly handled. Indeed at one point, this pragma was placed
24711 in Annex J (Obsolescent Features), on the grounds that it is never useful.
24713 Now that's a bit restrictive. In practice, the case in which
24714 @code{pragma Elaborate} is useful is when the caller knows that there
24715 are no transitive calls, or that the called unit contains all necessary
24716 transitive @code{pragma Elaborate} statements, and legacy code often
24717 contains such uses.
24719 Strictly speaking the static mode in GNAT should ignore such pragmas,
24720 since there is no assurance at compile time that the necessary safety
24721 conditions are met. In practice, this would cause GNAT to be incompatible
24722 with correctly written Ada 83 code that had all necessary
24723 @code{pragma Elaborate} statements in place. Consequently, we made the
24724 decision that GNAT in its default mode will believe that if it encounters
24725 a @code{pragma Elaborate} then the programmer knows what they are doing,
24726 and it will trust that no elaboration errors can occur.
24728 The result of this decision is two-fold. First to be safe using the
24729 static mode, you should remove all @code{pragma Elaborate} statements.
24730 Second, when fixing circularities in existing code, you can selectively
24731 use @code{pragma Elaborate} statements to convince the static mode of
24732 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
24735 When using the static mode with @option{-gnatwl}, any use of
24736 @code{pragma Elaborate} will generate a warning about possible
24739 @node Elaboration Issues for Library Tasks
24740 @section Elaboration Issues for Library Tasks
24741 @cindex Library tasks, elaboration issues
24742 @cindex Elaboration of library tasks
24745 In this section we examine special elaboration issues that arise for
24746 programs that declare library level tasks.
24748 Generally the model of execution of an Ada program is that all units are
24749 elaborated, and then execution of the program starts. However, the
24750 declaration of library tasks definitely does not fit this model. The
24751 reason for this is that library tasks start as soon as they are declared
24752 (more precisely, as soon as the statement part of the enclosing package
24753 body is reached), that is to say before elaboration
24754 of the program is complete. This means that if such a task calls a
24755 subprogram, or an entry in another task, the callee may or may not be
24756 elaborated yet, and in the standard
24757 Reference Manual model of dynamic elaboration checks, you can even
24758 get timing dependent Program_Error exceptions, since there can be
24759 a race between the elaboration code and the task code.
24761 The static model of elaboration in GNAT seeks to avoid all such
24762 dynamic behavior, by being conservative, and the conservative
24763 approach in this particular case is to assume that all the code
24764 in a task body is potentially executed at elaboration time if
24765 a task is declared at the library level.
24767 This can definitely result in unexpected circularities. Consider
24768 the following example
24770 @smallexample @c ada
24776 type My_Int is new Integer;
24778 function Ident (M : My_Int) return My_Int;
24782 package body Decls is
24783 task body Lib_Task is
24789 function Ident (M : My_Int) return My_Int is
24797 procedure Put_Val (Arg : Decls.My_Int);
24801 package body Utils is
24802 procedure Put_Val (Arg : Decls.My_Int) is
24804 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24811 Decls.Lib_Task.Start;
24816 If the above example is compiled in the default static elaboration
24817 mode, then a circularity occurs. The circularity comes from the call
24818 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
24819 this call occurs in elaboration code, we need an implicit pragma
24820 @code{Elaborate_All} for @code{Utils}. This means that not only must
24821 the spec and body of @code{Utils} be elaborated before the body
24822 of @code{Decls}, but also the spec and body of any unit that is
24823 @code{with'ed} by the body of @code{Utils} must also be elaborated before
24824 the body of @code{Decls}. This is the transitive implication of
24825 pragma @code{Elaborate_All} and it makes sense, because in general
24826 the body of @code{Put_Val} might have a call to something in a
24827 @code{with'ed} unit.
24829 In this case, the body of Utils (actually its spec) @code{with's}
24830 @code{Decls}. Unfortunately this means that the body of @code{Decls}
24831 must be elaborated before itself, in case there is a call from the
24832 body of @code{Utils}.
24834 Here is the exact chain of events we are worrying about:
24838 In the body of @code{Decls} a call is made from within the body of a library
24839 task to a subprogram in the package @code{Utils}. Since this call may
24840 occur at elaboration time (given that the task is activated at elaboration
24841 time), we have to assume the worst, i.e. that the
24842 call does happen at elaboration time.
24845 This means that the body and spec of @code{Util} must be elaborated before
24846 the body of @code{Decls} so that this call does not cause an access before
24850 Within the body of @code{Util}, specifically within the body of
24851 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
24855 One such @code{with}'ed package is package @code{Decls}, so there
24856 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
24857 In fact there is such a call in this example, but we would have to
24858 assume that there was such a call even if it were not there, since
24859 we are not supposed to write the body of @code{Decls} knowing what
24860 is in the body of @code{Utils}; certainly in the case of the
24861 static elaboration model, the compiler does not know what is in
24862 other bodies and must assume the worst.
24865 This means that the spec and body of @code{Decls} must also be
24866 elaborated before we elaborate the unit containing the call, but
24867 that unit is @code{Decls}! This means that the body of @code{Decls}
24868 must be elaborated before itself, and that's a circularity.
24872 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
24873 the body of @code{Decls} you will get a true Ada Reference Manual
24874 circularity that makes the program illegal.
24876 In practice, we have found that problems with the static model of
24877 elaboration in existing code often arise from library tasks, so
24878 we must address this particular situation.
24880 Note that if we compile and run the program above, using the dynamic model of
24881 elaboration (that is to say use the @option{-gnatE} switch),
24882 then it compiles, binds,
24883 links, and runs, printing the expected result of 2. Therefore in some sense
24884 the circularity here is only apparent, and we need to capture
24885 the properties of this program that distinguish it from other library-level
24886 tasks that have real elaboration problems.
24888 We have four possible answers to this question:
24893 Use the dynamic model of elaboration.
24895 If we use the @option{-gnatE} switch, then as noted above, the program works.
24896 Why is this? If we examine the task body, it is apparent that the task cannot
24898 @code{accept} statement until after elaboration has been completed, because
24899 the corresponding entry call comes from the main program, not earlier.
24900 This is why the dynamic model works here. But that's really giving
24901 up on a precise analysis, and we prefer to take this approach only if we cannot
24903 problem in any other manner. So let us examine two ways to reorganize
24904 the program to avoid the potential elaboration problem.
24907 Split library tasks into separate packages.
24909 Write separate packages, so that library tasks are isolated from
24910 other declarations as much as possible. Let us look at a variation on
24913 @smallexample @c ada
24921 package body Decls1 is
24922 task body Lib_Task is
24930 type My_Int is new Integer;
24931 function Ident (M : My_Int) return My_Int;
24935 package body Decls2 is
24936 function Ident (M : My_Int) return My_Int is
24944 procedure Put_Val (Arg : Decls2.My_Int);
24948 package body Utils is
24949 procedure Put_Val (Arg : Decls2.My_Int) is
24951 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
24958 Decls1.Lib_Task.Start;
24963 All we have done is to split @code{Decls} into two packages, one
24964 containing the library task, and one containing everything else. Now
24965 there is no cycle, and the program compiles, binds, links and executes
24966 using the default static model of elaboration.
24969 Declare separate task types.
24971 A significant part of the problem arises because of the use of the
24972 single task declaration form. This means that the elaboration of
24973 the task type, and the elaboration of the task itself (i.e. the
24974 creation of the task) happen at the same time. A good rule
24975 of style in Ada 95 is to always create explicit task types. By
24976 following the additional step of placing task objects in separate
24977 packages from the task type declaration, many elaboration problems
24978 are avoided. Here is another modified example of the example program:
24980 @smallexample @c ada
24982 task type Lib_Task_Type is
24986 type My_Int is new Integer;
24988 function Ident (M : My_Int) return My_Int;
24992 package body Decls is
24993 task body Lib_Task_Type is
24999 function Ident (M : My_Int) return My_Int is
25007 procedure Put_Val (Arg : Decls.My_Int);
25011 package body Utils is
25012 procedure Put_Val (Arg : Decls.My_Int) is
25014 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
25020 Lib_Task : Decls.Lib_Task_Type;
25026 Declst.Lib_Task.Start;
25031 What we have done here is to replace the @code{task} declaration in
25032 package @code{Decls} with a @code{task type} declaration. Then we
25033 introduce a separate package @code{Declst} to contain the actual
25034 task object. This separates the elaboration issues for
25035 the @code{task type}
25036 declaration, which causes no trouble, from the elaboration issues
25037 of the task object, which is also unproblematic, since it is now independent
25038 of the elaboration of @code{Utils}.
25039 This separation of concerns also corresponds to
25040 a generally sound engineering principle of separating declarations
25041 from instances. This version of the program also compiles, binds, links,
25042 and executes, generating the expected output.
25045 Use No_Entry_Calls_In_Elaboration_Code restriction.
25046 @cindex No_Entry_Calls_In_Elaboration_Code
25048 The previous two approaches described how a program can be restructured
25049 to avoid the special problems caused by library task bodies. in practice,
25050 however, such restructuring may be difficult to apply to existing legacy code,
25051 so we must consider solutions that do not require massive rewriting.
25053 Let us consider more carefully why our original sample program works
25054 under the dynamic model of elaboration. The reason is that the code
25055 in the task body blocks immediately on the @code{accept}
25056 statement. Now of course there is nothing to prohibit elaboration
25057 code from making entry calls (for example from another library level task),
25058 so we cannot tell in isolation that
25059 the task will not execute the accept statement during elaboration.
25061 However, in practice it is very unusual to see elaboration code
25062 make any entry calls, and the pattern of tasks starting
25063 at elaboration time and then immediately blocking on @code{accept} or
25064 @code{select} statements is very common. What this means is that
25065 the compiler is being too pessimistic when it analyzes the
25066 whole package body as though it might be executed at elaboration
25069 If we know that the elaboration code contains no entry calls, (a very safe
25070 assumption most of the time, that could almost be made the default
25071 behavior), then we can compile all units of the program under control
25072 of the following configuration pragma:
25075 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
25079 This pragma can be placed in the @file{gnat.adc} file in the usual
25080 manner. If we take our original unmodified program and compile it
25081 in the presence of a @file{gnat.adc} containing the above pragma,
25082 then once again, we can compile, bind, link, and execute, obtaining
25083 the expected result. In the presence of this pragma, the compiler does
25084 not trace calls in a task body, that appear after the first @code{accept}
25085 or @code{select} statement, and therefore does not report a potential
25086 circularity in the original program.
25088 The compiler will check to the extent it can that the above
25089 restriction is not violated, but it is not always possible to do a
25090 complete check at compile time, so it is important to use this
25091 pragma only if the stated restriction is in fact met, that is to say
25092 no task receives an entry call before elaboration of all units is completed.
25096 @node Mixing Elaboration Models
25097 @section Mixing Elaboration Models
25099 So far, we have assumed that the entire program is either compiled
25100 using the dynamic model or static model, ensuring consistency. It
25101 is possible to mix the two models, but rules have to be followed
25102 if this mixing is done to ensure that elaboration checks are not
25105 The basic rule is that @emph{a unit compiled with the static model cannot
25106 be @code{with'ed} by a unit compiled with the dynamic model}. The
25107 reason for this is that in the static model, a unit assumes that
25108 its clients guarantee to use (the equivalent of) pragma
25109 @code{Elaborate_All} so that no elaboration checks are required
25110 in inner subprograms, and this assumption is violated if the
25111 client is compiled with dynamic checks.
25113 The precise rule is as follows. A unit that is compiled with dynamic
25114 checks can only @code{with} a unit that meets at least one of the
25115 following criteria:
25120 The @code{with'ed} unit is itself compiled with dynamic elaboration
25121 checks (that is with the @option{-gnatE} switch.
25124 The @code{with'ed} unit is an internal GNAT implementation unit from
25125 the System, Interfaces, Ada, or GNAT hierarchies.
25128 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
25131 The @code{with'ing} unit (that is the client) has an explicit pragma
25132 @code{Elaborate_All} for the @code{with'ed} unit.
25137 If this rule is violated, that is if a unit with dynamic elaboration
25138 checks @code{with's} a unit that does not meet one of the above four
25139 criteria, then the binder (@code{gnatbind}) will issue a warning
25140 similar to that in the following example:
25143 warning: "x.ads" has dynamic elaboration checks and with's
25144 warning: "y.ads" which has static elaboration checks
25148 These warnings indicate that the rule has been violated, and that as a result
25149 elaboration checks may be missed in the resulting executable file.
25150 This warning may be suppressed using the @option{-ws} binder switch
25151 in the usual manner.
25153 One useful application of this mixing rule is in the case of a subsystem
25154 which does not itself @code{with} units from the remainder of the
25155 application. In this case, the entire subsystem can be compiled with
25156 dynamic checks to resolve a circularity in the subsystem, while
25157 allowing the main application that uses this subsystem to be compiled
25158 using the more reliable default static model.
25160 @node What to Do If the Default Elaboration Behavior Fails
25161 @section What to Do If the Default Elaboration Behavior Fails
25164 If the binder cannot find an acceptable order, it outputs detailed
25165 diagnostics. For example:
25171 error: elaboration circularity detected
25172 info: "proc (body)" must be elaborated before "pack (body)"
25173 info: reason: Elaborate_All probably needed in unit "pack (body)"
25174 info: recompile "pack (body)" with -gnatwl
25175 info: for full details
25176 info: "proc (body)"
25177 info: is needed by its spec:
25178 info: "proc (spec)"
25179 info: which is withed by:
25180 info: "pack (body)"
25181 info: "pack (body)" must be elaborated before "proc (body)"
25182 info: reason: pragma Elaborate in unit "proc (body)"
25188 In this case we have a cycle that the binder cannot break. On the one
25189 hand, there is an explicit pragma Elaborate in @code{proc} for
25190 @code{pack}. This means that the body of @code{pack} must be elaborated
25191 before the body of @code{proc}. On the other hand, there is elaboration
25192 code in @code{pack} that calls a subprogram in @code{proc}. This means
25193 that for maximum safety, there should really be a pragma
25194 Elaborate_All in @code{pack} for @code{proc} which would require that
25195 the body of @code{proc} be elaborated before the body of
25196 @code{pack}. Clearly both requirements cannot be satisfied.
25197 Faced with a circularity of this kind, you have three different options.
25200 @item Fix the program
25201 The most desirable option from the point of view of long-term maintenance
25202 is to rearrange the program so that the elaboration problems are avoided.
25203 One useful technique is to place the elaboration code into separate
25204 child packages. Another is to move some of the initialization code to
25205 explicitly called subprograms, where the program controls the order
25206 of initialization explicitly. Although this is the most desirable option,
25207 it may be impractical and involve too much modification, especially in
25208 the case of complex legacy code.
25210 @item Perform dynamic checks
25211 If the compilations are done using the
25213 (dynamic elaboration check) switch, then GNAT behaves in a quite different
25214 manner. Dynamic checks are generated for all calls that could possibly result
25215 in raising an exception. With this switch, the compiler does not generate
25216 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
25217 exactly as specified in the Ada 95 Reference Manual. The binder will generate
25218 an executable program that may or may not raise @code{Program_Error}, and then
25219 it is the programmer's job to ensure that it does not raise an exception. Note
25220 that it is important to compile all units with the switch, it cannot be used
25223 @item Suppress checks
25224 The drawback of dynamic checks is that they generate a
25225 significant overhead at run time, both in space and time. If you
25226 are absolutely sure that your program cannot raise any elaboration
25227 exceptions, and you still want to use the dynamic elaboration model,
25228 then you can use the configuration pragma
25229 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
25230 example this pragma could be placed in the @file{gnat.adc} file.
25232 @item Suppress checks selectively
25233 When you know that certain calls or instantiations in elaboration code cannot
25234 possibly lead to an elaboration error, and the binder nevertheless complains
25235 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
25236 elaboration circularities, it is possible to remove those warnings locally and
25237 obtain a program that will bind. Clearly this can be unsafe, and it is the
25238 responsibility of the programmer to make sure that the resulting program has no
25239 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
25240 used with different granularity to suppress warnings and break elaboration
25245 Place the pragma that names the called subprogram in the declarative part
25246 that contains the call.
25249 Place the pragma in the declarative part, without naming an entity. This
25250 disables warnings on all calls in the corresponding declarative region.
25253 Place the pragma in the package spec that declares the called subprogram,
25254 and name the subprogram. This disables warnings on all elaboration calls to
25258 Place the pragma in the package spec that declares the called subprogram,
25259 without naming any entity. This disables warnings on all elaboration calls to
25260 all subprograms declared in this spec.
25262 @item Use Pragma Elaborate
25263 As previously described in section @xref{Treatment of Pragma Elaborate},
25264 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
25265 that no elaboration checks are required on calls to the designated unit.
25266 There may be cases in which the caller knows that no transitive calls
25267 can occur, so that a @code{pragma Elaborate} will be sufficient in a
25268 case where @code{pragma Elaborate_All} would cause a circularity.
25272 These five cases are listed in order of decreasing safety, and therefore
25273 require increasing programmer care in their application. Consider the
25276 @smallexample @c adanocomment
25278 function F1 return Integer;
25283 function F2 return Integer;
25284 function Pure (x : integer) return integer;
25285 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
25286 -- pragma Suppress (Elaboration_Check); -- (4)
25290 package body Pack1 is
25291 function F1 return Integer is
25295 Val : integer := Pack2.Pure (11); -- Elab. call (1)
25298 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
25299 -- pragma Suppress(Elaboration_Check); -- (2)
25301 X1 := Pack2.F2 + 1; -- Elab. call (2)
25306 package body Pack2 is
25307 function F2 return Integer is
25311 function Pure (x : integer) return integer is
25313 return x ** 3 - 3 * x;
25317 with Pack1, Ada.Text_IO;
25320 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
25323 In the absence of any pragmas, an attempt to bind this program produces
25324 the following diagnostics:
25330 error: elaboration circularity detected
25331 info: "pack1 (body)" must be elaborated before "pack1 (body)"
25332 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
25333 info: recompile "pack1 (body)" with -gnatwl for full details
25334 info: "pack1 (body)"
25335 info: must be elaborated along with its spec:
25336 info: "pack1 (spec)"
25337 info: which is withed by:
25338 info: "pack2 (body)"
25339 info: which must be elaborated along with its spec:
25340 info: "pack2 (spec)"
25341 info: which is withed by:
25342 info: "pack1 (body)"
25345 The sources of the circularity are the two calls to @code{Pack2.Pure} and
25346 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
25347 F2 is safe, even though F2 calls F1, because the call appears after the
25348 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
25349 remove the warning on the call. It is also possible to use pragma (2)
25350 because there are no other potentially unsafe calls in the block.
25353 The call to @code{Pure} is safe because this function does not depend on the
25354 state of @code{Pack2}. Therefore any call to this function is safe, and it
25355 is correct to place pragma (3) in the corresponding package spec.
25358 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
25359 warnings on all calls to functions declared therein. Note that this is not
25360 necessarily safe, and requires more detailed examination of the subprogram
25361 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
25362 be already elaborated.
25366 It is hard to generalize on which of these four approaches should be
25367 taken. Obviously if it is possible to fix the program so that the default
25368 treatment works, this is preferable, but this may not always be practical.
25369 It is certainly simple enough to use
25371 but the danger in this case is that, even if the GNAT binder
25372 finds a correct elaboration order, it may not always do so,
25373 and certainly a binder from another Ada compiler might not. A
25374 combination of testing and analysis (for which the warnings generated
25377 switch can be useful) must be used to ensure that the program is free
25378 of errors. One switch that is useful in this testing is the
25379 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
25382 Normally the binder tries to find an order that has the best chance of
25383 of avoiding elaboration problems. With this switch, the binder
25384 plays a devil's advocate role, and tries to choose the order that
25385 has the best chance of failing. If your program works even with this
25386 switch, then it has a better chance of being error free, but this is still
25389 For an example of this approach in action, consider the C-tests (executable
25390 tests) from the ACVC suite. If these are compiled and run with the default
25391 treatment, then all but one of them succeed without generating any error
25392 diagnostics from the binder. However, there is one test that fails, and
25393 this is not surprising, because the whole point of this test is to ensure
25394 that the compiler can handle cases where it is impossible to determine
25395 a correct order statically, and it checks that an exception is indeed
25396 raised at run time.
25398 This one test must be compiled and run using the
25400 switch, and then it passes. Alternatively, the entire suite can
25401 be run using this switch. It is never wrong to run with the dynamic
25402 elaboration switch if your code is correct, and we assume that the
25403 C-tests are indeed correct (it is less efficient, but efficiency is
25404 not a factor in running the ACVC tests.)
25406 @node Elaboration for Access-to-Subprogram Values
25407 @section Elaboration for Access-to-Subprogram Values
25408 @cindex Access-to-subprogram
25411 The introduction of access-to-subprogram types in Ada 95 complicates
25412 the handling of elaboration. The trouble is that it becomes
25413 impossible to tell at compile time which procedure
25414 is being called. This means that it is not possible for the binder
25415 to analyze the elaboration requirements in this case.
25417 If at the point at which the access value is created
25418 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
25419 the body of the subprogram is
25420 known to have been elaborated, then the access value is safe, and its use
25421 does not require a check. This may be achieved by appropriate arrangement
25422 of the order of declarations if the subprogram is in the current unit,
25423 or, if the subprogram is in another unit, by using pragma
25424 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
25425 on the referenced unit.
25427 If the referenced body is not known to have been elaborated at the point
25428 the access value is created, then any use of the access value must do a
25429 dynamic check, and this dynamic check will fail and raise a
25430 @code{Program_Error} exception if the body has not been elaborated yet.
25431 GNAT will generate the necessary checks, and in addition, if the
25433 switch is set, will generate warnings that such checks are required.
25435 The use of dynamic dispatching for tagged types similarly generates
25436 a requirement for dynamic checks, and premature calls to any primitive
25437 operation of a tagged type before the body of the operation has been
25438 elaborated, will result in the raising of @code{Program_Error}.
25440 @node Summary of Procedures for Elaboration Control
25441 @section Summary of Procedures for Elaboration Control
25442 @cindex Elaboration control
25445 First, compile your program with the default options, using none of
25446 the special elaboration control switches. If the binder successfully
25447 binds your program, then you can be confident that, apart from issues
25448 raised by the use of access-to-subprogram types and dynamic dispatching,
25449 the program is free of elaboration errors. If it is important that the
25450 program be portable, then use the
25452 switch to generate warnings about missing @code{Elaborate} or
25453 @code{Elaborate_All} pragmas, and supply the missing pragmas.
25455 If the program fails to bind using the default static elaboration
25456 handling, then you can fix the program to eliminate the binder
25457 message, or recompile the entire program with the
25458 @option{-gnatE} switch to generate dynamic elaboration checks,
25459 and, if you are sure there really are no elaboration problems,
25460 use a global pragma @code{Suppress (Elaboration_Check)}.
25462 @node Other Elaboration Order Considerations
25463 @section Other Elaboration Order Considerations
25465 This section has been entirely concerned with the issue of finding a valid
25466 elaboration order, as defined by the Ada Reference Manual. In a case
25467 where several elaboration orders are valid, the task is to find one
25468 of the possible valid elaboration orders (and the static model in GNAT
25469 will ensure that this is achieved).
25471 The purpose of the elaboration rules in the Ada Reference Manual is to
25472 make sure that no entity is accessed before it has been elaborated. For
25473 a subprogram, this means that the spec and body must have been elaborated
25474 before the subprogram is called. For an object, this means that the object
25475 must have been elaborated before its value is read or written. A violation
25476 of either of these two requirements is an access before elaboration order,
25477 and this section has been all about avoiding such errors.
25479 In the case where more than one order of elaboration is possible, in the
25480 sense that access before elaboration errors are avoided, then any one of
25481 the orders is ``correct'' in the sense that it meets the requirements of
25482 the Ada Reference Manual, and no such error occurs.
25484 However, it may be the case for a given program, that there are
25485 constraints on the order of elaboration that come not from consideration
25486 of avoiding elaboration errors, but rather from extra-lingual logic
25487 requirements. Consider this example:
25489 @smallexample @c ada
25490 with Init_Constants;
25491 package Constants is
25496 package Init_Constants is
25497 procedure P; -- require a body
25498 end Init_Constants;
25501 package body Init_Constants is
25502 procedure P is begin null; end;
25506 end Init_Constants;
25510 Z : Integer := Constants.X + Constants.Y;
25514 with Text_IO; use Text_IO;
25517 Put_Line (Calc.Z'Img);
25522 In this example, there is more than one valid order of elaboration. For
25523 example both the following are correct orders:
25526 Init_Constants spec
25529 Init_Constants body
25534 Init_Constants spec
25535 Init_Constants body
25542 There is no language rule to prefer one or the other, both are correct
25543 from an order of elaboration point of view. But the programmatic effects
25544 of the two orders are very different. In the first, the elaboration routine
25545 of @code{Calc} initializes @code{Z} to zero, and then the main program
25546 runs with this value of zero. But in the second order, the elaboration
25547 routine of @code{Calc} runs after the body of Init_Constants has set
25548 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
25551 One could perhaps by applying pretty clever non-artificial intelligence
25552 to the situation guess that it is more likely that the second order of
25553 elaboration is the one desired, but there is no formal linguistic reason
25554 to prefer one over the other. In fact in this particular case, GNAT will
25555 prefer the second order, because of the rule that bodies are elaborated
25556 as soon as possible, but it's just luck that this is what was wanted
25557 (if indeed the second order was preferred).
25559 If the program cares about the order of elaboration routines in a case like
25560 this, it is important to specify the order required. In this particular
25561 case, that could have been achieved by adding to the spec of Calc:
25563 @smallexample @c ada
25564 pragma Elaborate_All (Constants);
25568 which requires that the body (if any) and spec of @code{Constants},
25569 as well as the body and spec of any unit @code{with}'ed by
25570 @code{Constants} be elaborated before @code{Calc} is elaborated.
25572 Clearly no automatic method can always guess which alternative you require,
25573 and if you are working with legacy code that had constraints of this kind
25574 which were not properly specified by adding @code{Elaborate} or
25575 @code{Elaborate_All} pragmas, then indeed it is possible that two different
25576 compilers can choose different orders.
25578 However, GNAT does attempt to diagnose the common situation where there
25579 are uninitialized variables in the visible part of a package spec, and the
25580 corresponding package body has an elaboration block that directly or
25581 indirectly initialized one or more of these variables. This is the situation
25582 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
25583 a warning that suggests this addition if it detects this situation.
25585 The @code{gnatbind}
25586 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
25587 out problems. This switch causes bodies to be elaborated as late as possible
25588 instead of as early as possible. In the example above, it would have forced
25589 the choice of the first elaboration order. If you get different results
25590 when using this switch, and particularly if one set of results is right,
25591 and one is wrong as far as you are concerned, it shows that you have some
25592 missing @code{Elaborate} pragmas. For the example above, we have the
25596 gnatmake -f -q main
25599 gnatmake -f -q main -bargs -p
25605 It is of course quite unlikely that both these results are correct, so
25606 it is up to you in a case like this to investigate the source of the
25607 difference, by looking at the two elaboration orders that are chosen,
25608 and figuring out which is correct, and then adding the necessary
25609 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
25611 @node Inline Assembler
25612 @appendix Inline Assembler
25615 If you need to write low-level software that interacts directly
25616 with the hardware, Ada provides two ways to incorporate assembly
25617 language code into your program. First, you can import and invoke
25618 external routines written in assembly language, an Ada feature fully
25619 supported by GNAT. However, for small sections of code it may be simpler
25620 or more efficient to include assembly language statements directly
25621 in your Ada source program, using the facilities of the implementation-defined
25622 package @code{System.Machine_Code}, which incorporates the gcc
25623 Inline Assembler. The Inline Assembler approach offers a number of advantages,
25624 including the following:
25627 @item No need to use non-Ada tools
25628 @item Consistent interface over different targets
25629 @item Automatic usage of the proper calling conventions
25630 @item Access to Ada constants and variables
25631 @item Definition of intrinsic routines
25632 @item Possibility of inlining a subprogram comprising assembler code
25633 @item Code optimizer can take Inline Assembler code into account
25636 This chapter presents a series of examples to show you how to use
25637 the Inline Assembler. Although it focuses on the Intel x86,
25638 the general approach applies also to other processors.
25639 It is assumed that you are familiar with Ada
25640 and with assembly language programming.
25643 * Basic Assembler Syntax::
25644 * A Simple Example of Inline Assembler::
25645 * Output Variables in Inline Assembler::
25646 * Input Variables in Inline Assembler::
25647 * Inlining Inline Assembler Code::
25648 * Other Asm Functionality::
25651 @c ---------------------------------------------------------------------------
25652 @node Basic Assembler Syntax
25653 @section Basic Assembler Syntax
25656 The assembler used by GNAT and gcc is based not on the Intel assembly
25657 language, but rather on a language that descends from the AT&T Unix
25658 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
25659 The following table summarizes the main features of @emph{as} syntax
25660 and points out the differences from the Intel conventions.
25661 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
25662 pre-processor) documentation for further information.
25665 @item Register names
25666 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
25668 Intel: No extra punctuation; for example @code{eax}
25670 @item Immediate operand
25671 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
25673 Intel: No extra punctuation; for example @code{4}
25676 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
25678 Intel: No extra punctuation; for example @code{loc}
25680 @item Memory contents
25681 gcc / @emph{as}: No extra punctuation; for example @code{loc}
25683 Intel: Square brackets; for example @code{[loc]}
25685 @item Register contents
25686 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
25688 Intel: Square brackets; for example @code{[eax]}
25690 @item Hexadecimal numbers
25691 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
25693 Intel: Trailing ``h''; for example @code{A0h}
25696 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
25699 Intel: Implicit, deduced by assembler; for example @code{mov}
25701 @item Instruction repetition
25702 gcc / @emph{as}: Split into two lines; for example
25708 Intel: Keep on one line; for example @code{rep stosl}
25710 @item Order of operands
25711 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
25713 Intel: Destination first; for example @code{mov eax, 4}
25716 @c ---------------------------------------------------------------------------
25717 @node A Simple Example of Inline Assembler
25718 @section A Simple Example of Inline Assembler
25721 The following example will generate a single assembly language statement,
25722 @code{nop}, which does nothing. Despite its lack of run-time effect,
25723 the example will be useful in illustrating the basics of
25724 the Inline Assembler facility.
25726 @smallexample @c ada
25728 with System.Machine_Code; use System.Machine_Code;
25729 procedure Nothing is
25736 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
25737 here it takes one parameter, a @emph{template string} that must be a static
25738 expression and that will form the generated instruction.
25739 @code{Asm} may be regarded as a compile-time procedure that parses
25740 the template string and additional parameters (none here),
25741 from which it generates a sequence of assembly language instructions.
25743 The examples in this chapter will illustrate several of the forms
25744 for invoking @code{Asm}; a complete specification of the syntax
25745 is found in the @cite{GNAT Reference Manual}.
25747 Under the standard GNAT conventions, the @code{Nothing} procedure
25748 should be in a file named @file{nothing.adb}.
25749 You can build the executable in the usual way:
25753 However, the interesting aspect of this example is not its run-time behavior
25754 but rather the generated assembly code.
25755 To see this output, invoke the compiler as follows:
25757 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
25759 where the options are:
25763 compile only (no bind or link)
25765 generate assembler listing
25766 @item -fomit-frame-pointer
25767 do not set up separate stack frames
25769 do not add runtime checks
25772 This gives a human-readable assembler version of the code. The resulting
25773 file will have the same name as the Ada source file, but with a @code{.s}
25774 extension. In our example, the file @file{nothing.s} has the following
25779 .file "nothing.adb"
25781 ___gnu_compiled_ada:
25784 .globl __ada_nothing
25796 The assembly code you included is clearly indicated by
25797 the compiler, between the @code{#APP} and @code{#NO_APP}
25798 delimiters. The character before the 'APP' and 'NOAPP'
25799 can differ on different targets. For example, GNU/Linux uses '#APP' while
25800 on NT you will see '/APP'.
25802 If you make a mistake in your assembler code (such as using the
25803 wrong size modifier, or using a wrong operand for the instruction) GNAT
25804 will report this error in a temporary file, which will be deleted when
25805 the compilation is finished. Generating an assembler file will help
25806 in such cases, since you can assemble this file separately using the
25807 @emph{as} assembler that comes with gcc.
25809 Assembling the file using the command
25812 as @file{nothing.s}
25815 will give you error messages whose lines correspond to the assembler
25816 input file, so you can easily find and correct any mistakes you made.
25817 If there are no errors, @emph{as} will generate an object file
25818 @file{nothing.out}.
25820 @c ---------------------------------------------------------------------------
25821 @node Output Variables in Inline Assembler
25822 @section Output Variables in Inline Assembler
25825 The examples in this section, showing how to access the processor flags,
25826 illustrate how to specify the destination operands for assembly language
25829 @smallexample @c ada
25831 with Interfaces; use Interfaces;
25832 with Ada.Text_IO; use Ada.Text_IO;
25833 with System.Machine_Code; use System.Machine_Code;
25834 procedure Get_Flags is
25835 Flags : Unsigned_32;
25838 Asm ("pushfl" & LF & HT & -- push flags on stack
25839 "popl %%eax" & LF & HT & -- load eax with flags
25840 "movl %%eax, %0", -- store flags in variable
25841 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25842 Put_Line ("Flags register:" & Flags'Img);
25847 In order to have a nicely aligned assembly listing, we have separated
25848 multiple assembler statements in the Asm template string with linefeed
25849 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
25850 The resulting section of the assembly output file is:
25857 movl %eax, -40(%ebp)
25862 It would have been legal to write the Asm invocation as:
25865 Asm ("pushfl popl %%eax movl %%eax, %0")
25868 but in the generated assembler file, this would come out as:
25872 pushfl popl %eax movl %eax, -40(%ebp)
25876 which is not so convenient for the human reader.
25878 We use Ada comments
25879 at the end of each line to explain what the assembler instructions
25880 actually do. This is a useful convention.
25882 When writing Inline Assembler instructions, you need to precede each register
25883 and variable name with a percent sign. Since the assembler already requires
25884 a percent sign at the beginning of a register name, you need two consecutive
25885 percent signs for such names in the Asm template string, thus @code{%%eax}.
25886 In the generated assembly code, one of the percent signs will be stripped off.
25888 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
25889 variables: operands you later define using @code{Input} or @code{Output}
25890 parameters to @code{Asm}.
25891 An output variable is illustrated in
25892 the third statement in the Asm template string:
25896 The intent is to store the contents of the eax register in a variable that can
25897 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
25898 necessarily work, since the compiler might optimize by using a register
25899 to hold Flags, and the expansion of the @code{movl} instruction would not be
25900 aware of this optimization. The solution is not to store the result directly
25901 but rather to advise the compiler to choose the correct operand form;
25902 that is the purpose of the @code{%0} output variable.
25904 Information about the output variable is supplied in the @code{Outputs}
25905 parameter to @code{Asm}:
25907 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25910 The output is defined by the @code{Asm_Output} attribute of the target type;
25911 the general format is
25913 Type'Asm_Output (constraint_string, variable_name)
25916 The constraint string directs the compiler how
25917 to store/access the associated variable. In the example
25919 Unsigned_32'Asm_Output ("=m", Flags);
25921 the @code{"m"} (memory) constraint tells the compiler that the variable
25922 @code{Flags} should be stored in a memory variable, thus preventing
25923 the optimizer from keeping it in a register. In contrast,
25925 Unsigned_32'Asm_Output ("=r", Flags);
25927 uses the @code{"r"} (register) constraint, telling the compiler to
25928 store the variable in a register.
25930 If the constraint is preceded by the equal character (@strong{=}), it tells
25931 the compiler that the variable will be used to store data into it.
25933 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
25934 allowing the optimizer to choose whatever it deems best.
25936 There are a fairly large number of constraints, but the ones that are
25937 most useful (for the Intel x86 processor) are the following:
25943 global (i.e. can be stored anywhere)
25961 use one of eax, ebx, ecx or edx
25963 use one of eax, ebx, ecx, edx, esi or edi
25966 The full set of constraints is described in the gcc and @emph{as}
25967 documentation; note that it is possible to combine certain constraints
25968 in one constraint string.
25970 You specify the association of an output variable with an assembler operand
25971 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
25973 @smallexample @c ada
25975 Asm ("pushfl" & LF & HT & -- push flags on stack
25976 "popl %%eax" & LF & HT & -- load eax with flags
25977 "movl %%eax, %0", -- store flags in variable
25978 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25982 @code{%0} will be replaced in the expanded code by the appropriate operand,
25984 the compiler decided for the @code{Flags} variable.
25986 In general, you may have any number of output variables:
25989 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
25991 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
25992 of @code{Asm_Output} attributes
25996 @smallexample @c ada
25998 Asm ("movl %%eax, %0" & LF & HT &
25999 "movl %%ebx, %1" & LF & HT &
26001 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
26002 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
26003 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
26007 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
26008 in the Ada program.
26010 As a variation on the @code{Get_Flags} example, we can use the constraints
26011 string to direct the compiler to store the eax register into the @code{Flags}
26012 variable, instead of including the store instruction explicitly in the
26013 @code{Asm} template string:
26015 @smallexample @c ada
26017 with Interfaces; use Interfaces;
26018 with Ada.Text_IO; use Ada.Text_IO;
26019 with System.Machine_Code; use System.Machine_Code;
26020 procedure Get_Flags_2 is
26021 Flags : Unsigned_32;
26024 Asm ("pushfl" & LF & HT & -- push flags on stack
26025 "popl %%eax", -- save flags in eax
26026 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
26027 Put_Line ("Flags register:" & Flags'Img);
26033 The @code{"a"} constraint tells the compiler that the @code{Flags}
26034 variable will come from the eax register. Here is the resulting code:
26042 movl %eax,-40(%ebp)
26047 The compiler generated the store of eax into Flags after
26048 expanding the assembler code.
26050 Actually, there was no need to pop the flags into the eax register;
26051 more simply, we could just pop the flags directly into the program variable:
26053 @smallexample @c ada
26055 with Interfaces; use Interfaces;
26056 with Ada.Text_IO; use Ada.Text_IO;
26057 with System.Machine_Code; use System.Machine_Code;
26058 procedure Get_Flags_3 is
26059 Flags : Unsigned_32;
26062 Asm ("pushfl" & LF & HT & -- push flags on stack
26063 "pop %0", -- save flags in Flags
26064 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26065 Put_Line ("Flags register:" & Flags'Img);
26070 @c ---------------------------------------------------------------------------
26071 @node Input Variables in Inline Assembler
26072 @section Input Variables in Inline Assembler
26075 The example in this section illustrates how to specify the source operands
26076 for assembly language statements.
26077 The program simply increments its input value by 1:
26079 @smallexample @c ada
26081 with Interfaces; use Interfaces;
26082 with Ada.Text_IO; use Ada.Text_IO;
26083 with System.Machine_Code; use System.Machine_Code;
26084 procedure Increment is
26086 function Incr (Value : Unsigned_32) return Unsigned_32 is
26087 Result : Unsigned_32;
26090 Inputs => Unsigned_32'Asm_Input ("a", Value),
26091 Outputs => Unsigned_32'Asm_Output ("=a", Result));
26095 Value : Unsigned_32;
26099 Put_Line ("Value before is" & Value'Img);
26100 Value := Incr (Value);
26101 Put_Line ("Value after is" & Value'Img);
26106 The @code{Outputs} parameter to @code{Asm} specifies
26107 that the result will be in the eax register and that it is to be stored
26108 in the @code{Result} variable.
26110 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
26111 but with an @code{Asm_Input} attribute.
26112 The @code{"="} constraint, indicating an output value, is not present.
26114 You can have multiple input variables, in the same way that you can have more
26115 than one output variable.
26117 The parameter count (%0, %1) etc, now starts at the first input
26118 statement, and continues with the output statements.
26119 When both parameters use the same variable, the
26120 compiler will treat them as the same %n operand, which is the case here.
26122 Just as the @code{Outputs} parameter causes the register to be stored into the
26123 target variable after execution of the assembler statements, so does the
26124 @code{Inputs} parameter cause its variable to be loaded into the register
26125 before execution of the assembler statements.
26127 Thus the effect of the @code{Asm} invocation is:
26129 @item load the 32-bit value of @code{Value} into eax
26130 @item execute the @code{incl %eax} instruction
26131 @item store the contents of eax into the @code{Result} variable
26134 The resulting assembler file (with @option{-O2} optimization) contains:
26137 _increment__incr.1:
26150 @c ---------------------------------------------------------------------------
26151 @node Inlining Inline Assembler Code
26152 @section Inlining Inline Assembler Code
26155 For a short subprogram such as the @code{Incr} function in the previous
26156 section, the overhead of the call and return (creating / deleting the stack
26157 frame) can be significant, compared to the amount of code in the subprogram
26158 body. A solution is to apply Ada's @code{Inline} pragma to the subprogram,
26159 which directs the compiler to expand invocations of the subprogram at the
26160 point(s) of call, instead of setting up a stack frame for out-of-line calls.
26161 Here is the resulting program:
26163 @smallexample @c ada
26165 with Interfaces; use Interfaces;
26166 with Ada.Text_IO; use Ada.Text_IO;
26167 with System.Machine_Code; use System.Machine_Code;
26168 procedure Increment_2 is
26170 function Incr (Value : Unsigned_32) return Unsigned_32 is
26171 Result : Unsigned_32;
26174 Inputs => Unsigned_32'Asm_Input ("a", Value),
26175 Outputs => Unsigned_32'Asm_Output ("=a", Result));
26178 pragma Inline (Increment);
26180 Value : Unsigned_32;
26184 Put_Line ("Value before is" & Value'Img);
26185 Value := Increment (Value);
26186 Put_Line ("Value after is" & Value'Img);
26191 Compile the program with both optimization (@option{-O2}) and inlining
26192 enabled (@option{-gnatpn} instead of @option{-gnatp}).
26194 The @code{Incr} function is still compiled as usual, but at the
26195 point in @code{Increment} where our function used to be called:
26200 call _increment__incr.1
26205 the code for the function body directly appears:
26218 thus saving the overhead of stack frame setup and an out-of-line call.
26220 @c ---------------------------------------------------------------------------
26221 @node Other Asm Functionality
26222 @section Other @code{Asm} Functionality
26225 This section describes two important parameters to the @code{Asm}
26226 procedure: @code{Clobber}, which identifies register usage;
26227 and @code{Volatile}, which inhibits unwanted optimizations.
26230 * The Clobber Parameter::
26231 * The Volatile Parameter::
26234 @c ---------------------------------------------------------------------------
26235 @node The Clobber Parameter
26236 @subsection The @code{Clobber} Parameter
26239 One of the dangers of intermixing assembly language and a compiled language
26240 such as Ada is that the compiler needs to be aware of which registers are
26241 being used by the assembly code. In some cases, such as the earlier examples,
26242 the constraint string is sufficient to indicate register usage (e.g.,
26244 the eax register). But more generally, the compiler needs an explicit
26245 identification of the registers that are used by the Inline Assembly
26248 Using a register that the compiler doesn't know about
26249 could be a side effect of an instruction (like @code{mull}
26250 storing its result in both eax and edx).
26251 It can also arise from explicit register usage in your
26252 assembly code; for example:
26255 Asm ("movl %0, %%ebx" & LF & HT &
26257 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
26258 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
26262 where the compiler (since it does not analyze the @code{Asm} template string)
26263 does not know you are using the ebx register.
26265 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
26266 to identify the registers that will be used by your assembly code:
26270 Asm ("movl %0, %%ebx" & LF & HT &
26272 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
26273 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
26278 The Clobber parameter is a static string expression specifying the
26279 register(s) you are using. Note that register names are @emph{not} prefixed
26280 by a percent sign. Also, if more than one register is used then their names
26281 are separated by commas; e.g., @code{"eax, ebx"}
26283 The @code{Clobber} parameter has several additional uses:
26285 @item Use ``register'' name @code{cc} to indicate that flags might have changed
26286 @item Use ``register'' name @code{memory} if you changed a memory location
26289 @c ---------------------------------------------------------------------------
26290 @node The Volatile Parameter
26291 @subsection The @code{Volatile} Parameter
26292 @cindex Volatile parameter
26295 Compiler optimizations in the presence of Inline Assembler may sometimes have
26296 unwanted effects. For example, when an @code{Asm} invocation with an input
26297 variable is inside a loop, the compiler might move the loading of the input
26298 variable outside the loop, regarding it as a one-time initialization.
26300 If this effect is not desired, you can disable such optimizations by setting
26301 the @code{Volatile} parameter to @code{True}; for example:
26303 @smallexample @c ada
26305 Asm ("movl %0, %%ebx" & LF & HT &
26307 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
26308 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
26314 By default, @code{Volatile} is set to @code{False} unless there is no
26315 @code{Outputs} parameter.
26317 Although setting @code{Volatile} to @code{True} prevents unwanted
26318 optimizations, it will also disable other optimizations that might be
26319 important for efficiency. In general, you should set @code{Volatile}
26320 to @code{True} only if the compiler's optimizations have created
26322 @c END OF INLINE ASSEMBLER CHAPTER
26323 @c ===============================
26325 @c ***********************************
26326 @c * Compatibility and Porting Guide *
26327 @c ***********************************
26328 @node Compatibility and Porting Guide
26329 @appendix Compatibility and Porting Guide
26332 This chapter describes the compatibility issues that may arise between
26333 GNAT and other Ada 83 and Ada 95 compilation systems, and shows how GNAT
26334 can expedite porting
26335 applications developed in other Ada environments.
26338 * Compatibility with Ada 83::
26339 * Implementation-dependent characteristics::
26340 * Compatibility with Other Ada 95 Systems::
26341 * Representation Clauses::
26343 @c Brief section is only in non-VMS version
26344 @c Full chapter is in VMS version
26345 * Compatibility with HP Ada 83::
26348 * Transitioning to 64-Bit GNAT for OpenVMS::
26352 @node Compatibility with Ada 83
26353 @section Compatibility with Ada 83
26354 @cindex Compatibility (between Ada 83 and Ada 95)
26357 Ada 95 is designed to be highly upwards compatible with Ada 83. In
26358 particular, the design intention is that the difficulties associated
26359 with moving from Ada 83 to Ada 95 should be no greater than those
26360 that occur when moving from one Ada 83 system to another.
26362 However, there are a number of points at which there are minor
26363 incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains
26364 full details of these issues,
26365 and should be consulted for a complete treatment.
26367 following subsections treat the most likely issues to be encountered.
26370 * Legal Ada 83 programs that are illegal in Ada 95::
26371 * More deterministic semantics::
26372 * Changed semantics::
26373 * Other language compatibility issues::
26376 @node Legal Ada 83 programs that are illegal in Ada 95
26377 @subsection Legal Ada 83 programs that are illegal in Ada 95
26380 @item Character literals
26381 Some uses of character literals are ambiguous. Since Ada 95 has introduced
26382 @code{Wide_Character} as a new predefined character type, some uses of
26383 character literals that were legal in Ada 83 are illegal in Ada 95.
26385 @smallexample @c ada
26386 for Char in 'A' .. 'Z' loop ... end loop;
26389 The problem is that @code{'A'} and @code{'Z'} could be from either
26390 @code{Character} or @code{Wide_Character}. The simplest correction
26391 is to make the type explicit; e.g.:
26392 @smallexample @c ada
26393 for Char in Character range 'A' .. 'Z' loop ... end loop;
26396 @item New reserved words
26397 The identifiers @code{abstract}, @code{aliased}, @code{protected},
26398 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
26399 Existing Ada 83 code using any of these identifiers must be edited to
26400 use some alternative name.
26402 @item Freezing rules
26403 The rules in Ada 95 are slightly different with regard to the point at
26404 which entities are frozen, and representation pragmas and clauses are
26405 not permitted past the freeze point. This shows up most typically in
26406 the form of an error message complaining that a representation item
26407 appears too late, and the appropriate corrective action is to move
26408 the item nearer to the declaration of the entity to which it refers.
26410 A particular case is that representation pragmas
26413 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
26415 cannot be applied to a subprogram body. If necessary, a separate subprogram
26416 declaration must be introduced to which the pragma can be applied.
26418 @item Optional bodies for library packages
26419 In Ada 83, a package that did not require a package body was nevertheless
26420 allowed to have one. This lead to certain surprises in compiling large
26421 systems (situations in which the body could be unexpectedly ignored by the
26422 binder). In Ada 95, if a package does not require a body then it is not
26423 permitted to have a body. To fix this problem, simply remove a redundant
26424 body if it is empty, or, if it is non-empty, introduce a dummy declaration
26425 into the spec that makes the body required. One approach is to add a private
26426 part to the package declaration (if necessary), and define a parameterless
26427 procedure called @code{Requires_Body}, which must then be given a dummy
26428 procedure body in the package body, which then becomes required.
26429 Another approach (assuming that this does not introduce elaboration
26430 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
26431 since one effect of this pragma is to require the presence of a package body.
26433 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
26434 In Ada 95, the exception @code{Numeric_Error} is a renaming of
26435 @code{Constraint_Error}.
26436 This means that it is illegal to have separate exception handlers for
26437 the two exceptions. The fix is simply to remove the handler for the
26438 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
26439 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
26441 @item Indefinite subtypes in generics
26442 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
26443 as the actual for a generic formal private type, but then the instantiation
26444 would be illegal if there were any instances of declarations of variables
26445 of this type in the generic body. In Ada 95, to avoid this clear violation
26446 of the methodological principle known as the ``contract model'',
26447 the generic declaration explicitly indicates whether
26448 or not such instantiations are permitted. If a generic formal parameter
26449 has explicit unknown discriminants, indicated by using @code{(<>)} after the
26450 type name, then it can be instantiated with indefinite types, but no
26451 stand-alone variables can be declared of this type. Any attempt to declare
26452 such a variable will result in an illegality at the time the generic is
26453 declared. If the @code{(<>)} notation is not used, then it is illegal
26454 to instantiate the generic with an indefinite type.
26455 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
26456 It will show up as a compile time error, and
26457 the fix is usually simply to add the @code{(<>)} to the generic declaration.
26460 @node More deterministic semantics
26461 @subsection More deterministic semantics
26465 Conversions from real types to integer types round away from 0. In Ada 83
26466 the conversion Integer(2.5) could deliver either 2 or 3 as its value. This
26467 implementation freedom was intended to support unbiased rounding in
26468 statistical applications, but in practice it interfered with portability.
26469 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
26470 is required. Numeric code may be affected by this change in semantics.
26471 Note, though, that this issue is no worse than already existed in Ada 83
26472 when porting code from one vendor to another.
26475 The Real-Time Annex introduces a set of policies that define the behavior of
26476 features that were implementation dependent in Ada 83, such as the order in
26477 which open select branches are executed.
26480 @node Changed semantics
26481 @subsection Changed semantics
26484 The worst kind of incompatibility is one where a program that is legal in
26485 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
26486 possible in Ada 83. Fortunately this is extremely rare, but the one
26487 situation that you should be alert to is the change in the predefined type
26488 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
26491 @item range of @code{Character}
26492 The range of @code{Standard.Character} is now the full 256 characters
26493 of Latin-1, whereas in most Ada 83 implementations it was restricted
26494 to 128 characters. Although some of the effects of
26495 this change will be manifest in compile-time rejection of legal
26496 Ada 83 programs it is possible for a working Ada 83 program to have
26497 a different effect in Ada 95, one that was not permitted in Ada 83.
26498 As an example, the expression
26499 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
26500 delivers @code{255} as its value.
26501 In general, you should look at the logic of any
26502 character-processing Ada 83 program and see whether it needs to be adapted
26503 to work correctly with Latin-1. Note that the predefined Ada 95 API has a
26504 character handling package that may be relevant if code needs to be adapted
26505 to account for the additional Latin-1 elements.
26506 The desirable fix is to
26507 modify the program to accommodate the full character set, but in some cases
26508 it may be convenient to define a subtype or derived type of Character that
26509 covers only the restricted range.
26513 @node Other language compatibility issues
26514 @subsection Other language compatibility issues
26516 @item @option{-gnat83 switch}
26517 All implementations of GNAT provide a switch that causes GNAT to operate
26518 in Ada 83 mode. In this mode, some but not all compatibility problems
26519 of the type described above are handled automatically. For example, the
26520 new Ada 95 reserved words are treated simply as identifiers as in Ada 83.
26522 in practice, it is usually advisable to make the necessary modifications
26523 to the program to remove the need for using this switch.
26524 See @ref{Compiling Different Versions of Ada}.
26526 @item Support for removed Ada 83 pragmas and attributes
26527 A number of pragmas and attributes from Ada 83 have been removed from Ada 95,
26528 generally because they have been replaced by other mechanisms. Ada 95
26529 compilers are allowed, but not required, to implement these missing
26530 elements. In contrast with some other Ada 95 compilers, GNAT implements all
26531 such pragmas and attributes, eliminating this compatibility concern. These
26532 include @code{pragma Interface} and the floating point type attributes
26533 (@code{Emax}, @code{Mantissa}, etc.), among other items.
26536 @node Implementation-dependent characteristics
26537 @section Implementation-dependent characteristics
26539 Although the Ada language defines the semantics of each construct as
26540 precisely as practical, in some situations (for example for reasons of
26541 efficiency, or where the effect is heavily dependent on the host or target
26542 platform) the implementation is allowed some freedom. In porting Ada 83
26543 code to GNAT, you need to be aware of whether / how the existing code
26544 exercised such implementation dependencies. Such characteristics fall into
26545 several categories, and GNAT offers specific support in assisting the
26546 transition from certain Ada 83 compilers.
26549 * Implementation-defined pragmas::
26550 * Implementation-defined attributes::
26552 * Elaboration order::
26553 * Target-specific aspects::
26556 @node Implementation-defined pragmas
26557 @subsection Implementation-defined pragmas
26560 Ada compilers are allowed to supplement the language-defined pragmas, and
26561 these are a potential source of non-portability. All GNAT-defined pragmas
26562 are described in the GNAT Reference Manual, and these include several that
26563 are specifically intended to correspond to other vendors' Ada 83 pragmas.
26564 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
26566 compatibility with HP Ada 83, GNAT supplies the pragmas
26567 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
26568 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
26569 and @code{Volatile}.
26570 Other relevant pragmas include @code{External} and @code{Link_With}.
26571 Some vendor-specific
26572 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
26574 avoiding compiler rejection of units that contain such pragmas; they are not
26575 relevant in a GNAT context and hence are not otherwise implemented.
26577 @node Implementation-defined attributes
26578 @subsection Implementation-defined attributes
26580 Analogous to pragmas, the set of attributes may be extended by an
26581 implementation. All GNAT-defined attributes are described in the
26582 @cite{GNAT Reference Manual}, and these include several that are specifically
26584 to correspond to other vendors' Ada 83 attributes. For migrating from VADS,
26585 the attribute @code{VADS_Size} may be useful. For compatibility with HP
26586 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
26590 @subsection Libraries
26592 Vendors may supply libraries to supplement the standard Ada API. If Ada 83
26593 code uses vendor-specific libraries then there are several ways to manage
26597 If the source code for the libraries (specifications and bodies) are
26598 available, then the libraries can be migrated in the same way as the
26601 If the source code for the specifications but not the bodies are
26602 available, then you can reimplement the bodies.
26604 Some new Ada 95 features obviate the need for library support. For
26605 example most Ada 83 vendors supplied a package for unsigned integers. The
26606 Ada 95 modular type feature is the preferred way to handle this need, so
26607 instead of migrating or reimplementing the unsigned integer package it may
26608 be preferable to retrofit the application using modular types.
26611 @node Elaboration order
26612 @subsection Elaboration order
26614 The implementation can choose any elaboration order consistent with the unit
26615 dependency relationship. This freedom means that some orders can result in
26616 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
26617 to invoke a subprogram its body has been elaborated, or to instantiate a
26618 generic before the generic body has been elaborated. By default GNAT
26619 attempts to choose a safe order (one that will not encounter access before
26620 elaboration problems) by implicitly inserting @code{Elaborate} or
26621 @code{Elaborate_All} pragmas where
26622 needed. However, this can lead to the creation of elaboration circularities
26623 and a resulting rejection of the program by gnatbind. This issue is
26624 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
26625 In brief, there are several
26626 ways to deal with this situation:
26630 Modify the program to eliminate the circularities, e.g. by moving
26631 elaboration-time code into explicitly-invoked procedures
26633 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
26634 @code{Elaborate} pragmas, and then inhibit the generation of implicit
26635 @code{Elaborate_All}
26636 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
26637 (by selectively suppressing elaboration checks via pragma
26638 @code{Suppress(Elaboration_Check)} when it is safe to do so).
26641 @node Target-specific aspects
26642 @subsection Target-specific aspects
26644 Low-level applications need to deal with machine addresses, data
26645 representations, interfacing with assembler code, and similar issues. If
26646 such an Ada 83 application is being ported to different target hardware (for
26647 example where the byte endianness has changed) then you will need to
26648 carefully examine the program logic; the porting effort will heavily depend
26649 on the robustness of the original design. Moreover, Ada 95 is sometimes
26650 incompatible with typical Ada 83 compiler practices regarding implicit
26651 packing, the meaning of the Size attribute, and the size of access values.
26652 GNAT's approach to these issues is described in @ref{Representation Clauses}.
26654 @node Compatibility with Other Ada 95 Systems
26655 @section Compatibility with Other Ada 95 Systems
26658 Providing that programs avoid the use of implementation dependent and
26659 implementation defined features of Ada 95, as documented in the Ada 95
26660 reference manual, there should be a high degree of portability between
26661 GNAT and other Ada 95 systems. The following are specific items which
26662 have proved troublesome in moving GNAT programs to other Ada 95
26663 compilers, but do not affect porting code to GNAT@.
26666 @item Ada 83 Pragmas and Attributes
26667 Ada 95 compilers are allowed, but not required, to implement the missing
26668 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
26669 GNAT implements all such pragmas and attributes, eliminating this as
26670 a compatibility concern, but some other Ada 95 compilers reject these
26671 pragmas and attributes.
26673 @item Special-needs Annexes
26674 GNAT implements the full set of special needs annexes. At the
26675 current time, it is the only Ada 95 compiler to do so. This means that
26676 programs making use of these features may not be portable to other Ada
26677 95 compilation systems.
26679 @item Representation Clauses
26680 Some other Ada 95 compilers implement only the minimal set of
26681 representation clauses required by the Ada 95 reference manual. GNAT goes
26682 far beyond this minimal set, as described in the next section.
26685 @node Representation Clauses
26686 @section Representation Clauses
26689 The Ada 83 reference manual was quite vague in describing both the minimal
26690 required implementation of representation clauses, and also their precise
26691 effects. The Ada 95 reference manual is much more explicit, but the minimal
26692 set of capabilities required in Ada 95 is quite limited.
26694 GNAT implements the full required set of capabilities described in the
26695 Ada 95 reference manual, but also goes much beyond this, and in particular
26696 an effort has been made to be compatible with existing Ada 83 usage to the
26697 greatest extent possible.
26699 A few cases exist in which Ada 83 compiler behavior is incompatible with
26700 requirements in the Ada 95 reference manual. These are instances of
26701 intentional or accidental dependence on specific implementation dependent
26702 characteristics of these Ada 83 compilers. The following is a list of
26703 the cases most likely to arise in existing legacy Ada 83 code.
26706 @item Implicit Packing
26707 Some Ada 83 compilers allowed a Size specification to cause implicit
26708 packing of an array or record. This could cause expensive implicit
26709 conversions for change of representation in the presence of derived
26710 types, and the Ada design intends to avoid this possibility.
26711 Subsequent AI's were issued to make it clear that such implicit
26712 change of representation in response to a Size clause is inadvisable,
26713 and this recommendation is represented explicitly in the Ada 95 RM
26714 as implementation advice that is followed by GNAT@.
26715 The problem will show up as an error
26716 message rejecting the size clause. The fix is simply to provide
26717 the explicit pragma @code{Pack}, or for more fine tuned control, provide
26718 a Component_Size clause.
26720 @item Meaning of Size Attribute
26721 The Size attribute in Ada 95 for discrete types is defined as being the
26722 minimal number of bits required to hold values of the type. For example,
26723 on a 32-bit machine, the size of Natural will typically be 31 and not
26724 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and
26725 some 32 in this situation. This problem will usually show up as a compile
26726 time error, but not always. It is a good idea to check all uses of the
26727 'Size attribute when porting Ada 83 code. The GNAT specific attribute
26728 Object_Size can provide a useful way of duplicating the behavior of
26729 some Ada 83 compiler systems.
26731 @item Size of Access Types
26732 A common assumption in Ada 83 code is that an access type is in fact a pointer,
26733 and that therefore it will be the same size as a System.Address value. This
26734 assumption is true for GNAT in most cases with one exception. For the case of
26735 a pointer to an unconstrained array type (where the bounds may vary from one
26736 value of the access type to another), the default is to use a ``fat pointer'',
26737 which is represented as two separate pointers, one to the bounds, and one to
26738 the array. This representation has a number of advantages, including improved
26739 efficiency. However, it may cause some difficulties in porting existing Ada 83
26740 code which makes the assumption that, for example, pointers fit in 32 bits on
26741 a machine with 32-bit addressing.
26743 To get around this problem, GNAT also permits the use of ``thin pointers'' for
26744 access types in this case (where the designated type is an unconstrained array
26745 type). These thin pointers are indeed the same size as a System.Address value.
26746 To specify a thin pointer, use a size clause for the type, for example:
26748 @smallexample @c ada
26749 type X is access all String;
26750 for X'Size use Standard'Address_Size;
26754 which will cause the type X to be represented using a single pointer.
26755 When using this representation, the bounds are right behind the array.
26756 This representation is slightly less efficient, and does not allow quite
26757 such flexibility in the use of foreign pointers or in using the
26758 Unrestricted_Access attribute to create pointers to non-aliased objects.
26759 But for any standard portable use of the access type it will work in
26760 a functionally correct manner and allow porting of existing code.
26761 Note that another way of forcing a thin pointer representation
26762 is to use a component size clause for the element size in an array,
26763 or a record representation clause for an access field in a record.
26767 @c This brief section is only in the non-VMS version
26768 @c The complete chapter on HP Ada is in the VMS version
26769 @node Compatibility with HP Ada 83
26770 @section Compatibility with HP Ada 83
26773 The VMS version of GNAT fully implements all the pragmas and attributes
26774 provided by HP Ada 83, as well as providing the standard HP Ada 83
26775 libraries, including Starlet. In addition, data layouts and parameter
26776 passing conventions are highly compatible. This means that porting
26777 existing HP Ada 83 code to GNAT in VMS systems should be easier than
26778 most other porting efforts. The following are some of the most
26779 significant differences between GNAT and HP Ada 83.
26782 @item Default floating-point representation
26783 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
26784 it is VMS format. GNAT does implement the necessary pragmas
26785 (Long_Float, Float_Representation) for changing this default.
26788 The package System in GNAT exactly corresponds to the definition in the
26789 Ada 95 reference manual, which means that it excludes many of the
26790 HP Ada 83 extensions. However, a separate package Aux_DEC is provided
26791 that contains the additional definitions, and a special pragma,
26792 Extend_System allows this package to be treated transparently as an
26793 extension of package System.
26796 The definitions provided by Aux_DEC are exactly compatible with those
26797 in the HP Ada 83 version of System, with one exception.
26798 HP Ada provides the following declarations:
26800 @smallexample @c ada
26801 TO_ADDRESS (INTEGER)
26802 TO_ADDRESS (UNSIGNED_LONGWORD)
26803 TO_ADDRESS (universal_integer)
26807 The version of TO_ADDRESS taking a universal integer argument is in fact
26808 an extension to Ada 83 not strictly compatible with the reference manual.
26809 In GNAT, we are constrained to be exactly compatible with the standard,
26810 and this means we cannot provide this capability. In HP Ada 83, the
26811 point of this definition is to deal with a call like:
26813 @smallexample @c ada
26814 TO_ADDRESS (16#12777#);
26818 Normally, according to the Ada 83 standard, one would expect this to be
26819 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
26820 of TO_ADDRESS@. However, in HP Ada 83, there is no ambiguity, since the
26821 definition using universal_integer takes precedence.
26823 In GNAT, since the version with universal_integer cannot be supplied, it is
26824 not possible to be 100% compatible. Since there are many programs using
26825 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
26826 to change the name of the function in the UNSIGNED_LONGWORD case, so the
26827 declarations provided in the GNAT version of AUX_Dec are:
26829 @smallexample @c ada
26830 function To_Address (X : Integer) return Address;
26831 pragma Pure_Function (To_Address);
26833 function To_Address_Long (X : Unsigned_Longword)
26835 pragma Pure_Function (To_Address_Long);
26839 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
26840 change the name to TO_ADDRESS_LONG@.
26842 @item Task_Id values
26843 The Task_Id values assigned will be different in the two systems, and GNAT
26844 does not provide a specified value for the Task_Id of the environment task,
26845 which in GNAT is treated like any other declared task.
26848 For full details on these and other less significant compatibility issues,
26849 see appendix E of the HP publication entitled @cite{HP Ada, Technical
26850 Overview and Comparison on HP Platforms}.
26852 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
26853 attributes are recognized, although only a subset of them can sensibly
26854 be implemented. The description of pragmas in the
26855 @cite{GNAT Reference Manual}
26856 indicates whether or not they are applicable to non-VMS systems.
26860 @node Transitioning to 64-Bit GNAT for OpenVMS
26861 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
26864 This section is meant to assist users of pre-2006 @value{EDITION}
26865 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
26866 the version of the GNAT technology supplied in 2006 and later for
26867 OpenVMS on both Alpha and I64.
26870 * Introduction to transitioning::
26871 * Migration of 32 bit code::
26872 * Taking advantage of 64 bit addressing::
26873 * Technical details::
26876 @node Introduction to transitioning
26877 @subsection Introduction
26880 64-bit @value{EDITION} for Open VMS has been designed to meet
26885 Providing a full conforming implementation of the Ada 95 language
26888 Allowing maximum backward compatibility, thus easing migration of existing
26892 Supplying a path for exploiting the full 64-bit address range
26896 Ada's strong typing semantics has made it
26897 impractical to have different 32-bit and 64-bit modes. As soon as
26898 one object could possibly be outside the 32-bit address space, this
26899 would make it necessary for the @code{System.Address} type to be 64 bits.
26900 In particular, this would cause inconsistencies if 32-bit code is
26901 called from 64-bit code that raises an exception.
26903 This issue has been resolved by always using 64-bit addressing
26904 at the system level, but allowing for automatic conversions between
26905 32-bit and 64-bit addresses where required. Thus users who
26906 do not currently require 64-bit addressing capabilities, can
26907 recompile their code with only minimal changes (and indeed
26908 if the code is written in portable Ada, with no assumptions about
26909 the size of the @code{Address} type, then no changes at all are necessary).
26911 this approach provides a simple, gradual upgrade path to future
26912 use of larger memories than available for 32-bit systems.
26913 Also, newly written applications or libraries will by default
26914 be fully compatible with future systems exploiting 64-bit
26915 addressing capabilities.
26917 @ref{Migration of 32 bit code}, will focus on porting applications
26918 that do not require more than 2 GB of
26919 addressable memory. This code will be referred to as
26920 @emph{32-bit code}.
26921 For applications intending to exploit the full 64-bit address space,
26922 @ref{Taking advantage of 64 bit addressing},
26923 will consider further changes that may be required.
26924 Such code will be referred to below as @emph{64-bit code}.
26926 @node Migration of 32 bit code
26927 @subsection Migration of 32-bit code
26932 * Unchecked conversions::
26933 * Predefined constants::
26934 * Interfacing with C::
26935 * Experience with source compatibility::
26938 @node Address types
26939 @subsubsection Address types
26942 To solve the problem of mixing 64-bit and 32-bit addressing,
26943 while maintaining maximum backward compatibility, the following
26944 approach has been taken:
26948 @code{System.Address} always has a size of 64 bits
26951 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
26955 Since @code{System.Short_Address} is a subtype of @code{System.Address},
26956 a @code{Short_Address}
26957 may be used where an @code{Address} is required, and vice versa, without
26958 needing explicit type conversions.
26959 By virtue of the Open VMS parameter passing conventions,
26961 and exported subprograms that have 32-bit address parameters are
26962 compatible with those that have 64-bit address parameters.
26963 (See @ref{Making code 64 bit clean} for details.)
26965 The areas that may need attention are those where record types have
26966 been defined that contain components of the type @code{System.Address}, and
26967 where objects of this type are passed to code expecting a record layout with
26970 Different compilers on different platforms cannot be
26971 expected to represent the same type in the same way,
26972 since alignment constraints
26973 and other system-dependent properties affect the compiler's decision.
26974 For that reason, Ada code
26975 generally uses representation clauses to specify the expected
26976 layout where required.
26978 If such a representation clause uses 32 bits for a component having
26979 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
26980 will detect that error and produce a specific diagnostic message.
26981 The developer should then determine whether the representation
26982 should be 64 bits or not and make either of two changes:
26983 change the size to 64 bits and leave the type as @code{System.Address}, or
26984 leave the size as 32 bits and change the type to @code{System.Short_Address}.
26985 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
26986 required in any code setting or accessing the field; the compiler will
26987 automatically perform any needed conversions between address
26991 @subsubsection Access types
26994 By default, objects designated by access values are always
26995 allocated in the 32-bit
26996 address space. Thus legacy code will never contain
26997 any objects that are not addressable with 32-bit addresses, and
26998 the compiler will never raise exceptions as result of mixing
26999 32-bit and 64-bit addresses.
27001 However, the access values themselves are represented in 64 bits, for optimum
27002 performance and future compatibility with 64-bit code. As was
27003 the case with @code{System.Address}, the compiler will give an error message
27004 if an object or record component has a representation clause that
27005 requires the access value to fit in 32 bits. In such a situation,
27006 an explicit size clause for the access type, specifying 32 bits,
27007 will have the desired effect.
27009 General access types (declared with @code{access all}) can never be
27010 32 bits, as values of such types must be able to refer to any object
27011 of the designated type,
27012 including objects residing outside the 32-bit address range.
27013 Existing Ada 83 code will not contain such type definitions,
27014 however, since general access types were introduced in Ada 95.
27016 @node Unchecked conversions
27017 @subsubsection Unchecked conversions
27020 In the case of an @code{Unchecked_Conversion} where the source type is a
27021 64-bit access type or the type @code{System.Address}, and the target
27022 type is a 32-bit type, the compiler will generate a warning.
27023 Even though the generated code will still perform the required
27024 conversions, it is highly recommended in these cases to use
27025 respectively a 32-bit access type or @code{System.Short_Address}
27026 as the source type.
27028 @node Predefined constants
27029 @subsubsection Predefined constants
27032 The following table shows the correspondence between pre-2006 versions of
27033 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
27036 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
27037 @item @b{Constant} @tab @b{Old} @tab @b{New}
27038 @item @code{System.Word_Size} @tab 32 @tab 64
27039 @item @code{System.Memory_Size} @tab 2**32 @tab 2**64
27040 @item @code{System.Short_Memory_Size} @tab 2**32 @tab 2**32
27041 @item @code{System.Address_Size} @tab 32 @tab 64
27045 If you need to refer to the specific
27046 memory size of a 32-bit implementation, instead of the
27047 actual memory size, use @code{System.Short_Memory_Size}
27048 rather than @code{System.Memory_Size}.
27049 Similarly, references to @code{System.Address_Size} may need
27050 to be replaced by @code{System.Short_Address'Size}.
27051 The program @command{gnatfind} may be useful for locating
27052 references to the above constants, so that you can verify that they
27055 @node Interfacing with C
27056 @subsubsection Interfacing with C
27059 In order to minimize the impact of the transition to 64-bit addresses on
27060 legacy programs, some fundamental types in the @code{Interfaces.C}
27061 package hierarchy continue to be represented in 32 bits.
27062 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
27063 This eases integration with the default HP C layout choices, for example
27064 as found in the system routines in @code{DECC$SHR.EXE}.
27065 Because of this implementation choice, the type fully compatible with
27066 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
27067 Depending on the context the compiler will issue a
27068 warning or an error when type @code{Address} is used, alerting the user to a
27069 potential problem. Otherwise 32-bit programs that use
27070 @code{Interfaces.C} should normally not require code modifications
27072 The other issue arising with C interfacing concerns pragma @code{Convention}.
27073 For VMS 64-bit systems, there is an issue of the appropriate default size
27074 of C convention pointers in the absence of an explicit size clause. The HP
27075 C compiler can choose either 32 or 64 bits depending on compiler options.
27076 GNAT chooses 32-bits rather than 64-bits in the default case where no size
27077 clause is given. This proves a better choice for porting 32-bit legacy
27078 applications. In order to have a 64-bit representation, it is necessary to
27079 specify a size representation clause. For example:
27081 @smallexample @c ada
27082 type int_star is access Interfaces.C.int;
27083 pragma Convention(C, int_star);
27084 for int_star'Size use 64; -- Necessary to get 64 and not 32 bits
27087 @node Experience with source compatibility
27088 @subsubsection Experience with source compatibility
27091 The Security Server and STARLET on I64 provide an interesting ``test case''
27092 for source compatibility issues, since it is in such system code
27093 where assumptions about @code{Address} size might be expected to occur.
27094 Indeed, there were a small number of occasions in the Security Server
27095 file @file{jibdef.ads}
27096 where a representation clause for a record type specified
27097 32 bits for a component of type @code{Address}.
27098 All of these errors were detected by the compiler.
27099 The repair was obvious and immediate; to simply replace @code{Address} by
27100 @code{Short_Address}.
27102 In the case of STARLET, there were several record types that should
27103 have had representation clauses but did not. In these record types
27104 there was an implicit assumption that an @code{Address} value occupied
27106 These compiled without error, but their usage resulted in run-time error
27107 returns from STARLET system calls.
27108 Future GNAT technology enhancements may include a tool that detects and flags
27109 these sorts of potential source code porting problems.
27111 @c ****************************************
27112 @node Taking advantage of 64 bit addressing
27113 @subsection Taking advantage of 64-bit addressing
27116 * Making code 64 bit clean::
27117 * Allocating memory from the 64 bit storage pool::
27118 * Restrictions on use of 64 bit objects::
27119 * Using 64 bit storage pools by default::
27120 * General access types::
27121 * STARLET and other predefined libraries::
27124 @node Making code 64 bit clean
27125 @subsubsection Making code 64-bit clean
27128 In order to prevent problems that may occur when (parts of) a
27129 system start using memory outside the 32-bit address range,
27130 we recommend some additional guidelines:
27134 For imported subprograms that take parameters of the
27135 type @code{System.Address}, ensure that these subprograms can
27136 indeed handle 64-bit addresses. If not, or when in doubt,
27137 change the subprogram declaration to specify
27138 @code{System.Short_Address} instead.
27141 Resolve all warnings related to size mismatches in
27142 unchecked conversions. Failing to do so causes
27143 erroneous execution if the source object is outside
27144 the 32-bit address space.
27147 (optional) Explicitly use the 32-bit storage pool
27148 for access types used in a 32-bit context, or use
27149 generic access types where possible
27150 (@pxref{Restrictions on use of 64 bit objects}).
27154 If these rules are followed, the compiler will automatically insert
27155 any necessary checks to ensure that no addresses or access values
27156 passed to 32-bit code ever refer to objects outside the 32-bit
27158 Any attempt to do this will raise @code{Constraint_Error}.
27160 @node Allocating memory from the 64 bit storage pool
27161 @subsubsection Allocating memory from the 64-bit storage pool
27164 For any access type @code{T} that potentially requires memory allocations
27165 beyond the 32-bit address space,
27166 use the following representation clause:
27168 @smallexample @c ada
27169 for T'Storage_Pool use System.Pool_64;
27172 @node Restrictions on use of 64 bit objects
27173 @subsubsection Restrictions on use of 64-bit objects
27176 Taking the address of an object allocated from a 64-bit storage pool,
27177 and then passing this address to a subprogram expecting
27178 @code{System.Short_Address},
27179 or assigning it to a variable of type @code{Short_Address}, will cause
27180 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
27181 (@pxref{Making code 64 bit clean}), or checks are suppressed,
27182 no exception is raised and execution
27183 will become erroneous.
27185 @node Using 64 bit storage pools by default
27186 @subsubsection Using 64-bit storage pools by default
27189 In some cases it may be desirable to have the compiler allocate
27190 from 64-bit storage pools by default. This may be the case for
27191 libraries that are 64-bit clean, but may be used in both 32-bit
27192 and 64-bit contexts. For these cases the following configuration
27193 pragma may be specified:
27195 @smallexample @c ada
27196 pragma Pool_64_Default;
27200 Any code compiled in the context of this pragma will by default
27201 use the @code{System.Pool_64} storage pool. This default may be overridden
27202 for a specific access type @code{T} by the representation clause:
27204 @smallexample @c ada
27205 for T'Storage_Pool use System.Pool_32;
27209 Any object whose address may be passed to a subprogram with a
27210 @code{Short_Address} argument, or assigned to a variable of type
27211 @code{Short_Address}, needs to be allocated from this pool.
27213 @node General access types
27214 @subsubsection General access types
27217 Objects designated by access values from a
27218 general access type (declared with @code{access all}) are never allocated
27219 from a 64-bit storage pool. Code that uses general access types will
27220 accept objects allocated in either 32-bit or 64-bit address spaces,
27221 but never allocate objects outside the 32-bit address space.
27222 Using general access types ensures maximum compatibility with both
27223 32-bit and 64-bit code.
27225 @node STARLET and other predefined libraries
27226 @subsubsection STARLET and other predefined libraries
27229 All code that comes as part of GNAT is 64-bit clean, but the
27230 restrictions given in @ref{Restrictions on use of 64 bit objects},
27231 still apply. Look at the package
27232 specifications to see in which contexts objects allocated
27233 in 64-bit address space are acceptable.
27235 @node Technical details
27236 @subsection Technical details
27239 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
27240 Ada standard with respect to the type of @code{System.Address}. Previous
27241 versions of GNAT Pro have defined this type as private and implemented it as a
27244 In order to allow defining @code{System.Short_Address} as a proper subtype,
27245 and to match the implicit sign extension in parameter passing,
27246 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
27247 visible (i.e., non-private) integer type.
27248 Standard operations on the type, such as the binary operators ``+'', ``-'',
27249 etc., that take @code{Address} operands and return an @code{Address} result,
27250 have been hidden by declaring these
27251 @code{abstract}, an Ada 95 feature that helps avoid the potential ambiguities
27252 that would otherwise result from overloading.
27253 (Note that, although @code{Address} is a visible integer type,
27254 good programming practice dictates against exploiting the type's
27255 integer properties such as literals, since this will compromise
27258 Defining @code{Address} as a visible integer type helps achieve
27259 maximum compatibility for existing Ada code,
27260 without sacrificing the capabilities of the 64-bit architecture.
27263 @c ************************************************
27265 @node Microsoft Windows Topics
27266 @appendix Microsoft Windows Topics
27272 This chapter describes topics that are specific to the Microsoft Windows
27273 platforms (NT, 2000, and XP Professional).
27276 * Using GNAT on Windows::
27277 * Using a network installation of GNAT::
27278 * CONSOLE and WINDOWS subsystems::
27279 * Temporary Files::
27280 * Mixed-Language Programming on Windows::
27281 * Windows Calling Conventions::
27282 * Introduction to Dynamic Link Libraries (DLLs)::
27283 * Using DLLs with GNAT::
27284 * Building DLLs with GNAT::
27285 * Building DLLs with GNAT Project files::
27286 * Building DLLs with gnatdll::
27287 * GNAT and Windows Resources::
27288 * Debugging a DLL::
27289 * Setting Stack Size from gnatlink::
27290 * Setting Heap Size from gnatlink::
27293 @node Using GNAT on Windows
27294 @section Using GNAT on Windows
27297 One of the strengths of the GNAT technology is that its tool set
27298 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
27299 @code{gdb} debugger, etc.) is used in the same way regardless of the
27302 On Windows this tool set is complemented by a number of Microsoft-specific
27303 tools that have been provided to facilitate interoperability with Windows
27304 when this is required. With these tools:
27309 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
27313 You can use any Dynamically Linked Library (DLL) in your Ada code (both
27314 relocatable and non-relocatable DLLs are supported).
27317 You can build Ada DLLs for use in other applications. These applications
27318 can be written in a language other than Ada (e.g., C, C++, etc). Again both
27319 relocatable and non-relocatable Ada DLLs are supported.
27322 You can include Windows resources in your Ada application.
27325 You can use or create COM/DCOM objects.
27329 Immediately below are listed all known general GNAT-for-Windows restrictions.
27330 Other restrictions about specific features like Windows Resources and DLLs
27331 are listed in separate sections below.
27336 It is not possible to use @code{GetLastError} and @code{SetLastError}
27337 when tasking, protected records, or exceptions are used. In these
27338 cases, in order to implement Ada semantics, the GNAT run-time system
27339 calls certain Win32 routines that set the last error variable to 0 upon
27340 success. It should be possible to use @code{GetLastError} and
27341 @code{SetLastError} when tasking, protected record, and exception
27342 features are not used, but it is not guaranteed to work.
27345 It is not possible to link against Microsoft libraries except for
27346 import libraries. The library must be built to be compatible with
27347 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
27348 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
27349 not be compatible with the GNAT runtime. Even if the library is
27350 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
27353 When the compilation environment is located on FAT32 drives, users may
27354 experience recompilations of the source files that have not changed if
27355 Daylight Saving Time (DST) state has changed since the last time files
27356 were compiled. NTFS drives do not have this problem.
27359 No components of the GNAT toolset use any entries in the Windows
27360 registry. The only entries that can be created are file associations and
27361 PATH settings, provided the user has chosen to create them at installation
27362 time, as well as some minimal book-keeping information needed to correctly
27363 uninstall or integrate different GNAT products.
27366 @node Using a network installation of GNAT
27367 @section Using a network installation of GNAT
27370 Make sure the system on which GNAT is installed is accessible from the
27371 current machine, i.e. the install location is shared over the network.
27372 Shared resources are accessed on Windows by means of UNC paths, which
27373 have the format @code{\\server\sharename\path}
27375 In order to use such a network installation, simply add the UNC path of the
27376 @file{bin} directory of your GNAT installation in front of your PATH. For
27377 example, if GNAT is installed in @file{\GNAT} directory of a share location
27378 called @file{c-drive} on a machine @file{LOKI}, the following command will
27381 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
27383 Be aware that every compilation using the network installation results in the
27384 transfer of large amounts of data across the network and will likely cause
27385 serious performance penalty.
27387 @node CONSOLE and WINDOWS subsystems
27388 @section CONSOLE and WINDOWS subsystems
27389 @cindex CONSOLE Subsystem
27390 @cindex WINDOWS Subsystem
27394 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
27395 (which is the default subsystem) will always create a console when
27396 launching the application. This is not something desirable when the
27397 application has a Windows GUI. To get rid of this console the
27398 application must be using the @code{WINDOWS} subsystem. To do so
27399 the @option{-mwindows} linker option must be specified.
27402 $ gnatmake winprog -largs -mwindows
27405 @node Temporary Files
27406 @section Temporary Files
27407 @cindex Temporary files
27410 It is possible to control where temporary files gets created by setting
27411 the TMP environment variable. The file will be created:
27414 @item Under the directory pointed to by the TMP environment variable if
27415 this directory exists.
27417 @item Under c:\temp, if the TMP environment variable is not set (or not
27418 pointing to a directory) and if this directory exists.
27420 @item Under the current working directory otherwise.
27424 This allows you to determine exactly where the temporary
27425 file will be created. This is particularly useful in networked
27426 environments where you may not have write access to some
27429 @node Mixed-Language Programming on Windows
27430 @section Mixed-Language Programming on Windows
27433 Developing pure Ada applications on Windows is no different than on
27434 other GNAT-supported platforms. However, when developing or porting an
27435 application that contains a mix of Ada and C/C++, the choice of your
27436 Windows C/C++ development environment conditions your overall
27437 interoperability strategy.
27439 If you use @command{gcc} to compile the non-Ada part of your application,
27440 there are no Windows-specific restrictions that affect the overall
27441 interoperability with your Ada code. If you plan to use
27442 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
27443 the following limitations:
27447 You cannot link your Ada code with an object or library generated with
27448 Microsoft tools if these use the @code{.tls} section (Thread Local
27449 Storage section) since the GNAT linker does not yet support this section.
27452 You cannot link your Ada code with an object or library generated with
27453 Microsoft tools if these use I/O routines other than those provided in
27454 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
27455 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
27456 libraries can cause a conflict with @code{msvcrt.dll} services. For
27457 instance Visual C++ I/O stream routines conflict with those in
27462 If you do want to use the Microsoft tools for your non-Ada code and hit one
27463 of the above limitations, you have two choices:
27467 Encapsulate your non Ada code in a DLL to be linked with your Ada
27468 application. In this case, use the Microsoft or whatever environment to
27469 build the DLL and use GNAT to build your executable
27470 (@pxref{Using DLLs with GNAT}).
27473 Or you can encapsulate your Ada code in a DLL to be linked with the
27474 other part of your application. In this case, use GNAT to build the DLL
27475 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
27476 environment to build your executable.
27479 @node Windows Calling Conventions
27480 @section Windows Calling Conventions
27485 * C Calling Convention::
27486 * Stdcall Calling Convention::
27487 * Win32 Calling Convention::
27488 * DLL Calling Convention::
27492 When a subprogram @code{F} (caller) calls a subprogram @code{G}
27493 (callee), there are several ways to push @code{G}'s parameters on the
27494 stack and there are several possible scenarios to clean up the stack
27495 upon @code{G}'s return. A calling convention is an agreed upon software
27496 protocol whereby the responsibilities between the caller (@code{F}) and
27497 the callee (@code{G}) are clearly defined. Several calling conventions
27498 are available for Windows:
27502 @code{C} (Microsoft defined)
27505 @code{Stdcall} (Microsoft defined)
27508 @code{Win32} (GNAT specific)
27511 @code{DLL} (GNAT specific)
27514 @node C Calling Convention
27515 @subsection @code{C} Calling Convention
27518 This is the default calling convention used when interfacing to C/C++
27519 routines compiled with either @command{gcc} or Microsoft Visual C++.
27521 In the @code{C} calling convention subprogram parameters are pushed on the
27522 stack by the caller from right to left. The caller itself is in charge of
27523 cleaning up the stack after the call. In addition, the name of a routine
27524 with @code{C} calling convention is mangled by adding a leading underscore.
27526 The name to use on the Ada side when importing (or exporting) a routine
27527 with @code{C} calling convention is the name of the routine. For
27528 instance the C function:
27531 int get_val (long);
27535 should be imported from Ada as follows:
27537 @smallexample @c ada
27539 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27540 pragma Import (C, Get_Val, External_Name => "get_val");
27545 Note that in this particular case the @code{External_Name} parameter could
27546 have been omitted since, when missing, this parameter is taken to be the
27547 name of the Ada entity in lower case. When the @code{Link_Name} parameter
27548 is missing, as in the above example, this parameter is set to be the
27549 @code{External_Name} with a leading underscore.
27551 When importing a variable defined in C, you should always use the @code{C}
27552 calling convention unless the object containing the variable is part of a
27553 DLL (in which case you should use the @code{Stdcall} calling
27554 convention, @pxref{Stdcall Calling Convention}).
27556 @node Stdcall Calling Convention
27557 @subsection @code{Stdcall} Calling Convention
27560 This convention, which was the calling convention used for Pascal
27561 programs, is used by Microsoft for all the routines in the Win32 API for
27562 efficiency reasons. It must be used to import any routine for which this
27563 convention was specified.
27565 In the @code{Stdcall} calling convention subprogram parameters are pushed
27566 on the stack by the caller from right to left. The callee (and not the
27567 caller) is in charge of cleaning the stack on routine exit. In addition,
27568 the name of a routine with @code{Stdcall} calling convention is mangled by
27569 adding a leading underscore (as for the @code{C} calling convention) and a
27570 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
27571 bytes) of the parameters passed to the routine.
27573 The name to use on the Ada side when importing a C routine with a
27574 @code{Stdcall} calling convention is the name of the C routine. The leading
27575 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
27576 the compiler. For instance the Win32 function:
27579 @b{APIENTRY} int get_val (long);
27583 should be imported from Ada as follows:
27585 @smallexample @c ada
27587 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27588 pragma Import (Stdcall, Get_Val);
27589 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
27594 As for the @code{C} calling convention, when the @code{External_Name}
27595 parameter is missing, it is taken to be the name of the Ada entity in lower
27596 case. If instead of writing the above import pragma you write:
27598 @smallexample @c ada
27600 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27601 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
27606 then the imported routine is @code{_retrieve_val@@4}. However, if instead
27607 of specifying the @code{External_Name} parameter you specify the
27608 @code{Link_Name} as in the following example:
27610 @smallexample @c ada
27612 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27613 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
27618 then the imported routine is @code{retrieve_val@@4}, that is, there is no
27619 trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always
27620 added at the end of the @code{Link_Name} by the compiler.
27623 Note, that in some special cases a DLL's entry point name lacks a trailing
27624 @code{@@}@code{@i{nn}} while the exported name generated for a call has it.
27625 The @code{gnatdll} tool, which creates the import library for the DLL, is able
27626 to handle those cases (@pxref{Using gnatdll} for the description of
27630 It is also possible to import variables defined in a DLL by using an
27631 import pragma for a variable. As an example, if a DLL contains a
27632 variable defined as:
27639 then, to access this variable from Ada you should write:
27641 @smallexample @c ada
27643 My_Var : Interfaces.C.int;
27644 pragma Import (Stdcall, My_Var);
27649 Note that to ease building cross-platform bindings this convention
27650 will be handled as a @code{C} calling convention on non Windows platforms.
27652 @node Win32 Calling Convention
27653 @subsection @code{Win32} Calling Convention
27656 This convention, which is GNAT-specific is fully equivalent to the
27657 @code{Stdcall} calling convention described above.
27659 @node DLL Calling Convention
27660 @subsection @code{DLL} Calling Convention
27663 This convention, which is GNAT-specific is fully equivalent to the
27664 @code{Stdcall} calling convention described above.
27666 @node Introduction to Dynamic Link Libraries (DLLs)
27667 @section Introduction to Dynamic Link Libraries (DLLs)
27671 A Dynamically Linked Library (DLL) is a library that can be shared by
27672 several applications running under Windows. A DLL can contain any number of
27673 routines and variables.
27675 One advantage of DLLs is that you can change and enhance them without
27676 forcing all the applications that depend on them to be relinked or
27677 recompiled. However, you should be aware than all calls to DLL routines are
27678 slower since, as you will understand below, such calls are indirect.
27680 To illustrate the remainder of this section, suppose that an application
27681 wants to use the services of a DLL @file{API.dll}. To use the services
27682 provided by @file{API.dll} you must statically link against the DLL or
27683 an import library which contains a jump table with an entry for each
27684 routine and variable exported by the DLL. In the Microsoft world this
27685 import library is called @file{API.lib}. When using GNAT this import
27686 library is called either @file{libAPI.a} or @file{libapi.a} (names are
27689 After you have linked your application with the DLL or the import library
27690 and you run your application, here is what happens:
27694 Your application is loaded into memory.
27697 The DLL @file{API.dll} is mapped into the address space of your
27698 application. This means that:
27702 The DLL will use the stack of the calling thread.
27705 The DLL will use the virtual address space of the calling process.
27708 The DLL will allocate memory from the virtual address space of the calling
27712 Handles (pointers) can be safely exchanged between routines in the DLL
27713 routines and routines in the application using the DLL.
27717 The entries in the jump table (from the import library @file{libAPI.a}
27718 or @file{API.lib} or automatically created when linking against a DLL)
27719 which is part of your application are initialized with the addresses
27720 of the routines and variables in @file{API.dll}.
27723 If present in @file{API.dll}, routines @code{DllMain} or
27724 @code{DllMainCRTStartup} are invoked. These routines typically contain
27725 the initialization code needed for the well-being of the routines and
27726 variables exported by the DLL.
27730 There is an additional point which is worth mentioning. In the Windows
27731 world there are two kind of DLLs: relocatable and non-relocatable
27732 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
27733 in the target application address space. If the addresses of two
27734 non-relocatable DLLs overlap and these happen to be used by the same
27735 application, a conflict will occur and the application will run
27736 incorrectly. Hence, when possible, it is always preferable to use and
27737 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
27738 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
27739 User's Guide) removes the debugging symbols from the DLL but the DLL can
27740 still be relocated.
27742 As a side note, an interesting difference between Microsoft DLLs and
27743 Unix shared libraries, is the fact that on most Unix systems all public
27744 routines are exported by default in a Unix shared library, while under
27745 Windows it is possible (but not required) to list exported routines in
27746 a definition file (@pxref{The Definition File}).
27748 @node Using DLLs with GNAT
27749 @section Using DLLs with GNAT
27752 * Creating an Ada Spec for the DLL Services::
27753 * Creating an Import Library::
27757 To use the services of a DLL, say @file{API.dll}, in your Ada application
27762 The Ada spec for the routines and/or variables you want to access in
27763 @file{API.dll}. If not available this Ada spec must be built from the C/C++
27764 header files provided with the DLL.
27767 The import library (@file{libAPI.a} or @file{API.lib}). As previously
27768 mentioned an import library is a statically linked library containing the
27769 import table which will be filled at load time to point to the actual
27770 @file{API.dll} routines. Sometimes you don't have an import library for the
27771 DLL you want to use. The following sections will explain how to build
27772 one. Note that this is optional.
27775 The actual DLL, @file{API.dll}.
27779 Once you have all the above, to compile an Ada application that uses the
27780 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
27781 you simply issue the command
27784 $ gnatmake my_ada_app -largs -lAPI
27788 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
27789 tells the GNAT linker to look first for a library named @file{API.lib}
27790 (Microsoft-style name) and if not found for a library named @file{libAPI.a}
27791 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
27792 contains the following pragma
27794 @smallexample @c ada
27795 pragma Linker_Options ("-lAPI");
27799 you do not have to add @option{-largs -lAPI} at the end of the
27800 @command{gnatmake} command.
27802 If any one of the items above is missing you will have to create it
27803 yourself. The following sections explain how to do so using as an
27804 example a fictitious DLL called @file{API.dll}.
27806 @node Creating an Ada Spec for the DLL Services
27807 @subsection Creating an Ada Spec for the DLL Services
27810 A DLL typically comes with a C/C++ header file which provides the
27811 definitions of the routines and variables exported by the DLL. The Ada
27812 equivalent of this header file is a package spec that contains definitions
27813 for the imported entities. If the DLL you intend to use does not come with
27814 an Ada spec you have to generate one such spec yourself. For example if
27815 the header file of @file{API.dll} is a file @file{api.h} containing the
27816 following two definitions:
27828 then the equivalent Ada spec could be:
27830 @smallexample @c ada
27833 with Interfaces.C.Strings;
27838 function Get (Str : C.Strings.Chars_Ptr) return C.int;
27841 pragma Import (C, Get);
27842 pragma Import (DLL, Some_Var);
27849 Note that a variable is
27850 @strong{always imported with a Stdcall convention}. A function
27851 can have @code{C} or @code{Stdcall} convention.
27852 (@pxref{Windows Calling Conventions}).
27854 @node Creating an Import Library
27855 @subsection Creating an Import Library
27856 @cindex Import library
27859 * The Definition File::
27860 * GNAT-Style Import Library::
27861 * Microsoft-Style Import Library::
27865 If a Microsoft-style import library @file{API.lib} or a GNAT-style
27866 import library @file{libAPI.a} is available with @file{API.dll} you
27867 can skip this section. You can also skip this section if
27868 @file{API.dll} is built with GNU tools as in this case it is possible
27869 to link directly against the DLL. Otherwise read on.
27871 @node The Definition File
27872 @subsubsection The Definition File
27873 @cindex Definition file
27877 As previously mentioned, and unlike Unix systems, the list of symbols
27878 that are exported from a DLL must be provided explicitly in Windows.
27879 The main goal of a definition file is precisely that: list the symbols
27880 exported by a DLL. A definition file (usually a file with a @code{.def}
27881 suffix) has the following structure:
27887 [DESCRIPTION @i{string}]
27897 @item LIBRARY @i{name}
27898 This section, which is optional, gives the name of the DLL.
27900 @item DESCRIPTION @i{string}
27901 This section, which is optional, gives a description string that will be
27902 embedded in the import library.
27905 This section gives the list of exported symbols (procedures, functions or
27906 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
27907 section of @file{API.def} looks like:
27921 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
27922 (@pxref{Windows Calling Conventions}) for a Stdcall
27923 calling convention function in the exported symbols list.
27926 There can actually be other sections in a definition file, but these
27927 sections are not relevant to the discussion at hand.
27929 @node GNAT-Style Import Library
27930 @subsubsection GNAT-Style Import Library
27933 To create a static import library from @file{API.dll} with the GNAT tools
27934 you should proceed as follows:
27938 Create the definition file @file{API.def} (@pxref{The Definition File}).
27939 For that use the @code{dll2def} tool as follows:
27942 $ dll2def API.dll > API.def
27946 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
27947 to standard output the list of entry points in the DLL. Note that if
27948 some routines in the DLL have the @code{Stdcall} convention
27949 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
27950 suffix then you'll have to edit @file{api.def} to add it, and specify
27951 @code{-k} to @code{gnatdll} when creating the import library.
27954 Here are some hints to find the right @code{@@}@i{nn} suffix.
27958 If you have the Microsoft import library (.lib), it is possible to get
27959 the right symbols by using Microsoft @code{dumpbin} tool (see the
27960 corresponding Microsoft documentation for further details).
27963 $ dumpbin /exports api.lib
27967 If you have a message about a missing symbol at link time the compiler
27968 tells you what symbol is expected. You just have to go back to the
27969 definition file and add the right suffix.
27973 Build the import library @code{libAPI.a}, using @code{gnatdll}
27974 (@pxref{Using gnatdll}) as follows:
27977 $ gnatdll -e API.def -d API.dll
27981 @code{gnatdll} takes as input a definition file @file{API.def} and the
27982 name of the DLL containing the services listed in the definition file
27983 @file{API.dll}. The name of the static import library generated is
27984 computed from the name of the definition file as follows: if the
27985 definition file name is @i{xyz}@code{.def}, the import library name will
27986 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
27987 @option{-e} could have been removed because the name of the definition
27988 file (before the ``@code{.def}'' suffix) is the same as the name of the
27989 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
27992 @node Microsoft-Style Import Library
27993 @subsubsection Microsoft-Style Import Library
27996 With GNAT you can either use a GNAT-style or Microsoft-style import
27997 library. A Microsoft import library is needed only if you plan to make an
27998 Ada DLL available to applications developed with Microsoft
27999 tools (@pxref{Mixed-Language Programming on Windows}).
28001 To create a Microsoft-style import library for @file{API.dll} you
28002 should proceed as follows:
28006 Create the definition file @file{API.def} from the DLL. For this use either
28007 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
28008 tool (see the corresponding Microsoft documentation for further details).
28011 Build the actual import library using Microsoft's @code{lib} utility:
28014 $ lib -machine:IX86 -def:API.def -out:API.lib
28018 If you use the above command the definition file @file{API.def} must
28019 contain a line giving the name of the DLL:
28026 See the Microsoft documentation for further details about the usage of
28030 @node Building DLLs with GNAT
28031 @section Building DLLs with GNAT
28032 @cindex DLLs, building
28035 This section explain how to build DLLs using the GNAT built-in DLL
28036 support. With the following procedure it is straight forward to build
28037 and use DLLs with GNAT.
28041 @item building object files
28043 The first step is to build all objects files that are to be included
28044 into the DLL. This is done by using the standard @command{gnatmake} tool.
28046 @item building the DLL
28048 To build the DLL you must use @command{gcc}'s @code{-shared}
28049 option. It is quite simple to use this method:
28052 $ gcc -shared -o api.dll obj1.o obj2.o ...
28055 It is important to note that in this case all symbols found in the
28056 object files are automatically exported. It is possible to restrict
28057 the set of symbols to export by passing to @command{gcc} a definition
28058 file, @pxref{The Definition File}. For example:
28061 $ gcc -shared -o api.dll api.def obj1.o obj2.o ...
28064 If you use a definition file you must export the elaboration procedures
28065 for every package that required one. Elaboration procedures are named
28066 using the package name followed by "_E".
28068 @item preparing DLL to be used
28070 For the DLL to be used by client programs the bodies must be hidden
28071 from it and the .ali set with read-only attribute. This is very important
28072 otherwise GNAT will recompile all packages and will not actually use
28073 the code in the DLL. For example:
28077 $ copy *.ads *.ali api.dll apilib
28078 $ attrib +R apilib\*.ali
28083 At this point it is possible to use the DLL by directly linking
28084 against it. Note that you must use the GNAT shared runtime when using
28085 GNAT shared libraries. This is achieved by using @code{-shared} binder's
28089 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
28092 @node Building DLLs with GNAT Project files
28093 @section Building DLLs with GNAT Project files
28094 @cindex DLLs, building
28097 There is nothing specific to Windows in this area. @pxref{Library Projects}.
28099 @node Building DLLs with gnatdll
28100 @section Building DLLs with gnatdll
28101 @cindex DLLs, building
28104 * Limitations When Using Ada DLLs from Ada::
28105 * Exporting Ada Entities::
28106 * Ada DLLs and Elaboration::
28107 * Ada DLLs and Finalization::
28108 * Creating a Spec for Ada DLLs::
28109 * Creating the Definition File::
28114 Note that it is preferred to use the built-in GNAT DLL support
28115 (@pxref{Building DLLs with GNAT}) or GNAT Project files
28116 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
28118 This section explains how to build DLLs containing Ada code using
28119 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
28120 remainder of this section.
28122 The steps required to build an Ada DLL that is to be used by Ada as well as
28123 non-Ada applications are as follows:
28127 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
28128 @code{Stdcall} calling convention to avoid any Ada name mangling for the
28129 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
28130 skip this step if you plan to use the Ada DLL only from Ada applications.
28133 Your Ada code must export an initialization routine which calls the routine
28134 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
28135 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
28136 routine exported by the Ada DLL must be invoked by the clients of the DLL
28137 to initialize the DLL.
28140 When useful, the DLL should also export a finalization routine which calls
28141 routine @code{adafinal} generated by @command{gnatbind} to perform the
28142 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
28143 The finalization routine exported by the Ada DLL must be invoked by the
28144 clients of the DLL when the DLL services are no further needed.
28147 You must provide a spec for the services exported by the Ada DLL in each
28148 of the programming languages to which you plan to make the DLL available.
28151 You must provide a definition file listing the exported entities
28152 (@pxref{The Definition File}).
28155 Finally you must use @code{gnatdll} to produce the DLL and the import
28156 library (@pxref{Using gnatdll}).
28160 Note that a relocatable DLL stripped using the @code{strip}
28161 binutils tool will not be relocatable anymore. To build a DLL without
28162 debug information pass @code{-largs -s} to @code{gnatdll}. This
28163 restriction does not apply to a DLL built using a Library Project.
28164 @pxref{Library Projects}.
28166 @node Limitations When Using Ada DLLs from Ada
28167 @subsection Limitations When Using Ada DLLs from Ada
28170 When using Ada DLLs from Ada applications there is a limitation users
28171 should be aware of. Because on Windows the GNAT run time is not in a DLL of
28172 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
28173 each Ada DLL includes the services of the GNAT run time that are necessary
28174 to the Ada code inside the DLL. As a result, when an Ada program uses an
28175 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
28176 one in the main program.
28178 It is therefore not possible to exchange GNAT run-time objects between the
28179 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
28180 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
28183 It is completely safe to exchange plain elementary, array or record types,
28184 Windows object handles, etc.
28186 @node Exporting Ada Entities
28187 @subsection Exporting Ada Entities
28188 @cindex Export table
28191 Building a DLL is a way to encapsulate a set of services usable from any
28192 application. As a result, the Ada entities exported by a DLL should be
28193 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
28194 any Ada name mangling. As an example here is an Ada package
28195 @code{API}, spec and body, exporting two procedures, a function, and a
28198 @smallexample @c ada
28201 with Interfaces.C; use Interfaces;
28203 Count : C.int := 0;
28204 function Factorial (Val : C.int) return C.int;
28206 procedure Initialize_API;
28207 procedure Finalize_API;
28208 -- Initialization & Finalization routines. More in the next section.
28210 pragma Export (C, Initialize_API);
28211 pragma Export (C, Finalize_API);
28212 pragma Export (C, Count);
28213 pragma Export (C, Factorial);
28219 @smallexample @c ada
28222 package body API is
28223 function Factorial (Val : C.int) return C.int is
28226 Count := Count + 1;
28227 for K in 1 .. Val loop
28233 procedure Initialize_API is
28235 pragma Import (C, Adainit);
28238 end Initialize_API;
28240 procedure Finalize_API is
28241 procedure Adafinal;
28242 pragma Import (C, Adafinal);
28252 If the Ada DLL you are building will only be used by Ada applications
28253 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
28254 convention. As an example, the previous package could be written as
28257 @smallexample @c ada
28261 Count : Integer := 0;
28262 function Factorial (Val : Integer) return Integer;
28264 procedure Initialize_API;
28265 procedure Finalize_API;
28266 -- Initialization and Finalization routines.
28272 @smallexample @c ada
28275 package body API is
28276 function Factorial (Val : Integer) return Integer is
28277 Fact : Integer := 1;
28279 Count := Count + 1;
28280 for K in 1 .. Val loop
28287 -- The remainder of this package body is unchanged.
28294 Note that if you do not export the Ada entities with a @code{C} or
28295 @code{Stdcall} convention you will have to provide the mangled Ada names
28296 in the definition file of the Ada DLL
28297 (@pxref{Creating the Definition File}).
28299 @node Ada DLLs and Elaboration
28300 @subsection Ada DLLs and Elaboration
28301 @cindex DLLs and elaboration
28304 The DLL that you are building contains your Ada code as well as all the
28305 routines in the Ada library that are needed by it. The first thing a
28306 user of your DLL must do is elaborate the Ada code
28307 (@pxref{Elaboration Order Handling in GNAT}).
28309 To achieve this you must export an initialization routine
28310 (@code{Initialize_API} in the previous example), which must be invoked
28311 before using any of the DLL services. This elaboration routine must call
28312 the Ada elaboration routine @code{adainit} generated by the GNAT binder
28313 (@pxref{Binding with Non-Ada Main Programs}). See the body of
28314 @code{Initialize_Api} for an example. Note that the GNAT binder is
28315 automatically invoked during the DLL build process by the @code{gnatdll}
28316 tool (@pxref{Using gnatdll}).
28318 When a DLL is loaded, Windows systematically invokes a routine called
28319 @code{DllMain}. It would therefore be possible to call @code{adainit}
28320 directly from @code{DllMain} without having to provide an explicit
28321 initialization routine. Unfortunately, it is not possible to call
28322 @code{adainit} from the @code{DllMain} if your program has library level
28323 tasks because access to the @code{DllMain} entry point is serialized by
28324 the system (that is, only a single thread can execute ``through'' it at a
28325 time), which means that the GNAT run time will deadlock waiting for the
28326 newly created task to complete its initialization.
28328 @node Ada DLLs and Finalization
28329 @subsection Ada DLLs and Finalization
28330 @cindex DLLs and finalization
28333 When the services of an Ada DLL are no longer needed, the client code should
28334 invoke the DLL finalization routine, if available. The DLL finalization
28335 routine is in charge of releasing all resources acquired by the DLL. In the
28336 case of the Ada code contained in the DLL, this is achieved by calling
28337 routine @code{adafinal} generated by the GNAT binder
28338 (@pxref{Binding with Non-Ada Main Programs}).
28339 See the body of @code{Finalize_Api} for an
28340 example. As already pointed out the GNAT binder is automatically invoked
28341 during the DLL build process by the @code{gnatdll} tool
28342 (@pxref{Using gnatdll}).
28344 @node Creating a Spec for Ada DLLs
28345 @subsection Creating a Spec for Ada DLLs
28348 To use the services exported by the Ada DLL from another programming
28349 language (e.g. C), you have to translate the specs of the exported Ada
28350 entities in that language. For instance in the case of @code{API.dll},
28351 the corresponding C header file could look like:
28356 extern int *_imp__count;
28357 #define count (*_imp__count)
28358 int factorial (int);
28364 It is important to understand that when building an Ada DLL to be used by
28365 other Ada applications, you need two different specs for the packages
28366 contained in the DLL: one for building the DLL and the other for using
28367 the DLL. This is because the @code{DLL} calling convention is needed to
28368 use a variable defined in a DLL, but when building the DLL, the variable
28369 must have either the @code{Ada} or @code{C} calling convention. As an
28370 example consider a DLL comprising the following package @code{API}:
28372 @smallexample @c ada
28376 Count : Integer := 0;
28378 -- Remainder of the package omitted.
28385 After producing a DLL containing package @code{API}, the spec that
28386 must be used to import @code{API.Count} from Ada code outside of the
28389 @smallexample @c ada
28394 pragma Import (DLL, Count);
28400 @node Creating the Definition File
28401 @subsection Creating the Definition File
28404 The definition file is the last file needed to build the DLL. It lists
28405 the exported symbols. As an example, the definition file for a DLL
28406 containing only package @code{API} (where all the entities are exported
28407 with a @code{C} calling convention) is:
28422 If the @code{C} calling convention is missing from package @code{API},
28423 then the definition file contains the mangled Ada names of the above
28424 entities, which in this case are:
28433 api__initialize_api
28438 @node Using gnatdll
28439 @subsection Using @code{gnatdll}
28443 * gnatdll Example::
28444 * gnatdll behind the Scenes::
28449 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
28450 and non-Ada sources that make up your DLL have been compiled.
28451 @code{gnatdll} is actually in charge of two distinct tasks: build the
28452 static import library for the DLL and the actual DLL. The form of the
28453 @code{gnatdll} command is
28457 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
28462 where @i{list-of-files} is a list of ALI and object files. The object
28463 file list must be the exact list of objects corresponding to the non-Ada
28464 sources whose services are to be included in the DLL. The ALI file list
28465 must be the exact list of ALI files for the corresponding Ada sources
28466 whose services are to be included in the DLL. If @i{list-of-files} is
28467 missing, only the static import library is generated.
28470 You may specify any of the following switches to @code{gnatdll}:
28473 @item -a[@var{address}]
28474 @cindex @option{-a} (@code{gnatdll})
28475 Build a non-relocatable DLL at @var{address}. If @var{address} is not
28476 specified the default address @var{0x11000000} will be used. By default,
28477 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
28478 advise the reader to build relocatable DLL.
28480 @item -b @var{address}
28481 @cindex @option{-b} (@code{gnatdll})
28482 Set the relocatable DLL base address. By default the address is
28485 @item -bargs @var{opts}
28486 @cindex @option{-bargs} (@code{gnatdll})
28487 Binder options. Pass @var{opts} to the binder.
28489 @item -d @var{dllfile}
28490 @cindex @option{-d} (@code{gnatdll})
28491 @var{dllfile} is the name of the DLL. This switch must be present for
28492 @code{gnatdll} to do anything. The name of the generated import library is
28493 obtained algorithmically from @var{dllfile} as shown in the following
28494 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
28495 @code{libxyz.a}. The name of the definition file to use (if not specified
28496 by option @option{-e}) is obtained algorithmically from @var{dllfile}
28497 as shown in the following example:
28498 if @var{dllfile} is @code{xyz.dll}, the definition
28499 file used is @code{xyz.def}.
28501 @item -e @var{deffile}
28502 @cindex @option{-e} (@code{gnatdll})
28503 @var{deffile} is the name of the definition file.
28506 @cindex @option{-g} (@code{gnatdll})
28507 Generate debugging information. This information is stored in the object
28508 file and copied from there to the final DLL file by the linker,
28509 where it can be read by the debugger. You must use the
28510 @option{-g} switch if you plan on using the debugger or the symbolic
28514 @cindex @option{-h} (@code{gnatdll})
28515 Help mode. Displays @code{gnatdll} switch usage information.
28518 @cindex @option{-I} (@code{gnatdll})
28519 Direct @code{gnatdll} to search the @var{dir} directory for source and
28520 object files needed to build the DLL.
28521 (@pxref{Search Paths and the Run-Time Library (RTL)}).
28524 @cindex @option{-k} (@code{gnatdll})
28525 Removes the @code{@@}@i{nn} suffix from the import library's exported
28526 names, but keeps them for the link names. You must specify this
28527 option if you want to use a @code{Stdcall} function in a DLL for which
28528 the @code{@@}@i{nn} suffix has been removed. This is the case for most
28529 of the Windows NT DLL for example. This option has no effect when
28530 @option{-n} option is specified.
28532 @item -l @var{file}
28533 @cindex @option{-l} (@code{gnatdll})
28534 The list of ALI and object files used to build the DLL are listed in
28535 @var{file}, instead of being given in the command line. Each line in
28536 @var{file} contains the name of an ALI or object file.
28539 @cindex @option{-n} (@code{gnatdll})
28540 No Import. Do not create the import library.
28543 @cindex @option{-q} (@code{gnatdll})
28544 Quiet mode. Do not display unnecessary messages.
28547 @cindex @option{-v} (@code{gnatdll})
28548 Verbose mode. Display extra information.
28550 @item -largs @var{opts}
28551 @cindex @option{-largs} (@code{gnatdll})
28552 Linker options. Pass @var{opts} to the linker.
28555 @node gnatdll Example
28556 @subsubsection @code{gnatdll} Example
28559 As an example the command to build a relocatable DLL from @file{api.adb}
28560 once @file{api.adb} has been compiled and @file{api.def} created is
28563 $ gnatdll -d api.dll api.ali
28567 The above command creates two files: @file{libapi.a} (the import
28568 library) and @file{api.dll} (the actual DLL). If you want to create
28569 only the DLL, just type:
28572 $ gnatdll -d api.dll -n api.ali
28576 Alternatively if you want to create just the import library, type:
28579 $ gnatdll -d api.dll
28582 @node gnatdll behind the Scenes
28583 @subsubsection @code{gnatdll} behind the Scenes
28586 This section details the steps involved in creating a DLL. @code{gnatdll}
28587 does these steps for you. Unless you are interested in understanding what
28588 goes on behind the scenes, you should skip this section.
28590 We use the previous example of a DLL containing the Ada package @code{API},
28591 to illustrate the steps necessary to build a DLL. The starting point is a
28592 set of objects that will make up the DLL and the corresponding ALI
28593 files. In the case of this example this means that @file{api.o} and
28594 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
28599 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
28600 the information necessary to generate relocation information for the
28606 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
28611 In addition to the base file, the @command{gnatlink} command generates an
28612 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
28613 asks @command{gnatlink} to generate the routines @code{DllMain} and
28614 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
28615 is loaded into memory.
28618 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
28619 export table (@file{api.exp}). The export table contains the relocation
28620 information in a form which can be used during the final link to ensure
28621 that the Windows loader is able to place the DLL anywhere in memory.
28625 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28626 --output-exp api.exp
28631 @code{gnatdll} builds the base file using the new export table. Note that
28632 @command{gnatbind} must be called once again since the binder generated file
28633 has been deleted during the previous call to @command{gnatlink}.
28638 $ gnatlink api -o api.jnk api.exp -mdll
28639 -Wl,--base-file,api.base
28644 @code{gnatdll} builds the new export table using the new base file and
28645 generates the DLL import library @file{libAPI.a}.
28649 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28650 --output-exp api.exp --output-lib libAPI.a
28655 Finally @code{gnatdll} builds the relocatable DLL using the final export
28661 $ gnatlink api api.exp -o api.dll -mdll
28666 @node Using dlltool
28667 @subsubsection Using @code{dlltool}
28670 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
28671 DLLs and static import libraries. This section summarizes the most
28672 common @code{dlltool} switches. The form of the @code{dlltool} command
28676 $ dlltool [@var{switches}]
28680 @code{dlltool} switches include:
28683 @item --base-file @var{basefile}
28684 @cindex @option{--base-file} (@command{dlltool})
28685 Read the base file @var{basefile} generated by the linker. This switch
28686 is used to create a relocatable DLL.
28688 @item --def @var{deffile}
28689 @cindex @option{--def} (@command{dlltool})
28690 Read the definition file.
28692 @item --dllname @var{name}
28693 @cindex @option{--dllname} (@command{dlltool})
28694 Gives the name of the DLL. This switch is used to embed the name of the
28695 DLL in the static import library generated by @code{dlltool} with switch
28696 @option{--output-lib}.
28699 @cindex @option{-k} (@command{dlltool})
28700 Kill @code{@@}@i{nn} from exported names
28701 (@pxref{Windows Calling Conventions}
28702 for a discussion about @code{Stdcall}-style symbols.
28705 @cindex @option{--help} (@command{dlltool})
28706 Prints the @code{dlltool} switches with a concise description.
28708 @item --output-exp @var{exportfile}
28709 @cindex @option{--output-exp} (@command{dlltool})
28710 Generate an export file @var{exportfile}. The export file contains the
28711 export table (list of symbols in the DLL) and is used to create the DLL.
28713 @item --output-lib @i{libfile}
28714 @cindex @option{--output-lib} (@command{dlltool})
28715 Generate a static import library @var{libfile}.
28718 @cindex @option{-v} (@command{dlltool})
28721 @item --as @i{assembler-name}
28722 @cindex @option{--as} (@command{dlltool})
28723 Use @i{assembler-name} as the assembler. The default is @code{as}.
28726 @node GNAT and Windows Resources
28727 @section GNAT and Windows Resources
28728 @cindex Resources, windows
28731 * Building Resources::
28732 * Compiling Resources::
28733 * Using Resources::
28737 Resources are an easy way to add Windows specific objects to your
28738 application. The objects that can be added as resources include:
28767 This section explains how to build, compile and use resources.
28769 @node Building Resources
28770 @subsection Building Resources
28771 @cindex Resources, building
28774 A resource file is an ASCII file. By convention resource files have an
28775 @file{.rc} extension.
28776 The easiest way to build a resource file is to use Microsoft tools
28777 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
28778 @code{dlgedit.exe} to build dialogs.
28779 It is always possible to build an @file{.rc} file yourself by writing a
28782 It is not our objective to explain how to write a resource file. A
28783 complete description of the resource script language can be found in the
28784 Microsoft documentation.
28786 @node Compiling Resources
28787 @subsection Compiling Resources
28790 @cindex Resources, compiling
28793 This section describes how to build a GNAT-compatible (COFF) object file
28794 containing the resources. This is done using the Resource Compiler
28795 @code{windres} as follows:
28798 $ windres -i myres.rc -o myres.o
28802 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
28803 file. You can specify an alternate preprocessor (usually named
28804 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
28805 parameter. A list of all possible options may be obtained by entering
28806 the command @code{windres} @option{--help}.
28808 It is also possible to use the Microsoft resource compiler @code{rc.exe}
28809 to produce a @file{.res} file (binary resource file). See the
28810 corresponding Microsoft documentation for further details. In this case
28811 you need to use @code{windres} to translate the @file{.res} file to a
28812 GNAT-compatible object file as follows:
28815 $ windres -i myres.res -o myres.o
28818 @node Using Resources
28819 @subsection Using Resources
28820 @cindex Resources, using
28823 To include the resource file in your program just add the
28824 GNAT-compatible object file for the resource(s) to the linker
28825 arguments. With @command{gnatmake} this is done by using the @option{-largs}
28829 $ gnatmake myprog -largs myres.o
28832 @node Debugging a DLL
28833 @section Debugging a DLL
28834 @cindex DLL debugging
28837 * Program and DLL Both Built with GCC/GNAT::
28838 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
28842 Debugging a DLL is similar to debugging a standard program. But
28843 we have to deal with two different executable parts: the DLL and the
28844 program that uses it. We have the following four possibilities:
28848 The program and the DLL are built with @code{GCC/GNAT}.
28850 The program is built with foreign tools and the DLL is built with
28853 The program is built with @code{GCC/GNAT} and the DLL is built with
28859 In this section we address only cases one and two above.
28860 There is no point in trying to debug
28861 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
28862 information in it. To do so you must use a debugger compatible with the
28863 tools suite used to build the DLL.
28865 @node Program and DLL Both Built with GCC/GNAT
28866 @subsection Program and DLL Both Built with GCC/GNAT
28869 This is the simplest case. Both the DLL and the program have @code{GDB}
28870 compatible debugging information. It is then possible to break anywhere in
28871 the process. Let's suppose here that the main procedure is named
28872 @code{ada_main} and that in the DLL there is an entry point named
28876 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
28877 program must have been built with the debugging information (see GNAT -g
28878 switch). Here are the step-by-step instructions for debugging it:
28881 @item Launch @code{GDB} on the main program.
28887 @item Start the program and stop at the beginning of the main procedure
28894 This step is required to be able to set a breakpoint inside the DLL. As long
28895 as the program is not run, the DLL is not loaded. This has the
28896 consequence that the DLL debugging information is also not loaded, so it is not
28897 possible to set a breakpoint in the DLL.
28899 @item Set a breakpoint inside the DLL
28902 (gdb) break ada_dll
28909 At this stage a breakpoint is set inside the DLL. From there on
28910 you can use the standard approach to debug the whole program
28911 (@pxref{Running and Debugging Ada Programs}).
28914 @c This used to work, probably because the DLLs were non-relocatable
28915 @c keep this section around until the problem is sorted out.
28917 To break on the @code{DllMain} routine it is not possible to follow
28918 the procedure above. At the time the program stop on @code{ada_main}
28919 the @code{DllMain} routine as already been called. Either you can use
28920 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
28923 @item Launch @code{GDB} on the main program.
28929 @item Load DLL symbols
28932 (gdb) add-sym api.dll
28935 @item Set a breakpoint inside the DLL
28938 (gdb) break ada_dll.adb:45
28941 Note that at this point it is not possible to break using the routine symbol
28942 directly as the program is not yet running. The solution is to break
28943 on the proper line (break in @file{ada_dll.adb} line 45).
28945 @item Start the program
28954 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
28955 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
28958 * Debugging the DLL Directly::
28959 * Attaching to a Running Process::
28963 In this case things are slightly more complex because it is not possible to
28964 start the main program and then break at the beginning to load the DLL and the
28965 associated DLL debugging information. It is not possible to break at the
28966 beginning of the program because there is no @code{GDB} debugging information,
28967 and therefore there is no direct way of getting initial control. This
28968 section addresses this issue by describing some methods that can be used
28969 to break somewhere in the DLL to debug it.
28972 First suppose that the main procedure is named @code{main} (this is for
28973 example some C code built with Microsoft Visual C) and that there is a
28974 DLL named @code{test.dll} containing an Ada entry point named
28978 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
28979 been built with debugging information (see GNAT -g option).
28981 @node Debugging the DLL Directly
28982 @subsubsection Debugging the DLL Directly
28986 Find out the executable starting address
28989 $ objdump --file-header main.exe
28992 The starting address is reported on the last line. For example:
28995 main.exe: file format pei-i386
28996 architecture: i386, flags 0x0000010a:
28997 EXEC_P, HAS_DEBUG, D_PAGED
28998 start address 0x00401010
29002 Launch the debugger on the executable.
29009 Set a breakpoint at the starting address, and launch the program.
29012 $ (gdb) break *0x00401010
29016 The program will stop at the given address.
29019 Set a breakpoint on a DLL subroutine.
29022 (gdb) break ada_dll.adb:45
29025 Or if you want to break using a symbol on the DLL, you need first to
29026 select the Ada language (language used by the DLL).
29029 (gdb) set language ada
29030 (gdb) break ada_dll
29034 Continue the program.
29041 This will run the program until it reaches the breakpoint that has been
29042 set. From that point you can use the standard way to debug a program
29043 as described in (@pxref{Running and Debugging Ada Programs}).
29048 It is also possible to debug the DLL by attaching to a running process.
29050 @node Attaching to a Running Process
29051 @subsubsection Attaching to a Running Process
29052 @cindex DLL debugging, attach to process
29055 With @code{GDB} it is always possible to debug a running process by
29056 attaching to it. It is possible to debug a DLL this way. The limitation
29057 of this approach is that the DLL must run long enough to perform the
29058 attach operation. It may be useful for instance to insert a time wasting
29059 loop in the code of the DLL to meet this criterion.
29063 @item Launch the main program @file{main.exe}.
29069 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
29070 that the process PID for @file{main.exe} is 208.
29078 @item Attach to the running process to be debugged.
29084 @item Load the process debugging information.
29087 (gdb) symbol-file main.exe
29090 @item Break somewhere in the DLL.
29093 (gdb) break ada_dll
29096 @item Continue process execution.
29105 This last step will resume the process execution, and stop at
29106 the breakpoint we have set. From there you can use the standard
29107 approach to debug a program as described in
29108 (@pxref{Running and Debugging Ada Programs}).
29110 @node Setting Stack Size from gnatlink
29111 @section Setting Stack Size from @command{gnatlink}
29114 It is possible to specify the program stack size at link time. On modern
29115 versions of Windows, starting with XP, this is mostly useful to set the size of
29116 the main stack (environment task). The other task stacks are set with pragma
29117 Storage_Size or with gnatbind -d.
29119 Older versions of Windows (2000, NT4, etc.) do
29120 not provide any means of setting the reserve size of individual tasks, thus the
29121 link-time stack size applies to all tasks and pragma Storage_Size has no effect.
29122 It means, in particular, that Stack Overflow checks are made against this
29123 link-time specified size.
29125 This setting can be done with
29126 @command{gnatlink} using either:
29130 @item using @option{-Xlinker} linker option
29133 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
29136 This sets the stack reserve size to 0x10000 bytes and the stack commit
29137 size to 0x1000 bytes.
29139 @item using @option{-Wl} linker option
29142 $ gnatlink hello -Wl,--stack=0x1000000
29145 This sets the stack reserve size to 0x1000000 bytes. Note that with
29146 @option{-Wl} option it is not possible to set the stack commit size
29147 because the coma is a separator for this option.
29151 @node Setting Heap Size from gnatlink
29152 @section Setting Heap Size from @command{gnatlink}
29155 Under Windows systems, it is possible to specify the program heap size from
29156 @command{gnatlink} using either:
29160 @item using @option{-Xlinker} linker option
29163 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
29166 This sets the heap reserve size to 0x10000 bytes and the heap commit
29167 size to 0x1000 bytes.
29169 @item using @option{-Wl} linker option
29172 $ gnatlink hello -Wl,--heap=0x1000000
29175 This sets the heap reserve size to 0x1000000 bytes. Note that with
29176 @option{-Wl} option it is not possible to set the heap commit size
29177 because the coma is a separator for this option.
29183 @c **********************************
29184 @c * GNU Free Documentation License *
29185 @c **********************************
29187 @c GNU Free Documentation License
29189 @node Index,,GNU Free Documentation License, Top
29195 @c Put table of contents at end, otherwise it precedes the "title page" in
29196 @c the .txt version
29197 @c Edit the pdf file to move the contents to the beginning, after the title