1 \input texinfo @c -*-texinfo-*-
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
6 @c GNAT DOCUMENTATION o
10 @c Copyright (C) 1992-2005 Ada Core Technologies, Inc. o
12 @c GNAT is free software; you can redistribute it and/or modify it under o
13 @c terms of the GNU General Public License as published by the Free Soft- o
14 @c ware Foundation; either version 2, or (at your option) any later ver- o
15 @c sion. GNAT is distributed in the hope that it will be useful, but WITH- o
16 @c OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY o
17 @c or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License o
18 @c for more details. You should have received a copy of the GNU General o
19 @c Public License distributed with GNAT; see file COPYING. If not, write o
20 @c to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, o
21 @c MA 02111-1307, USA. o
23 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
25 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
27 @c GNAT_UGN Style Guide
29 @c 1. Always put a @noindent on the line before the first paragraph
30 @c after any of these commands:
42 @c 2. DO NOT use @example. Use @smallexample instead.
43 @c a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
44 @c context. These can interfere with the readability of the texi
45 @c source file. Instead, use one of the following annotated
46 @c @smallexample commands, and preprocess the texi file with the
47 @c ada2texi tool (which generates appropriate highlighting):
48 @c @smallexample @c ada
49 @c @smallexample @c adanocomment
50 @c @smallexample @c projectfile
51 @c b) The "@c ada" markup will result in boldface for reserved words
52 @c and italics for comments
53 @c c) The "@c adanocomment" markup will result only in boldface for
54 @c reserved words (comments are left alone)
55 @c d) The "@c projectfile" markup is like "@c ada" except that the set
56 @c of reserved words include the new reserved words for project files
58 @c 3. Each @chapter, @section, @subsection, @subsubsection, etc.
59 @c command must be preceded by two empty lines
61 @c 4. The @item command should be on a line of its own if it is in an
62 @c @itemize or @enumerate command.
64 @c 5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
67 @c 6. DO NOT put trailing spaces at the end of a line. Such spaces will
68 @c cause the document build to fail.
70 @c 7. DO NOT use @cartouche for examples that are longer than around 10 lines.
71 @c This command inhibits page breaks, so long examples in a @cartouche can
72 @c lead to large, ugly patches of empty space on a page.
74 @c NOTE: This file should be submitted to xgnatugn with either the vms flag
75 @c or the unw flag set. The unw flag covers topics for both Unix and
78 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
81 @setfilename gnat_ugn_vms.info
85 @setfilename gnat_ugn_unw.info
93 @set FILE gnat_ugn_unw
98 @set FILE gnat_ugn_vms
101 @settitle @value{EDITION} User's Guide @value{PLATFORM}
102 @dircategory GNU Ada tools
104 * @value{EDITION} User's Guide (@value{FILE}) @value{PLATFORM}
107 @include gcc-common.texi
109 @setchapternewpage odd
114 Copyright @copyright{} 1995-2005, Free Software Foundation
116 Permission is granted to copy, distribute and/or modify this document
117 under the terms of the GNU Free Documentation License, Version 1.2
118 or any later version published by the Free Software Foundation;
119 with the Invariant Sections being ``GNU Free Documentation License'', with the
120 Front-Cover Texts being
121 ``@value{EDITION} User's Guide'',
122 and with no Back-Cover Texts.
123 A copy of the license is included in the section entitled
124 ``GNU Free Documentation License''.
129 @title @value{EDITION} User's Guide
134 @titlefont{@i{@value{PLATFORM}}}
140 @subtitle GNAT, The GNU Ada 95 Compiler
141 @subtitle GCC version @value{version-GCC}
146 @vskip 0pt plus 1filll
153 @node Top, About This Guide, (dir), (dir)
154 @top @value{EDITION} User's Guide
157 @value{EDITION} User's Guide @value{PLATFORM}
160 GNAT, The GNU Ada 95 Compiler@*
161 GCC version @value{version-GCC}@*
168 * Getting Started with GNAT::
169 * The GNAT Compilation Model::
170 * Compiling Using gcc::
171 * Binding Using gnatbind::
172 * Linking Using gnatlink::
173 * The GNAT Make Program gnatmake::
174 * Improving Performance::
175 * Renaming Files Using gnatchop::
176 * Configuration Pragmas::
177 * Handling Arbitrary File Naming Conventions Using gnatname::
178 * GNAT Project Manager::
179 * The Cross-Referencing Tools gnatxref and gnatfind::
180 * The GNAT Pretty-Printer gnatpp::
181 * The GNAT Metric Tool gnatmetric::
182 * File Name Krunching Using gnatkr::
183 * Preprocessing Using gnatprep::
185 * The GNAT Run-Time Library Builder gnatlbr::
187 * The GNAT Library Browser gnatls::
188 * Cleaning Up Using gnatclean::
190 * GNAT and Libraries::
191 * Using the GNU make Utility::
193 * Memory Management Issues::
194 * Creating Sample Bodies Using gnatstub::
195 * Other Utility Programs::
196 * Running and Debugging Ada Programs::
198 * Compatibility with DEC Ada::
200 * Platform-Specific Information for the Run-Time Libraries::
201 * Example of Binder Output File::
202 * Elaboration Order Handling in GNAT::
204 * Compatibility and Porting Guide::
206 * Microsoft Windows Topics::
208 * GNU Free Documentation License::
211 --- The Detailed Node Listing ---
215 * What This Guide Contains::
216 * What You Should Know before Reading This Guide::
217 * Related Information::
220 Getting Started with GNAT
223 * Running a Simple Ada Program::
224 * Running a Program with Multiple Units::
225 * Using the gnatmake Utility::
227 * Editing with Emacs::
230 * Introduction to GPS::
231 * Introduction to Glide and GVD::
234 The GNAT Compilation Model
236 * Source Representation::
237 * Foreign Language Representation::
238 * File Naming Rules::
239 * Using Other File Names::
240 * Alternative File Naming Schemes::
241 * Generating Object Files::
242 * Source Dependencies::
243 * The Ada Library Information Files::
244 * Binding an Ada Program::
245 * Mixed Language Programming::
246 * Building Mixed Ada & C++ Programs::
247 * Comparison between GNAT and C/C++ Compilation Models::
248 * Comparison between GNAT and Conventional Ada Library Models::
250 * Placement of temporary files::
253 Foreign Language Representation
256 * Other 8-Bit Codes::
257 * Wide Character Encodings::
259 Compiling Ada Programs With gcc
261 * Compiling Programs::
263 * Search Paths and the Run-Time Library (RTL)::
264 * Order of Compilation Issues::
269 * Output and Error Message Control::
270 * Warning Message Control::
271 * Debugging and Assertion Control::
272 * Validity Checking::
275 * Stack Overflow Checking::
276 * Using gcc for Syntax Checking::
277 * Using gcc for Semantic Checking::
278 * Compiling Ada 83 Programs::
279 * Character Set Control::
280 * File Naming Control::
281 * Subprogram Inlining Control::
282 * Auxiliary Output Control::
283 * Debugging Control::
284 * Exception Handling Control::
285 * Units to Sources Mapping Files::
286 * Integrated Preprocessing::
291 Binding Ada Programs With gnatbind
294 * Switches for gnatbind::
295 * Command-Line Access::
296 * Search Paths for gnatbind::
297 * Examples of gnatbind Usage::
299 Switches for gnatbind
301 * Consistency-Checking Modes::
302 * Binder Error Message Control::
303 * Elaboration Control::
305 * Binding with Non-Ada Main Programs::
306 * Binding Programs with No Main Subprogram::
308 Linking Using gnatlink
311 * Switches for gnatlink::
312 * Setting Stack Size from gnatlink::
313 * Setting Heap Size from gnatlink::
315 The GNAT Make Program gnatmake
318 * Switches for gnatmake::
319 * Mode Switches for gnatmake::
320 * Notes on the Command Line::
321 * How gnatmake Works::
322 * Examples of gnatmake Usage::
324 Improving Performance
325 * Performance Considerations::
326 * Reducing the Size of Ada Executables with gnatelim::
328 Performance Considerations
329 * Controlling Run-Time Checks::
330 * Use of Restrictions::
331 * Optimization Levels::
332 * Debugging Optimized Code::
333 * Inlining of Subprograms::
334 * Optimization and Strict Aliasing::
336 * Coverage Analysis::
339 Reducing the Size of Ada Executables with gnatelim
342 * Correcting the List of Eliminate Pragmas::
343 * Making Your Executables Smaller::
344 * Summary of the gnatelim Usage Cycle::
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 * Using Third-Party Libraries through Projects::
381 * Stand-alone Library Projects::
382 * Switches Related to Project Files::
383 * Tools Supporting Project Files::
384 * An Extended Example::
385 * Project File Complete Syntax::
387 The Cross-Referencing Tools gnatxref and gnatfind
389 * gnatxref Switches::
390 * gnatfind Switches::
391 * Project Files for gnatxref and gnatfind::
392 * Regular Expressions in gnatfind and gnatxref::
393 * Examples of gnatxref Usage::
394 * Examples of gnatfind Usage::
396 The GNAT Pretty-Printer gnatpp
398 * Switches for gnatpp::
401 The GNAT Metrics Tool gnatmetric
403 * Switches for gnatmetric::
405 File Name Krunching Using gnatkr
410 * Examples of gnatkr Usage::
412 Preprocessing Using gnatprep
415 * Switches for gnatprep::
416 * Form of Definitions File::
417 * Form of Input Text for gnatprep::
420 The GNAT Run-Time Library Builder gnatlbr
423 * Switches for gnatlbr::
424 * Examples of gnatlbr Usage::
427 The GNAT Library Browser gnatls
430 * Switches for gnatls::
431 * Examples of gnatls Usage::
433 Cleaning Up Using gnatclean
435 * Running gnatclean::
436 * Switches for gnatclean::
437 * Examples of gnatclean Usage::
443 * Introduction to Libraries in GNAT::
444 * General Ada Libraries::
445 * Stand-alone Ada Libraries::
446 * Rebuilding the GNAT Run-Time Library::
448 Using the GNU make Utility
450 * Using gnatmake in a Makefile::
451 * Automatically Creating a List of Directories::
452 * Generating the Command Line Switches::
453 * Overcoming Command Line Length Limits::
456 Memory Management Issues
458 * Some Useful Memory Pools::
459 * The GNAT Debug Pool Facility::
464 Some Useful Memory Pools
466 The GNAT Debug Pool Facility
472 * Switches for gnatmem::
473 * Example of gnatmem Usage::
476 Sample Bodies Using gnatstub
479 * Switches for gnatstub::
481 Other Utility Programs
483 * Using Other Utility Programs with GNAT::
484 * The External Symbol Naming Scheme of GNAT::
486 * Ada Mode for Glide::
488 * Converting Ada Files to html with gnathtml::
490 Running and Debugging Ada Programs
492 * The GNAT Debugger GDB::
494 * Introduction to GDB Commands::
495 * Using Ada Expressions::
496 * Calling User-Defined Subprograms::
497 * Using the Next Command in a Function::
500 * Debugging Generic Units::
501 * GNAT Abnormal Termination or Failure to Terminate::
502 * Naming Conventions for GNAT Source Files::
503 * Getting Internal Debugging Information::
511 Compatibility with DEC Ada
513 * Ada 95 Compatibility::
514 * Differences in the Definition of Package System::
515 * Language-Related Features::
516 * The Package STANDARD::
517 * The Package SYSTEM::
518 * Tasking and Task-Related Features::
519 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
520 * Pragmas and Pragma-Related Features::
521 * Library of Predefined Units::
523 * Main Program Definition::
524 * Implementation-Defined Attributes::
525 * Compiler and Run-Time Interfacing::
526 * Program Compilation and Library Management::
528 * Implementation Limits::
531 Language-Related Features
533 * Integer Types and Representations::
534 * Floating-Point Types and Representations::
535 * Pragmas Float_Representation and Long_Float::
536 * Fixed-Point Types and Representations::
537 * Record and Array Component Alignment::
539 * Other Representation Clauses::
541 Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
543 * Assigning Task IDs::
544 * Task IDs and Delays::
545 * Task-Related Pragmas::
546 * Scheduling and Task Priority::
548 * External Interrupts::
550 Pragmas and Pragma-Related Features
552 * Restrictions on the Pragma INLINE::
553 * Restrictions on the Pragma INTERFACE::
554 * Restrictions on the Pragma SYSTEM_NAME::
556 Library of Predefined Units
558 * Changes to DECLIB::
562 * Shared Libraries and Options Files::
566 Platform-Specific Information for the Run-Time Libraries
568 * Summary of Run-Time Configurations::
569 * Specifying a Run-Time Library::
570 * Choosing between Native and FSU Threads Libraries::
571 * Choosing the Scheduling Policy::
572 * Solaris-Specific Considerations::
573 * IRIX-Specific Considerations::
574 * Linux-Specific Considerations::
575 * AIX-Specific Considerations::
577 Example of Binder Output File
579 Elaboration Order Handling in GNAT
581 * Elaboration Code in Ada 95::
582 * Checking the Elaboration Order in Ada 95::
583 * Controlling the Elaboration Order in Ada 95::
584 * Controlling Elaboration in GNAT - Internal Calls::
585 * Controlling Elaboration in GNAT - External Calls::
586 * Default Behavior in GNAT - Ensuring Safety::
587 * Treatment of Pragma Elaborate::
588 * Elaboration Issues for Library Tasks::
589 * Mixing Elaboration Models::
590 * What to Do If the Default Elaboration Behavior Fails::
591 * Elaboration for Access-to-Subprogram Values::
592 * Summary of Procedures for Elaboration Control::
593 * Other Elaboration Order Considerations::
597 * Basic Assembler Syntax::
598 * A Simple Example of Inline Assembler::
599 * Output Variables in Inline Assembler::
600 * Input Variables in Inline Assembler::
601 * Inlining Inline Assembler Code::
602 * Other Asm Functionality::
603 * A Complete Example::
605 Compatibility and Porting Guide
607 * Compatibility with Ada 83::
608 * Implementation-dependent characteristics::
609 * Compatibility with DEC Ada 83::
610 * Compatibility with Other Ada 95 Systems::
611 * Representation Clauses::
613 * Transitioning from Alpha to Integrity OpenVMS::
617 Microsoft Windows Topics
619 * Using GNAT on Windows::
620 * CONSOLE and WINDOWS subsystems::
622 * Mixed-Language Programming on Windows::
623 * Windows Calling Conventions::
624 * Introduction to Dynamic Link Libraries (DLLs)::
625 * Using DLLs with GNAT::
626 * Building DLLs with GNAT::
627 * GNAT and Windows Resources::
629 * GNAT and COM/DCOM Objects::
636 @node About This Guide
637 @unnumbered About This Guide
641 This guide describes the use of @value{EDITION},
642 a full language compiler for the Ada
643 95 programming language, implemented on HP's Alpha and
644 Integrity (ia64) OpenVMS platforms.
647 This guide describes the use of @value{EDITION},
648 a compiler and software development
649 toolset for the full Ada 95 programming language.
651 It describes the features of the compiler and tools, and details
652 how to use them to build Ada 95 applications.
655 For ease of exposition, ``GNAT Pro'' will be referred to simply as
656 ``GNAT'' in the remainder of this document.
660 * What This Guide Contains::
661 * What You Should Know before Reading This Guide::
662 * Related Information::
666 @node What This Guide Contains
667 @unnumberedsec What This Guide Contains
670 This guide contains the following chapters:
674 @ref{Getting Started with GNAT}, describes how to get started compiling
675 and running Ada programs with the GNAT Ada programming environment.
677 @ref{The GNAT Compilation Model}, describes the compilation model used
681 @ref{Compiling Using gcc}, describes how to compile
682 Ada programs with @code{gcc}, the Ada compiler.
685 @ref{Binding Using gnatbind}, describes how to
686 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
690 @ref{Linking Using gnatlink},
691 describes @code{gnatlink}, a
692 program that provides for linking using the GNAT run-time library to
693 construct a program. @code{gnatlink} can also incorporate foreign language
694 object units into the executable.
697 @ref{The GNAT Make Program gnatmake}, describes @code{gnatmake}, a
698 utility that automatically determines the set of sources
699 needed by an Ada compilation unit, and executes the necessary compilations
703 @ref{Improving Performance}, shows various techniques for making your
704 Ada program run faster or take less space.
705 It discusses the effect of the compiler's optimization switch and
706 also describes the @command{gnatelim} tool.
709 @ref{Renaming Files Using gnatchop}, describes
710 @code{gnatchop}, a utility that allows you to preprocess a file that
711 contains Ada source code, and split it into one or more new files, one
712 for each compilation unit.
715 @ref{Configuration Pragmas}, describes the configuration pragmas
719 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
720 shows how to override the default GNAT file naming conventions,
721 either for an individual unit or globally.
724 @ref{GNAT Project Manager}, describes how to use project files
725 to organize large projects.
728 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
729 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
730 way to navigate through sources.
733 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
734 version of an Ada source file with control over casing, indentation,
735 comment placement, and other elements of program presentation style.
738 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
739 metrics for an Ada source file, such as the number of types and subprograms,
740 and assorted complexity measures.
743 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
744 file name krunching utility, used to handle shortened
745 file names on operating systems with a limit on the length of names.
748 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
749 preprocessor utility that allows a single source file to be used to
750 generate multiple or parameterized source files, by means of macro
755 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
756 a tool for rebuilding the GNAT run time with user-supplied
757 configuration pragmas.
761 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
762 utility that displays information about compiled units, including dependences
763 on the corresponding sources files, and consistency of compilations.
766 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
767 to delete files that are produced by the compiler, binder and linker.
771 @ref{GNAT and Libraries}, describes the process of creating and using
772 Libraries with GNAT. It also describes how to recompile the GNAT run-time
776 @ref{Using the GNU make Utility}, describes some techniques for using
777 the GNAT toolset in Makefiles.
781 @ref{Memory Management Issues}, describes some useful predefined storage pools
782 and in particular the GNAT Debug Pool facility, which helps detect incorrect
785 It also describes @command{gnatmem}, a utility that monitors dynamic
786 allocation and deallocation and helps detect ``memory leaks''.
790 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
791 a utility that generates empty but compilable bodies for library units.
794 @ref{Other Utility Programs}, discusses several other GNAT utilities,
795 including @code{gnathtml}.
798 @ref{Running and Debugging Ada Programs}, describes how to run and debug
803 @ref{Compatibility with DEC Ada}, details the compatibility of GNAT with
804 DEC Ada 83 @footnote{``DEC Ada'' refers to the legacy product originally
805 developed by Digital Equipment Corporation and currently supported by HP.}
810 @ref{Platform-Specific Information for the Run-Time Libraries},
811 describes the various run-time
812 libraries supported by GNAT on various platforms and explains how to
813 choose a particular library.
816 @ref{Example of Binder Output File}, shows the source code for the binder
817 output file for a sample program.
820 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
821 you deal with elaboration order issues.
824 @ref{Inline Assembler}, shows how to use the inline assembly facility
828 @ref{Compatibility and Porting Guide}, includes sections on compatibility
829 of GNAT with other Ada 83 and Ada 95 compilation systems, to assist
830 in porting code from other environments.
834 @ref{Microsoft Windows Topics}, presents information relevant to the
835 Microsoft Windows platform.
839 @c *************************************************
840 @node What You Should Know before Reading This Guide
841 @c *************************************************
842 @unnumberedsec What You Should Know before Reading This Guide
844 @cindex Ada 95 Language Reference Manual
846 This user's guide assumes that you are familiar with Ada 95 language, as
847 described in the International Standard ANSI/ISO/IEC-8652:1995, January
850 @node Related Information
851 @unnumberedsec Related Information
854 For further information about related tools, refer to the following
859 @cite{GNAT Reference Manual}, which contains all reference
860 material for the GNAT implementation of Ada 95.
864 @cite{Using the GNAT Programming System}, which describes the GPS
865 integrated development environment.
868 @cite{GNAT Programming System Tutorial}, which introduces the
869 main GPS features through examples.
873 @cite{Ada 95 Language Reference Manual}, which contains all reference
874 material for the Ada 95 programming language.
877 @cite{Debugging with GDB}
879 , located in the GNU:[DOCS] directory,
881 contains all details on the use of the GNU source-level debugger.
884 @cite{GNU Emacs Manual}
886 , located in the GNU:[DOCS] directory if the EMACS kit is installed,
888 contains full information on the extensible editor and programming
895 @unnumberedsec Conventions
897 @cindex Typographical conventions
900 Following are examples of the typographical and graphic conventions used
905 @code{Functions}, @code{utility program names}, @code{standard names},
912 @file{File Names}, @file{button names}, and @file{field names}.
921 [optional information or parameters]
924 Examples are described by text
926 and then shown this way.
931 Commands that are entered by the user are preceded in this manual by the
932 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
933 uses this sequence as a prompt, then the commands will appear exactly as
934 you see them in the manual. If your system uses some other prompt, then
935 the command will appear with the @code{$} replaced by whatever prompt
936 character you are using.
939 Full file names are shown with the ``@code{/}'' character
940 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
941 If you are using GNAT on a Windows platform, please note that
942 the ``@code{\}'' character should be used instead.
945 @c ****************************
946 @node Getting Started with GNAT
947 @chapter Getting Started with GNAT
950 This chapter describes some simple ways of using GNAT to build
951 executable Ada programs.
953 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
954 show how to use the command line environment.
955 @ref{Introduction to Glide and GVD}, provides a brief
956 introduction to the visually-oriented IDE for GNAT.
957 Supplementing Glide on some platforms is GPS, the
958 GNAT Programming System, which offers a richer graphical
959 ``look and feel'', enhanced configurability, support for
960 development in other programming language, comprehensive
961 browsing features, and many other capabilities.
962 For information on GPS please refer to
963 @cite{Using the GNAT Programming System}.
968 * Running a Simple Ada Program::
969 * Running a Program with Multiple Units::
970 * Using the gnatmake Utility::
972 * Editing with Emacs::
975 * Introduction to GPS::
976 * Introduction to Glide and GVD::
981 @section Running GNAT
984 Three steps are needed to create an executable file from an Ada source
989 The source file(s) must be compiled.
991 The file(s) must be bound using the GNAT binder.
993 All appropriate object files must be linked to produce an executable.
997 All three steps are most commonly handled by using the @code{gnatmake}
998 utility program that, given the name of the main program, automatically
999 performs the necessary compilation, binding and linking steps.
1001 @node Running a Simple Ada Program
1002 @section Running a Simple Ada Program
1005 Any text editor may be used to prepare an Ada program.
1008 used, the optional Ada mode may be helpful in laying out the program.
1011 program text is a normal text file. We will suppose in our initial
1012 example that you have used your editor to prepare the following
1013 standard format text file:
1015 @smallexample @c ada
1017 with Ada.Text_IO; use Ada.Text_IO;
1020 Put_Line ("Hello WORLD!");
1026 This file should be named @file{hello.adb}.
1027 With the normal default file naming conventions, GNAT requires
1029 contain a single compilation unit whose file name is the
1031 with periods replaced by hyphens; the
1032 extension is @file{ads} for a
1033 spec and @file{adb} for a body.
1034 You can override this default file naming convention by use of the
1035 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1036 Alternatively, if you want to rename your files according to this default
1037 convention, which is probably more convenient if you will be using GNAT
1038 for all your compilations, then the @code{gnatchop} utility
1039 can be used to generate correctly-named source files
1040 (@pxref{Renaming Files Using gnatchop}).
1042 You can compile the program using the following command (@code{$} is used
1043 as the command prompt in the examples in this document):
1050 @code{gcc} is the command used to run the compiler. This compiler is
1051 capable of compiling programs in several languages, including Ada 95 and
1052 C. It assumes that you have given it an Ada program if the file extension is
1053 either @file{.ads} or @file{.adb}, and it will then call
1054 the GNAT compiler to compile the specified file.
1057 The @option{-c} switch is required. It tells @command{gcc} to only do a
1058 compilation. (For C programs, @command{gcc} can also do linking, but this
1059 capability is not used directly for Ada programs, so the @option{-c}
1060 switch must always be present.)
1063 This compile command generates a file
1064 @file{hello.o}, which is the object
1065 file corresponding to your Ada program. It also generates
1066 an ``Ada Library Information'' file @file{hello.ali},
1067 which contains additional information used to check
1068 that an Ada program is consistent.
1069 To build an executable file,
1070 use @code{gnatbind} to bind the program
1071 and @code{gnatlink} to link it. The
1072 argument to both @code{gnatbind} and @code{gnatlink} is the name of the
1073 @file{ALI} file, but the default extension of @file{.ali} can
1074 be omitted. This means that in the most common case, the argument
1075 is simply the name of the main program:
1083 A simpler method of carrying out these steps is to use
1085 a master program that invokes all the required
1086 compilation, binding and linking tools in the correct order. In particular,
1087 @command{gnatmake} automatically recompiles any sources that have been
1088 modified since they were last compiled, or sources that depend
1089 on such modified sources, so that ``version skew'' is avoided.
1090 @cindex Version skew (avoided by @command{gnatmake})
1093 $ gnatmake hello.adb
1097 The result is an executable program called @file{hello}, which can be
1100 @c The following should be removed (BMB 2001-01-23)
1102 @c $ ^./hello^$ RUN HELLO^
1103 @c @end smallexample
1110 assuming that the current directory is on the search path
1111 for executable programs.
1114 and, if all has gone well, you will see
1121 appear in response to this command.
1123 @c ****************************************
1124 @node Running a Program with Multiple Units
1125 @section Running a Program with Multiple Units
1128 Consider a slightly more complicated example that has three files: a
1129 main program, and the spec and body of a package:
1131 @smallexample @c ada
1134 package Greetings is
1139 with Ada.Text_IO; use Ada.Text_IO;
1140 package body Greetings is
1143 Put_Line ("Hello WORLD!");
1146 procedure Goodbye is
1148 Put_Line ("Goodbye WORLD!");
1165 Following the one-unit-per-file rule, place this program in the
1166 following three separate files:
1170 spec of package @code{Greetings}
1173 body of package @code{Greetings}
1176 body of main program
1180 To build an executable version of
1181 this program, we could use four separate steps to compile, bind, and link
1182 the program, as follows:
1186 $ gcc -c greetings.adb
1192 Note that there is no required order of compilation when using GNAT.
1193 In particular it is perfectly fine to compile the main program first.
1194 Also, it is not necessary to compile package specs in the case where
1195 there is an accompanying body; you only need to compile the body. If you want
1196 to submit these files to the compiler for semantic checking and not code
1197 generation, then use the
1198 @option{-gnatc} switch:
1201 $ gcc -c greetings.ads -gnatc
1205 Although the compilation can be done in separate steps as in the
1206 above example, in practice it is almost always more convenient
1207 to use the @code{gnatmake} tool. All you need to know in this case
1208 is the name of the main program's source file. The effect of the above four
1209 commands can be achieved with a single one:
1212 $ gnatmake gmain.adb
1216 In the next section we discuss the advantages of using @code{gnatmake} in
1219 @c *****************************
1220 @node Using the gnatmake Utility
1221 @section Using the @command{gnatmake} Utility
1224 If you work on a program by compiling single components at a time using
1225 @code{gcc}, you typically keep track of the units you modify. In order to
1226 build a consistent system, you compile not only these units, but also any
1227 units that depend on the units you have modified.
1228 For example, in the preceding case,
1229 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1230 you edit @file{greetings.ads}, you must recompile both
1231 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1232 units that depend on @file{greetings.ads}.
1234 @code{gnatbind} will warn you if you forget one of these compilation
1235 steps, so that it is impossible to generate an inconsistent program as a
1236 result of forgetting to do a compilation. Nevertheless it is tedious and
1237 error-prone to keep track of dependencies among units.
1238 One approach to handle the dependency-bookkeeping is to use a
1239 makefile. However, makefiles present maintenance problems of their own:
1240 if the dependencies change as you change the program, you must make
1241 sure that the makefile is kept up-to-date manually, which is also an
1242 error-prone process.
1244 The @code{gnatmake} utility takes care of these details automatically.
1245 Invoke it using either one of the following forms:
1248 $ gnatmake gmain.adb
1249 $ gnatmake ^gmain^GMAIN^
1253 The argument is the name of the file containing the main program;
1254 you may omit the extension. @code{gnatmake}
1255 examines the environment, automatically recompiles any files that need
1256 recompiling, and binds and links the resulting set of object files,
1257 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1258 In a large program, it
1259 can be extremely helpful to use @code{gnatmake}, because working out by hand
1260 what needs to be recompiled can be difficult.
1262 Note that @code{gnatmake}
1263 takes into account all the Ada 95 rules that
1264 establish dependencies among units. These include dependencies that result
1265 from inlining subprogram bodies, and from
1266 generic instantiation. Unlike some other
1267 Ada make tools, @code{gnatmake} does not rely on the dependencies that were
1268 found by the compiler on a previous compilation, which may possibly
1269 be wrong when sources change. @code{gnatmake} determines the exact set of
1270 dependencies from scratch each time it is run.
1273 @node Editing with Emacs
1274 @section Editing with Emacs
1278 Emacs is an extensible self-documenting text editor that is available in a
1279 separate VMSINSTAL kit.
1281 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1282 click on the Emacs Help menu and run the Emacs Tutorial.
1283 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1284 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1286 Documentation on Emacs and other tools is available in Emacs under the
1287 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1288 use the middle mouse button to select a topic (e.g. Emacs).
1290 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1291 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1292 get to the Emacs manual.
1293 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1296 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1297 which is sufficiently extensible to provide for a complete programming
1298 environment and shell for the sophisticated user.
1302 @node Introduction to GPS
1303 @section Introduction to GPS
1304 @cindex GPS (GNAT Programming System)
1305 @cindex GNAT Programming System (GPS)
1307 Although the command line interface (@command{gnatmake}, etc.) alone
1308 is sufficient, a graphical Interactive Development
1309 Environment can make it easier for you to compose, navigate, and debug
1310 programs. This section describes the main features of GPS
1311 (``GNAT Programming System''), the GNAT graphical IDE.
1312 You will see how to use GPS to build and debug an executable, and
1313 you will also learn some of the basics of the GNAT ``project'' facility.
1315 GPS enables you to do much more than is presented here;
1316 e.g., you can produce a call graph, interface to a third-party
1317 Version Control System, and inspect the generated assembly language
1319 Indeed, GPS also supports languages other than Ada.
1320 Such additional information, and an explanation of all of the GPS menu
1321 items. may be found in the on-line help, which includes
1322 a user's guide and a tutorial (these are also accessible from the GNAT
1326 * Building a New Program with GPS::
1327 * Simple Debugging with GPS::
1330 @node Building a New Program with GPS
1331 @subsection Building a New Program with GPS
1333 GPS invokes the GNAT compilation tools using information
1334 contained in a @emph{project} (also known as a @emph{project file}):
1335 a collection of properties such
1336 as source directories, identities of main subprograms, tool switches, etc.,
1337 and their associated values.
1338 (See @ref{GNAT Project Manager}, for details.)
1339 In order to run GPS, you will need to either create a new project
1340 or else open an existing one.
1342 This section will explain how you can use GPS to create a project,
1343 to associate Ada source files with a project, and to build and run
1347 @item @emph{Creating a project}
1349 Invoke GPS, either from the command line or the platform's IDE.
1350 After it starts, GPS will display a ``Welcome'' screen with three
1355 @code{Start with default project in directory}
1358 @code{Create new project with wizard}
1361 @code{Open existing project}
1365 Select @code{Create new project with wizard} and press @code{OK}.
1366 A new window will appear. In the text box labeled with
1367 @code{Enter the name of the project to create}, type @file{sample}
1368 as the project name.
1369 In the next box, browse to choose the directory in which you
1370 would like to create the project file.
1371 After selecting an appropriate directory, press @code{Forward}.
1373 A window will appear with the title
1374 @code{Version Control System Configuration}.
1375 Simply press @code{Forward}.
1377 A window will appear with the title
1378 @code{Please select the source directories for this project}.
1379 The directory that you specified for the project file will be selected
1380 by default as the one to use for sources; simply press @code{Forward}.
1382 A window will appear with the title
1383 @code{Please select the build directory for this project}.
1384 The directory that you specified for the project file will be selected
1385 by default for object files and executables;
1386 simply press @code{Forward}.
1388 A window will appear with the title
1389 @code{Please select the main units for this project}.
1390 You will supply this information later, after creating the source file.
1391 Simply press @code{Forward} for now.
1393 A window will appear with the title
1394 @code{Please select the switches to build the project}.
1395 Press @code{Apply}. This will create a project file named
1396 @file{sample.prj} in the directory that you had specified.
1398 @item @emph{Creating and saving the source file}
1400 After you create the new project, a GPS window will appear, which is
1401 partitioned into two main sections:
1405 A @emph{Workspace area}, initially greyed out, which you will use for
1406 creating and editing source files
1409 Directly below, a @emph{Messages area}, which initially displays a
1410 ``Welcome'' message.
1411 (If the Messages area is not visible, drag its border upward to expand it.)
1415 Select @code{File} on the menu bar, and then the @code{New} command.
1416 The Workspace area will become white, and you can now
1417 enter the source program explicitly.
1418 Type the following text
1420 @smallexample @c ada
1422 with Ada.Text_IO; use Ada.Text_IO;
1425 Put_Line("Hello from GPS!");
1431 Select @code{File}, then @code{Save As}, and enter the source file name
1433 The file will be saved in the same directory you specified as the
1434 location of the default project file.
1436 @item @emph{Updating the project file}
1438 You need to add the new source file to the project.
1440 the @code{Project} menu and then @code{Edit project properties}.
1441 Click the @code{Main files} tab on the left, and then the
1443 Choose @file{hello.adb} from the list, and press @code{Open}.
1444 The project settings window will reflect this action.
1447 @item @emph{Building and running the program}
1449 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1450 and select @file{hello.adb}.
1451 The Messages window will display the resulting invocations of @command{gcc},
1452 @command{gnatbind}, and @command{gnatlink}
1453 (reflecting the default switch settings from the
1454 project file that you created) and then a ``successful compilation/build''
1457 To run the program, choose the @code{Build} menu, then @code{Run}, and
1458 select @command{hello}.
1459 An @emph{Arguments Selection} window will appear.
1460 There are no command line arguments, so just click @code{OK}.
1462 The Messages window will now display the program's output (the string
1463 @code{Hello from GPS}), and at the bottom of the GPS window a status
1464 update is displayed (@code{Run: hello}).
1465 Close the GPS window (or select @code{File}, then @code{Exit}) to
1466 terminate this GPS session.
1469 @node Simple Debugging with GPS
1470 @subsection Simple Debugging with GPS
1472 This section illustrates basic debugging techniques (setting breakpoints,
1473 examining/modifying variables, single stepping).
1476 @item @emph{Opening a project}
1478 Start GPS and select @code{Open existing project}; browse to
1479 specify the project file @file{sample.prj} that you had created in the
1482 @item @emph{Creating a source file}
1484 Select @code{File}, then @code{New}, and type in the following program:
1486 @smallexample @c ada
1488 with Ada.Text_IO; use Ada.Text_IO;
1489 procedure Example is
1490 Line : String (1..80);
1493 Put_Line("Type a line of text at each prompt; an empty line to exit");
1497 Put_Line (Line (1..N) );
1505 Select @code{File}, then @code{Save as}, and enter the file name
1508 @item @emph{Updating the project file}
1510 Add @code{Example} as a new main unit for the project:
1513 Select @code{Project}, then @code{Edit Project Properties}.
1516 Select the @code{Main files} tab, click @code{Add}, then
1517 select the file @file{example.adb} from the list, and
1519 You will see the file name appear in the list of main units
1525 @item @emph{Building/running the executable}
1527 To build the executable
1528 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1530 Run the program to see its effect (in the Messages area).
1531 Each line that you enter is displayed; an empty line will
1532 cause the loop to exit and the program to terminate.
1534 @item @emph{Debugging the program}
1536 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1537 which are required for debugging, are on by default when you create
1539 Thus unless you intentionally remove these settings, you will be able
1540 to debug any program that you develop using GPS.
1543 @item @emph{Initializing}
1545 Select @code{Debug}, then @code{Initialize}, then @file{example}
1547 @item @emph{Setting a breakpoint}
1549 After performing the initialization step, you will observe a small
1550 icon to the right of each line number.
1551 This serves as a toggle for breakpoints; clicking the icon will
1552 set a breakpoint at the corresponding line (the icon will change to
1553 a red circle with an ``x''), and clicking it again
1554 will remove the breakpoint / reset the icon.
1556 For purposes of this example, set a breakpoint at line 10 (the
1557 statement @code{Put_Line@ (Line@ (1..N));}
1559 @item @emph{Starting program execution}
1561 Select @code{Debug}, then @code{Run}. When the
1562 @code{Program Arguments} window appears, click @code{OK}.
1563 A console window will appear; enter some line of text,
1564 e.g. @code{abcde}, at the prompt.
1565 The program will pause execution when it gets to the
1566 breakpoint, and the corresponding line is highlighted.
1568 @item @emph{Examining a variable}
1570 Move the mouse over one of the occurrences of the variable @code{N}.
1571 You will see the value (5) displayed, in ``tool tip'' fashion.
1572 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1573 You will see information about @code{N} appear in the @code{Debugger Data}
1574 pane, showing the value as 5.
1576 @item @emph{Assigning a new value to a variable}
1578 Right click on the @code{N} in the @code{Debugger Data} pane, and
1579 select @code{Set value of N}.
1580 When the input window appears, enter the value @code{4} and click
1582 This value does not automatically appear in the @code{Debugger Data}
1583 pane; to see it, right click again on the @code{N} in the
1584 @code{Debugger Data} pane and select @code{Update value}.
1585 The new value, 4, will appear in red.
1587 @item @emph{Single stepping}
1589 Select @code{Debug}, then @code{Next}.
1590 This will cause the next statement to be executed, in this case the
1591 call of @code{Put_Line} with the string slice.
1592 Notice in the console window that the displayed string is simply
1593 @code{abcd} and not @code{abcde} which you had entered.
1594 This is because the upper bound of the slice is now 4 rather than 5.
1596 @item @emph{Removing a breakpoint}
1598 Toggle the breakpoint icon at line 10.
1600 @item @emph{Resuming execution from a breakpoint}
1602 Select @code{Debug}, then @code{Continue}.
1603 The program will reach the next iteration of the loop, and
1604 wait for input after displaying the prompt.
1605 This time, just hit the @kbd{Enter} key.
1606 The value of @code{N} will be 0, and the program will terminate.
1607 The console window will disappear.
1611 @node Introduction to Glide and GVD
1612 @section Introduction to Glide and GVD
1616 This section describes the main features of Glide,
1617 a GNAT graphical IDE, and also shows how to use the basic commands in GVD,
1618 the GNU Visual Debugger.
1619 These tools may be present in addition to, or in place of, GPS on some
1621 Additional information on Glide and GVD may be found
1622 in the on-line help for these tools.
1625 * Building a New Program with Glide::
1626 * Simple Debugging with GVD::
1627 * Other Glide Features::
1630 @node Building a New Program with Glide
1631 @subsection Building a New Program with Glide
1633 The simplest way to invoke Glide is to enter @command{glide}
1634 at the command prompt. It will generally be useful to issue this
1635 as a background command, thus allowing you to continue using
1636 your command window for other purposes while Glide is running:
1643 Glide will start up with an initial screen displaying the top-level menu items
1644 as well as some other information. The menu selections are as follows
1646 @item @code{Buffers}
1657 For this introductory example, you will need to create a new Ada source file.
1658 First, select the @code{Files} menu. This will pop open a menu with around
1659 a dozen or so items. To create a file, select the @code{Open file...} choice.
1660 Depending on the platform, you may see a pop-up window where you can browse
1661 to an appropriate directory and then enter the file name, or else simply
1662 see a line at the bottom of the Glide window where you can likewise enter
1663 the file name. Note that in Glide, when you attempt to open a non-existent
1664 file, the effect is to create a file with that name. For this example enter
1665 @file{hello.adb} as the name of the file.
1667 A new buffer will now appear, occupying the entire Glide window,
1668 with the file name at the top. The menu selections are slightly different
1669 from the ones you saw on the opening screen; there is an @code{Entities} item,
1670 and in place of @code{Glide} there is now an @code{Ada} item. Glide uses
1671 the file extension to identify the source language, so @file{adb} indicates
1674 You will enter some of the source program lines explicitly,
1675 and use the syntax-oriented template mechanism to enter other lines.
1676 First, type the following text:
1678 with Ada.Text_IO; use Ada.Text_IO;
1684 Observe that Glide uses different colors to distinguish reserved words from
1685 identifiers. Also, after the @code{procedure Hello is} line, the cursor is
1686 automatically indented in anticipation of declarations. When you enter
1687 @code{begin}, Glide recognizes that there are no declarations and thus places
1688 @code{begin} flush left. But after the @code{begin} line the cursor is again
1689 indented, where the statement(s) will be placed.
1691 The main part of the program will be a @code{for} loop. Instead of entering
1692 the text explicitly, however, use a statement template. Select the @code{Ada}
1693 item on the top menu bar, move the mouse to the @code{Statements} item,
1694 and you will see a large selection of alternatives. Choose @code{for loop}.
1695 You will be prompted (at the bottom of the buffer) for a loop name;
1696 simply press the @key{Enter} key since a loop name is not needed.
1697 You should see the beginning of a @code{for} loop appear in the source
1698 program window. You will now be prompted for the name of the loop variable;
1699 enter a line with the identifier @code{ind} (lower case). Note that,
1700 by default, Glide capitalizes the name (you can override such behavior
1701 if you wish, although this is outside the scope of this introduction).
1702 Next, Glide prompts you for the loop range; enter a line containing
1703 @code{1..5} and you will see this also appear in the source program,
1704 together with the remaining elements of the @code{for} loop syntax.
1706 Next enter the statement (with an intentional error, a missing semicolon)
1707 that will form the body of the loop:
1709 Put_Line("Hello, World" & Integer'Image(I))
1713 Finally, type @code{end Hello;} as the last line in the program.
1714 Now save the file: choose the @code{File} menu item, and then the
1715 @code{Save buffer} selection. You will see a message at the bottom
1716 of the buffer confirming that the file has been saved.
1718 You are now ready to attempt to build the program. Select the @code{Ada}
1719 item from the top menu bar. Although we could choose simply to compile
1720 the file, we will instead attempt to do a build (which invokes
1721 @command{gnatmake}) since, if the compile is successful, we want to build
1722 an executable. Thus select @code{Ada build}. This will fail because of the
1723 compilation error, and you will notice that the Glide window has been split:
1724 the top window contains the source file, and the bottom window contains the
1725 output from the GNAT tools. Glide allows you to navigate from a compilation
1726 error to the source file position corresponding to the error: click the
1727 middle mouse button (or simultaneously press the left and right buttons,
1728 on a two-button mouse) on the diagnostic line in the tool window. The
1729 focus will shift to the source window, and the cursor will be positioned
1730 on the character at which the error was detected.
1732 Correct the error: type in a semicolon to terminate the statement.
1733 Although you can again save the file explicitly, you can also simply invoke
1734 @code{Ada} @result{} @code{Build} and you will be prompted to save the file.
1735 This time the build will succeed; the tool output window shows you the
1736 options that are supplied by default. The GNAT tools' output (e.g.
1737 object and ALI files, executable) will go in the directory from which
1740 To execute the program, choose @code{Ada} and then @code{Run}.
1741 You should see the program's output displayed in the bottom window:
1751 @node Simple Debugging with GVD
1752 @subsection Simple Debugging with GVD
1755 This section describes how to set breakpoints, examine/modify variables,
1756 and step through execution.
1758 In order to enable debugging, you need to pass the @option{-g} switch
1759 to both the compiler and to @command{gnatlink}. If you are using
1760 the command line, passing @option{-g} to @command{gnatmake} will have
1761 this effect. You can then launch GVD, e.g. on the @code{hello} program,
1762 by issuing the command:
1769 If you are using Glide, then @option{-g} is passed to the relevant tools
1770 by default when you do a build. Start the debugger by selecting the
1771 @code{Ada} menu item, and then @code{Debug}.
1773 GVD comes up in a multi-part window. One pane shows the names of files
1774 comprising your executable; another pane shows the source code of the current
1775 unit (initially your main subprogram), another pane shows the debugger output
1776 and user interactions, and the fourth pane (the data canvas at the top
1777 of the window) displays data objects that you have selected.
1779 To the left of the source file pane, you will notice green dots adjacent
1780 to some lines. These are lines for which object code exists and where
1781 breakpoints can thus be set. You set/reset a breakpoint by clicking
1782 the green dot. When a breakpoint is set, the dot is replaced by an @code{X}
1783 in a red circle. Clicking the circle toggles the breakpoint off,
1784 and the red circle is replaced by the green dot.
1786 For this example, set a breakpoint at the statement where @code{Put_Line}
1789 Start program execution by selecting the @code{Run} button on the top menu bar.
1790 (The @code{Start} button will also start your program, but it will
1791 cause program execution to break at the entry to your main subprogram.)
1792 Evidence of reaching the breakpoint will appear: the source file line will be
1793 highlighted, and the debugger interactions pane will display
1796 You can examine the values of variables in several ways. Move the mouse
1797 over an occurrence of @code{Ind} in the @code{for} loop, and you will see
1798 the value (now @code{1}) displayed. Alternatively, right-click on @code{Ind}
1799 and select @code{Display Ind}; a box showing the variable's name and value
1800 will appear in the data canvas.
1802 Although a loop index is a constant with respect to Ada semantics,
1803 you can change its value in the debugger. Right-click in the box
1804 for @code{Ind}, and select the @code{Set Value of Ind} item.
1805 Enter @code{2} as the new value, and press @command{OK}.
1806 The box for @code{Ind} shows the update.
1808 Press the @code{Step} button on the top menu bar; this will step through
1809 one line of program text (the invocation of @code{Put_Line}), and you can
1810 observe the effect of having modified @code{Ind} since the value displayed
1813 Remove the breakpoint, and resume execution by selecting the @code{Cont}
1814 button. You will see the remaining output lines displayed in the debugger
1815 interaction window, along with a message confirming normal program
1818 @node Other Glide Features
1819 @subsection Other Glide Features
1822 You may have observed that some of the menu selections contain abbreviations;
1823 e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu.
1824 These are @emph{shortcut keys} that you can use instead of selecting
1825 menu items. The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means
1826 @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead
1827 of selecting @code{Files} and then @code{Open file...}.
1829 To abort a Glide command, type @key{Ctrl-g}.
1831 If you want Glide to start with an existing source file, you can either
1832 launch Glide as above and then open the file via @code{Files} @result{}
1833 @code{Open file...}, or else simply pass the name of the source file
1834 on the command line:
1841 While you are using Glide, a number of @emph{buffers} exist.
1842 You create some explicitly; e.g., when you open/create a file.
1843 Others arise as an effect of the commands that you issue; e.g., the buffer
1844 containing the output of the tools invoked during a build. If a buffer
1845 is hidden, you can bring it into a visible window by first opening
1846 the @code{Buffers} menu and then selecting the desired entry.
1848 If a buffer occupies only part of the Glide screen and you want to expand it
1849 to fill the entire screen, then click in the buffer and then select
1850 @code{Files} @result{} @code{One Window}.
1852 If a window is occupied by one buffer and you want to split the window
1853 to bring up a second buffer, perform the following steps:
1855 @item Select @code{Files} @result{} @code{Split Window};
1856 this will produce two windows each of which holds the original buffer
1857 (these are not copies, but rather different views of the same buffer contents)
1859 @item With the focus in one of the windows,
1860 select the desired buffer from the @code{Buffers} menu
1864 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1867 @node The GNAT Compilation Model
1868 @chapter The GNAT Compilation Model
1869 @cindex GNAT compilation model
1870 @cindex Compilation model
1873 * Source Representation::
1874 * Foreign Language Representation::
1875 * File Naming Rules::
1876 * Using Other File Names::
1877 * Alternative File Naming Schemes::
1878 * Generating Object Files::
1879 * Source Dependencies::
1880 * The Ada Library Information Files::
1881 * Binding an Ada Program::
1882 * Mixed Language Programming::
1883 * Building Mixed Ada & C++ Programs::
1884 * Comparison between GNAT and C/C++ Compilation Models::
1885 * Comparison between GNAT and Conventional Ada Library Models::
1887 * Placement of temporary files::
1892 This chapter describes the compilation model used by GNAT. Although
1893 similar to that used by other languages, such as C and C++, this model
1894 is substantially different from the traditional Ada compilation models,
1895 which are based on a library. The model is initially described without
1896 reference to the library-based model. If you have not previously used an
1897 Ada compiler, you need only read the first part of this chapter. The
1898 last section describes and discusses the differences between the GNAT
1899 model and the traditional Ada compiler models. If you have used other
1900 Ada compilers, this section will help you to understand those
1901 differences, and the advantages of the GNAT model.
1903 @node Source Representation
1904 @section Source Representation
1908 Ada source programs are represented in standard text files, using
1909 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1910 7-bit ASCII set, plus additional characters used for
1911 representing foreign languages (@pxref{Foreign Language Representation}
1912 for support of non-USA character sets). The format effector characters
1913 are represented using their standard ASCII encodings, as follows:
1918 Vertical tab, @code{16#0B#}
1922 Horizontal tab, @code{16#09#}
1926 Carriage return, @code{16#0D#}
1930 Line feed, @code{16#0A#}
1934 Form feed, @code{16#0C#}
1938 Source files are in standard text file format. In addition, GNAT will
1939 recognize a wide variety of stream formats, in which the end of physical
1940 physical lines is marked by any of the following sequences:
1941 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1942 in accommodating files that are imported from other operating systems.
1944 @cindex End of source file
1945 @cindex Source file, end
1947 The end of a source file is normally represented by the physical end of
1948 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1949 recognized as signalling the end of the source file. Again, this is
1950 provided for compatibility with other operating systems where this
1951 code is used to represent the end of file.
1953 Each file contains a single Ada compilation unit, including any pragmas
1954 associated with the unit. For example, this means you must place a
1955 package declaration (a package @dfn{spec}) and the corresponding body in
1956 separate files. An Ada @dfn{compilation} (which is a sequence of
1957 compilation units) is represented using a sequence of files. Similarly,
1958 you will place each subunit or child unit in a separate file.
1960 @node Foreign Language Representation
1961 @section Foreign Language Representation
1964 GNAT supports the standard character sets defined in Ada 95 as well as
1965 several other non-standard character sets for use in localized versions
1966 of the compiler (@pxref{Character Set Control}).
1969 * Other 8-Bit Codes::
1970 * Wide Character Encodings::
1978 The basic character set is Latin-1. This character set is defined by ISO
1979 standard 8859, part 1. The lower half (character codes @code{16#00#}
1980 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1981 is used to represent additional characters. These include extended letters
1982 used by European languages, such as French accents, the vowels with umlauts
1983 used in German, and the extra letter A-ring used in Swedish.
1985 @findex Ada.Characters.Latin_1
1986 For a complete list of Latin-1 codes and their encodings, see the source
1987 file of library unit @code{Ada.Characters.Latin_1} in file
1988 @file{a-chlat1.ads}.
1989 You may use any of these extended characters freely in character or
1990 string literals. In addition, the extended characters that represent
1991 letters can be used in identifiers.
1993 @node Other 8-Bit Codes
1994 @subsection Other 8-Bit Codes
1997 GNAT also supports several other 8-bit coding schemes:
2000 @item ISO 8859-2 (Latin-2)
2003 Latin-2 letters allowed in identifiers, with uppercase and lowercase
2006 @item ISO 8859-3 (Latin-3)
2009 Latin-3 letters allowed in identifiers, with uppercase and lowercase
2012 @item ISO 8859-4 (Latin-4)
2015 Latin-4 letters allowed in identifiers, with uppercase and lowercase
2018 @item ISO 8859-5 (Cyrillic)
2021 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
2022 lowercase equivalence.
2024 @item ISO 8859-15 (Latin-9)
2027 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
2028 lowercase equivalence
2030 @item IBM PC (code page 437)
2031 @cindex code page 437
2032 This code page is the normal default for PCs in the U.S. It corresponds
2033 to the original IBM PC character set. This set has some, but not all, of
2034 the extended Latin-1 letters, but these letters do not have the same
2035 encoding as Latin-1. In this mode, these letters are allowed in
2036 identifiers with uppercase and lowercase equivalence.
2038 @item IBM PC (code page 850)
2039 @cindex code page 850
2040 This code page is a modification of 437 extended to include all the
2041 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
2042 mode, all these letters are allowed in identifiers with uppercase and
2043 lowercase equivalence.
2045 @item Full Upper 8-bit
2046 Any character in the range 80-FF allowed in identifiers, and all are
2047 considered distinct. In other words, there are no uppercase and lowercase
2048 equivalences in this range. This is useful in conjunction with
2049 certain encoding schemes used for some foreign character sets (e.g.
2050 the typical method of representing Chinese characters on the PC).
2053 No upper-half characters in the range 80-FF are allowed in identifiers.
2054 This gives Ada 83 compatibility for identifier names.
2058 For precise data on the encodings permitted, and the uppercase and lowercase
2059 equivalences that are recognized, see the file @file{csets.adb} in
2060 the GNAT compiler sources. You will need to obtain a full source release
2061 of GNAT to obtain this file.
2063 @node Wide Character Encodings
2064 @subsection Wide Character Encodings
2067 GNAT allows wide character codes to appear in character and string
2068 literals, and also optionally in identifiers, by means of the following
2069 possible encoding schemes:
2074 In this encoding, a wide character is represented by the following five
2082 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2083 characters (using uppercase letters) of the wide character code. For
2084 example, ESC A345 is used to represent the wide character with code
2086 This scheme is compatible with use of the full Wide_Character set.
2088 @item Upper-Half Coding
2089 @cindex Upper-Half Coding
2090 The wide character with encoding @code{16#abcd#} where the upper bit is on
2091 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
2092 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
2093 character, but is not required to be in the upper half. This method can
2094 be also used for shift-JIS or EUC, where the internal coding matches the
2097 @item Shift JIS Coding
2098 @cindex Shift JIS Coding
2099 A wide character is represented by a two-character sequence,
2101 @code{16#cd#}, with the restrictions described for upper-half encoding as
2102 described above. The internal character code is the corresponding JIS
2103 character according to the standard algorithm for Shift-JIS
2104 conversion. Only characters defined in the JIS code set table can be
2105 used with this encoding method.
2109 A wide character is represented by a two-character sequence
2111 @code{16#cd#}, with both characters being in the upper half. The internal
2112 character code is the corresponding JIS character according to the EUC
2113 encoding algorithm. Only characters defined in the JIS code set table
2114 can be used with this encoding method.
2117 A wide character is represented using
2118 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
2119 10646-1/Am.2. Depending on the character value, the representation
2120 is a one, two, or three byte sequence:
2125 16#0000#-16#007f#: 2#0xxxxxxx#
2126 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
2127 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
2132 where the xxx bits correspond to the left-padded bits of the
2133 16-bit character value. Note that all lower half ASCII characters
2134 are represented as ASCII bytes and all upper half characters and
2135 other wide characters are represented as sequences of upper-half
2136 (The full UTF-8 scheme allows for encoding 31-bit characters as
2137 6-byte sequences, but in this implementation, all UTF-8 sequences
2138 of four or more bytes length will be treated as illegal).
2139 @item Brackets Coding
2140 In this encoding, a wide character is represented by the following eight
2148 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2149 characters (using uppercase letters) of the wide character code. For
2150 example, [``A345''] is used to represent the wide character with code
2151 @code{16#A345#}. It is also possible (though not required) to use the
2152 Brackets coding for upper half characters. For example, the code
2153 @code{16#A3#} can be represented as @code{[``A3'']}.
2155 This scheme is compatible with use of the full Wide_Character set,
2156 and is also the method used for wide character encoding in the standard
2157 ACVC (Ada Compiler Validation Capability) test suite distributions.
2162 Note: Some of these coding schemes do not permit the full use of the
2163 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
2164 use of the upper half of the Latin-1 set.
2166 @node File Naming Rules
2167 @section File Naming Rules
2170 The default file name is determined by the name of the unit that the
2171 file contains. The name is formed by taking the full expanded name of
2172 the unit and replacing the separating dots with hyphens and using
2173 ^lowercase^uppercase^ for all letters.
2175 An exception arises if the file name generated by the above rules starts
2176 with one of the characters
2183 and the second character is a
2184 minus. In this case, the character ^tilde^dollar sign^ is used in place
2185 of the minus. The reason for this special rule is to avoid clashes with
2186 the standard names for child units of the packages System, Ada,
2187 Interfaces, and GNAT, which use the prefixes
2196 The file extension is @file{.ads} for a spec and
2197 @file{.adb} for a body. The following list shows some
2198 examples of these rules.
2205 @item arith_functions.ads
2206 Arith_Functions (package spec)
2207 @item arith_functions.adb
2208 Arith_Functions (package body)
2210 Func.Spec (child package spec)
2212 Func.Spec (child package body)
2214 Sub (subunit of Main)
2215 @item ^a~bad.adb^A$BAD.ADB^
2216 A.Bad (child package body)
2220 Following these rules can result in excessively long
2221 file names if corresponding
2222 unit names are long (for example, if child units or subunits are
2223 heavily nested). An option is available to shorten such long file names
2224 (called file name ``krunching''). This may be particularly useful when
2225 programs being developed with GNAT are to be used on operating systems
2226 with limited file name lengths. @xref{Using gnatkr}.
2228 Of course, no file shortening algorithm can guarantee uniqueness over
2229 all possible unit names; if file name krunching is used, it is your
2230 responsibility to ensure no name clashes occur. Alternatively you
2231 can specify the exact file names that you want used, as described
2232 in the next section. Finally, if your Ada programs are migrating from a
2233 compiler with a different naming convention, you can use the gnatchop
2234 utility to produce source files that follow the GNAT naming conventions.
2235 (For details @pxref{Renaming Files Using gnatchop}.)
2237 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2238 systems, case is not significant. So for example on @code{Windows XP}
2239 if the canonical name is @code{main-sub.adb}, you can use the file name
2240 @code{Main-Sub.adb} instead. However, case is significant for other
2241 operating systems, so for example, if you want to use other than
2242 canonically cased file names on a Unix system, you need to follow
2243 the procedures described in the next section.
2245 @node Using Other File Names
2246 @section Using Other File Names
2250 In the previous section, we have described the default rules used by
2251 GNAT to determine the file name in which a given unit resides. It is
2252 often convenient to follow these default rules, and if you follow them,
2253 the compiler knows without being explicitly told where to find all
2256 However, in some cases, particularly when a program is imported from
2257 another Ada compiler environment, it may be more convenient for the
2258 programmer to specify which file names contain which units. GNAT allows
2259 arbitrary file names to be used by means of the Source_File_Name pragma.
2260 The form of this pragma is as shown in the following examples:
2261 @cindex Source_File_Name pragma
2263 @smallexample @c ada
2265 pragma Source_File_Name (My_Utilities.Stacks,
2266 Spec_File_Name => "myutilst_a.ada");
2267 pragma Source_File_name (My_Utilities.Stacks,
2268 Body_File_Name => "myutilst.ada");
2273 As shown in this example, the first argument for the pragma is the unit
2274 name (in this example a child unit). The second argument has the form
2275 of a named association. The identifier
2276 indicates whether the file name is for a spec or a body;
2277 the file name itself is given by a string literal.
2279 The source file name pragma is a configuration pragma, which means that
2280 normally it will be placed in the @file{gnat.adc}
2281 file used to hold configuration
2282 pragmas that apply to a complete compilation environment.
2283 For more details on how the @file{gnat.adc} file is created and used
2284 @pxref{Handling of Configuration Pragmas}
2285 @cindex @file{gnat.adc}
2288 GNAT allows completely arbitrary file names to be specified using the
2289 source file name pragma. However, if the file name specified has an
2290 extension other than @file{.ads} or @file{.adb} it is necessary to use
2291 a special syntax when compiling the file. The name in this case must be
2292 preceded by the special sequence @code{-x} followed by a space and the name
2293 of the language, here @code{ada}, as in:
2296 $ gcc -c -x ada peculiar_file_name.sim
2301 @code{gnatmake} handles non-standard file names in the usual manner (the
2302 non-standard file name for the main program is simply used as the
2303 argument to gnatmake). Note that if the extension is also non-standard,
2304 then it must be included in the gnatmake command, it may not be omitted.
2306 @node Alternative File Naming Schemes
2307 @section Alternative File Naming Schemes
2308 @cindex File naming schemes, alternative
2311 In the previous section, we described the use of the @code{Source_File_Name}
2312 pragma to allow arbitrary names to be assigned to individual source files.
2313 However, this approach requires one pragma for each file, and especially in
2314 large systems can result in very long @file{gnat.adc} files, and also create
2315 a maintenance problem.
2317 GNAT also provides a facility for specifying systematic file naming schemes
2318 other than the standard default naming scheme previously described. An
2319 alternative scheme for naming is specified by the use of
2320 @code{Source_File_Name} pragmas having the following format:
2321 @cindex Source_File_Name pragma
2323 @smallexample @c ada
2324 pragma Source_File_Name (
2325 Spec_File_Name => FILE_NAME_PATTERN
2326 [,Casing => CASING_SPEC]
2327 [,Dot_Replacement => STRING_LITERAL]);
2329 pragma Source_File_Name (
2330 Body_File_Name => FILE_NAME_PATTERN
2331 [,Casing => CASING_SPEC]
2332 [,Dot_Replacement => STRING_LITERAL]);
2334 pragma Source_File_Name (
2335 Subunit_File_Name => FILE_NAME_PATTERN
2336 [,Casing => CASING_SPEC]
2337 [,Dot_Replacement => STRING_LITERAL]);
2339 FILE_NAME_PATTERN ::= STRING_LITERAL
2340 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2344 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2345 It contains a single asterisk character, and the unit name is substituted
2346 systematically for this asterisk. The optional parameter
2347 @code{Casing} indicates
2348 whether the unit name is to be all upper-case letters, all lower-case letters,
2349 or mixed-case. If no
2350 @code{Casing} parameter is used, then the default is all
2351 ^lower-case^upper-case^.
2353 The optional @code{Dot_Replacement} string is used to replace any periods
2354 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2355 argument is used then separating dots appear unchanged in the resulting
2357 Although the above syntax indicates that the
2358 @code{Casing} argument must appear
2359 before the @code{Dot_Replacement} argument, but it
2360 is also permissible to write these arguments in the opposite order.
2362 As indicated, it is possible to specify different naming schemes for
2363 bodies, specs, and subunits. Quite often the rule for subunits is the
2364 same as the rule for bodies, in which case, there is no need to give
2365 a separate @code{Subunit_File_Name} rule, and in this case the
2366 @code{Body_File_name} rule is used for subunits as well.
2368 The separate rule for subunits can also be used to implement the rather
2369 unusual case of a compilation environment (e.g. a single directory) which
2370 contains a subunit and a child unit with the same unit name. Although
2371 both units cannot appear in the same partition, the Ada Reference Manual
2372 allows (but does not require) the possibility of the two units coexisting
2373 in the same environment.
2375 The file name translation works in the following steps:
2380 If there is a specific @code{Source_File_Name} pragma for the given unit,
2381 then this is always used, and any general pattern rules are ignored.
2384 If there is a pattern type @code{Source_File_Name} pragma that applies to
2385 the unit, then the resulting file name will be used if the file exists. If
2386 more than one pattern matches, the latest one will be tried first, and the
2387 first attempt resulting in a reference to a file that exists will be used.
2390 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2391 for which the corresponding file exists, then the standard GNAT default
2392 naming rules are used.
2397 As an example of the use of this mechanism, consider a commonly used scheme
2398 in which file names are all lower case, with separating periods copied
2399 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2400 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2403 @smallexample @c ada
2404 pragma Source_File_Name
2405 (Spec_File_Name => "*.1.ada");
2406 pragma Source_File_Name
2407 (Body_File_Name => "*.2.ada");
2411 The default GNAT scheme is actually implemented by providing the following
2412 default pragmas internally:
2414 @smallexample @c ada
2415 pragma Source_File_Name
2416 (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2417 pragma Source_File_Name
2418 (Body_File_Name => "*.adb", Dot_Replacement => "-");
2422 Our final example implements a scheme typically used with one of the
2423 Ada 83 compilers, where the separator character for subunits was ``__''
2424 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2425 by adding @file{.ADA}, and subunits by
2426 adding @file{.SEP}. All file names were
2427 upper case. Child units were not present of course since this was an
2428 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2429 the same double underscore separator for child units.
2431 @smallexample @c ada
2432 pragma Source_File_Name
2433 (Spec_File_Name => "*_.ADA",
2434 Dot_Replacement => "__",
2435 Casing = Uppercase);
2436 pragma Source_File_Name
2437 (Body_File_Name => "*.ADA",
2438 Dot_Replacement => "__",
2439 Casing = Uppercase);
2440 pragma Source_File_Name
2441 (Subunit_File_Name => "*.SEP",
2442 Dot_Replacement => "__",
2443 Casing = Uppercase);
2446 @node Generating Object Files
2447 @section Generating Object Files
2450 An Ada program consists of a set of source files, and the first step in
2451 compiling the program is to generate the corresponding object files.
2452 These are generated by compiling a subset of these source files.
2453 The files you need to compile are the following:
2457 If a package spec has no body, compile the package spec to produce the
2458 object file for the package.
2461 If a package has both a spec and a body, compile the body to produce the
2462 object file for the package. The source file for the package spec need
2463 not be compiled in this case because there is only one object file, which
2464 contains the code for both the spec and body of the package.
2467 For a subprogram, compile the subprogram body to produce the object file
2468 for the subprogram. The spec, if one is present, is as usual in a
2469 separate file, and need not be compiled.
2473 In the case of subunits, only compile the parent unit. A single object
2474 file is generated for the entire subunit tree, which includes all the
2478 Compile child units independently of their parent units
2479 (though, of course, the spec of all the ancestor unit must be present in order
2480 to compile a child unit).
2484 Compile generic units in the same manner as any other units. The object
2485 files in this case are small dummy files that contain at most the
2486 flag used for elaboration checking. This is because GNAT always handles generic
2487 instantiation by means of macro expansion. However, it is still necessary to
2488 compile generic units, for dependency checking and elaboration purposes.
2492 The preceding rules describe the set of files that must be compiled to
2493 generate the object files for a program. Each object file has the same
2494 name as the corresponding source file, except that the extension is
2497 You may wish to compile other files for the purpose of checking their
2498 syntactic and semantic correctness. For example, in the case where a
2499 package has a separate spec and body, you would not normally compile the
2500 spec. However, it is convenient in practice to compile the spec to make
2501 sure it is error-free before compiling clients of this spec, because such
2502 compilations will fail if there is an error in the spec.
2504 GNAT provides an option for compiling such files purely for the
2505 purposes of checking correctness; such compilations are not required as
2506 part of the process of building a program. To compile a file in this
2507 checking mode, use the @option{-gnatc} switch.
2509 @node Source Dependencies
2510 @section Source Dependencies
2513 A given object file clearly depends on the source file which is compiled
2514 to produce it. Here we are using @dfn{depends} in the sense of a typical
2515 @code{make} utility; in other words, an object file depends on a source
2516 file if changes to the source file require the object file to be
2518 In addition to this basic dependency, a given object may depend on
2519 additional source files as follows:
2523 If a file being compiled @code{with}'s a unit @var{X}, the object file
2524 depends on the file containing the spec of unit @var{X}. This includes
2525 files that are @code{with}'ed implicitly either because they are parents
2526 of @code{with}'ed child units or they are run-time units required by the
2527 language constructs used in a particular unit.
2530 If a file being compiled instantiates a library level generic unit, the
2531 object file depends on both the spec and body files for this generic
2535 If a file being compiled instantiates a generic unit defined within a
2536 package, the object file depends on the body file for the package as
2537 well as the spec file.
2541 @cindex @option{-gnatn} switch
2542 If a file being compiled contains a call to a subprogram for which
2543 pragma @code{Inline} applies and inlining is activated with the
2544 @option{-gnatn} switch, the object file depends on the file containing the
2545 body of this subprogram as well as on the file containing the spec. Note
2546 that for inlining to actually occur as a result of the use of this switch,
2547 it is necessary to compile in optimizing mode.
2549 @cindex @option{-gnatN} switch
2550 The use of @option{-gnatN} activates a more extensive inlining optimization
2551 that is performed by the front end of the compiler. This inlining does
2552 not require that the code generation be optimized. Like @option{-gnatn},
2553 the use of this switch generates additional dependencies.
2555 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
2556 to specify both options.
2559 If an object file O depends on the proper body of a subunit through inlining
2560 or instantiation, it depends on the parent unit of the subunit. This means that
2561 any modification of the parent unit or one of its subunits affects the
2565 The object file for a parent unit depends on all its subunit body files.
2568 The previous two rules meant that for purposes of computing dependencies and
2569 recompilation, a body and all its subunits are treated as an indivisible whole.
2572 These rules are applied transitively: if unit @code{A} @code{with}'s
2573 unit @code{B}, whose elaboration calls an inlined procedure in package
2574 @code{C}, the object file for unit @code{A} will depend on the body of
2575 @code{C}, in file @file{c.adb}.
2577 The set of dependent files described by these rules includes all the
2578 files on which the unit is semantically dependent, as described in the
2579 Ada 95 Language Reference Manual. However, it is a superset of what the
2580 ARM describes, because it includes generic, inline, and subunit dependencies.
2582 An object file must be recreated by recompiling the corresponding source
2583 file if any of the source files on which it depends are modified. For
2584 example, if the @code{make} utility is used to control compilation,
2585 the rule for an Ada object file must mention all the source files on
2586 which the object file depends, according to the above definition.
2587 The determination of the necessary
2588 recompilations is done automatically when one uses @code{gnatmake}.
2591 @node The Ada Library Information Files
2592 @section The Ada Library Information Files
2593 @cindex Ada Library Information files
2594 @cindex @file{ALI} files
2597 Each compilation actually generates two output files. The first of these
2598 is the normal object file that has a @file{.o} extension. The second is a
2599 text file containing full dependency information. It has the same
2600 name as the source file, but an @file{.ali} extension.
2601 This file is known as the Ada Library Information (@file{ALI}) file.
2602 The following information is contained in the @file{ALI} file.
2606 Version information (indicates which version of GNAT was used to compile
2607 the unit(s) in question)
2610 Main program information (including priority and time slice settings,
2611 as well as the wide character encoding used during compilation).
2614 List of arguments used in the @code{gcc} command for the compilation
2617 Attributes of the unit, including configuration pragmas used, an indication
2618 of whether the compilation was successful, exception model used etc.
2621 A list of relevant restrictions applying to the unit (used for consistency)
2625 Categorization information (e.g. use of pragma @code{Pure}).
2628 Information on all @code{with}'ed units, including presence of
2629 @code{Elaborate} or @code{Elaborate_All} pragmas.
2632 Information from any @code{Linker_Options} pragmas used in the unit
2635 Information on the use of @code{Body_Version} or @code{Version}
2636 attributes in the unit.
2639 Dependency information. This is a list of files, together with
2640 time stamp and checksum information. These are files on which
2641 the unit depends in the sense that recompilation is required
2642 if any of these units are modified.
2645 Cross-reference data. Contains information on all entities referenced
2646 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2647 provide cross-reference information.
2652 For a full detailed description of the format of the @file{ALI} file,
2653 see the source of the body of unit @code{Lib.Writ}, contained in file
2654 @file{lib-writ.adb} in the GNAT compiler sources.
2656 @node Binding an Ada Program
2657 @section Binding an Ada Program
2660 When using languages such as C and C++, once the source files have been
2661 compiled the only remaining step in building an executable program
2662 is linking the object modules together. This means that it is possible to
2663 link an inconsistent version of a program, in which two units have
2664 included different versions of the same header.
2666 The rules of Ada do not permit such an inconsistent program to be built.
2667 For example, if two clients have different versions of the same package,
2668 it is illegal to build a program containing these two clients.
2669 These rules are enforced by the GNAT binder, which also determines an
2670 elaboration order consistent with the Ada rules.
2672 The GNAT binder is run after all the object files for a program have
2673 been created. It is given the name of the main program unit, and from
2674 this it determines the set of units required by the program, by reading the
2675 corresponding ALI files. It generates error messages if the program is
2676 inconsistent or if no valid order of elaboration exists.
2678 If no errors are detected, the binder produces a main program, in Ada by
2679 default, that contains calls to the elaboration procedures of those
2680 compilation unit that require them, followed by
2681 a call to the main program. This Ada program is compiled to generate the
2682 object file for the main program. The name of
2683 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2684 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2687 Finally, the linker is used to build the resulting executable program,
2688 using the object from the main program from the bind step as well as the
2689 object files for the Ada units of the program.
2691 @node Mixed Language Programming
2692 @section Mixed Language Programming
2693 @cindex Mixed Language Programming
2696 This section describes how to develop a mixed-language program,
2697 specifically one that comprises units in both Ada and C.
2700 * Interfacing to C::
2701 * Calling Conventions::
2704 @node Interfacing to C
2705 @subsection Interfacing to C
2707 Interfacing Ada with a foreign language such as C involves using
2708 compiler directives to import and/or export entity definitions in each
2709 language---using @code{extern} statements in C, for instance, and the
2710 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada. For
2711 a full treatment of these topics, read Appendix B, section 1 of the Ada
2712 95 Language Reference Manual.
2714 There are two ways to build a program using GNAT that contains some Ada
2715 sources and some foreign language sources, depending on whether or not
2716 the main subprogram is written in Ada. Here is a source example with
2717 the main subprogram in Ada:
2723 void print_num (int num)
2725 printf ("num is %d.\n", num);
2731 /* num_from_Ada is declared in my_main.adb */
2732 extern int num_from_Ada;
2736 return num_from_Ada;
2740 @smallexample @c ada
2742 procedure My_Main is
2744 -- Declare then export an Integer entity called num_from_Ada
2745 My_Num : Integer := 10;
2746 pragma Export (C, My_Num, "num_from_Ada");
2748 -- Declare an Ada function spec for Get_Num, then use
2749 -- C function get_num for the implementation.
2750 function Get_Num return Integer;
2751 pragma Import (C, Get_Num, "get_num");
2753 -- Declare an Ada procedure spec for Print_Num, then use
2754 -- C function print_num for the implementation.
2755 procedure Print_Num (Num : Integer);
2756 pragma Import (C, Print_Num, "print_num");
2759 Print_Num (Get_Num);
2765 To build this example, first compile the foreign language files to
2766 generate object files:
2773 Then, compile the Ada units to produce a set of object files and ALI
2776 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2780 Run the Ada binder on the Ada main program:
2782 gnatbind my_main.ali
2786 Link the Ada main program, the Ada objects and the other language
2789 gnatlink my_main.ali file1.o file2.o
2793 The last three steps can be grouped in a single command:
2795 gnatmake my_main.adb -largs file1.o file2.o
2798 @cindex Binder output file
2800 If the main program is in a language other than Ada, then you may have
2801 more than one entry point into the Ada subsystem. You must use a special
2802 binder option to generate callable routines that initialize and
2803 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2804 Calls to the initialization and finalization routines must be inserted
2805 in the main program, or some other appropriate point in the code. The
2806 call to initialize the Ada units must occur before the first Ada
2807 subprogram is called, and the call to finalize the Ada units must occur
2808 after the last Ada subprogram returns. The binder will place the
2809 initialization and finalization subprograms into the
2810 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2811 sources. To illustrate, we have the following example:
2815 extern void adainit (void);
2816 extern void adafinal (void);
2817 extern int add (int, int);
2818 extern int sub (int, int);
2820 int main (int argc, char *argv[])
2826 /* Should print "21 + 7 = 28" */
2827 printf ("%d + %d = %d\n", a, b, add (a, b));
2828 /* Should print "21 - 7 = 14" */
2829 printf ("%d - %d = %d\n", a, b, sub (a, b));
2835 @smallexample @c ada
2838 function Add (A, B : Integer) return Integer;
2839 pragma Export (C, Add, "add");
2843 package body Unit1 is
2844 function Add (A, B : Integer) return Integer is
2852 function Sub (A, B : Integer) return Integer;
2853 pragma Export (C, Sub, "sub");
2857 package body Unit2 is
2858 function Sub (A, B : Integer) return Integer is
2867 The build procedure for this application is similar to the last
2868 example's. First, compile the foreign language files to generate object
2875 Next, compile the Ada units to produce a set of object files and ALI
2878 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2879 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2883 Run the Ada binder on every generated ALI file. Make sure to use the
2884 @option{-n} option to specify a foreign main program:
2886 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2890 Link the Ada main program, the Ada objects and the foreign language
2891 objects. You need only list the last ALI file here:
2893 gnatlink unit2.ali main.o -o exec_file
2896 This procedure yields a binary executable called @file{exec_file}.
2899 @node Calling Conventions
2900 @subsection Calling Conventions
2901 @cindex Foreign Languages
2902 @cindex Calling Conventions
2903 GNAT follows standard calling sequence conventions and will thus interface
2904 to any other language that also follows these conventions. The following
2905 Convention identifiers are recognized by GNAT:
2908 @cindex Interfacing to Ada
2909 @cindex Other Ada compilers
2910 @cindex Convention Ada
2912 This indicates that the standard Ada calling sequence will be
2913 used and all Ada data items may be passed without any limitations in the
2914 case where GNAT is used to generate both the caller and callee. It is also
2915 possible to mix GNAT generated code and code generated by another Ada
2916 compiler. In this case, the data types should be restricted to simple
2917 cases, including primitive types. Whether complex data types can be passed
2918 depends on the situation. Probably it is safe to pass simple arrays, such
2919 as arrays of integers or floats. Records may or may not work, depending
2920 on whether both compilers lay them out identically. Complex structures
2921 involving variant records, access parameters, tasks, or protected types,
2922 are unlikely to be able to be passed.
2924 Note that in the case of GNAT running
2925 on a platform that supports DEC Ada 83, a higher degree of compatibility
2926 can be guaranteed, and in particular records are layed out in an identical
2927 manner in the two compilers. Note also that if output from two different
2928 compilers is mixed, the program is responsible for dealing with elaboration
2929 issues. Probably the safest approach is to write the main program in the
2930 version of Ada other than GNAT, so that it takes care of its own elaboration
2931 requirements, and then call the GNAT-generated adainit procedure to ensure
2932 elaboration of the GNAT components. Consult the documentation of the other
2933 Ada compiler for further details on elaboration.
2935 However, it is not possible to mix the tasking run time of GNAT and
2936 DEC Ada 83, All the tasking operations must either be entirely within
2937 GNAT compiled sections of the program, or entirely within DEC Ada 83
2938 compiled sections of the program.
2940 @cindex Interfacing to Assembly
2941 @cindex Convention Assembler
2943 Specifies assembler as the convention. In practice this has the
2944 same effect as convention Ada (but is not equivalent in the sense of being
2945 considered the same convention).
2947 @cindex Convention Asm
2950 Equivalent to Assembler.
2952 @cindex Interfacing to COBOL
2953 @cindex Convention COBOL
2956 Data will be passed according to the conventions described
2957 in section B.4 of the Ada 95 Reference Manual.
2960 @cindex Interfacing to C
2961 @cindex Convention C
2963 Data will be passed according to the conventions described
2964 in section B.3 of the Ada 95 Reference Manual.
2966 @findex C varargs function
2967 @cindex Intefacing to C varargs function
2968 @cindex varargs function intefacs
2969 @item C varargs function
2970 In C, @code{varargs} allows a function to take a variable number of
2971 arguments. There is no direct equivalent in this to Ada. One
2972 approach that can be used is to create a C wrapper for each
2973 different profile and then interface to this C wrapper. For
2974 example, to print an @code{int} value using @code{printf},
2975 create a C function @code{printfi} that takes two arguments, a
2976 pointer to a string and an int, and calls @code{printf}.
2977 Then in the Ada program, use pragma @code{Import} to
2978 interface to printfi.
2980 It may work on some platforms to directly interface to
2981 a @code{varargs} function by providing a specific Ada profile
2982 for a a particular call. However, this does not work on
2983 all platforms, since there is no guarantee that the
2984 calling sequence for a two argument normal C function
2985 is the same as for calling a @code{varargs} C function with
2986 the same two arguments.
2988 @cindex Convention Default
2993 @cindex Convention External
2999 @cindex Interfacing to C++
3000 @cindex Convention C++
3002 This stands for C++. For most purposes this is identical to C.
3003 See the separate description of the specialized GNAT pragmas relating to
3004 C++ interfacing for further details.
3007 @cindex Interfacing to Fortran
3008 @cindex Convention Fortran
3010 Data will be passed according to the conventions described
3011 in section B.5 of the Ada 95 Reference Manual.
3014 This applies to an intrinsic operation, as defined in the Ada 95
3015 Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram,
3016 this means that the body of the subprogram is provided by the compiler itself,
3017 usually by means of an efficient code sequence, and that the user does not
3018 supply an explicit body for it. In an application program, the pragma can
3019 only be applied to the following two sets of names, which the GNAT compiler
3024 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_-
3025 Arithmetic. The corresponding subprogram declaration must have
3026 two formal parameters. The
3027 first one must be a signed integer type or a modular type with a binary
3028 modulus, and the second parameter must be of type Natural.
3029 The return type must be the same as the type of the first argument. The size
3030 of this type can only be 8, 16, 32, or 64.
3031 @item binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
3032 The corresponding operator declaration must have parameters and result type
3033 that have the same root numeric type (for example, all three are long_float
3034 types). This simplifies the definition of operations that use type checking
3035 to perform dimensional checks:
3037 @smallexample @c ada
3038 type Distance is new Long_Float;
3039 type Time is new Long_Float;
3040 type Velocity is new Long_Float;
3041 function "/" (D : Distance; T : Time)
3043 pragma Import (Intrinsic, "/");
3047 This common idiom is often programmed with a generic definition and an
3048 explicit body. The pragma makes it simpler to introduce such declarations.
3049 It incurs no overhead in compilation time or code size, because it is
3050 implemented as a single machine instruction.
3056 @cindex Convention Stdcall
3058 This is relevant only to NT/Win95 implementations of GNAT,
3059 and specifies that the Stdcall calling sequence will be used, as defined
3063 @cindex Convention DLL
3065 This is equivalent to Stdcall.
3068 @cindex Convention Win32
3070 This is equivalent to Stdcall.
3074 @cindex Convention Stubbed
3076 This is a special convention that indicates that the compiler
3077 should provide a stub body that raises @code{Program_Error}.
3081 GNAT additionally provides a useful pragma @code{Convention_Identifier}
3082 that can be used to parametrize conventions and allow additional synonyms
3083 to be specified. For example if you have legacy code in which the convention
3084 identifier Fortran77 was used for Fortran, you can use the configuration
3087 @smallexample @c ada
3088 pragma Convention_Identifier (Fortran77, Fortran);
3092 And from now on the identifier Fortran77 may be used as a convention
3093 identifier (for example in an @code{Import} pragma) with the same
3096 @node Building Mixed Ada & C++ Programs
3097 @section Building Mixed Ada & C++ Programs
3100 A programmer inexperienced with mixed-language development may find that
3101 building an application containing both Ada and C++ code can be a
3102 challenge. As a matter of fact, interfacing with C++ has not been
3103 standardized in the Ada 95 Reference Manual due to the immaturity of --
3104 and lack of standards for -- C++ at the time. This section gives a few
3105 hints that should make this task easier. The first section addresses
3106 the differences regarding interfacing with C. The second section
3107 looks into the delicate problem of linking the complete application from
3108 its Ada and C++ parts. The last section gives some hints on how the GNAT
3109 run time can be adapted in order to allow inter-language dispatching
3110 with a new C++ compiler.
3113 * Interfacing to C++::
3114 * Linking a Mixed C++ & Ada Program::
3115 * A Simple Example::
3116 * Adapting the Run Time to a New C++ Compiler::
3119 @node Interfacing to C++
3120 @subsection Interfacing to C++
3123 GNAT supports interfacing with C++ compilers generating code that is
3124 compatible with the standard Application Binary Interface of the given
3128 Interfacing can be done at 3 levels: simple data, subprograms, and
3129 classes. In the first two cases, GNAT offers a specific @var{Convention
3130 CPP} that behaves exactly like @var{Convention C}. Usually, C++ mangles
3131 the names of subprograms, and currently, GNAT does not provide any help
3132 to solve the demangling problem. This problem can be addressed in two
3136 by modifying the C++ code in order to force a C convention using
3137 the @code{extern "C"} syntax.
3140 by figuring out the mangled name and use it as the Link_Name argument of
3145 Interfacing at the class level can be achieved by using the GNAT specific
3146 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
3147 Reference Manual for additional information.
3149 @node Linking a Mixed C++ & Ada Program
3150 @subsection Linking a Mixed C++ & Ada Program
3153 Usually the linker of the C++ development system must be used to link
3154 mixed applications because most C++ systems will resolve elaboration
3155 issues (such as calling constructors on global class instances)
3156 transparently during the link phase. GNAT has been adapted to ease the
3157 use of a foreign linker for the last phase. Three cases can be
3162 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3163 The C++ linker can simply be called by using the C++ specific driver
3164 called @code{c++}. Note that this setup is not very common because it
3165 may involve recompiling the whole GCC tree from sources, which makes it
3166 harder to upgrade the compilation system for one language without
3167 destabilizing the other.
3172 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
3176 Using GNAT and G++ from two different GCC installations: If both
3177 compilers are on the PATH, the previous method may be used. It is
3178 important to note that environment variables such as C_INCLUDE_PATH,
3179 GCC_EXEC_PREFIX, BINUTILS_ROOT, and GCC_ROOT will affect both compilers
3180 at the same time and may make one of the two compilers operate
3181 improperly if set during invocation of the wrong compiler. It is also
3182 very important that the linker uses the proper @file{libgcc.a} GCC
3183 library -- that is, the one from the C++ compiler installation. The
3184 implicit link command as suggested in the gnatmake command from the
3185 former example can be replaced by an explicit link command with the
3186 full-verbosity option in order to verify which library is used:
3189 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3191 If there is a problem due to interfering environment variables, it can
3192 be worked around by using an intermediate script. The following example
3193 shows the proper script to use when GNAT has not been installed at its
3194 default location and g++ has been installed at its default location:
3202 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3206 Using a non-GNU C++ compiler: The commands previously described can be
3207 used to insure that the C++ linker is used. Nonetheless, you need to add
3208 the path to libgcc explicitly, since some libraries needed by GNAT are
3209 located in this directory:
3214 CC $* `gcc -print-libgcc-file-name`
3215 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3218 Where CC is the name of the non-GNU C++ compiler.
3222 @node A Simple Example
3223 @subsection A Simple Example
3225 The following example, provided as part of the GNAT examples, shows how
3226 to achieve procedural interfacing between Ada and C++ in both
3227 directions. The C++ class A has two methods. The first method is exported
3228 to Ada by the means of an extern C wrapper function. The second method
3229 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3230 a limited record with a layout comparable to the C++ class. The Ada
3231 subprogram, in turn, calls the C++ method. So, starting from the C++
3232 main program, the process passes back and forth between the two
3236 Here are the compilation commands:
3238 $ gnatmake -c simple_cpp_interface
3241 $ gnatbind -n simple_cpp_interface
3242 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3243 -lstdc++ ex7.o cpp_main.o
3247 Here are the corresponding sources:
3255 void adainit (void);
3256 void adafinal (void);
3257 void method1 (A *t);
3279 class A : public Origin @{
3281 void method1 (void);
3282 void method2 (int v);
3292 extern "C" @{ void ada_method2 (A *t, int v);@}
3294 void A::method1 (void)
3297 printf ("in A::method1, a_value = %d \n",a_value);
3301 void A::method2 (int v)
3303 ada_method2 (this, v);
3304 printf ("in A::method2, a_value = %d \n",a_value);
3311 printf ("in A::A, a_value = %d \n",a_value);
3315 @b{package} @b{body} Simple_Cpp_Interface @b{is}
3317 @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
3321 @b{end} Ada_Method2;
3323 @b{end} Simple_Cpp_Interface;
3325 @b{package} Simple_Cpp_Interface @b{is}
3326 @b{type} A @b{is} @b{limited}
3331 @b{pragma} Convention (C, A);
3333 @b{procedure} Method1 (This : @b{in} @b{out} A);
3334 @b{pragma} Import (C, Method1);
3336 @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
3337 @b{pragma} Export (C, Ada_Method2);
3339 @b{end} Simple_Cpp_Interface;
3342 @node Adapting the Run Time to a New C++ Compiler
3343 @subsection Adapting the Run Time to a New C++ Compiler
3345 GNAT offers the capability to derive Ada 95 tagged types directly from
3346 preexisting C++ classes and . See ``Interfacing with C++'' in the
3347 @cite{GNAT Reference Manual}. The mechanism used by GNAT for achieving
3349 has been made user configurable through a GNAT library unit
3350 @code{Interfaces.CPP}. The default version of this file is adapted to
3351 the GNU C++ compiler. Internal knowledge of the virtual
3352 table layout used by the new C++ compiler is needed to configure
3353 properly this unit. The Interface of this unit is known by the compiler
3354 and cannot be changed except for the value of the constants defining the
3355 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
3356 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
3357 of this unit for more details.
3359 @node Comparison between GNAT and C/C++ Compilation Models
3360 @section Comparison between GNAT and C/C++ Compilation Models
3363 The GNAT model of compilation is close to the C and C++ models. You can
3364 think of Ada specs as corresponding to header files in C. As in C, you
3365 don't need to compile specs; they are compiled when they are used. The
3366 Ada @code{with} is similar in effect to the @code{#include} of a C
3369 One notable difference is that, in Ada, you may compile specs separately
3370 to check them for semantic and syntactic accuracy. This is not always
3371 possible with C headers because they are fragments of programs that have
3372 less specific syntactic or semantic rules.
3374 The other major difference is the requirement for running the binder,
3375 which performs two important functions. First, it checks for
3376 consistency. In C or C++, the only defense against assembling
3377 inconsistent programs lies outside the compiler, in a makefile, for
3378 example. The binder satisfies the Ada requirement that it be impossible
3379 to construct an inconsistent program when the compiler is used in normal
3382 @cindex Elaboration order control
3383 The other important function of the binder is to deal with elaboration
3384 issues. There are also elaboration issues in C++ that are handled
3385 automatically. This automatic handling has the advantage of being
3386 simpler to use, but the C++ programmer has no control over elaboration.
3387 Where @code{gnatbind} might complain there was no valid order of
3388 elaboration, a C++ compiler would simply construct a program that
3389 malfunctioned at run time.
3391 @node Comparison between GNAT and Conventional Ada Library Models
3392 @section Comparison between GNAT and Conventional Ada Library Models
3395 This section is intended to be useful to Ada programmers who have
3396 previously used an Ada compiler implementing the traditional Ada library
3397 model, as described in the Ada 95 Language Reference Manual. If you
3398 have not used such a system, please go on to the next section.
3400 @cindex GNAT library
3401 In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of
3402 source files themselves acts as the library. Compiling Ada programs does
3403 not generate any centralized information, but rather an object file and
3404 a ALI file, which are of interest only to the binder and linker.
3405 In a traditional system, the compiler reads information not only from
3406 the source file being compiled, but also from the centralized library.
3407 This means that the effect of a compilation depends on what has been
3408 previously compiled. In particular:
3412 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3413 to the version of the unit most recently compiled into the library.
3416 Inlining is effective only if the necessary body has already been
3417 compiled into the library.
3420 Compiling a unit may obsolete other units in the library.
3424 In GNAT, compiling one unit never affects the compilation of any other
3425 units because the compiler reads only source files. Only changes to source
3426 files can affect the results of a compilation. In particular:
3430 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3431 to the source version of the unit that is currently accessible to the
3436 Inlining requires the appropriate source files for the package or
3437 subprogram bodies to be available to the compiler. Inlining is always
3438 effective, independent of the order in which units are complied.
3441 Compiling a unit never affects any other compilations. The editing of
3442 sources may cause previous compilations to be out of date if they
3443 depended on the source file being modified.
3447 The most important result of these differences is that order of compilation
3448 is never significant in GNAT. There is no situation in which one is
3449 required to do one compilation before another. What shows up as order of
3450 compilation requirements in the traditional Ada library becomes, in
3451 GNAT, simple source dependencies; in other words, there is only a set
3452 of rules saying what source files must be present when a file is
3456 @node Placement of temporary files
3457 @section Placement of temporary files
3458 @cindex Temporary files (user control over placement)
3461 GNAT creates temporary files in the directory designated by the environment
3462 variable @env{TMPDIR}.
3463 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3464 for detailed information on how environment variables are resolved.
3465 For most users the easiest way to make use of this feature is to simply
3466 define @env{TMPDIR} as a job level logical name).
3467 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3468 for compiler temporary files, then you can include something like the
3469 following command in your @file{LOGIN.COM} file:
3472 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3476 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3477 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3478 designated by @env{TEMP}.
3479 If none of these environment variables are defined then GNAT uses the
3480 directory designated by the logical name @code{SYS$SCRATCH:}
3481 (by default the user's home directory). If all else fails
3482 GNAT uses the current directory for temporary files.
3485 @c *************************
3486 @node Compiling Using gcc
3487 @chapter Compiling Using @code{gcc}
3490 This chapter discusses how to compile Ada programs using the @code{gcc}
3491 command. It also describes the set of switches
3492 that can be used to control the behavior of the compiler.
3494 * Compiling Programs::
3495 * Switches for gcc::
3496 * Search Paths and the Run-Time Library (RTL)::
3497 * Order of Compilation Issues::
3501 @node Compiling Programs
3502 @section Compiling Programs
3505 The first step in creating an executable program is to compile the units
3506 of the program using the @code{gcc} command. You must compile the
3511 the body file (@file{.adb}) for a library level subprogram or generic
3515 the spec file (@file{.ads}) for a library level package or generic
3516 package that has no body
3519 the body file (@file{.adb}) for a library level package
3520 or generic package that has a body
3525 You need @emph{not} compile the following files
3530 the spec of a library unit which has a body
3537 because they are compiled as part of compiling related units. GNAT
3539 when the corresponding body is compiled, and subunits when the parent is
3542 @cindex cannot generate code
3543 If you attempt to compile any of these files, you will get one of the
3544 following error messages (where fff is the name of the file you compiled):
3547 cannot generate code for file @var{fff} (package spec)
3548 to check package spec, use -gnatc
3550 cannot generate code for file @var{fff} (missing subunits)
3551 to check parent unit, use -gnatc
3553 cannot generate code for file @var{fff} (subprogram spec)
3554 to check subprogram spec, use -gnatc
3556 cannot generate code for file @var{fff} (subunit)
3557 to check subunit, use -gnatc
3561 As indicated by the above error messages, if you want to submit
3562 one of these files to the compiler to check for correct semantics
3563 without generating code, then use the @option{-gnatc} switch.
3565 The basic command for compiling a file containing an Ada unit is
3568 $ gcc -c [@var{switches}] @file{file name}
3572 where @var{file name} is the name of the Ada file (usually
3574 @file{.ads} for a spec or @file{.adb} for a body).
3577 @option{-c} switch to tell @code{gcc} to compile, but not link, the file.
3579 The result of a successful compilation is an object file, which has the
3580 same name as the source file but an extension of @file{.o} and an Ada
3581 Library Information (ALI) file, which also has the same name as the
3582 source file, but with @file{.ali} as the extension. GNAT creates these
3583 two output files in the current directory, but you may specify a source
3584 file in any directory using an absolute or relative path specification
3585 containing the directory information.
3588 @code{gcc} is actually a driver program that looks at the extensions of
3589 the file arguments and loads the appropriate compiler. For example, the
3590 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3591 These programs are in directories known to the driver program (in some
3592 configurations via environment variables you set), but need not be in
3593 your path. The @code{gcc} driver also calls the assembler and any other
3594 utilities needed to complete the generation of the required object
3597 It is possible to supply several file names on the same @code{gcc}
3598 command. This causes @code{gcc} to call the appropriate compiler for
3599 each file. For example, the following command lists three separate
3600 files to be compiled:
3603 $ gcc -c x.adb y.adb z.c
3607 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3608 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3609 The compiler generates three object files @file{x.o}, @file{y.o} and
3610 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3611 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3614 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3617 @node Switches for gcc
3618 @section Switches for @code{gcc}
3621 The @code{gcc} command accepts switches that control the
3622 compilation process. These switches are fully described in this section.
3623 First we briefly list all the switches, in alphabetical order, then we
3624 describe the switches in more detail in functionally grouped sections.
3627 * Output and Error Message Control::
3628 * Warning Message Control::
3629 * Debugging and Assertion Control::
3630 * Validity Checking::
3633 * Stack Overflow Checking::
3634 * Using gcc for Syntax Checking::
3635 * Using gcc for Semantic Checking::
3636 * Compiling Ada 83 Programs::
3637 * Character Set Control::
3638 * File Naming Control::
3639 * Subprogram Inlining Control::
3640 * Auxiliary Output Control::
3641 * Debugging Control::
3642 * Exception Handling Control::
3643 * Units to Sources Mapping Files::
3644 * Integrated Preprocessing::
3645 * Code Generation Control::
3654 @cindex @option{-b} (@code{gcc})
3655 @item -b @var{target}
3656 Compile your program to run on @var{target}, which is the name of a
3657 system configuration. You must have a GNAT cross-compiler built if
3658 @var{target} is not the same as your host system.
3661 @cindex @option{-B} (@code{gcc})
3662 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3663 from @var{dir} instead of the default location. Only use this switch
3664 when multiple versions of the GNAT compiler are available. See the
3665 @code{gcc} manual page for further details. You would normally use the
3666 @option{-b} or @option{-V} switch instead.
3669 @cindex @option{-c} (@code{gcc})
3670 Compile. Always use this switch when compiling Ada programs.
3672 Note: for some other languages when using @code{gcc}, notably in
3673 the case of C and C++, it is possible to use
3674 use @code{gcc} without a @option{-c} switch to
3675 compile and link in one step. In the case of GNAT, you
3676 cannot use this approach, because the binder must be run
3677 and @code{gcc} cannot be used to run the GNAT binder.
3681 @cindex @option{-fno-inline} (@code{gcc})
3682 Suppresses all back-end inlining, even if other optimization or inlining
3684 This includes suppression of inlining that results
3685 from the use of the pragma @code{Inline_Always}.
3686 See also @option{-gnatn} and @option{-gnatN}.
3688 @item -fno-strict-aliasing
3689 @cindex @option{-fno-strict-aliasing} (@code{gcc})
3690 Causes the compiler to avoid assumptions regarding non-aliasing
3691 of objects of different types. See section
3692 @pxref{Optimization and Strict Aliasing} for details.
3695 @cindex @option{-fstack-check} (@code{gcc})
3696 Activates stack checking.
3697 See @ref{Stack Overflow Checking} for details of the use of this option.
3700 @cindex @option{^-g^/DEBUG^} (@code{gcc})
3701 Generate debugging information. This information is stored in the object
3702 file and copied from there to the final executable file by the linker,
3703 where it can be read by the debugger. You must use the
3704 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3707 @cindex @option{-gnat83} (@code{gcc})
3708 Enforce Ada 83 restrictions.
3711 @cindex @option{-gnata} (@code{gcc})
3712 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3716 @cindex @option{-gnatA} (@code{gcc})
3717 Avoid processing @file{gnat.adc}. If a gnat.adc file is present,
3721 @cindex @option{-gnatb} (@code{gcc})
3722 Generate brief messages to @file{stderr} even if verbose mode set.
3725 @cindex @option{-gnatc} (@code{gcc})
3726 Check syntax and semantics only (no code generation attempted).
3729 @cindex @option{-gnatd} (@code{gcc})
3730 Specify debug options for the compiler. The string of characters after
3731 the @option{-gnatd} specify the specific debug options. The possible
3732 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3733 compiler source file @file{debug.adb} for details of the implemented
3734 debug options. Certain debug options are relevant to applications
3735 programmers, and these are documented at appropriate points in this
3739 @cindex @option{-gnatD} (@code{gcc})
3740 Create expanded source files for source level debugging. This switch
3741 also suppress generation of cross-reference information
3742 (see @option{-gnatx}).
3744 @item -gnatec=@var{path}
3745 @cindex @option{-gnatec} (@code{gcc})
3746 Specify a configuration pragma file
3748 (the equal sign is optional)
3750 (see @ref{The Configuration Pragmas Files}).
3752 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
3753 @cindex @option{-gnateD} (@code{gcc})
3754 Defines a symbol, associated with value, for preprocessing.
3755 (see @ref{Integrated Preprocessing})
3758 @cindex @option{-gnatef} (@code{gcc})
3759 Display full source path name in brief error messages.
3761 @item -gnatem=@var{path}
3762 @cindex @option{-gnatem} (@code{gcc})
3763 Specify a mapping file
3765 (the equal sign is optional)
3767 (see @ref{Units to Sources Mapping Files}).
3769 @item -gnatep=@var{file}
3770 @cindex @option{-gnatep} (@code{gcc})
3771 Specify a preprocessing data file
3773 (the equal sign is optional)
3775 (see @ref{Integrated Preprocessing}).
3778 @cindex @option{-gnatE} (@code{gcc})
3779 Full dynamic elaboration checks.
3782 @cindex @option{-gnatf} (@code{gcc})
3783 Full errors. Multiple errors per line, all undefined references, do not
3784 attempt to suppress cascaded errors.
3787 @cindex @option{-gnatF} (@code{gcc})
3788 Externals names are folded to all uppercase.
3791 @cindex @option{-gnatg} (@code{gcc})
3792 Internal GNAT implementation mode. This should not be used for
3793 applications programs, it is intended only for use by the compiler
3794 and its run-time library. For documentation, see the GNAT sources.
3795 Note that @option{-gnatg} implies @option{-gnatwu} so that warnings
3796 are generated on unreferenced entities, and all warnings are treated
3800 @cindex @option{-gnatG} (@code{gcc})
3801 List generated expanded code in source form.
3803 @item ^-gnath^/HELP^
3804 @cindex @option{^-gnath^/HELP^} (@code{gcc})
3805 Output usage information. The output is written to @file{stdout}.
3807 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3808 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@code{gcc})
3809 Identifier character set
3811 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3814 For details of the possible selections for @var{c},
3815 see @xref{Character Set Control}.
3818 @item -gnatk=@var{n}
3819 @cindex @option{-gnatk} (@code{gcc})
3820 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3823 @cindex @option{-gnatl} (@code{gcc})
3824 Output full source listing with embedded error messages.
3827 @cindex @option{-gnatL} (@code{gcc})
3828 Use the longjmp/setjmp method for exception handling
3830 @item -gnatm=@var{n}
3831 @cindex @option{-gnatm} (@code{gcc})
3832 Limit number of detected error or warning messages to @var{n}
3833 where @var{n} is in the range 1..999_999. The default setting if
3834 no switch is given is 9999. Compilation is terminated if this
3838 @cindex @option{-gnatn} (@code{gcc})
3839 Activate inlining for subprograms for which
3840 pragma @code{inline} is specified. This inlining is performed
3841 by the GCC back-end.
3844 @cindex @option{-gnatN} (@code{gcc})
3845 Activate front end inlining for subprograms for which
3846 pragma @code{Inline} is specified. This inlining is performed
3847 by the front end and will be visible in the
3848 @option{-gnatG} output.
3849 In some cases, this has proved more effective than the back end
3850 inlining resulting from the use of
3853 @option{-gnatN} automatically implies
3854 @option{-gnatn} so it is not necessary
3855 to specify both options. There are a few cases that the back-end inlining
3856 catches that cannot be dealt with in the front-end.
3859 @cindex @option{-gnato} (@code{gcc})
3860 Enable numeric overflow checking (which is not normally enabled by
3861 default). Not that division by zero is a separate check that is not
3862 controlled by this switch (division by zero checking is on by default).
3865 @cindex @option{-gnatp} (@code{gcc})
3866 Suppress all checks.
3869 @cindex @option{-gnatP} (@code{gcc})
3870 Enable polling. This is required on some systems (notably Windows NT) to
3871 obtain asynchronous abort and asynchronous transfer of control capability.
3872 See the description of pragma Polling in the GNAT Reference Manual for
3876 @cindex @option{-gnatq} (@code{gcc})
3877 Don't quit; try semantics, even if parse errors.
3880 @cindex @option{-gnatQ} (@code{gcc})
3881 Don't quit; generate @file{ALI} and tree files even if illegalities.
3883 @item ^-gnatR[0/1/2/3[s]]^/REPRESENTATION_INFO^
3884 @cindex @option{-gnatR} (@code{gcc})
3885 Output representation information for declared types and objects.
3888 @cindex @option{-gnats} (@code{gcc})
3892 @cindex @option{-gnatS} (@code{gcc})
3893 Print package Standard.
3896 @cindex @option{-gnatt} (@code{gcc})
3897 Generate tree output file.
3899 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
3900 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@code{gcc})
3901 All compiler tables start at @var{nnn} times usual starting size.
3904 @cindex @option{-gnatu} (@code{gcc})
3905 List units for this compilation.
3908 @cindex @option{-gnatU} (@code{gcc})
3909 Tag all error messages with the unique string ``error:''
3912 @cindex @option{-gnatv} (@code{gcc})
3913 Verbose mode. Full error output with source lines to @file{stdout}.
3916 @cindex @option{-gnatV} (@code{gcc})
3917 Control level of validity checking. See separate section describing
3920 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}[,...])^
3921 @cindex @option{^-gnatw^/WARNINGS^} (@code{gcc})
3923 ^@var{xxx} is a string of option letters that^the list of options^ denotes
3924 the exact warnings that
3925 are enabled or disabled. (see @ref{Warning Message Control})
3927 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
3928 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@code{gcc})
3929 Wide character encoding method
3931 (@var{e}=n/h/u/s/e/8).
3934 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
3938 @cindex @option{-gnatx} (@code{gcc})
3939 Suppress generation of cross-reference information.
3941 @item ^-gnaty^/STYLE_CHECKS=(option,option..)^
3942 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@code{gcc})
3943 Enable built-in style checks. (see @ref{Style Checking})
3945 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
3946 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@code{gcc})
3947 Distribution stub generation and compilation
3949 (@var{m}=r/c for receiver/caller stubs).
3952 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
3953 to be generated and compiled).
3957 Use the zero cost method for exception handling
3959 @item ^-I^/SEARCH=^@var{dir}
3960 @cindex @option{^-I^/SEARCH^} (@code{gcc})
3962 Direct GNAT to search the @var{dir} directory for source files needed by
3963 the current compilation
3964 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3966 @item ^-I-^/NOCURRENT_DIRECTORY^
3967 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gcc})
3969 Except for the source file named in the command line, do not look for source
3970 files in the directory containing the source file named in the command line
3971 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3975 @cindex @option{-mbig-switch} (@command{gcc})
3976 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
3977 This standard gcc switch causes the compiler to use larger offsets in its
3978 jump table representation for @code{case} statements.
3979 This may result in less efficient code, but is sometimes necessary
3980 (for example on HP-UX targets)
3981 @cindex HP-UX and @option{-mbig-switch} option
3982 in order to compile large and/or nested @code{case} statements.
3985 @cindex @option{-o} (@code{gcc})
3986 This switch is used in @code{gcc} to redirect the generated object file
3987 and its associated ALI file. Beware of this switch with GNAT, because it may
3988 cause the object file and ALI file to have different names which in turn
3989 may confuse the binder and the linker.
3993 @cindex @option{-nostdinc} (@command{gcc})
3994 Inhibit the search of the default location for the GNAT Run Time
3995 Library (RTL) source files.
3998 @cindex @option{-nostdlib} (@command{gcc})
3999 Inhibit the search of the default location for the GNAT Run Time
4000 Library (RTL) ALI files.
4004 @cindex @option{-O} (@code{gcc})
4005 @var{n} controls the optimization level.
4009 No optimization, the default setting if no @option{-O} appears
4012 Normal optimization, the default if you specify @option{-O} without
4016 Extensive optimization
4019 Extensive optimization with automatic inlining of subprograms not
4020 specified by pragma @code{Inline}. This applies only to
4021 inlining within a unit. For details on control of inlining
4022 see @xref{Subprogram Inlining Control}.
4028 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4029 Equivalent to @option{/OPTIMIZE=NONE}.
4030 This is the default behavior in the absence of an @option{/OPTMIZE}
4033 @item /OPTIMIZE[=(keyword[,...])]
4034 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4035 Selects the level of optimization for your program. The supported
4036 keywords are as follows:
4039 Perform most optimizations, including those that
4041 This is the default if the @option{/OPTMIZE} qualifier is supplied
4042 without keyword options.
4045 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4048 Perform some optimizations, but omit ones that are costly.
4051 Same as @code{SOME}.
4054 Full optimization, and also attempt automatic inlining of small
4055 subprograms within a unit even when pragma @code{Inline}
4056 is not specified (@pxref{Inlining of Subprograms}).
4059 Try to unroll loops. This keyword may be specified together with
4060 any keyword above other than @code{NONE}. Loop unrolling
4061 usually, but not always, improves the performance of programs.
4066 @item -pass-exit-codes
4067 @cindex @option{-pass-exit-codes} (@code{gcc})
4068 Catch exit codes from the compiler and use the most meaningful as
4072 @item --RTS=@var{rts-path}
4073 @cindex @option{--RTS} (@code{gcc})
4074 Specifies the default location of the runtime library. Same meaning as the
4075 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
4078 @cindex @option{^-S^/ASM^} (@code{gcc})
4079 ^Used in place of @option{-c} to^Used to^
4080 cause the assembler source file to be
4081 generated, using @file{^.s^.S^} as the extension,
4082 instead of the object file.
4083 This may be useful if you need to examine the generated assembly code.
4085 @item ^-fverbose-asm^/VERBOSE_ASM^
4086 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@code{gcc})
4087 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4088 to cause the generated assembly code file to be annotated with variable
4089 names, making it significantly easier to follow.
4092 @cindex @option{^-v^/VERBOSE^} (@code{gcc})
4093 Show commands generated by the @code{gcc} driver. Normally used only for
4094 debugging purposes or if you need to be sure what version of the
4095 compiler you are executing.
4099 @cindex @option{-V} (@code{gcc})
4100 Execute @var{ver} version of the compiler. This is the @code{gcc}
4101 version, not the GNAT version.
4107 You may combine a sequence of GNAT switches into a single switch. For
4108 example, the combined switch
4110 @cindex Combining GNAT switches
4116 is equivalent to specifying the following sequence of switches:
4119 -gnato -gnatf -gnati3
4123 @c NEED TO CHECK THIS FOR VMS
4126 The following restrictions apply to the combination of switches
4131 The switch @option{-gnatc} if combined with other switches must come
4132 first in the string.
4135 The switch @option{-gnats} if combined with other switches must come
4136 first in the string.
4140 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4141 may not be combined with any other switches.
4145 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4146 switch), then all further characters in the switch are interpreted
4147 as style modifiers (see description of @option{-gnaty}).
4150 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4151 switch), then all further characters in the switch are interpreted
4152 as debug flags (see description of @option{-gnatd}).
4155 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4156 switch), then all further characters in the switch are interpreted
4157 as warning mode modifiers (see description of @option{-gnatw}).
4160 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4161 switch), then all further characters in the switch are interpreted
4162 as validity checking options (see description of @option{-gnatV}).
4166 @node Output and Error Message Control
4167 @subsection Output and Error Message Control
4171 The standard default format for error messages is called ``brief format''.
4172 Brief format messages are written to @file{stderr} (the standard error
4173 file) and have the following form:
4176 e.adb:3:04: Incorrect spelling of keyword "function"
4177 e.adb:4:20: ";" should be "is"
4181 The first integer after the file name is the line number in the file,
4182 and the second integer is the column number within the line.
4183 @code{glide} can parse the error messages
4184 and point to the referenced character.
4185 The following switches provide control over the error message
4191 @cindex @option{-gnatv} (@code{gcc})
4194 The v stands for verbose.
4196 The effect of this setting is to write long-format error
4197 messages to @file{stdout} (the standard output file.
4198 The same program compiled with the
4199 @option{-gnatv} switch would generate:
4203 3. funcion X (Q : Integer)
4205 >>> Incorrect spelling of keyword "function"
4208 >>> ";" should be "is"
4213 The vertical bar indicates the location of the error, and the @samp{>>>}
4214 prefix can be used to search for error messages. When this switch is
4215 used the only source lines output are those with errors.
4218 @cindex @option{-gnatl} (@code{gcc})
4220 The @code{l} stands for list.
4222 This switch causes a full listing of
4223 the file to be generated. The output might look as follows:
4229 3. funcion X (Q : Integer)
4231 >>> Incorrect spelling of keyword "function"
4234 >>> ";" should be "is"
4246 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4247 standard output is redirected, a brief summary is written to
4248 @file{stderr} (standard error) giving the number of error messages and
4249 warning messages generated.
4252 @cindex @option{-gnatU} (@code{gcc})
4253 This switch forces all error messages to be preceded by the unique
4254 string ``error:''. This means that error messages take a few more
4255 characters in space, but allows easy searching for and identification
4259 @cindex @option{-gnatb} (@code{gcc})
4261 The @code{b} stands for brief.
4263 This switch causes GNAT to generate the
4264 brief format error messages to @file{stderr} (the standard error
4265 file) as well as the verbose
4266 format message or full listing (which as usual is written to
4267 @file{stdout} (the standard output file).
4269 @item -gnatm^^=^@var{n}
4270 @cindex @option{-gnatm} (@code{gcc})
4272 The @code{m} stands for maximum.
4274 @var{n} is a decimal integer in the
4275 range of 1 to 999 and limits the number of error messages to be
4276 generated. For example, using @option{-gnatm2} might yield
4279 e.adb:3:04: Incorrect spelling of keyword "function"
4280 e.adb:5:35: missing ".."
4281 fatal error: maximum errors reached
4282 compilation abandoned
4286 @cindex @option{-gnatf} (@code{gcc})
4287 @cindex Error messages, suppressing
4289 The @code{f} stands for full.
4291 Normally, the compiler suppresses error messages that are likely to be
4292 redundant. This switch causes all error
4293 messages to be generated. In particular, in the case of
4294 references to undefined variables. If a given variable is referenced
4295 several times, the normal format of messages is
4297 e.adb:7:07: "V" is undefined (more references follow)
4301 where the parenthetical comment warns that there are additional
4302 references to the variable @code{V}. Compiling the same program with the
4303 @option{-gnatf} switch yields
4306 e.adb:7:07: "V" is undefined
4307 e.adb:8:07: "V" is undefined
4308 e.adb:8:12: "V" is undefined
4309 e.adb:8:16: "V" is undefined
4310 e.adb:9:07: "V" is undefined
4311 e.adb:9:12: "V" is undefined
4315 The @option{-gnatf} switch also generates additional information for
4316 some error messages. Some examples are:
4320 Full details on entities not available in high integrity mode
4322 Details on possibly non-portable unchecked conversion
4324 List possible interpretations for ambiguous calls
4326 Additional details on incorrect parameters
4330 @cindex @option{-gnatq} (@code{gcc})
4332 The @code{q} stands for quit (really ``don't quit'').
4334 In normal operation mode, the compiler first parses the program and
4335 determines if there are any syntax errors. If there are, appropriate
4336 error messages are generated and compilation is immediately terminated.
4338 GNAT to continue with semantic analysis even if syntax errors have been
4339 found. This may enable the detection of more errors in a single run. On
4340 the other hand, the semantic analyzer is more likely to encounter some
4341 internal fatal error when given a syntactically invalid tree.
4344 @cindex @option{-gnatQ} (@code{gcc})
4345 In normal operation mode, the @file{ALI} file is not generated if any
4346 illegalities are detected in the program. The use of @option{-gnatQ} forces
4347 generation of the @file{ALI} file. This file is marked as being in
4348 error, so it cannot be used for binding purposes, but it does contain
4349 reasonably complete cross-reference information, and thus may be useful
4350 for use by tools (e.g. semantic browsing tools or integrated development
4351 environments) that are driven from the @file{ALI} file. This switch
4352 implies @option{-gnatq}, since the semantic phase must be run to get a
4353 meaningful ALI file.
4355 In addition, if @option{-gnatt} is also specified, then the tree file is
4356 generated even if there are illegalities. It may be useful in this case
4357 to also specify @option{-gnatq} to ensure that full semantic processing
4358 occurs. The resulting tree file can be processed by ASIS, for the purpose
4359 of providing partial information about illegal units, but if the error
4360 causes the tree to be badly malformed, then ASIS may crash during the
4363 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4364 being in error, @code{gnatmake} will attempt to recompile the source when it
4365 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4367 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4368 since ALI files are never generated if @option{-gnats} is set.
4372 @node Warning Message Control
4373 @subsection Warning Message Control
4374 @cindex Warning messages
4376 In addition to error messages, which correspond to illegalities as defined
4377 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
4380 First, the compiler considers some constructs suspicious and generates a
4381 warning message to alert you to a possible error. Second, if the
4382 compiler detects a situation that is sure to raise an exception at
4383 run time, it generates a warning message. The following shows an example
4384 of warning messages:
4386 e.adb:4:24: warning: creation of object may raise Storage_Error
4387 e.adb:10:17: warning: static value out of range
4388 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4392 GNAT considers a large number of situations as appropriate
4393 for the generation of warning messages. As always, warnings are not
4394 definite indications of errors. For example, if you do an out-of-range
4395 assignment with the deliberate intention of raising a
4396 @code{Constraint_Error} exception, then the warning that may be
4397 issued does not indicate an error. Some of the situations for which GNAT
4398 issues warnings (at least some of the time) are given in the following
4399 list. This list is not complete, and new warnings are often added to
4400 subsequent versions of GNAT. The list is intended to give a general idea
4401 of the kinds of warnings that are generated.
4405 Possible infinitely recursive calls
4408 Out-of-range values being assigned
4411 Possible order of elaboration problems
4417 Fixed-point type declarations with a null range
4420 Direct_IO or Sequential_IO instantiated with a type that has access values
4423 Variables that are never assigned a value
4426 Variables that are referenced before being initialized
4429 Task entries with no corresponding @code{accept} statement
4432 Duplicate accepts for the same task entry in a @code{select}
4435 Objects that take too much storage
4438 Unchecked conversion between types of differing sizes
4441 Missing @code{return} statement along some execution path in a function
4444 Incorrect (unrecognized) pragmas
4447 Incorrect external names
4450 Allocation from empty storage pool
4453 Potentially blocking operation in protected type
4456 Suspicious parenthesization of expressions
4459 Mismatching bounds in an aggregate
4462 Attempt to return local value by reference
4465 Premature instantiation of a generic body
4468 Attempt to pack aliased components
4471 Out of bounds array subscripts
4474 Wrong length on string assignment
4477 Violations of style rules if style checking is enabled
4480 Unused @code{with} clauses
4483 @code{Bit_Order} usage that does not have any effect
4486 @code{Standard.Duration} used to resolve universal fixed expression
4489 Dereference of possibly null value
4492 Declaration that is likely to cause storage error
4495 Internal GNAT unit @code{with}'ed by application unit
4498 Values known to be out of range at compile time
4501 Unreferenced labels and variables
4504 Address overlays that could clobber memory
4507 Unexpected initialization when address clause present
4510 Bad alignment for address clause
4513 Useless type conversions
4516 Redundant assignment statements and other redundant constructs
4519 Useless exception handlers
4522 Accidental hiding of name by child unit
4525 Access before elaboration detected at compile time
4528 A range in a @code{for} loop that is known to be null or might be null
4533 The following switches are available to control the handling of
4539 @emph{Activate all optional errors.}
4540 @cindex @option{-gnatwa} (@code{gcc})
4541 This switch activates most optional warning messages, see remaining list
4542 in this section for details on optional warning messages that can be
4543 individually controlled. The warnings that are not turned on by this
4545 @option{-gnatwd} (implicit dereferencing),
4546 @option{-gnatwh} (hiding),
4547 and @option{-gnatwl} (elaboration warnings).
4548 All other optional warnings are turned on.
4551 @emph{Suppress all optional errors.}
4552 @cindex @option{-gnatwA} (@code{gcc})
4553 This switch suppresses all optional warning messages, see remaining list
4554 in this section for details on optional warning messages that can be
4555 individually controlled.
4558 @emph{Activate warnings on conditionals.}
4559 @cindex @option{-gnatwc} (@code{gcc})
4560 @cindex Conditionals, constant
4561 This switch activates warnings for conditional expressions used in
4562 tests that are known to be True or False at compile time. The default
4563 is that such warnings are not generated.
4564 Note that this warning does
4565 not get issued for the use of boolean variables or constants whose
4566 values are known at compile time, since this is a standard technique
4567 for conditional compilation in Ada, and this would generate too many
4568 ``false positive'' warnings.
4569 This warning can also be turned on using @option{-gnatwa}.
4572 @emph{Suppress warnings on conditionals.}
4573 @cindex @option{-gnatwC} (@code{gcc})
4574 This switch suppresses warnings for conditional expressions used in
4575 tests that are known to be True or False at compile time.
4578 @emph{Activate warnings on implicit dereferencing.}
4579 @cindex @option{-gnatwd} (@code{gcc})
4580 If this switch is set, then the use of a prefix of an access type
4581 in an indexed component, slice, or selected component without an
4582 explicit @code{.all} will generate a warning. With this warning
4583 enabled, access checks occur only at points where an explicit
4584 @code{.all} appears in the source code (assuming no warnings are
4585 generated as a result of this switch). The default is that such
4586 warnings are not generated.
4587 Note that @option{-gnatwa} does not affect the setting of
4588 this warning option.
4591 @emph{Suppress warnings on implicit dereferencing.}
4592 @cindex @option{-gnatwD} (@code{gcc})
4593 @cindex Implicit dereferencing
4594 @cindex Dereferencing, implicit
4595 This switch suppresses warnings for implicit dereferences in
4596 indexed components, slices, and selected components.
4599 @emph{Treat warnings as errors.}
4600 @cindex @option{-gnatwe} (@code{gcc})
4601 @cindex Warnings, treat as error
4602 This switch causes warning messages to be treated as errors.
4603 The warning string still appears, but the warning messages are counted
4604 as errors, and prevent the generation of an object file.
4607 @emph{Activate warnings on unreferenced formals.}
4608 @cindex @option{-gnatwf} (@code{gcc})
4609 @cindex Formals, unreferenced
4610 This switch causes a warning to be generated if a formal parameter
4611 is not referenced in the body of the subprogram. This warning can
4612 also be turned on using @option{-gnatwa} or @option{-gnatwu}.
4615 @emph{Suppress warnings on unreferenced formals.}
4616 @cindex @option{-gnatwF} (@code{gcc})
4617 This switch suppresses warnings for unreferenced formal
4618 parameters. Note that the
4619 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4620 effect of warning on unreferenced entities other than subprogram
4624 @emph{Activate warnings on unrecognized pragmas.}
4625 @cindex @option{-gnatwg} (@code{gcc})
4626 @cindex Pragmas, unrecognized
4627 This switch causes a warning to be generated if an unrecognized
4628 pragma is encountered. Apart from issuing this warning, the
4629 pragma is ignored and has no effect. This warning can
4630 also be turned on using @option{-gnatwa}. The default
4631 is that such warnings are issued (satisfying the Ada Reference
4632 Manual requirement that such warnings appear).
4635 @emph{Suppress warnings on unrecognized pragmas.}
4636 @cindex @option{-gnatwG} (@code{gcc})
4637 This switch suppresses warnings for unrecognized pragmas.
4640 @emph{Activate warnings on hiding.}
4641 @cindex @option{-gnatwh} (@code{gcc})
4642 @cindex Hiding of Declarations
4643 This switch activates warnings on hiding declarations.
4644 A declaration is considered hiding
4645 if it is for a non-overloadable entity, and it declares an entity with the
4646 same name as some other entity that is directly or use-visible. The default
4647 is that such warnings are not generated.
4648 Note that @option{-gnatwa} does not affect the setting of this warning option.
4651 @emph{Suppress warnings on hiding.}
4652 @cindex @option{-gnatwH} (@code{gcc})
4653 This switch suppresses warnings on hiding declarations.
4656 @emph{Activate warnings on implementation units.}
4657 @cindex @option{-gnatwi} (@code{gcc})
4658 This switch activates warnings for a @code{with} of an internal GNAT
4659 implementation unit, defined as any unit from the @code{Ada},
4660 @code{Interfaces}, @code{GNAT},
4661 ^^@code{DEC},^ or @code{System}
4662 hierarchies that is not
4663 documented in either the Ada Reference Manual or the GNAT
4664 Programmer's Reference Manual. Such units are intended only
4665 for internal implementation purposes and should not be @code{with}'ed
4666 by user programs. The default is that such warnings are generated
4667 This warning can also be turned on using @option{-gnatwa}.
4670 @emph{Disable warnings on implementation units.}
4671 @cindex @option{-gnatwI} (@code{gcc})
4672 This switch disables warnings for a @code{with} of an internal GNAT
4673 implementation unit.
4676 @emph{Activate warnings on obsolescent features (Annex J).}
4677 @cindex @option{-gnatwj} (@code{gcc})
4678 @cindex Features, obsolescent
4679 @cindex Obsolescent features
4680 If this warning option is activated, then warnings are generated for
4681 calls to subprograms marked with @code{pragma Obsolescent} and
4682 for use of features in Annex J of the Ada Reference Manual. In the
4683 case of Annex J, not all features are flagged. In particular use
4684 of the renamed packages (like @code{Text_IO}) and use of package
4685 @code{ASCII} are not flagged, since these are very common and
4686 would generate many annoying positive warnings. The default is that
4687 such warnings are not generated.
4689 In addition to the above cases, warnings are also generated for
4690 GNAT features that have been provided in past versions but which
4691 have been superceded (typically by features in the new Ada standard).
4692 For example, @code{pragma Ravenscar} will be flagged since its
4693 function is replaced by @code{pragma Profile(Ravenscar)}.
4695 Note that this warning option functions differently from the
4696 restriction @code{No_Obsolescent_Features} in two respects.
4697 First, the restriction applies only to annex J features.
4698 Second, the restriction does flag uses of package @code{ASCII}.
4701 @emph{Suppress warnings on obsolescent features (Annex J).}
4702 @cindex @option{-gnatwJ} (@code{gcc})
4703 This switch disables warnings on use of obsolescent features.
4706 @emph{Activate warnings on variables that could be constants.}
4707 @cindex @option{-gnatwk} (@code{gcc})
4708 This switch activates warnings for variables that are initialized but
4709 never modified, and then could be declared constants.
4712 @emph{Suppress warnings on variables that could be constants.}
4713 @cindex @option{-gnatwK} (@code{gcc})
4714 This switch disables warnings on variables that could be declared constants.
4717 @emph{Activate warnings for missing elaboration pragmas.}
4718 @cindex @option{-gnatwl} (@code{gcc})
4719 @cindex Elaboration, warnings
4720 This switch activates warnings on missing
4721 @code{pragma Elaborate_All} statements.
4722 See the section in this guide on elaboration checking for details on
4723 when such pragma should be used. Warnings are also generated if you
4724 are using the static mode of elaboration, and a @code{pragma Elaborate}
4725 is encountered. The default is that such warnings
4727 This warning is not automatically turned on by the use of @option{-gnatwa}.
4730 @emph{Suppress warnings for missing elaboration pragmas.}
4731 @cindex @option{-gnatwL} (@code{gcc})
4732 This switch suppresses warnings on missing pragma Elaborate_All statements.
4733 See the section in this guide on elaboration checking for details on
4734 when such pragma should be used.
4737 @emph{Activate warnings on modified but unreferenced variables.}
4738 @cindex @option{-gnatwm} (@code{gcc})
4739 This switch activates warnings for variables that are assigned (using
4740 an initialization value or with one or more assignment statements) but
4741 whose value is never read. The warning is suppressed for volatile
4742 variables and also for variables that are renamings of other variables
4743 or for which an address clause is given.
4744 This warning can also be turned on using @option{-gnatwa}.
4747 @emph{Disable warnings on modified but unreferenced variables.}
4748 @cindex @option{-gnatwM} (@code{gcc})
4749 This switch disables warnings for variables that are assigned or
4750 initialized, but never read.
4753 @emph{Set normal warnings mode.}
4754 @cindex @option{-gnatwn} (@code{gcc})
4755 This switch sets normal warning mode, in which enabled warnings are
4756 issued and treated as warnings rather than errors. This is the default
4757 mode. the switch @option{-gnatwn} can be used to cancel the effect of
4758 an explicit @option{-gnatws} or
4759 @option{-gnatwe}. It also cancels the effect of the
4760 implicit @option{-gnatwe} that is activated by the
4761 use of @option{-gnatg}.
4764 @emph{Activate warnings on address clause overlays.}
4765 @cindex @option{-gnatwo} (@code{gcc})
4766 @cindex Address Clauses, warnings
4767 This switch activates warnings for possibly unintended initialization
4768 effects of defining address clauses that cause one variable to overlap
4769 another. The default is that such warnings are generated.
4770 This warning can also be turned on using @option{-gnatwa}.
4773 @emph{Suppress warnings on address clause overlays.}
4774 @cindex @option{-gnatwO} (@code{gcc})
4775 This switch suppresses warnings on possibly unintended initialization
4776 effects of defining address clauses that cause one variable to overlap
4780 @emph{Activate warnings on ineffective pragma Inlines.}
4781 @cindex @option{-gnatwp} (@code{gcc})
4782 @cindex Inlining, warnings
4783 This switch activates warnings for failure of front end inlining
4784 (activated by @option{-gnatN}) to inline a particular call. There are
4785 many reasons for not being able to inline a call, including most
4786 commonly that the call is too complex to inline.
4787 This warning can also be turned on using @option{-gnatwa}.
4790 @emph{Suppress warnings on ineffective pragma Inlines.}
4791 @cindex @option{-gnatwP} (@code{gcc})
4792 This switch suppresses warnings on ineffective pragma Inlines. If the
4793 inlining mechanism cannot inline a call, it will simply ignore the
4797 @emph{Activate warnings on redundant constructs.}
4798 @cindex @option{-gnatwr} (@code{gcc})
4799 This switch activates warnings for redundant constructs. The following
4800 is the current list of constructs regarded as redundant:
4801 This warning can also be turned on using @option{-gnatwa}.
4805 Assignment of an item to itself.
4807 Type conversion that converts an expression to its own type.
4809 Use of the attribute @code{Base} where @code{typ'Base} is the same
4812 Use of pragma @code{Pack} when all components are placed by a record
4813 representation clause.
4815 Exception handler containing only a reraise statement (raise with no
4816 operand) which has no effect.
4818 Use of the operator abs on an operand that is known at compile time
4821 Comparison of boolean expressions to an explicit True value.
4825 @emph{Suppress warnings on redundant constructs.}
4826 @cindex @option{-gnatwR} (@code{gcc})
4827 This switch suppresses warnings for redundant constructs.
4830 @emph{Suppress all warnings.}
4831 @cindex @option{-gnatws} (@code{gcc})
4832 This switch completely suppresses the
4833 output of all warning messages from the GNAT front end.
4834 Note that it does not suppress warnings from the @code{gcc} back end.
4835 To suppress these back end warnings as well, use the switch @option{-w}
4836 in addition to @option{-gnatws}.
4839 @emph{Activate warnings on unused entities.}
4840 @cindex @option{-gnatwu} (@code{gcc})
4841 This switch activates warnings to be generated for entities that
4842 are declared but not referenced, and for units that are @code{with}'ed
4844 referenced. In the case of packages, a warning is also generated if
4845 no entities in the package are referenced. This means that if the package
4846 is referenced but the only references are in @code{use}
4847 clauses or @code{renames}
4848 declarations, a warning is still generated. A warning is also generated
4849 for a generic package that is @code{with}'ed but never instantiated.
4850 In the case where a package or subprogram body is compiled, and there
4851 is a @code{with} on the corresponding spec
4852 that is only referenced in the body,
4853 a warning is also generated, noting that the
4854 @code{with} can be moved to the body. The default is that
4855 such warnings are not generated.
4856 This switch also activates warnings on unreferenced formals
4857 (it is includes the effect of @option{-gnatwf}).
4858 This warning can also be turned on using @option{-gnatwa}.
4861 @emph{Suppress warnings on unused entities.}
4862 @cindex @option{-gnatwU} (@code{gcc})
4863 This switch suppresses warnings for unused entities and packages.
4864 It also turns off warnings on unreferenced formals (and thus includes
4865 the effect of @option{-gnatwF}).
4868 @emph{Activate warnings on unassigned variables.}
4869 @cindex @option{-gnatwv} (@code{gcc})
4870 @cindex Unassigned variable warnings
4871 This switch activates warnings for access to variables which
4872 may not be properly initialized. The default is that
4873 such warnings are generated.
4876 @emph{Suppress warnings on unassigned variables.}
4877 @cindex @option{-gnatwV} (@code{gcc})
4878 This switch suppresses warnings for access to variables which
4879 may not be properly initialized.
4882 @emph{Activate warnings on Export/Import pragmas.}
4883 @cindex @option{-gnatwx} (@code{gcc})
4884 @cindex Export/Import pragma warnings
4885 This switch activates warnings on Export/Import pragmas when
4886 the compiler detects a possible conflict between the Ada and
4887 foreign language calling sequences. For example, the use of
4888 default parameters in a convention C procedure is dubious
4889 because the C compiler cannot supply the proper default, so
4890 a warning is issued. The default is that such warnings are
4894 @emph{Suppress warnings on Export/Import pragmas.}
4895 @cindex @option{-gnatwX} (@code{gcc})
4896 This switch suppresses warnings on Export/Import pragmas.
4897 The sense of this is that you are telling the compiler that
4898 you know what you are doing in writing the pragma, and it
4899 should not complain at you.
4902 @emph{Activate warnings on unchecked conversions.}
4903 @cindex @option{-gnatwz} (@code{gcc})
4904 @cindex Unchecked_Conversion warnings
4905 This switch activates warnings for unchecked conversions
4906 where the types are known at compile time to have different
4908 is that such warnings are generated.
4911 @emph{Suppress warnings on unchecked conversions.}
4912 @cindex @option{-gnatwZ} (@code{gcc})
4913 This switch suppresses warnings for unchecked conversions
4914 where the types are known at compile time to have different
4917 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
4918 @cindex @option{-Wuninitialized}
4919 The warnings controlled by the @option{-gnatw} switch are generated by the
4920 front end of the compiler. In some cases, the @option{^gcc^GCC^} back end
4921 can provide additional warnings. One such useful warning is provided by
4922 @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^}. This must be used in
4923 conjunction with tunrning on optimization mode. This causes the flow
4924 analysis circuits of the back end optimizer to output additional
4925 warnings about uninitialized variables.
4927 @item ^-w^/NO_BACK_END_WARNINGS^
4929 This switch suppresses warnings from the @option{^gcc^GCC^} back end. It may
4930 be used in conjunction with @option{-gnatws} to ensure that all warnings
4931 are suppressed during the entire compilation process.
4937 A string of warning parameters can be used in the same parameter. For example:
4944 will turn on all optional warnings except for elaboration pragma warnings,
4945 and also specify that warnings should be treated as errors.
4947 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
4972 @node Debugging and Assertion Control
4973 @subsection Debugging and Assertion Control
4977 @cindex @option{-gnata} (@code{gcc})
4983 The pragmas @code{Assert} and @code{Debug} normally have no effect and
4984 are ignored. This switch, where @samp{a} stands for assert, causes
4985 @code{Assert} and @code{Debug} pragmas to be activated.
4987 The pragmas have the form:
4991 @b{pragma} Assert (@var{Boolean-expression} [,
4992 @var{static-string-expression}])
4993 @b{pragma} Debug (@var{procedure call})
4998 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
4999 If the result is @code{True}, the pragma has no effect (other than
5000 possible side effects from evaluating the expression). If the result is
5001 @code{False}, the exception @code{Assert_Failure} declared in the package
5002 @code{System.Assertions} is
5003 raised (passing @var{static-string-expression}, if present, as the
5004 message associated with the exception). If no string expression is
5005 given the default is a string giving the file name and line number
5008 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5009 @code{pragma Debug} may appear within a declaration sequence, allowing
5010 debugging procedures to be called between declarations.
5013 @item /DEBUG[=debug-level]
5015 Specifies how much debugging information is to be included in
5016 the resulting object file where 'debug-level' is one of the following:
5019 Include both debugger symbol records and traceback
5021 This is the default setting.
5023 Include both debugger symbol records and traceback in
5026 Excludes both debugger symbol records and traceback
5027 the object file. Same as /NODEBUG.
5029 Includes only debugger symbol records in the object
5030 file. Note that this doesn't include traceback information.
5035 @node Validity Checking
5036 @subsection Validity Checking
5037 @findex Validity Checking
5040 The Ada 95 Reference Manual has specific requirements for checking
5041 for invalid values. In particular, RM 13.9.1 requires that the
5042 evaluation of invalid values (for example from unchecked conversions),
5043 not result in erroneous execution. In GNAT, the result of such an
5044 evaluation in normal default mode is to either use the value
5045 unmodified, or to raise Constraint_Error in those cases where use
5046 of the unmodified value would cause erroneous execution. The cases
5047 where unmodified values might lead to erroneous execution are case
5048 statements (where a wild jump might result from an invalid value),
5049 and subscripts on the left hand side (where memory corruption could
5050 occur as a result of an invalid value).
5052 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5055 The @code{x} argument is a string of letters that
5056 indicate validity checks that are performed or not performed in addition
5057 to the default checks described above.
5060 The options allowed for this qualifier
5061 indicate validity checks that are performed or not performed in addition
5062 to the default checks described above.
5068 @emph{All validity checks.}
5069 @cindex @option{-gnatVa} (@code{gcc})
5070 All validity checks are turned on.
5072 That is, @option{-gnatVa} is
5073 equivalent to @option{gnatVcdfimorst}.
5077 @emph{Validity checks for copies.}
5078 @cindex @option{-gnatVc} (@code{gcc})
5079 The right hand side of assignments, and the initializing values of
5080 object declarations are validity checked.
5083 @emph{Default (RM) validity checks.}
5084 @cindex @option{-gnatVd} (@code{gcc})
5085 Some validity checks are done by default following normal Ada semantics
5087 A check is done in case statements that the expression is within the range
5088 of the subtype. If it is not, Constraint_Error is raised.
5089 For assignments to array components, a check is done that the expression used
5090 as index is within the range. If it is not, Constraint_Error is raised.
5091 Both these validity checks may be turned off using switch @option{-gnatVD}.
5092 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5093 switch @option{-gnatVd} will leave the checks turned on.
5094 Switch @option{-gnatVD} should be used only if you are sure that all such
5095 expressions have valid values. If you use this switch and invalid values
5096 are present, then the program is erroneous, and wild jumps or memory
5097 overwriting may occur.
5100 @emph{Validity checks for floating-point values.}
5101 @cindex @option{-gnatVf} (@code{gcc})
5102 In the absence of this switch, validity checking occurs only for discrete
5103 values. If @option{-gnatVf} is specified, then validity checking also applies
5104 for floating-point values, and NaN's and infinities are considered invalid,
5105 as well as out of range values for constrained types. Note that this means
5106 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
5107 in which floating-point values are checked depends on the setting of other
5108 options. For example,
5109 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5110 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5111 (the order does not matter) specifies that floating-point parameters of mode
5112 @code{in} should be validity checked.
5115 @emph{Validity checks for @code{in} mode parameters}
5116 @cindex @option{-gnatVi} (@code{gcc})
5117 Arguments for parameters of mode @code{in} are validity checked in function
5118 and procedure calls at the point of call.
5121 @emph{Validity checks for @code{in out} mode parameters.}
5122 @cindex @option{-gnatVm} (@code{gcc})
5123 Arguments for parameters of mode @code{in out} are validity checked in
5124 procedure calls at the point of call. The @code{'m'} here stands for
5125 modify, since this concerns parameters that can be modified by the call.
5126 Note that there is no specific option to test @code{out} parameters,
5127 but any reference within the subprogram will be tested in the usual
5128 manner, and if an invalid value is copied back, any reference to it
5129 will be subject to validity checking.
5132 @emph{No validity checks.}
5133 @cindex @option{-gnatVn} (@code{gcc})
5134 This switch turns off all validity checking, including the default checking
5135 for case statements and left hand side subscripts. Note that the use of
5136 the switch @option{-gnatp} suppresses all run-time checks, including
5137 validity checks, and thus implies @option{-gnatVn}. When this switch
5138 is used, it cancels any other @option{-gnatV} previously issued.
5141 @emph{Validity checks for operator and attribute operands.}
5142 @cindex @option{-gnatVo} (@code{gcc})
5143 Arguments for predefined operators and attributes are validity checked.
5144 This includes all operators in package @code{Standard},
5145 the shift operators defined as intrinsic in package @code{Interfaces}
5146 and operands for attributes such as @code{Pos}. Checks are also made
5147 on individual component values for composite comparisons.
5150 @emph{Validity checks for parameters.}
5151 @cindex @option{-gnatVp} (@code{gcc})
5152 This controls the treatment of parameters within a subprogram (as opposed
5153 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5154 of parameters on a call. If either of these call options is used, then
5155 normally an assumption is made within a subprogram that the input arguments
5156 have been validity checking at the point of call, and do not need checking
5157 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5158 is not made, and parameters are not assumed to be valid, so their validity
5159 will be checked (or rechecked) within the subprogram.
5162 @emph{Validity checks for function returns.}
5163 @cindex @option{-gnatVr} (@code{gcc})
5164 The expression in @code{return} statements in functions is validity
5168 @emph{Validity checks for subscripts.}
5169 @cindex @option{-gnatVs} (@code{gcc})
5170 All subscripts expressions are checked for validity, whether they appear
5171 on the right side or left side (in default mode only left side subscripts
5172 are validity checked).
5175 @emph{Validity checks for tests.}
5176 @cindex @option{-gnatVt} (@code{gcc})
5177 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5178 statements are checked, as well as guard expressions in entry calls.
5183 The @option{-gnatV} switch may be followed by
5184 ^a string of letters^a list of options^
5185 to turn on a series of validity checking options.
5187 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5188 specifies that in addition to the default validity checking, copies and
5189 function return expressions are to be validity checked.
5190 In order to make it easier
5191 to specify the desired combination of effects,
5193 the upper case letters @code{CDFIMORST} may
5194 be used to turn off the corresponding lower case option.
5197 the prefix @code{NO} on an option turns off the corresponding validity
5200 @item @code{NOCOPIES}
5201 @item @code{NODEFAULT}
5202 @item @code{NOFLOATS}
5203 @item @code{NOIN_PARAMS}
5204 @item @code{NOMOD_PARAMS}
5205 @item @code{NOOPERANDS}
5206 @item @code{NORETURNS}
5207 @item @code{NOSUBSCRIPTS}
5208 @item @code{NOTESTS}
5212 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5213 turns on all validity checking options except for
5214 checking of @code{@b{in out}} procedure arguments.
5216 The specification of additional validity checking generates extra code (and
5217 in the case of @option{-gnatVa} the code expansion can be substantial.
5218 However, these additional checks can be very useful in detecting
5219 uninitialized variables, incorrect use of unchecked conversion, and other
5220 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5221 is useful in conjunction with the extra validity checking, since this
5222 ensures that wherever possible uninitialized variables have invalid values.
5224 See also the pragma @code{Validity_Checks} which allows modification of
5225 the validity checking mode at the program source level, and also allows for
5226 temporary disabling of validity checks.
5228 @node Style Checking
5229 @subsection Style Checking
5230 @findex Style checking
5233 The @option{-gnaty^x^(option,option,...)^} switch
5234 @cindex @option{-gnaty} (@code{gcc})
5235 causes the compiler to
5236 enforce specified style rules. A limited set of style rules has been used
5237 in writing the GNAT sources themselves. This switch allows user programs
5238 to activate all or some of these checks. If the source program fails a
5239 specified style check, an appropriate warning message is given, preceded by
5240 the character sequence ``(style)''.
5242 @code{(option,option,...)} is a sequence of keywords
5245 The string @var{x} is a sequence of letters or digits
5247 indicating the particular style
5248 checks to be performed. The following checks are defined:
5253 @emph{Specify indentation level.}
5254 If a digit from 1-9 appears
5255 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5256 then proper indentation is checked, with the digit indicating the
5257 indentation level required.
5258 The general style of required indentation is as specified by
5259 the examples in the Ada Reference Manual. Full line comments must be
5260 aligned with the @code{--} starting on a column that is a multiple of
5261 the alignment level.
5264 @emph{Check attribute casing.}
5265 If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty}
5266 then attribute names, including the case of keywords such as @code{digits}
5267 used as attributes names, must be written in mixed case, that is, the
5268 initial letter and any letter following an underscore must be uppercase.
5269 All other letters must be lowercase.
5272 @emph{Blanks not allowed at statement end.}
5273 If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then
5274 trailing blanks are not allowed at the end of statements. The purpose of this
5275 rule, together with h (no horizontal tabs), is to enforce a canonical format
5276 for the use of blanks to separate source tokens.
5279 @emph{Check comments.}
5280 If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty}
5281 then comments must meet the following set of rules:
5286 The ``@code{--}'' that starts the column must either start in column one,
5287 or else at least one blank must precede this sequence.
5290 Comments that follow other tokens on a line must have at least one blank
5291 following the ``@code{--}'' at the start of the comment.
5294 Full line comments must have two blanks following the ``@code{--}'' that
5295 starts the comment, with the following exceptions.
5298 A line consisting only of the ``@code{--}'' characters, possibly preceded
5299 by blanks is permitted.
5302 A comment starting with ``@code{--x}'' where @code{x} is a special character
5304 This allows proper processing of the output generated by specialized tools
5305 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5307 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5308 special character is defined as being in one of the ASCII ranges
5309 @code{16#21#..16#2F#} or @code{16#3A#..16#3F#}.
5310 Note that this usage is not permitted
5311 in GNAT implementation units (i.e. when @option{-gnatg} is used).
5314 A line consisting entirely of minus signs, possibly preceded by blanks, is
5315 permitted. This allows the construction of box comments where lines of minus
5316 signs are used to form the top and bottom of the box.
5319 If a comment starts and ends with ``@code{--}'' is permitted as long as at
5320 least one blank follows the initial ``@code{--}''. Together with the preceding
5321 rule, this allows the construction of box comments, as shown in the following
5324 ---------------------------
5325 -- This is a box comment --
5326 -- with two text lines. --
5327 ---------------------------
5332 @emph{Check end/exit labels.}
5333 If the ^letter e^word END^ appears in the string after @option{-gnaty} then
5334 optional labels on @code{end} statements ending subprograms and on
5335 @code{exit} statements exiting named loops, are required to be present.
5338 @emph{No form feeds or vertical tabs.}
5339 If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then
5340 neither form feeds nor vertical tab characters are not permitted
5344 @emph{No horizontal tabs.}
5345 If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then
5346 horizontal tab characters are not permitted in the source text.
5347 Together with the b (no blanks at end of line) check, this
5348 enforces a canonical form for the use of blanks to separate
5352 @emph{Check if-then layout.}
5353 If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty},
5354 then the keyword @code{then} must appear either on the same
5355 line as corresponding @code{if}, or on a line on its own, lined
5356 up under the @code{if} with at least one non-blank line in between
5357 containing all or part of the condition to be tested.
5360 @emph{Check keyword casing.}
5361 If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then
5362 all keywords must be in lower case (with the exception of keywords
5363 such as @code{digits} used as attribute names to which this check
5367 @emph{Check layout.}
5368 If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then
5369 layout of statement and declaration constructs must follow the
5370 recommendations in the Ada Reference Manual, as indicated by the
5371 form of the syntax rules. For example an @code{else} keyword must
5372 be lined up with the corresponding @code{if} keyword.
5374 There are two respects in which the style rule enforced by this check
5375 option are more liberal than those in the Ada Reference Manual. First
5376 in the case of record declarations, it is permissible to put the
5377 @code{record} keyword on the same line as the @code{type} keyword, and
5378 then the @code{end} in @code{end record} must line up under @code{type}.
5379 For example, either of the following two layouts is acceptable:
5381 @smallexample @c ada
5397 Second, in the case of a block statement, a permitted alternative
5398 is to put the block label on the same line as the @code{declare} or
5399 @code{begin} keyword, and then line the @code{end} keyword up under
5400 the block label. For example both the following are permitted:
5402 @smallexample @c ada
5420 The same alternative format is allowed for loops. For example, both of
5421 the following are permitted:
5423 @smallexample @c ada
5425 Clear : while J < 10 loop
5436 @item ^Lnnn^MAX_NESTING=nnn^
5437 @emph{Set maximum nesting level}
5438 If the sequence ^Lnnn^MAX_NESTING=nnn^, where nnn is a decimal number in
5439 the range 0-999, appears in the string after @option{-gnaty} then the
5440 maximum level of nesting of constructs (including subprograms, loops,
5441 blocks, packages, and conditionals) may not exceed the given value. A
5442 value of zero disconnects this style check.
5444 @item ^m^LINE_LENGTH^
5445 @emph{Check maximum line length.}
5446 If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty}
5447 then the length of source lines must not exceed 79 characters, including
5448 any trailing blanks. The value of 79 allows convenient display on an
5449 80 character wide device or window, allowing for possible special
5450 treatment of 80 character lines. Note that this count is of raw
5451 characters in the source text. This means that a tab character counts
5452 as one character in this count and a wide character sequence counts as
5453 several characters (however many are needed in the encoding).
5455 @item ^Mnnn^MAX_LENGTH=nnn^
5456 @emph{Set maximum line length.}
5457 If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in
5458 the string after @option{-gnaty} then the length of lines must not exceed the
5461 @item ^n^STANDARD_CASING^
5462 @emph{Check casing of entities in Standard.}
5463 If the ^letter n^word STANDARD_CASING^ appears in the string
5464 after @option{-gnaty} then any identifier from Standard must be cased
5465 to match the presentation in the Ada Reference Manual (for example,
5466 @code{Integer} and @code{ASCII.NUL}).
5468 @item ^o^ORDERED_SUBPROGRAMS^
5469 @emph{Check order of subprogram bodies.}
5470 If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string
5471 after @option{-gnaty} then all subprogram bodies in a given scope
5472 (e.g. a package body) must be in alphabetical order. The ordering
5473 rule uses normal Ada rules for comparing strings, ignoring casing
5474 of letters, except that if there is a trailing numeric suffix, then
5475 the value of this suffix is used in the ordering (e.g. Junk2 comes
5479 @emph{Check pragma casing.}
5480 If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then
5481 pragma names must be written in mixed case, that is, the
5482 initial letter and any letter following an underscore must be uppercase.
5483 All other letters must be lowercase.
5485 @item ^r^REFERENCES^
5486 @emph{Check references.}
5487 If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty}
5488 then all identifier references must be cased in the same way as the
5489 corresponding declaration. No specific casing style is imposed on
5490 identifiers. The only requirement is for consistency of references
5494 @emph{Check separate specs.}
5495 If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then
5496 separate declarations (``specs'') are required for subprograms (a
5497 body is not allowed to serve as its own declaration). The only
5498 exception is that parameterless library level procedures are
5499 not required to have a separate declaration. This exception covers
5500 the most frequent form of main program procedures.
5503 @emph{Check token spacing.}
5504 If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then
5505 the following token spacing rules are enforced:
5510 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
5513 The token @code{=>} must be surrounded by spaces.
5516 The token @code{<>} must be preceded by a space or a left parenthesis.
5519 Binary operators other than @code{**} must be surrounded by spaces.
5520 There is no restriction on the layout of the @code{**} binary operator.
5523 Colon must be surrounded by spaces.
5526 Colon-equal (assignment, initialization) must be surrounded by spaces.
5529 Comma must be the first non-blank character on the line, or be
5530 immediately preceded by a non-blank character, and must be followed
5534 If the token preceding a left parenthesis ends with a letter or digit, then
5535 a space must separate the two tokens.
5538 A right parenthesis must either be the first non-blank character on
5539 a line, or it must be preceded by a non-blank character.
5542 A semicolon must not be preceded by a space, and must not be followed by
5543 a non-blank character.
5546 A unary plus or minus may not be followed by a space.
5549 A vertical bar must be surrounded by spaces.
5552 @item ^x^XTRA_PARENS^
5553 @emph{Check extra parentheses.}
5554 Check for the use of an unnecessary extra level of parentheses (C-style)
5555 around conditions in @code{if} statements, @code{while} statements and
5556 @code{exit} statements.
5561 In the above rules, appearing in column one is always permitted, that is,
5562 counts as meeting either a requirement for a required preceding space,
5563 or as meeting a requirement for no preceding space.
5565 Appearing at the end of a line is also always permitted, that is, counts
5566 as meeting either a requirement for a following space, or as meeting
5567 a requirement for no following space.
5570 If any of these style rules is violated, a message is generated giving
5571 details on the violation. The initial characters of such messages are
5572 always ``@code{(style)}''. Note that these messages are treated as warning
5573 messages, so they normally do not prevent the generation of an object
5574 file. The @option{-gnatwe} switch can be used to treat warning messages,
5575 including style messages, as fatal errors.
5579 @option{-gnaty} on its own (that is not
5580 followed by any letters or digits),
5581 is equivalent to @code{gnaty3abcefhiklmprst}, that is all checking
5582 options enabled with the exception of -gnatyo,
5585 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
5586 the exception of ORDERED_SUBPROGRAMS,
5588 with an indentation level of 3. This is the standard
5589 checking option that is used for the GNAT sources.
5598 clears any previously set style checks.
5600 @node Run-Time Checks
5601 @subsection Run-Time Checks
5602 @cindex Division by zero
5603 @cindex Access before elaboration
5604 @cindex Checks, division by zero
5605 @cindex Checks, access before elaboration
5608 If you compile with the default options, GNAT will insert many run-time
5609 checks into the compiled code, including code that performs range
5610 checking against constraints, but not arithmetic overflow checking for
5611 integer operations (including division by zero) or checks for access
5612 before elaboration on subprogram calls. All other run-time checks, as
5613 required by the Ada 95 Reference Manual, are generated by default.
5614 The following @code{gcc} switches refine this default behavior:
5619 @cindex @option{-gnatp} (@code{gcc})
5620 @cindex Suppressing checks
5621 @cindex Checks, suppressing
5623 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
5624 had been present in the source. Validity checks are also suppressed (in
5625 other words @option{-gnatp} also implies @option{-gnatVn}.
5626 Use this switch to improve the performance
5627 of the code at the expense of safety in the presence of invalid data or
5631 @cindex @option{-gnato} (@code{gcc})
5632 @cindex Overflow checks
5633 @cindex Check, overflow
5634 Enables overflow checking for integer operations.
5635 This causes GNAT to generate slower and larger executable
5636 programs by adding code to check for overflow (resulting in raising
5637 @code{Constraint_Error} as required by standard Ada
5638 semantics). These overflow checks correspond to situations in which
5639 the true value of the result of an operation may be outside the base
5640 range of the result type. The following example shows the distinction:
5642 @smallexample @c ada
5643 X1 : Integer := Integer'Last;
5644 X2 : Integer range 1 .. 5 := 5;
5645 X3 : Integer := Integer'Last;
5646 X4 : Integer range 1 .. 5 := 5;
5647 F : Float := 2.0E+20;
5656 Here the first addition results in a value that is outside the base range
5657 of Integer, and hence requires an overflow check for detection of the
5658 constraint error. Thus the first assignment to @code{X1} raises a
5659 @code{Constraint_Error} exception only if @option{-gnato} is set.
5661 The second increment operation results in a violation
5662 of the explicit range constraint, and such range checks are always
5663 performed (unless specifically suppressed with a pragma @code{suppress}
5664 or the use of @option{-gnatp}).
5666 The two conversions of @code{F} both result in values that are outside
5667 the base range of type @code{Integer} and thus will raise
5668 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
5669 The fact that the result of the second conversion is assigned to
5670 variable @code{X4} with a restricted range is irrelevant, since the problem
5671 is in the conversion, not the assignment.
5673 Basically the rule is that in the default mode (@option{-gnato} not
5674 used), the generated code assures that all integer variables stay
5675 within their declared ranges, or within the base range if there is
5676 no declared range. This prevents any serious problems like indexes
5677 out of range for array operations.
5679 What is not checked in default mode is an overflow that results in
5680 an in-range, but incorrect value. In the above example, the assignments
5681 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
5682 range of the target variable, but the result is wrong in the sense that
5683 it is too large to be represented correctly. Typically the assignment
5684 to @code{X1} will result in wrap around to the largest negative number.
5685 The conversions of @code{F} will result in some @code{Integer} value
5686 and if that integer value is out of the @code{X4} range then the
5687 subsequent assignment would generate an exception.
5689 @findex Machine_Overflows
5690 Note that the @option{-gnato} switch does not affect the code generated
5691 for any floating-point operations; it applies only to integer
5693 For floating-point, GNAT has the @code{Machine_Overflows}
5694 attribute set to @code{False} and the normal mode of operation is to
5695 generate IEEE NaN and infinite values on overflow or invalid operations
5696 (such as dividing 0.0 by 0.0).
5698 The reason that we distinguish overflow checking from other kinds of
5699 range constraint checking is that a failure of an overflow check can
5700 generate an incorrect value, but cannot cause erroneous behavior. This
5701 is unlike the situation with a constraint check on an array subscript,
5702 where failure to perform the check can result in random memory description,
5703 or the range check on a case statement, where failure to perform the check
5704 can cause a wild jump.
5706 Note again that @option{-gnato} is off by default, so overflow checking is
5707 not performed in default mode. This means that out of the box, with the
5708 default settings, GNAT does not do all the checks expected from the
5709 language description in the Ada Reference Manual. If you want all constraint
5710 checks to be performed, as described in this Manual, then you must
5711 explicitly use the -gnato switch either on the @code{gnatmake} or
5715 @cindex @option{-gnatE} (@code{gcc})
5716 @cindex Elaboration checks
5717 @cindex Check, elaboration
5718 Enables dynamic checks for access-before-elaboration
5719 on subprogram calls and generic instantiations.
5720 For full details of the effect and use of this switch,
5721 @xref{Compiling Using gcc}.
5726 The setting of these switches only controls the default setting of the
5727 checks. You may modify them using either @code{Suppress} (to remove
5728 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
5731 @node Stack Overflow Checking
5732 @subsection Stack Overflow Checking
5733 @cindex Stack Overflow Checking
5734 @cindex -fstack-check
5737 For most operating systems, @code{gcc} does not perform stack overflow
5738 checking by default. This means that if the main environment task or
5739 some other task exceeds the available stack space, then unpredictable
5740 behavior will occur.
5742 To activate stack checking, compile all units with the gcc option
5743 @option{-fstack-check}. For example:
5746 gcc -c -fstack-check package1.adb
5750 Units compiled with this option will generate extra instructions to check
5751 that any use of the stack (for procedure calls or for declaring local
5752 variables in declare blocks) do not exceed the available stack space.
5753 If the space is exceeded, then a @code{Storage_Error} exception is raised.
5755 For declared tasks, the stack size is always controlled by the size
5756 given in an applicable @code{Storage_Size} pragma (or is set to
5757 the default size if no pragma is used.
5759 For the environment task, the stack size depends on
5760 system defaults and is unknown to the compiler. The stack
5761 may even dynamically grow on some systems, precluding the
5762 normal Ada semantics for stack overflow. In the worst case,
5763 unbounded stack usage, causes unbounded stack expansion
5764 resulting in the system running out of virtual memory.
5766 The stack checking may still work correctly if a fixed
5767 size stack is allocated, but this cannot be guaranteed.
5768 To ensure that a clean exception is signalled for stack
5769 overflow, set the environment variable
5770 @code{GNAT_STACK_LIMIT} to indicate the maximum
5771 stack area that can be used, as in:
5772 @cindex GNAT_STACK_LIMIT
5775 SET GNAT_STACK_LIMIT 1600
5779 The limit is given in kilobytes, so the above declaration would
5780 set the stack limit of the environment task to 1.6 megabytes.
5781 Note that the only purpose of this usage is to limit the amount
5782 of stack used by the environment task. If it is necessary to
5783 increase the amount of stack for the environment task, then this
5784 is an operating systems issue, and must be addressed with the
5785 appropriate operating systems commands.
5787 @node Using gcc for Syntax Checking
5788 @subsection Using @code{gcc} for Syntax Checking
5791 @cindex @option{-gnats} (@code{gcc})
5795 The @code{s} stands for ``syntax''.
5798 Run GNAT in syntax checking only mode. For
5799 example, the command
5802 $ gcc -c -gnats x.adb
5806 compiles file @file{x.adb} in syntax-check-only mode. You can check a
5807 series of files in a single command
5809 , and can use wild cards to specify such a group of files.
5810 Note that you must specify the @option{-c} (compile
5811 only) flag in addition to the @option{-gnats} flag.
5814 You may use other switches in conjunction with @option{-gnats}. In
5815 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
5816 format of any generated error messages.
5818 When the source file is empty or contains only empty lines and/or comments,
5819 the output is a warning:
5822 $ gcc -c -gnats -x ada toto.txt
5823 toto.txt:1:01: warning: empty file, contains no compilation units
5827 Otherwise, the output is simply the error messages, if any. No object file or
5828 ALI file is generated by a syntax-only compilation. Also, no units other
5829 than the one specified are accessed. For example, if a unit @code{X}
5830 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
5831 check only mode does not access the source file containing unit
5834 @cindex Multiple units, syntax checking
5835 Normally, GNAT allows only a single unit in a source file. However, this
5836 restriction does not apply in syntax-check-only mode, and it is possible
5837 to check a file containing multiple compilation units concatenated
5838 together. This is primarily used by the @code{gnatchop} utility
5839 (@pxref{Renaming Files Using gnatchop}).
5842 @node Using gcc for Semantic Checking
5843 @subsection Using @code{gcc} for Semantic Checking
5846 @cindex @option{-gnatc} (@code{gcc})
5850 The @code{c} stands for ``check''.
5852 Causes the compiler to operate in semantic check mode,
5853 with full checking for all illegalities specified in the
5854 Ada 95 Reference Manual, but without generation of any object code
5855 (no object file is generated).
5857 Because dependent files must be accessed, you must follow the GNAT
5858 semantic restrictions on file structuring to operate in this mode:
5862 The needed source files must be accessible
5863 (@pxref{Search Paths and the Run-Time Library (RTL)}).
5866 Each file must contain only one compilation unit.
5869 The file name and unit name must match (@pxref{File Naming Rules}).
5872 The output consists of error messages as appropriate. No object file is
5873 generated. An @file{ALI} file is generated for use in the context of
5874 cross-reference tools, but this file is marked as not being suitable
5875 for binding (since no object file is generated).
5876 The checking corresponds exactly to the notion of
5877 legality in the Ada 95 Reference Manual.
5879 Any unit can be compiled in semantics-checking-only mode, including
5880 units that would not normally be compiled (subunits,
5881 and specifications where a separate body is present).
5884 @node Compiling Ada 83 Programs
5885 @subsection Compiling Ada 83 Programs
5887 @cindex Ada 83 compatibility
5889 @cindex @option{-gnat83} (@code{gcc})
5890 @cindex ACVC, Ada 83 tests
5893 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
5894 specify that an Ada 83 program is to be compiled in Ada 83 mode. If you specify
5895 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
5896 where this can be done easily.
5897 It is not possible to guarantee this switch does a perfect
5898 job; for example, some subtle tests, such as are
5899 found in earlier ACVC tests (and that have been removed from the ACATS suite
5900 for Ada 95), might not compile correctly.
5901 Nevertheless, this switch may be useful in some circumstances, for example
5902 where, due to contractual reasons, legacy code needs to be maintained
5903 using only Ada 83 features.
5905 With few exceptions (most notably the need to use @code{<>} on
5906 @cindex Generic formal parameters
5907 unconstrained generic formal parameters, the use of the new Ada 95
5908 reserved words, and the use of packages
5909 with optional bodies), it is not necessary to use the
5910 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
5911 exceptions, Ada 95 is upwardly compatible with Ada 83. This
5912 means that a correct Ada 83 program is usually also a correct Ada 95
5914 For further information, please refer to @ref{Compatibility and Porting Guide}.
5918 @node Character Set Control
5919 @subsection Character Set Control
5921 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
5922 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@code{gcc})
5925 Normally GNAT recognizes the Latin-1 character set in source program
5926 identifiers, as described in the Ada 95 Reference Manual.
5928 GNAT to recognize alternate character sets in identifiers. @var{c} is a
5929 single character ^^or word^ indicating the character set, as follows:
5933 ISO 8859-1 (Latin-1) identifiers
5936 ISO 8859-2 (Latin-2) letters allowed in identifiers
5939 ISO 8859-3 (Latin-3) letters allowed in identifiers
5942 ISO 8859-4 (Latin-4) letters allowed in identifiers
5945 ISO 8859-5 (Cyrillic) letters allowed in identifiers
5948 ISO 8859-15 (Latin-9) letters allowed in identifiers
5951 IBM PC letters (code page 437) allowed in identifiers
5954 IBM PC letters (code page 850) allowed in identifiers
5956 @item ^f^FULL_UPPER^
5957 Full upper-half codes allowed in identifiers
5960 No upper-half codes allowed in identifiers
5963 Wide-character codes (that is, codes greater than 255)
5964 allowed in identifiers
5967 @xref{Foreign Language Representation}, for full details on the
5968 implementation of these character sets.
5970 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
5971 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@code{gcc})
5972 Specify the method of encoding for wide characters.
5973 @var{e} is one of the following:
5978 Hex encoding (brackets coding also recognized)
5981 Upper half encoding (brackets encoding also recognized)
5984 Shift/JIS encoding (brackets encoding also recognized)
5987 EUC encoding (brackets encoding also recognized)
5990 UTF-8 encoding (brackets encoding also recognized)
5993 Brackets encoding only (default value)
5995 For full details on the these encoding
5996 methods see @xref{Wide Character Encodings}.
5997 Note that brackets coding is always accepted, even if one of the other
5998 options is specified, so for example @option{-gnatW8} specifies that both
5999 brackets and @code{UTF-8} encodings will be recognized. The units that are
6000 with'ed directly or indirectly will be scanned using the specified
6001 representation scheme, and so if one of the non-brackets scheme is
6002 used, it must be used consistently throughout the program. However,
6003 since brackets encoding is always recognized, it may be conveniently
6004 used in standard libraries, allowing these libraries to be used with
6005 any of the available coding schemes.
6006 scheme. If no @option{-gnatW?} parameter is present, then the default
6007 representation is Brackets encoding only.
6009 Note that the wide character representation that is specified (explicitly
6010 or by default) for the main program also acts as the default encoding used
6011 for Wide_Text_IO files if not specifically overridden by a WCEM form
6015 @node File Naming Control
6016 @subsection File Naming Control
6019 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6020 @cindex @option{-gnatk} (@code{gcc})
6021 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6022 1-999, indicates the maximum allowable length of a file name (not
6023 including the @file{.ads} or @file{.adb} extension). The default is not
6024 to enable file name krunching.
6026 For the source file naming rules, @xref{File Naming Rules}.
6029 @node Subprogram Inlining Control
6030 @subsection Subprogram Inlining Control
6035 @cindex @option{-gnatn} (@code{gcc})
6037 The @code{n} here is intended to suggest the first syllable of the
6040 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6041 inlining to actually occur, optimization must be enabled. To enable
6042 inlining of subprograms specified by pragma @code{Inline},
6043 you must also specify this switch.
6044 In the absence of this switch, GNAT does not attempt
6045 inlining and does not need to access the bodies of
6046 subprograms for which @code{pragma Inline} is specified if they are not
6047 in the current unit.
6049 If you specify this switch the compiler will access these bodies,
6050 creating an extra source dependency for the resulting object file, and
6051 where possible, the call will be inlined.
6052 For further details on when inlining is possible
6053 see @xref{Inlining of Subprograms}.
6056 @cindex @option{-gnatN} (@code{gcc})
6057 The front end inlining activated by this switch is generally more extensive,
6058 and quite often more effective than the standard @option{-gnatn} inlining mode.
6059 It will also generate additional dependencies.
6061 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
6062 to specify both options.
6065 @node Auxiliary Output Control
6066 @subsection Auxiliary Output Control
6070 @cindex @option{-gnatt} (@code{gcc})
6071 @cindex Writing internal trees
6072 @cindex Internal trees, writing to file
6073 Causes GNAT to write the internal tree for a unit to a file (with the
6074 extension @file{.adt}.
6075 This not normally required, but is used by separate analysis tools.
6077 these tools do the necessary compilations automatically, so you should
6078 not have to specify this switch in normal operation.
6081 @cindex @option{-gnatu} (@code{gcc})
6082 Print a list of units required by this compilation on @file{stdout}.
6083 The listing includes all units on which the unit being compiled depends
6084 either directly or indirectly.
6087 @item -pass-exit-codes
6088 @cindex @option{-pass-exit-codes} (@code{gcc})
6089 If this switch is not used, the exit code returned by @code{gcc} when
6090 compiling multiple files indicates whether all source files have
6091 been successfully used to generate object files or not.
6093 When @option{-pass-exit-codes} is used, @code{gcc} exits with an extended
6094 exit status and allows an integrated development environment to better
6095 react to a compilation failure. Those exit status are:
6099 There was an error in at least one source file.
6101 At least one source file did not generate an object file.
6103 The compiler died unexpectedly (internal error for example).
6105 An object file has been generated for every source file.
6110 @node Debugging Control
6111 @subsection Debugging Control
6115 @cindex Debugging options
6118 @cindex @option{-gnatd} (@code{gcc})
6119 Activate internal debugging switches. @var{x} is a letter or digit, or
6120 string of letters or digits, which specifies the type of debugging
6121 outputs desired. Normally these are used only for internal development
6122 or system debugging purposes. You can find full documentation for these
6123 switches in the body of the @code{Debug} unit in the compiler source
6124 file @file{debug.adb}.
6128 @cindex @option{-gnatG} (@code{gcc})
6129 This switch causes the compiler to generate auxiliary output containing
6130 a pseudo-source listing of the generated expanded code. Like most Ada
6131 compilers, GNAT works by first transforming the high level Ada code into
6132 lower level constructs. For example, tasking operations are transformed
6133 into calls to the tasking run-time routines. A unique capability of GNAT
6134 is to list this expanded code in a form very close to normal Ada source.
6135 This is very useful in understanding the implications of various Ada
6136 usage on the efficiency of the generated code. There are many cases in
6137 Ada (e.g. the use of controlled types), where simple Ada statements can
6138 generate a lot of run-time code. By using @option{-gnatG} you can identify
6139 these cases, and consider whether it may be desirable to modify the coding
6140 approach to improve efficiency.
6142 The format of the output is very similar to standard Ada source, and is
6143 easily understood by an Ada programmer. The following special syntactic
6144 additions correspond to low level features used in the generated code that
6145 do not have any exact analogies in pure Ada source form. The following
6146 is a partial list of these special constructions. See the specification
6147 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6150 @item new @var{xxx} [storage_pool = @var{yyy}]
6151 Shows the storage pool being used for an allocator.
6153 @item at end @var{procedure-name};
6154 Shows the finalization (cleanup) procedure for a scope.
6156 @item (if @var{expr} then @var{expr} else @var{expr})
6157 Conditional expression equivalent to the @code{x?y:z} construction in C.
6159 @item @var{target}^^^(@var{source})
6160 A conversion with floating-point truncation instead of rounding.
6162 @item @var{target}?(@var{source})
6163 A conversion that bypasses normal Ada semantic checking. In particular
6164 enumeration types and fixed-point types are treated simply as integers.
6166 @item @var{target}?^^^(@var{source})
6167 Combines the above two cases.
6169 @item @var{x} #/ @var{y}
6170 @itemx @var{x} #mod @var{y}
6171 @itemx @var{x} #* @var{y}
6172 @itemx @var{x} #rem @var{y}
6173 A division or multiplication of fixed-point values which are treated as
6174 integers without any kind of scaling.
6176 @item free @var{expr} [storage_pool = @var{xxx}]
6177 Shows the storage pool associated with a @code{free} statement.
6179 @item freeze @var{typename} [@var{actions}]
6180 Shows the point at which @var{typename} is frozen, with possible
6181 associated actions to be performed at the freeze point.
6183 @item reference @var{itype}
6184 Reference (and hence definition) to internal type @var{itype}.
6186 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6187 Intrinsic function call.
6189 @item @var{labelname} : label
6190 Declaration of label @var{labelname}.
6192 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
6193 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6194 @var{expr}, but handled more efficiently).
6196 @item [constraint_error]
6197 Raise the @code{Constraint_Error} exception.
6199 @item @var{expression}'reference
6200 A pointer to the result of evaluating @var{expression}.
6202 @item @var{target-type}!(@var{source-expression})
6203 An unchecked conversion of @var{source-expression} to @var{target-type}.
6205 @item [@var{numerator}/@var{denominator}]
6206 Used to represent internal real literals (that) have no exact
6207 representation in base 2-16 (for example, the result of compile time
6208 evaluation of the expression 1.0/27.0).
6212 @cindex @option{-gnatD} (@code{gcc})
6213 When used in conjunction with @option{-gnatG}, this switch causes
6214 the expanded source, as described above for
6215 @option{-gnatG} to be written to files with names
6216 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6217 instead of to the standard ooutput file. For
6218 example, if the source file name is @file{hello.adb}, then a file
6219 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written. The debugging
6220 information generated by the @code{gcc} @option{^-g^/DEBUG^} switch
6221 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6222 you to do source level debugging using the generated code which is
6223 sometimes useful for complex code, for example to find out exactly
6224 which part of a complex construction raised an exception. This switch
6225 also suppress generation of cross-reference information (see
6226 @option{-gnatx}) since otherwise the cross-reference information
6227 would refer to the @file{^.dg^.DG^} file, which would cause
6228 confusion since this is not the original source file.
6230 Note that @option{-gnatD} actually implies @option{-gnatG}
6231 automatically, so it is not necessary to give both options.
6232 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6235 @item -gnatR[0|1|2|3[s]]
6236 @cindex @option{-gnatR} (@code{gcc})
6237 This switch controls output from the compiler of a listing showing
6238 representation information for declared types and objects. For
6239 @option{-gnatR0}, no information is output (equivalent to omitting
6240 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6241 so @option{-gnatR} with no parameter has the same effect), size and alignment
6242 information is listed for declared array and record types. For
6243 @option{-gnatR2}, size and alignment information is listed for all
6244 expression information for values that are computed at run time for
6245 variant records. These symbolic expressions have a mostly obvious
6246 format with #n being used to represent the value of the n'th
6247 discriminant. See source files @file{repinfo.ads/adb} in the
6248 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6249 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
6250 the output is to a file with the name @file{^file.rep^file_REP^} where
6251 file is the name of the corresponding source file.
6254 @item /REPRESENTATION_INFO
6255 @cindex @option{/REPRESENTATION_INFO} (@code{gcc})
6256 This qualifier controls output from the compiler of a listing showing
6257 representation information for declared types and objects. For
6258 @option{/REPRESENTATION_INFO=NONE}, no information is output
6259 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6260 @option{/REPRESENTATION_INFO} without option is equivalent to
6261 @option{/REPRESENTATION_INFO=ARRAYS}.
6262 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6263 information is listed for declared array and record types. For
6264 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6265 is listed for all expression information for values that are computed
6266 at run time for variant records. These symbolic expressions have a mostly
6267 obvious format with #n being used to represent the value of the n'th
6268 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6269 @code{GNAT} sources for full details on the format of
6270 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6271 If _FILE is added at the end of an option
6272 (e.g. @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6273 then the output is to a file with the name @file{file_REP} where
6274 file is the name of the corresponding source file.
6278 @cindex @option{-gnatS} (@code{gcc})
6279 The use of the switch @option{-gnatS} for an
6280 Ada compilation will cause the compiler to output a
6281 representation of package Standard in a form very
6282 close to standard Ada. It is not quite possible to
6283 do this entirely in standard Ada (since new
6284 numeric base types cannot be created in standard
6285 Ada), but the output is easily
6286 readable to any Ada programmer, and is useful to
6287 determine the characteristics of target dependent
6288 types in package Standard.
6291 @cindex @option{-gnatx} (@code{gcc})
6292 Normally the compiler generates full cross-referencing information in
6293 the @file{ALI} file. This information is used by a number of tools,
6294 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
6295 suppresses this information. This saves some space and may slightly
6296 speed up compilation, but means that these tools cannot be used.
6299 @node Exception Handling Control
6300 @subsection Exception Handling Control
6303 GNAT uses two methods for handling exceptions at run-time. The
6304 @code{longjmp/setjmp} method saves the context when entering
6305 a frame with an exception handler. Then when an exception is
6306 raised, the context can be restored immediately, without the
6307 need for tracing stack frames. This method provides very fast
6308 exception propagation, but introduces significant overhead for
6309 the use of exception handlers, even if no exception is raised.
6311 The other approach is called ``zero cost'' exception handling.
6312 With this method, the compiler builds static tables to describe
6313 the exception ranges. No dynamic code is required when entering
6314 a frame containing an exception handler. When an exception is
6315 raised, the tables are used to control a back trace of the
6316 subprogram invocation stack to locate the required exception
6317 handler. This method has considerably poorer performance for
6318 the propagation of exceptions, but there is no overhead for
6319 exception handlers if no exception is raised.
6321 The following switches can be used to control which of the
6322 two exception handling methods is used.
6328 @cindex @option{-gnatL} (@code{gcc})
6329 This switch causes the longjmp/setjmp approach to be used
6330 for exception handling. If this is the default mechanism for the
6331 target (see below), then this has no effect. If the default
6332 mechanism for the target is zero cost exceptions, then
6333 this switch can be used to modify this default, but it must be
6334 used for all units in the partition, including all run-time
6335 library units. One way to achieve this is to use the
6336 @option{-a} and @option{-f} switches for @code{gnatmake}.
6337 This option is rarely used. One case in which it may be
6338 advantageous is if you have an application where exception
6339 raising is common and the overall performance of the
6340 application is improved by favoring exception propagation.
6343 @cindex @option{-gnatZ} (@code{gcc})
6344 @cindex Zero Cost Exceptions
6345 This switch causes the zero cost approach to be sed
6346 for exception handling. If this is the default mechanism for the
6347 target (see below), then this has no effect. If the default
6348 mechanism for the target is longjmp/setjmp exceptions, then
6349 this switch can be used to modify this default, but it must be
6350 used for all units in the partition, including all run-time
6351 library units. One way to achieve this is to use the
6352 @option{-a} and @option{-f} switches for @code{gnatmake}.
6353 This option can only be used if the zero cost approach
6354 is available for the target in use (see below).
6358 The @code{longjmp/setjmp} approach is available on all targets, but
6359 the @code{zero cost} approach is only available on selected targets.
6360 To determine whether zero cost exceptions can be used for a
6361 particular target, look at the private part of the file system.ads.
6362 Either @code{GCC_ZCX_Support} or @code{Front_End_ZCX_Support} must
6363 be True to use the zero cost approach. If both of these switches
6364 are set to False, this means that zero cost exception handling
6365 is not yet available for that target. The switch
6366 @code{ZCX_By_Default} indicates the default approach. If this
6367 switch is set to True, then the @code{zero cost} approach is
6370 @node Units to Sources Mapping Files
6371 @subsection Units to Sources Mapping Files
6375 @item -gnatem^^=^@var{path}
6376 @cindex @option{-gnatem} (@code{gcc})
6377 A mapping file is a way to communicate to the compiler two mappings:
6378 from unit names to file names (without any directory information) and from
6379 file names to path names (with full directory information). These mappings
6380 are used by the compiler to short-circuit the path search.
6382 The use of mapping files is not required for correct operation of the
6383 compiler, but mapping files can improve efficiency, particularly when
6384 sources are read over a slow network connection. In normal operation,
6385 you need not be concerned with the format or use of mapping files,
6386 and the @option{-gnatem} switch is not a switch that you would use
6387 explicitly. it is intended only for use by automatic tools such as
6388 @code{gnatmake} running under the project file facility. The
6389 description here of the format of mapping files is provided
6390 for completeness and for possible use by other tools.
6392 A mapping file is a sequence of sets of three lines. In each set,
6393 the first line is the unit name, in lower case, with ``@code{%s}''
6395 specifications and ``@code{%b}'' appended for bodies; the second line is the
6396 file name; and the third line is the path name.
6402 /gnat/project1/sources/main.2.ada
6405 When the switch @option{-gnatem} is specified, the compiler will create
6406 in memory the two mappings from the specified file. If there is any problem
6407 (non existent file, truncated file or duplicate entries), no mapping
6410 Several @option{-gnatem} switches may be specified; however, only the last
6411 one on the command line will be taken into account.
6413 When using a project file, @code{gnatmake} create a temporary mapping file
6414 and communicates it to the compiler using this switch.
6418 @node Integrated Preprocessing
6419 @subsection Integrated Preprocessing
6422 GNAT sources may be preprocessed immediately before compilation; the actual
6423 text of the source is not the text of the source file, but is derived from it
6424 through a process called preprocessing. Integrated preprocessing is specified
6425 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
6426 indicates, through a text file, the preprocessing data to be used.
6427 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
6430 It is recommended that @code{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
6431 used when Integrated Preprocessing is used. The reason is that preprocessing
6432 with another Preprocessing Data file without changing the sources will
6433 not trigger recompilation without this switch.
6436 Note that @code{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
6437 always trigger recompilation for sources that are preprocessed,
6438 because @code{gnatmake} cannot compute the checksum of the source after
6442 The actual preprocessing function is described in details in section
6443 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
6444 preprocessing is triggered and parameterized.
6448 @item -gnatep=@var{file}
6449 @cindex @option{-gnatep} (@code{gcc})
6450 This switch indicates to the compiler the file name (without directory
6451 information) of the preprocessor data file to use. The preprocessor data file
6452 should be found in the source directories.
6455 A preprocessing data file is a text file with significant lines indicating
6456 how should be preprocessed either a specific source or all sources not
6457 mentioned in other lines. A significant line is a non empty, non comment line.
6458 Comments are similar to Ada comments.
6461 Each significant line starts with either a literal string or the character '*'.
6462 A literal string is the file name (without directory information) of the source
6463 to preprocess. A character '*' indicates the preprocessing for all the sources
6464 that are not specified explicitly on other lines (order of the lines is not
6465 significant). It is an error to have two lines with the same file name or two
6466 lines starting with the character '*'.
6469 After the file name or the character '*', another optional literal string
6470 indicating the file name of the definition file to be used for preprocessing.
6471 (see @ref{Form of Definitions File}. The definition files are found by the
6472 compiler in one of the source directories. In some cases, when compiling
6473 a source in a directory other than the current directory, if the definition
6474 file is in the current directory, it may be necessary to add the current
6475 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
6476 the compiler would not find the definition file.
6479 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
6480 be found. Those ^switches^switches^ are:
6485 Causes both preprocessor lines and the lines deleted by
6486 preprocessing to be replaced by blank lines, preserving the line number.
6487 This ^switch^switch^ is always implied; however, if specified after @option{-c}
6488 it cancels the effect of @option{-c}.
6491 Causes both preprocessor lines and the lines deleted
6492 by preprocessing to be retained as comments marked
6493 with the special string ``@code{--! }''.
6495 @item -Dsymbol=value
6496 Define or redefine a symbol, associated with value. A symbol is an Ada
6497 identifier, or an Ada reserved word, with the exception of @code{if},
6498 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6499 @code{value} is either a literal string, an Ada identifier or any Ada reserved
6500 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
6501 same name defined in a definition file.
6504 Causes a sorted list of symbol names and values to be
6505 listed on the standard output file.
6508 Causes undefined symbols to be treated as having the value @code{FALSE}
6510 of a preprocessor test. In the absence of this option, an undefined symbol in
6511 a @code{#if} or @code{#elsif} test will be treated as an error.
6516 Examples of valid lines in a preprocessor data file:
6519 "toto.adb" "prep.def" -u
6520 -- preprocess "toto.adb", using definition file "prep.def",
6521 -- undefined symbol are False.
6524 -- preprocess all other sources without a definition file;
6525 -- suppressed lined are commented; symbol VERSION has the value V101.
6527 "titi.adb" "prep2.def" -s
6528 -- preprocess "titi.adb", using definition file "prep2.def";
6529 -- list all symbols with their values.
6532 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
6533 @cindex @option{-gnateD} (@code{gcc})
6534 Define or redefine a preprocessing symbol, associated with value. If no value
6535 is given on the command line, then the value of the symbol is @code{True}.
6536 A symbol is an identifier, following normal Ada (case-insensitive)
6537 rules for its syntax, and value is any sequence (including an empty sequence)
6538 of characters from the set (letters, digits, period, underline).
6539 Ada reserved words may be used as symbols, with the exceptions of @code{if},
6540 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6543 A symbol declared with this ^switch^switch^ on the command line replaces a
6544 symbol with the same name either in a definition file or specified with a
6545 ^switch^switch^ -D in the preprocessor data file.
6548 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
6552 @node Code Generation Control
6553 @subsection Code Generation Control
6557 The GCC technology provides a wide range of target dependent
6558 @option{-m} switches for controlling
6559 details of code generation with respect to different versions of
6560 architectures. This includes variations in instruction sets (e.g.
6561 different members of the power pc family), and different requirements
6562 for optimal arrangement of instructions (e.g. different members of
6563 the x86 family). The list of available @option{-m} switches may be
6564 found in the GCC documentation.
6566 Use of the these @option{-m} switches may in some cases result in improved
6569 The GNAT Pro technology is tested and qualified without any
6570 @option{-m} switches,
6571 so generally the most reliable approach is to avoid the use of these
6572 switches. However, we generally expect most of these switches to work
6573 successfully with GNAT Pro, and many customers have reported successful
6574 use of these options.
6576 Our general advice is to avoid the use of @option{-m} switches unless
6577 special needs lead to requirements in this area. In particular,
6578 there is no point in using @option{-m} switches to improve performance
6579 unless you actually see a performance improvement.
6583 @subsection Return Codes
6584 @cindex Return Codes
6585 @cindex @option{/RETURN_CODES=VMS}
6588 On VMS, GNAT compiled programs return POSIX-style codes by default,
6589 e.g. @option{/RETURN_CODES=POSIX}.
6591 To enable VMS style return codes, GNAT LINK with the option
6592 @option{/RETURN_CODES=VMS}. For example:
6595 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
6599 Programs built with /RETURN_CODES=VMS are suitable to be called in
6600 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
6601 are suitable for spawning with appropriate GNAT RTL routines.
6605 @node Search Paths and the Run-Time Library (RTL)
6606 @section Search Paths and the Run-Time Library (RTL)
6609 With the GNAT source-based library system, the compiler must be able to
6610 find source files for units that are needed by the unit being compiled.
6611 Search paths are used to guide this process.
6613 The compiler compiles one source file whose name must be given
6614 explicitly on the command line. In other words, no searching is done
6615 for this file. To find all other source files that are needed (the most
6616 common being the specs of units), the compiler examines the following
6617 directories, in the following order:
6621 The directory containing the source file of the main unit being compiled
6622 (the file name on the command line).
6625 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
6626 @code{gcc} command line, in the order given.
6629 @findex ADA_INCLUDE_PATH
6630 Each of the directories listed in the value of the
6631 @code{ADA_INCLUDE_PATH} ^environment variable^logical name^.
6633 Construct this value
6634 exactly as the @code{PATH} environment variable: a list of directory
6635 names separated by colons (semicolons when working with the NT version).
6638 Normally, define this value as a logical name containing a comma separated
6639 list of directory names.
6641 This variable can also be defined by means of an environment string
6642 (an argument to the DEC C exec* set of functions).
6646 DEFINE ANOTHER_PATH FOO:[BAG]
6647 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
6650 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
6651 first, followed by the standard Ada 95
6652 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
6653 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
6654 (Text_IO, Sequential_IO, etc)
6655 instead of the Ada95 packages. Thus, in order to get the Ada 95
6656 packages by default, ADA_INCLUDE_PATH must be redefined.
6660 @findex ADA_PRJ_INCLUDE_FILE
6661 Each of the directories listed in the text file whose name is given
6662 by the @code{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
6665 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
6666 driver when project files are used. It should not normally be set
6670 The content of the @file{ada_source_path} file which is part of the GNAT
6671 installation tree and is used to store standard libraries such as the
6672 GNAT Run Time Library (RTL) source files.
6674 @ref{Installing a library}
6679 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
6680 inhibits the use of the directory
6681 containing the source file named in the command line. You can still
6682 have this directory on your search path, but in this case it must be
6683 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
6685 Specifying the switch @option{-nostdinc}
6686 inhibits the search of the default location for the GNAT Run Time
6687 Library (RTL) source files.
6689 The compiler outputs its object files and ALI files in the current
6692 Caution: The object file can be redirected with the @option{-o} switch;
6693 however, @code{gcc} and @code{gnat1} have not been coordinated on this
6694 so the @file{ALI} file will not go to the right place. Therefore, you should
6695 avoid using the @option{-o} switch.
6699 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
6700 children make up the GNAT RTL, together with the simple @code{System.IO}
6701 package used in the @code{"Hello World"} example. The sources for these units
6702 are needed by the compiler and are kept together in one directory. Not
6703 all of the bodies are needed, but all of the sources are kept together
6704 anyway. In a normal installation, you need not specify these directory
6705 names when compiling or binding. Either the environment variables or
6706 the built-in defaults cause these files to be found.
6708 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
6709 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
6710 consisting of child units of @code{GNAT}. This is a collection of generally
6711 useful types, subprograms, etc. See the @cite{GNAT Reference Manual} for
6714 Besides simplifying access to the RTL, a major use of search paths is
6715 in compiling sources from multiple directories. This can make
6716 development environments much more flexible.
6718 @node Order of Compilation Issues
6719 @section Order of Compilation Issues
6722 If, in our earlier example, there was a spec for the @code{hello}
6723 procedure, it would be contained in the file @file{hello.ads}; yet this
6724 file would not have to be explicitly compiled. This is the result of the
6725 model we chose to implement library management. Some of the consequences
6726 of this model are as follows:
6730 There is no point in compiling specs (except for package
6731 specs with no bodies) because these are compiled as needed by clients. If
6732 you attempt a useless compilation, you will receive an error message.
6733 It is also useless to compile subunits because they are compiled as needed
6737 There are no order of compilation requirements: performing a
6738 compilation never obsoletes anything. The only way you can obsolete
6739 something and require recompilations is to modify one of the
6740 source files on which it depends.
6743 There is no library as such, apart from the ALI files
6744 (@pxref{The Ada Library Information Files}, for information on the format
6745 of these files). For now we find it convenient to create separate ALI files,
6746 but eventually the information therein may be incorporated into the object
6750 When you compile a unit, the source files for the specs of all units
6751 that it @code{with}'s, all its subunits, and the bodies of any generics it
6752 instantiates must be available (reachable by the search-paths mechanism
6753 described above), or you will receive a fatal error message.
6760 The following are some typical Ada compilation command line examples:
6763 @item $ gcc -c xyz.adb
6764 Compile body in file @file{xyz.adb} with all default options.
6767 @item $ gcc -c -O2 -gnata xyz-def.adb
6770 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
6773 Compile the child unit package in file @file{xyz-def.adb} with extensive
6774 optimizations, and pragma @code{Assert}/@code{Debug} statements
6777 @item $ gcc -c -gnatc abc-def.adb
6778 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
6782 @node Binding Using gnatbind
6783 @chapter Binding Using @code{gnatbind}
6787 * Running gnatbind::
6788 * Switches for gnatbind::
6789 * Command-Line Access::
6790 * Search Paths for gnatbind::
6791 * Examples of gnatbind Usage::
6795 This chapter describes the GNAT binder, @code{gnatbind}, which is used
6796 to bind compiled GNAT objects. The @code{gnatbind} program performs
6797 four separate functions:
6801 Checks that a program is consistent, in accordance with the rules in
6802 Chapter 10 of the Ada 95 Reference Manual. In particular, error
6803 messages are generated if a program uses inconsistent versions of a
6807 Checks that an acceptable order of elaboration exists for the program
6808 and issues an error message if it cannot find an order of elaboration
6809 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
6812 Generates a main program incorporating the given elaboration order.
6813 This program is a small Ada package (body and spec) that
6814 must be subsequently compiled
6815 using the GNAT compiler. The necessary compilation step is usually
6816 performed automatically by @code{gnatlink}. The two most important
6817 functions of this program
6818 are to call the elaboration routines of units in an appropriate order
6819 and to call the main program.
6822 Determines the set of object files required by the given main program.
6823 This information is output in the forms of comments in the generated program,
6824 to be read by the @code{gnatlink} utility used to link the Ada application.
6827 @node Running gnatbind
6828 @section Running @code{gnatbind}
6831 The form of the @code{gnatbind} command is
6834 $ gnatbind [@i{switches}] @i{mainprog}[.ali] [@i{switches}]
6838 where @file{@i{mainprog}.adb} is the Ada file containing the main program
6839 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
6840 package in two files whose names are
6841 @file{b~@i{mainprog}.ads}, and @file{b~@i{mainprog}.adb}.
6842 For example, if given the
6843 parameter @file{hello.ali}, for a main program contained in file
6844 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
6845 and @file{b~hello.adb}.
6847 When doing consistency checking, the binder takes into consideration
6848 any source files it can locate. For example, if the binder determines
6849 that the given main program requires the package @code{Pack}, whose
6851 file is @file{pack.ali} and whose corresponding source spec file is
6852 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
6853 (using the same search path conventions as previously described for the
6854 @code{gcc} command). If it can locate this source file, it checks that
6856 or source checksums of the source and its references to in @file{ALI} files
6857 match. In other words, any @file{ALI} files that mentions this spec must have
6858 resulted from compiling this version of the source file (or in the case
6859 where the source checksums match, a version close enough that the
6860 difference does not matter).
6862 @cindex Source files, use by binder
6863 The effect of this consistency checking, which includes source files, is
6864 that the binder ensures that the program is consistent with the latest
6865 version of the source files that can be located at bind time. Editing a
6866 source file without compiling files that depend on the source file cause
6867 error messages to be generated by the binder.
6869 For example, suppose you have a main program @file{hello.adb} and a
6870 package @code{P}, from file @file{p.ads} and you perform the following
6875 Enter @code{gcc -c hello.adb} to compile the main program.
6878 Enter @code{gcc -c p.ads} to compile package @code{P}.
6881 Edit file @file{p.ads}.
6884 Enter @code{gnatbind hello}.
6888 At this point, the file @file{p.ali} contains an out-of-date time stamp
6889 because the file @file{p.ads} has been edited. The attempt at binding
6890 fails, and the binder generates the following error messages:
6893 error: "hello.adb" must be recompiled ("p.ads" has been modified)
6894 error: "p.ads" has been modified and must be recompiled
6898 Now both files must be recompiled as indicated, and then the bind can
6899 succeed, generating a main program. You need not normally be concerned
6900 with the contents of this file, but for reference purposes a sample
6901 binder output file is given in @ref{Example of Binder Output File}.
6903 In most normal usage, the default mode of @command{gnatbind} which is to
6904 generate the main package in Ada, as described in the previous section.
6905 In particular, this means that any Ada programmer can read and understand
6906 the generated main program. It can also be debugged just like any other
6907 Ada code provided the @option{^-g^/DEBUG^} switch is used for
6908 @command{gnatbind} and @command{gnatlink}.
6910 However for some purposes it may be convenient to generate the main
6911 program in C rather than Ada. This may for example be helpful when you
6912 are generating a mixed language program with the main program in C. The
6913 GNAT compiler itself is an example.
6914 The use of the @option{^-C^/BIND_FILE=C^} switch
6915 for both @code{gnatbind} and @code{gnatlink} will cause the program to
6916 be generated in C (and compiled using the gnu C compiler).
6918 @node Switches for gnatbind
6919 @section Switches for @command{gnatbind}
6922 The following switches are available with @code{gnatbind}; details will
6923 be presented in subsequent sections.
6926 * Consistency-Checking Modes::
6927 * Binder Error Message Control::
6928 * Elaboration Control::
6930 * Binding with Non-Ada Main Programs::
6931 * Binding Programs with No Main Subprogram::
6936 @item ^-aO^/OBJECT_SEARCH^
6937 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
6938 Specify directory to be searched for ALI files.
6940 @item ^-aI^/SOURCE_SEARCH^
6941 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
6942 Specify directory to be searched for source file.
6944 @item ^-A^/BIND_FILE=ADA^
6945 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
6946 Generate binder program in Ada (default)
6948 @item ^-b^/REPORT_ERRORS=BRIEF^
6949 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
6950 Generate brief messages to @file{stderr} even if verbose mode set.
6952 @item ^-c^/NOOUTPUT^
6953 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
6954 Check only, no generation of binder output file.
6956 @item ^-C^/BIND_FILE=C^
6957 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
6958 Generate binder program in C
6960 @item ^-e^/ELABORATION_DEPENDENCIES^
6961 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
6962 Output complete list of elaboration-order dependencies.
6964 @item ^-E^/STORE_TRACEBACKS^
6965 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
6966 Store tracebacks in exception occurrences when the target supports it.
6967 This is the default with the zero cost exception mechanism.
6969 @c The following may get moved to an appendix
6970 This option is currently supported on the following targets:
6971 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
6973 See also the packages @code{GNAT.Traceback} and
6974 @code{GNAT.Traceback.Symbolic} for more information.
6976 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
6980 @item ^-F^/FORCE_ELABS_FLAGS^
6981 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
6982 Force the checks of elaboration flags. @command{gnatbind} does not normally
6983 generate checks of elaboration flags for the main executable, except when
6984 a Stand-Alone Library is used. However, there are cases when this cannot be
6985 detected by gnatbind. An example is importing an interface of a Stand-Alone
6986 Library through a pragma Import and only specifying through a linker switch
6987 this Stand-Alone Library. This switch is used to guarantee that elaboration
6988 flag checks are generated.
6991 @cindex @option{^-h^/HELP^} (@command{gnatbind})
6992 Output usage (help) information
6995 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
6996 Specify directory to be searched for source and ALI files.
6998 @item ^-I-^/NOCURRENT_DIRECTORY^
6999 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
7000 Do not look for sources in the current directory where @code{gnatbind} was
7001 invoked, and do not look for ALI files in the directory containing the
7002 ALI file named in the @code{gnatbind} command line.
7004 @item ^-l^/ORDER_OF_ELABORATION^
7005 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
7006 Output chosen elaboration order.
7008 @item ^-Lxxx^/BUILD_LIBRARY=xxx^
7009 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
7010 Binds the units for library building. In this case the adainit and
7011 adafinal procedures (See @pxref{Binding with Non-Ada Main Programs})
7012 are renamed to ^xxxinit^XXXINIT^ and
7013 ^xxxfinal^XXXFINAL^.
7014 Implies ^-n^/NOCOMPILE^.
7016 (@pxref{GNAT and Libraries}, for more details.)
7019 On OpenVMS, these init and final procedures are exported in uppercase
7020 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
7021 the init procedure will be "TOTOINIT" and the exported name of the final
7022 procedure will be "TOTOFINAL".
7025 @item ^-Mxyz^/RENAME_MAIN=xyz^
7026 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
7027 Rename generated main program from main to xyz
7029 @item ^-m^/ERROR_LIMIT=^@var{n}
7030 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
7031 Limit number of detected errors to @var{n}, where @var{n} is
7032 in the range 1..999_999. The default value if no switch is
7033 given is 9999. Binding is terminated if the limit is exceeded.
7035 Furthermore, under Windows, the sources pointed to by the libraries path
7036 set in the registry are not searched for.
7040 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7044 @cindex @option{-nostdinc} (@command{gnatbind})
7045 Do not look for sources in the system default directory.
7048 @cindex @option{-nostdlib} (@command{gnatbind})
7049 Do not look for library files in the system default directory.
7051 @item --RTS=@var{rts-path}
7052 @cindex @option{--RTS} (@code{gnatbind})
7053 Specifies the default location of the runtime library. Same meaning as the
7054 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
7056 @item ^-o ^/OUTPUT=^@var{file}
7057 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7058 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7059 Note that if this option is used, then linking must be done manually,
7060 gnatlink cannot be used.
7062 @item ^-O^/OBJECT_LIST^
7063 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7066 @item ^-p^/PESSIMISTIC_ELABORATION^
7067 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7068 Pessimistic (worst-case) elaboration order
7070 @item ^-s^/READ_SOURCES=ALL^
7071 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7072 Require all source files to be present.
7074 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7075 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7076 Specifies the value to be used when detecting uninitialized scalar
7077 objects with pragma Initialize_Scalars.
7078 The @var{xxx} ^string specified with the switch^option^ may be either
7080 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7081 @item ``@option{^lo^LOW^}'' for the lowest possible value
7082 possible, and the low
7083 @item ``@option{^hi^HIGH^}'' for the highest possible value
7084 @item ``@option{xx}'' for a value consisting of repeated bytes with the
7085 value 16#xx# (i.e. xx is a string of two hexadecimal digits).
7088 In addition, you can specify @option{-Sev} to indicate that the value is
7089 to be set at run time. In this case, the program will look for an environment
7090 @cindex GNAT_INIT_SCALARS
7091 variable of the form @code{GNAT_INIT_SCALARS=xx}, where xx is one
7092 of @option{in/lo/hi/xx} with the same meanings as above.
7093 If no environment variable is found, or if it does not have a valid value,
7094 then the default is @option{in} (invalid values).
7098 @cindex @option{-static} (@code{gnatbind})
7099 Link against a static GNAT run time.
7102 @cindex @option{-shared} (@code{gnatbind})
7103 Link against a shared GNAT run time when available.
7106 @item ^-t^/NOTIME_STAMP_CHECK^
7107 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7108 Tolerate time stamp and other consistency errors
7110 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7111 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7112 Set the time slice value to @var{n} milliseconds. If the system supports
7113 the specification of a specific time slice value, then the indicated value
7114 is used. If the system does not support specific time slice values, but
7115 does support some general notion of round-robin scheduling, then any
7116 non-zero value will activate round-robin scheduling.
7118 A value of zero is treated specially. It turns off time
7119 slicing, and in addition, indicates to the tasking run time that the
7120 semantics should match as closely as possible the Annex D
7121 requirements of the Ada RM, and in particular sets the default
7122 scheduling policy to @code{FIFO_Within_Priorities}.
7124 @item ^-v^/REPORT_ERRORS=VERBOSE^
7125 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7126 Verbose mode. Write error messages, header, summary output to
7131 @cindex @option{-w} (@code{gnatbind})
7132 Warning mode (@var{x}=s/e for suppress/treat as error)
7136 @item /WARNINGS=NORMAL
7137 @cindex @option{/WARNINGS} (@code{gnatbind})
7138 Normal warnings mode. Warnings are issued but ignored
7140 @item /WARNINGS=SUPPRESS
7141 @cindex @option{/WARNINGS} (@code{gnatbind})
7142 All warning messages are suppressed
7144 @item /WARNINGS=ERROR
7145 @cindex @option{/WARNINGS} (@code{gnatbind})
7146 Warning messages are treated as fatal errors
7149 @item ^-x^/READ_SOURCES=NONE^
7150 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7151 Exclude source files (check object consistency only).
7154 @item /READ_SOURCES=AVAILABLE
7155 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7156 Default mode, in which sources are checked for consistency only if
7160 @item ^-z^/ZERO_MAIN^
7161 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7167 You may obtain this listing of switches by running @code{gnatbind} with
7171 @node Consistency-Checking Modes
7172 @subsection Consistency-Checking Modes
7175 As described earlier, by default @code{gnatbind} checks
7176 that object files are consistent with one another and are consistent
7177 with any source files it can locate. The following switches control binder
7182 @item ^-s^/READ_SOURCES=ALL^
7183 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
7184 Require source files to be present. In this mode, the binder must be
7185 able to locate all source files that are referenced, in order to check
7186 their consistency. In normal mode, if a source file cannot be located it
7187 is simply ignored. If you specify this switch, a missing source
7190 @item ^-x^/READ_SOURCES=NONE^
7191 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
7192 Exclude source files. In this mode, the binder only checks that ALI
7193 files are consistent with one another. Source files are not accessed.
7194 The binder runs faster in this mode, and there is still a guarantee that
7195 the resulting program is self-consistent.
7196 If a source file has been edited since it was last compiled, and you
7197 specify this switch, the binder will not detect that the object
7198 file is out of date with respect to the source file. Note that this is the
7199 mode that is automatically used by @code{gnatmake} because in this
7200 case the checking against sources has already been performed by
7201 @code{gnatmake} in the course of compilation (i.e. before binding).
7204 @item /READ_SOURCES=AVAILABLE
7205 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
7206 This is the default mode in which source files are checked if they are
7207 available, and ignored if they are not available.
7211 @node Binder Error Message Control
7212 @subsection Binder Error Message Control
7215 The following switches provide control over the generation of error
7216 messages from the binder:
7220 @item ^-v^/REPORT_ERRORS=VERBOSE^
7221 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7222 Verbose mode. In the normal mode, brief error messages are generated to
7223 @file{stderr}. If this switch is present, a header is written
7224 to @file{stdout} and any error messages are directed to @file{stdout}.
7225 All that is written to @file{stderr} is a brief summary message.
7227 @item ^-b^/REPORT_ERRORS=BRIEF^
7228 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
7229 Generate brief error messages to @file{stderr} even if verbose mode is
7230 specified. This is relevant only when used with the
7231 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
7235 @cindex @option{-m} (@code{gnatbind})
7236 Limits the number of error messages to @var{n}, a decimal integer in the
7237 range 1-999. The binder terminates immediately if this limit is reached.
7240 @cindex @option{-M} (@code{gnatbind})
7241 Renames the generated main program from @code{main} to @code{xxx}.
7242 This is useful in the case of some cross-building environments, where
7243 the actual main program is separate from the one generated
7247 @item ^-ws^/WARNINGS=SUPPRESS^
7248 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
7250 Suppress all warning messages.
7252 @item ^-we^/WARNINGS=ERROR^
7253 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
7254 Treat any warning messages as fatal errors.
7257 @item /WARNINGS=NORMAL
7258 Standard mode with warnings generated, but warnings do not get treated
7262 @item ^-t^/NOTIME_STAMP_CHECK^
7263 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7264 @cindex Time stamp checks, in binder
7265 @cindex Binder consistency checks
7266 @cindex Consistency checks, in binder
7267 The binder performs a number of consistency checks including:
7271 Check that time stamps of a given source unit are consistent
7273 Check that checksums of a given source unit are consistent
7275 Check that consistent versions of @code{GNAT} were used for compilation
7277 Check consistency of configuration pragmas as required
7281 Normally failure of such checks, in accordance with the consistency
7282 requirements of the Ada Reference Manual, causes error messages to be
7283 generated which abort the binder and prevent the output of a binder
7284 file and subsequent link to obtain an executable.
7286 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
7287 into warnings, so that
7288 binding and linking can continue to completion even in the presence of such
7289 errors. The result may be a failed link (due to missing symbols), or a
7290 non-functional executable which has undefined semantics.
7291 @emph{This means that
7292 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
7296 @node Elaboration Control
7297 @subsection Elaboration Control
7300 The following switches provide additional control over the elaboration
7301 order. For full details see @xref{Elaboration Order Handling in GNAT}.
7304 @item ^-p^/PESSIMISTIC_ELABORATION^
7305 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
7306 Normally the binder attempts to choose an elaboration order that is
7307 likely to minimize the likelihood of an elaboration order error resulting
7308 in raising a @code{Program_Error} exception. This switch reverses the
7309 action of the binder, and requests that it deliberately choose an order
7310 that is likely to maximize the likelihood of an elaboration error.
7311 This is useful in ensuring portability and avoiding dependence on
7312 accidental fortuitous elaboration ordering.
7314 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
7316 elaboration checking is used (@option{-gnatE} switch used for compilation).
7317 This is because in the default static elaboration mode, all necessary
7318 @code{Elaborate_All} pragmas are implicitly inserted.
7319 These implicit pragmas are still respected by the binder in
7320 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
7321 safe elaboration order is assured.
7324 @node Output Control
7325 @subsection Output Control
7328 The following switches allow additional control over the output
7329 generated by the binder.
7334 @item ^-A^/BIND_FILE=ADA^
7335 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
7336 Generate binder program in Ada (default). The binder program is named
7337 @file{b~@var{mainprog}.adb} by default. This can be changed with
7338 @option{^-o^/OUTPUT^} @code{gnatbind} option.
7340 @item ^-c^/NOOUTPUT^
7341 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
7342 Check only. Do not generate the binder output file. In this mode the
7343 binder performs all error checks but does not generate an output file.
7345 @item ^-C^/BIND_FILE=C^
7346 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
7347 Generate binder program in C. The binder program is named
7348 @file{b_@var{mainprog}.c}.
7349 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
7352 @item ^-e^/ELABORATION_DEPENDENCIES^
7353 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
7354 Output complete list of elaboration-order dependencies, showing the
7355 reason for each dependency. This output can be rather extensive but may
7356 be useful in diagnosing problems with elaboration order. The output is
7357 written to @file{stdout}.
7360 @cindex @option{^-h^/HELP^} (@code{gnatbind})
7361 Output usage information. The output is written to @file{stdout}.
7363 @item ^-K^/LINKER_OPTION_LIST^
7364 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
7365 Output linker options to @file{stdout}. Includes library search paths,
7366 contents of pragmas Ident and Linker_Options, and libraries added
7369 @item ^-l^/ORDER_OF_ELABORATION^
7370 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
7371 Output chosen elaboration order. The output is written to @file{stdout}.
7373 @item ^-O^/OBJECT_LIST^
7374 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
7375 Output full names of all the object files that must be linked to provide
7376 the Ada component of the program. The output is written to @file{stdout}.
7377 This list includes the files explicitly supplied and referenced by the user
7378 as well as implicitly referenced run-time unit files. The latter are
7379 omitted if the corresponding units reside in shared libraries. The
7380 directory names for the run-time units depend on the system configuration.
7382 @item ^-o ^/OUTPUT=^@var{file}
7383 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
7384 Set name of output file to @var{file} instead of the normal
7385 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
7386 binder generated body filename. In C mode you would normally give
7387 @var{file} an extension of @file{.c} because it will be a C source program.
7388 Note that if this option is used, then linking must be done manually.
7389 It is not possible to use gnatlink in this case, since it cannot locate
7392 @item ^-r^/RESTRICTION_LIST^
7393 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
7394 Generate list of @code{pragma Restrictions} that could be applied to
7395 the current unit. This is useful for code audit purposes, and also may
7396 be used to improve code generation in some cases.
7400 @node Binding with Non-Ada Main Programs
7401 @subsection Binding with Non-Ada Main Programs
7404 In our description so far we have assumed that the main
7405 program is in Ada, and that the task of the binder is to generate a
7406 corresponding function @code{main} that invokes this Ada main
7407 program. GNAT also supports the building of executable programs where
7408 the main program is not in Ada, but some of the called routines are
7409 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
7410 The following switch is used in this situation:
7414 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
7415 No main program. The main program is not in Ada.
7419 In this case, most of the functions of the binder are still required,
7420 but instead of generating a main program, the binder generates a file
7421 containing the following callable routines:
7426 You must call this routine to initialize the Ada part of the program by
7427 calling the necessary elaboration routines. A call to @code{adainit} is
7428 required before the first call to an Ada subprogram.
7430 Note that it is assumed that the basic execution environment must be setup
7431 to be appropriate for Ada execution at the point where the first Ada
7432 subprogram is called. In particular, if the Ada code will do any
7433 floating-point operations, then the FPU must be setup in an appropriate
7434 manner. For the case of the x86, for example, full precision mode is
7435 required. The procedure GNAT.Float_Control.Reset may be used to ensure
7436 that the FPU is in the right state.
7440 You must call this routine to perform any library-level finalization
7441 required by the Ada subprograms. A call to @code{adafinal} is required
7442 after the last call to an Ada subprogram, and before the program
7447 If the @option{^-n^/NOMAIN^} switch
7448 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7449 @cindex Binder, multiple input files
7450 is given, more than one ALI file may appear on
7451 the command line for @code{gnatbind}. The normal @dfn{closure}
7452 calculation is performed for each of the specified units. Calculating
7453 the closure means finding out the set of units involved by tracing
7454 @code{with} references. The reason it is necessary to be able to
7455 specify more than one ALI file is that a given program may invoke two or
7456 more quite separate groups of Ada units.
7458 The binder takes the name of its output file from the last specified ALI
7459 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
7460 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
7461 The output is an Ada unit in source form that can
7462 be compiled with GNAT unless the -C switch is used in which case the
7463 output is a C source file, which must be compiled using the C compiler.
7464 This compilation occurs automatically as part of the @code{gnatlink}
7467 Currently the GNAT run time requires a FPU using 80 bits mode
7468 precision. Under targets where this is not the default it is required to
7469 call GNAT.Float_Control.Reset before using floating point numbers (this
7470 include float computation, float input and output) in the Ada code. A
7471 side effect is that this could be the wrong mode for the foreign code
7472 where floating point computation could be broken after this call.
7474 @node Binding Programs with No Main Subprogram
7475 @subsection Binding Programs with No Main Subprogram
7478 It is possible to have an Ada program which does not have a main
7479 subprogram. This program will call the elaboration routines of all the
7480 packages, then the finalization routines.
7482 The following switch is used to bind programs organized in this manner:
7485 @item ^-z^/ZERO_MAIN^
7486 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7487 Normally the binder checks that the unit name given on the command line
7488 corresponds to a suitable main subprogram. When this switch is used,
7489 a list of ALI files can be given, and the execution of the program
7490 consists of elaboration of these units in an appropriate order.
7493 @node Command-Line Access
7494 @section Command-Line Access
7497 The package @code{Ada.Command_Line} provides access to the command-line
7498 arguments and program name. In order for this interface to operate
7499 correctly, the two variables
7511 are declared in one of the GNAT library routines. These variables must
7512 be set from the actual @code{argc} and @code{argv} values passed to the
7513 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
7514 generates the C main program to automatically set these variables.
7515 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
7516 set these variables. If they are not set, the procedures in
7517 @code{Ada.Command_Line} will not be available, and any attempt to use
7518 them will raise @code{Constraint_Error}. If command line access is
7519 required, your main program must set @code{gnat_argc} and
7520 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
7523 @node Search Paths for gnatbind
7524 @section Search Paths for @code{gnatbind}
7527 The binder takes the name of an ALI file as its argument and needs to
7528 locate source files as well as other ALI files to verify object consistency.
7530 For source files, it follows exactly the same search rules as @code{gcc}
7531 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
7532 directories searched are:
7536 The directory containing the ALI file named in the command line, unless
7537 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
7540 All directories specified by @option{^-I^/SEARCH^}
7541 switches on the @code{gnatbind}
7542 command line, in the order given.
7545 @findex ADA_OBJECTS_PATH
7546 Each of the directories listed in the value of the
7547 @code{ADA_OBJECTS_PATH} ^environment variable^logical name^.
7549 Construct this value
7550 exactly as the @code{PATH} environment variable: a list of directory
7551 names separated by colons (semicolons when working with the NT version
7555 Normally, define this value as a logical name containing a comma separated
7556 list of directory names.
7558 This variable can also be defined by means of an environment string
7559 (an argument to the DEC C exec* set of functions).
7563 DEFINE ANOTHER_PATH FOO:[BAG]
7564 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7567 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7568 first, followed by the standard Ada 95
7569 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
7570 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
7571 (Text_IO, Sequential_IO, etc)
7572 instead of the Ada95 packages. Thus, in order to get the Ada 95
7573 packages by default, ADA_OBJECTS_PATH must be redefined.
7577 @findex ADA_PRJ_OBJECTS_FILE
7578 Each of the directories listed in the text file whose name is given
7579 by the @code{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
7582 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7583 driver when project files are used. It should not normally be set
7587 The content of the @file{ada_object_path} file which is part of the GNAT
7588 installation tree and is used to store standard libraries such as the
7589 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
7592 @ref{Installing a library}
7597 In the binder the switch @option{^-I^/SEARCH^}
7598 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7599 is used to specify both source and
7600 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
7601 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7602 instead if you want to specify
7603 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
7604 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
7605 if you want to specify library paths
7606 only. This means that for the binder
7607 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
7608 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
7609 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
7610 The binder generates the bind file (a C language source file) in the
7611 current working directory.
7617 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7618 children make up the GNAT Run-Time Library, together with the package
7619 GNAT and its children, which contain a set of useful additional
7620 library functions provided by GNAT. The sources for these units are
7621 needed by the compiler and are kept together in one directory. The ALI
7622 files and object files generated by compiling the RTL are needed by the
7623 binder and the linker and are kept together in one directory, typically
7624 different from the directory containing the sources. In a normal
7625 installation, you need not specify these directory names when compiling
7626 or binding. Either the environment variables or the built-in defaults
7627 cause these files to be found.
7629 Besides simplifying access to the RTL, a major use of search paths is
7630 in compiling sources from multiple directories. This can make
7631 development environments much more flexible.
7633 @node Examples of gnatbind Usage
7634 @section Examples of @code{gnatbind} Usage
7637 This section contains a number of examples of using the GNAT binding
7638 utility @code{gnatbind}.
7641 @item gnatbind hello
7642 The main program @code{Hello} (source program in @file{hello.adb}) is
7643 bound using the standard switch settings. The generated main program is
7644 @file{b~hello.adb}. This is the normal, default use of the binder.
7647 @item gnatbind hello -o mainprog.adb
7650 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
7652 The main program @code{Hello} (source program in @file{hello.adb}) is
7653 bound using the standard switch settings. The generated main program is
7654 @file{mainprog.adb} with the associated spec in
7655 @file{mainprog.ads}. Note that you must specify the body here not the
7656 spec, in the case where the output is in Ada. Note that if this option
7657 is used, then linking must be done manually, since gnatlink will not
7658 be able to find the generated file.
7661 @item gnatbind main -C -o mainprog.c -x
7664 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
7666 The main program @code{Main} (source program in
7667 @file{main.adb}) is bound, excluding source files from the
7668 consistency checking, generating
7669 the file @file{mainprog.c}.
7672 @item gnatbind -x main_program -C -o mainprog.c
7673 This command is exactly the same as the previous example. Switches may
7674 appear anywhere in the command line, and single letter switches may be
7675 combined into a single switch.
7679 @item gnatbind -n math dbase -C -o ada-control.c
7682 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
7684 The main program is in a language other than Ada, but calls to
7685 subprograms in packages @code{Math} and @code{Dbase} appear. This call
7686 to @code{gnatbind} generates the file @file{ada-control.c} containing
7687 the @code{adainit} and @code{adafinal} routines to be called before and
7688 after accessing the Ada units.
7691 @c ------------------------------------
7692 @node Linking Using gnatlink
7693 @chapter Linking Using @code{gnatlink}
7694 @c ------------------------------------
7698 This chapter discusses @code{gnatlink}, a tool that links
7699 an Ada program and builds an executable file. This utility
7700 invokes the system linker ^(via the @code{gcc} command)^^
7701 with a correct list of object files and library references.
7702 @code{gnatlink} automatically determines the list of files and
7703 references for the Ada part of a program. It uses the binder file
7704 generated by the @command{gnatbind} to determine this list.
7707 * Running gnatlink::
7708 * Switches for gnatlink::
7709 * Setting Stack Size from gnatlink::
7710 * Setting Heap Size from gnatlink::
7713 @node Running gnatlink
7714 @section Running @code{gnatlink}
7717 The form of the @code{gnatlink} command is
7720 $ gnatlink [@var{switches}] @var{mainprog}[.ali]
7721 [@var{non-Ada objects}] [@var{linker options}]
7725 The arguments of @code{gnatlink} (switches, main @file{ALI} file,
7727 or linker options) may be in any order, provided that no non-Ada object may
7728 be mistaken for a main @file{ALI} file.
7729 Any file name @file{F} without the @file{.ali}
7730 extension will be taken as the main @file{ALI} file if a file exists
7731 whose name is the concatenation of @file{F} and @file{.ali}.
7734 @file{@var{mainprog}.ali} references the ALI file of the main program.
7735 The @file{.ali} extension of this file can be omitted. From this
7736 reference, @code{gnatlink} locates the corresponding binder file
7737 @file{b~@var{mainprog}.adb} and, using the information in this file along
7738 with the list of non-Ada objects and linker options, constructs a
7739 linker command file to create the executable.
7741 The arguments other than the @code{gnatlink} switches and the main @file{ALI}
7742 file are passed to the linker uninterpreted.
7743 They typically include the names of
7744 object files for units written in other languages than Ada and any library
7745 references required to resolve references in any of these foreign language
7746 units, or in @code{Import} pragmas in any Ada units.
7748 @var{linker options} is an optional list of linker specific
7750 The default linker called by gnatlink is @var{gcc} which in
7751 turn calls the appropriate system linker.
7752 Standard options for the linker such as @option{-lmy_lib} or
7753 @option{-Ldir} can be added as is.
7754 For options that are not recognized by
7755 @var{gcc} as linker options, use the @var{gcc} switches @option{-Xlinker} or
7757 Refer to the GCC documentation for
7758 details. Here is an example showing how to generate a linker map:
7762 $ gnatlink my_prog -Wl,-Map,MAPFILE
7767 <<Need example for VMS>>
7770 Using @var{linker options} it is possible to set the program stack and
7771 heap size. See @ref{Setting Stack Size from gnatlink}, and
7772 @ref{Setting Heap Size from gnatlink}.
7774 @code{gnatlink} determines the list of objects required by the Ada
7775 program and prepends them to the list of objects passed to the linker.
7776 @code{gnatlink} also gathers any arguments set by the use of
7777 @code{pragma Linker_Options} and adds them to the list of arguments
7778 presented to the linker.
7781 @code{gnatlink} accepts the following types of extra files on the command
7782 line: objects (.OBJ), libraries (.OLB), sharable images (.EXE), and
7783 options files (.OPT). These are recognized and handled according to their
7787 @node Switches for gnatlink
7788 @section Switches for @code{gnatlink}
7791 The following switches are available with the @code{gnatlink} utility:
7796 @item ^-A^/BIND_FILE=ADA^
7797 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatlink})
7798 The binder has generated code in Ada. This is the default.
7800 @item ^-C^/BIND_FILE=C^
7801 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatlink})
7802 If instead of generating a file in Ada, the binder has generated one in
7803 C, then the linker needs to know about it. Use this switch to signal
7804 to @code{gnatlink} that the binder has generated C code rather than
7807 @item ^-f^/FORCE_OBJECT_FILE_LIST^
7808 @cindex Command line length
7809 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@code{gnatlink})
7810 On some targets, the command line length is limited, and @code{gnatlink}
7811 will generate a separate file for the linker if the list of object files
7813 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
7814 to be generated even if
7815 the limit is not exceeded. This is useful in some cases to deal with
7816 special situations where the command line length is exceeded.
7819 @cindex Debugging information, including
7820 @cindex @option{^-g^/DEBUG^} (@code{gnatlink})
7821 The option to include debugging information causes the Ada bind file (in
7822 other words, @file{b~@var{mainprog}.adb}) to be compiled with
7823 @option{^-g^/DEBUG^}.
7824 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
7825 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
7826 Without @option{^-g^/DEBUG^}, the binder removes these files by
7827 default. The same procedure apply if a C bind file was generated using
7828 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
7829 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
7831 @item ^-n^/NOCOMPILE^
7832 @cindex @option{^-n^/NOCOMPILE^} (@code{gnatlink})
7833 Do not compile the file generated by the binder. This may be used when
7834 a link is rerun with different options, but there is no need to recompile
7838 @cindex @option{^-v^/VERBOSE^} (@code{gnatlink})
7839 Causes additional information to be output, including a full list of the
7840 included object files. This switch option is most useful when you want
7841 to see what set of object files are being used in the link step.
7843 @item ^-v -v^/VERBOSE/VERBOSE^
7844 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@code{gnatlink})
7845 Very verbose mode. Requests that the compiler operate in verbose mode when
7846 it compiles the binder file, and that the system linker run in verbose mode.
7848 @item ^-o ^/EXECUTABLE=^@var{exec-name}
7849 @cindex @option{^-o^/EXECUTABLE^} (@code{gnatlink})
7850 @var{exec-name} specifies an alternate name for the generated
7851 executable program. If this switch is omitted, the executable has the same
7852 name as the main unit. For example, @code{gnatlink try.ali} creates
7853 an executable called @file{^try^TRY.EXE^}.
7856 @item -b @var{target}
7857 @cindex @option{-b} (@code{gnatlink})
7858 Compile your program to run on @var{target}, which is the name of a
7859 system configuration. You must have a GNAT cross-compiler built if
7860 @var{target} is not the same as your host system.
7863 @cindex @option{-B} (@code{gnatlink})
7864 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
7865 from @var{dir} instead of the default location. Only use this switch
7866 when multiple versions of the GNAT compiler are available. See the
7867 @code{gcc} manual page for further details. You would normally use the
7868 @option{-b} or @option{-V} switch instead.
7870 @item --GCC=@var{compiler_name}
7871 @cindex @option{--GCC=compiler_name} (@code{gnatlink})
7872 Program used for compiling the binder file. The default is
7873 `@code{gcc}'. You need to use quotes around @var{compiler_name} if
7874 @code{compiler_name} contains spaces or other separator characters. As
7875 an example @option{--GCC="foo -x -y"} will instruct @code{gnatlink} to use
7876 @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
7877 inserted after your command name. Thus in the above example the compiler
7878 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
7879 If several @option{--GCC=compiler_name} are used, only the last
7880 @var{compiler_name} is taken into account. However, all the additional
7881 switches are also taken into account. Thus,
7882 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7883 @option{--GCC="bar -x -y -z -t"}.
7885 @item --LINK=@var{name}
7886 @cindex @option{--LINK=} (@code{gnatlink})
7887 @var{name} is the name of the linker to be invoked. This is especially
7888 useful in mixed language programs since languages such as C++ require
7889 their own linker to be used. When this switch is omitted, the default
7890 name for the linker is (@file{gcc}). When this switch is used, the
7891 specified linker is called instead of (@file{gcc}) with exactly the same
7892 parameters that would have been passed to (@file{gcc}) so if the desired
7893 linker requires different parameters it is necessary to use a wrapper
7894 script that massages the parameters before invoking the real linker. It
7895 may be useful to control the exact invocation by using the verbose
7901 @item /DEBUG=TRACEBACK
7902 @cindex @code{/DEBUG=TRACEBACK} (@code{gnatlink})
7903 This qualifier causes sufficient information to be included in the
7904 executable file to allow a traceback, but does not include the full
7905 symbol information needed by the debugger.
7907 @item /IDENTIFICATION="<string>"
7908 @code{"<string>"} specifies the string to be stored in the image file
7909 identification field in the image header.
7910 It overrides any pragma @code{Ident} specified string.
7912 @item /NOINHIBIT-EXEC
7913 Generate the executable file even if there are linker warnings.
7915 @item /NOSTART_FILES
7916 Don't link in the object file containing the ``main'' transfer address.
7917 Used when linking with a foreign language main program compiled with a
7921 Prefer linking with object libraries over sharable images, even without
7927 @node Setting Stack Size from gnatlink
7928 @section Setting Stack Size from @code{gnatlink}
7931 Under Windows systems, it is possible to specify the program stack size from
7932 @code{gnatlink} using either:
7936 @item using @option{-Xlinker} linker option
7939 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
7942 This sets the stack reserve size to 0x10000 bytes and the stack commit
7943 size to 0x1000 bytes.
7945 @item using @option{-Wl} linker option
7948 $ gnatlink hello -Wl,--stack=0x1000000
7951 This sets the stack reserve size to 0x1000000 bytes. Note that with
7952 @option{-Wl} option it is not possible to set the stack commit size
7953 because the coma is a separator for this option.
7957 @node Setting Heap Size from gnatlink
7958 @section Setting Heap Size from @code{gnatlink}
7961 Under Windows systems, it is possible to specify the program heap size from
7962 @code{gnatlink} using either:
7966 @item using @option{-Xlinker} linker option
7969 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
7972 This sets the heap reserve size to 0x10000 bytes and the heap commit
7973 size to 0x1000 bytes.
7975 @item using @option{-Wl} linker option
7978 $ gnatlink hello -Wl,--heap=0x1000000
7981 This sets the heap reserve size to 0x1000000 bytes. Note that with
7982 @option{-Wl} option it is not possible to set the heap commit size
7983 because the coma is a separator for this option.
7987 @node The GNAT Make Program gnatmake
7988 @chapter The GNAT Make Program @code{gnatmake}
7992 * Running gnatmake::
7993 * Switches for gnatmake::
7994 * Mode Switches for gnatmake::
7995 * Notes on the Command Line::
7996 * How gnatmake Works::
7997 * Examples of gnatmake Usage::
8000 A typical development cycle when working on an Ada program consists of
8001 the following steps:
8005 Edit some sources to fix bugs.
8011 Compile all sources affected.
8021 The third step can be tricky, because not only do the modified files
8022 @cindex Dependency rules
8023 have to be compiled, but any files depending on these files must also be
8024 recompiled. The dependency rules in Ada can be quite complex, especially
8025 in the presence of overloading, @code{use} clauses, generics and inlined
8028 @code{gnatmake} automatically takes care of the third and fourth steps
8029 of this process. It determines which sources need to be compiled,
8030 compiles them, and binds and links the resulting object files.
8032 Unlike some other Ada make programs, the dependencies are always
8033 accurately recomputed from the new sources. The source based approach of
8034 the GNAT compilation model makes this possible. This means that if
8035 changes to the source program cause corresponding changes in
8036 dependencies, they will always be tracked exactly correctly by
8039 @node Running gnatmake
8040 @section Running @code{gnatmake}
8043 The usual form of the @code{gnatmake} command is
8046 $ gnatmake [@var{switches}] @var{file_name}
8047 [@var{file_names}] [@var{mode_switches}]
8051 The only required argument is one @var{file_name}, which specifies
8052 a compilation unit that is a main program. Several @var{file_names} can be
8053 specified: this will result in several executables being built.
8054 If @code{switches} are present, they can be placed before the first
8055 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8056 If @var{mode_switches} are present, they must always be placed after
8057 the last @var{file_name} and all @code{switches}.
8059 If you are using standard file extensions (.adb and .ads), then the
8060 extension may be omitted from the @var{file_name} arguments. However, if
8061 you are using non-standard extensions, then it is required that the
8062 extension be given. A relative or absolute directory path can be
8063 specified in a @var{file_name}, in which case, the input source file will
8064 be searched for in the specified directory only. Otherwise, the input
8065 source file will first be searched in the directory where
8066 @code{gnatmake} was invoked and if it is not found, it will be search on
8067 the source path of the compiler as described in
8068 @ref{Search Paths and the Run-Time Library (RTL)}.
8070 All @code{gnatmake} output (except when you specify
8071 @option{^-M^/DEPENDENCIES_LIST^}) is to
8072 @file{stderr}. The output produced by the
8073 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8076 @node Switches for gnatmake
8077 @section Switches for @code{gnatmake}
8080 You may specify any of the following switches to @code{gnatmake}:
8085 @item --GCC=@var{compiler_name}
8086 @cindex @option{--GCC=compiler_name} (@code{gnatmake})
8087 Program used for compiling. The default is `@code{gcc}'. You need to use
8088 quotes around @var{compiler_name} if @code{compiler_name} contains
8089 spaces or other separator characters. As an example @option{--GCC="foo -x
8090 -y"} will instruct @code{gnatmake} to use @code{foo -x -y} as your
8091 compiler. Note that switch @option{-c} is always inserted after your
8092 command name. Thus in the above example the compiler command that will
8093 be used by @code{gnatmake} will be @code{foo -c -x -y}.
8094 If several @option{--GCC=compiler_name} are used, only the last
8095 @var{compiler_name} is taken into account. However, all the additional
8096 switches are also taken into account. Thus,
8097 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8098 @option{--GCC="bar -x -y -z -t"}.
8100 @item --GNATBIND=@var{binder_name}
8101 @cindex @option{--GNATBIND=binder_name} (@code{gnatmake})
8102 Program used for binding. The default is `@code{gnatbind}'. You need to
8103 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8104 or other separator characters. As an example @option{--GNATBIND="bar -x
8105 -y"} will instruct @code{gnatmake} to use @code{bar -x -y} as your
8106 binder. Binder switches that are normally appended by @code{gnatmake} to
8107 `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8109 @item --GNATLINK=@var{linker_name}
8110 @cindex @option{--GNATLINK=linker_name} (@code{gnatmake})
8111 Program used for linking. The default is `@code{gnatlink}'. You need to
8112 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8113 or other separator characters. As an example @option{--GNATLINK="lan -x
8114 -y"} will instruct @code{gnatmake} to use @code{lan -x -y} as your
8115 linker. Linker switches that are normally appended by @code{gnatmake} to
8116 `@code{gnatlink}' are now appended to the end of @code{lan -x -y}.
8120 @item ^-a^/ALL_FILES^
8121 @cindex @option{^-a^/ALL_FILES^} (@code{gnatmake})
8122 Consider all files in the make process, even the GNAT internal system
8123 files (for example, the predefined Ada library files), as well as any
8124 locked files. Locked files are files whose ALI file is write-protected.
8126 @code{gnatmake} does not check these files,
8127 because the assumption is that the GNAT internal files are properly up
8128 to date, and also that any write protected ALI files have been properly
8129 installed. Note that if there is an installation problem, such that one
8130 of these files is not up to date, it will be properly caught by the
8132 You may have to specify this switch if you are working on GNAT
8133 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8134 in conjunction with @option{^-f^/FORCE_COMPILE^}
8135 if you need to recompile an entire application,
8136 including run-time files, using special configuration pragmas,
8137 such as a @code{Normalize_Scalars} pragma.
8140 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8143 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8146 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8149 @item ^-b^/ACTIONS=BIND^
8150 @cindex @option{^-b^/ACTIONS=BIND^} (@code{gnatmake})
8151 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8152 compilation and binding, but no link.
8153 Can be combined with @option{^-l^/ACTIONS=LINK^}
8154 to do binding and linking. When not combined with
8155 @option{^-c^/ACTIONS=COMPILE^}
8156 all the units in the closure of the main program must have been previously
8157 compiled and must be up to date. The root unit specified by @var{file_name}
8158 may be given without extension, with the source extension or, if no GNAT
8159 Project File is specified, with the ALI file extension.
8161 @item ^-c^/ACTIONS=COMPILE^
8162 @cindex @option{^-c^/ACTIONS=COMPILE^} (@code{gnatmake})
8163 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8164 is also specified. Do not perform linking, except if both
8165 @option{^-b^/ACTIONS=BIND^} and
8166 @option{^-l^/ACTIONS=LINK^} are also specified.
8167 If the root unit specified by @var{file_name} is not a main unit, this is the
8168 default. Otherwise @code{gnatmake} will attempt binding and linking
8169 unless all objects are up to date and the executable is more recent than
8173 @cindex @option{^-C^/MAPPING^} (@code{gnatmake})
8174 Use a temporary mapping file. A mapping file is a way to communicate to the
8175 compiler two mappings: from unit names to file names (without any directory
8176 information) and from file names to path names (with full directory
8177 information). These mappings are used by the compiler to short-circuit the path
8178 search. When @code{gnatmake} is invoked with this switch, it will create
8179 a temporary mapping file, initially populated by the project manager,
8180 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8181 Each invocation of the compiler will add the newly accessed sources to the
8182 mapping file. This will improve the source search during the next invocation
8185 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8186 @cindex @option{^-C=^/USE_MAPPING^} (@code{gnatmake})
8187 Use a specific mapping file. The file, specified as a path name (absolute or
8188 relative) by this switch, should already exist, otherwise the switch is
8189 ineffective. The specified mapping file will be communicated to the compiler.
8190 This switch is not compatible with a project file
8191 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8192 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8194 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
8195 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatmake})
8196 Put all object files and ALI file in directory @var{dir}.
8197 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
8198 and ALI files go in the current working directory.
8200 This switch cannot be used when using a project file.
8204 @cindex @option{-eL} (@code{gnatmake})
8205 Follow all symbolic links when processing project files.
8208 @item ^-f^/FORCE_COMPILE^
8209 @cindex @option{^-f^/FORCE_COMPILE^} (@code{gnatmake})
8210 Force recompilations. Recompile all sources, even though some object
8211 files may be up to date, but don't recompile predefined or GNAT internal
8212 files or locked files (files with a write-protected ALI file),
8213 unless the @option{^-a^/ALL_FILES^} switch is also specified.
8215 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
8216 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatmake})
8217 When using project files, if some errors or warnings are detected during
8218 parsing and verbose mode is not in effect (no use of switch
8219 ^-v^/VERBOSE^), then error lines start with the full path name of the project
8220 file, rather than its simple file name.
8222 @item ^-i^/IN_PLACE^
8223 @cindex @option{^-i^/IN_PLACE^} (@code{gnatmake})
8224 In normal mode, @code{gnatmake} compiles all object files and ALI files
8225 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
8226 then instead object files and ALI files that already exist are overwritten
8227 in place. This means that once a large project is organized into separate
8228 directories in the desired manner, then @code{gnatmake} will automatically
8229 maintain and update this organization. If no ALI files are found on the
8230 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
8231 the new object and ALI files are created in the
8232 directory containing the source being compiled. If another organization
8233 is desired, where objects and sources are kept in different directories,
8234 a useful technique is to create dummy ALI files in the desired directories.
8235 When detecting such a dummy file, @code{gnatmake} will be forced to recompile
8236 the corresponding source file, and it will be put the resulting object
8237 and ALI files in the directory where it found the dummy file.
8239 @item ^-j^/PROCESSES=^@var{n}
8240 @cindex @option{^-j^/PROCESSES^} (@code{gnatmake})
8241 @cindex Parallel make
8242 Use @var{n} processes to carry out the (re)compilations. On a
8243 multiprocessor machine compilations will occur in parallel. In the
8244 event of compilation errors, messages from various compilations might
8245 get interspersed (but @code{gnatmake} will give you the full ordered
8246 list of failing compiles at the end). If this is problematic, rerun
8247 the make process with n set to 1 to get a clean list of messages.
8249 @item ^-k^/CONTINUE_ON_ERROR^
8250 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@code{gnatmake})
8251 Keep going. Continue as much as possible after a compilation error. To
8252 ease the programmer's task in case of compilation errors, the list of
8253 sources for which the compile fails is given when @code{gnatmake}
8256 If @code{gnatmake} is invoked with several @file{file_names} and with this
8257 switch, if there are compilation errors when building an executable,
8258 @code{gnatmake} will not attempt to build the following executables.
8260 @item ^-l^/ACTIONS=LINK^
8261 @cindex @option{^-l^/ACTIONS=LINK^} (@code{gnatmake})
8262 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
8263 and linking. Linking will not be performed if combined with
8264 @option{^-c^/ACTIONS=COMPILE^}
8265 but not with @option{^-b^/ACTIONS=BIND^}.
8266 When not combined with @option{^-b^/ACTIONS=BIND^}
8267 all the units in the closure of the main program must have been previously
8268 compiled and must be up to date, and the main program need to have been bound.
8269 The root unit specified by @var{file_name}
8270 may be given without extension, with the source extension or, if no GNAT
8271 Project File is specified, with the ALI file extension.
8273 @item ^-m^/MINIMAL_RECOMPILATION^
8274 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@code{gnatmake})
8275 Specifies that the minimum necessary amount of recompilations
8276 be performed. In this mode @code{gnatmake} ignores time
8277 stamp differences when the only
8278 modifications to a source file consist in adding/removing comments,
8279 empty lines, spaces or tabs. This means that if you have changed the
8280 comments in a source file or have simply reformatted it, using this
8281 switch will tell gnatmake not to recompile files that depend on it
8282 (provided other sources on which these files depend have undergone no
8283 semantic modifications). Note that the debugging information may be
8284 out of date with respect to the sources if the @option{-m} switch causes
8285 a compilation to be switched, so the use of this switch represents a
8286 trade-off between compilation time and accurate debugging information.
8288 @item ^-M^/DEPENDENCIES_LIST^
8289 @cindex Dependencies, producing list
8290 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@code{gnatmake})
8291 Check if all objects are up to date. If they are, output the object
8292 dependences to @file{stdout} in a form that can be directly exploited in
8293 a @file{Makefile}. By default, each source file is prefixed with its
8294 (relative or absolute) directory name. This name is whatever you
8295 specified in the various @option{^-aI^/SOURCE_SEARCH^}
8296 and @option{^-I^/SEARCH^} switches. If you use
8297 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
8298 @option{^-q^/QUIET^}
8299 (see below), only the source file names,
8300 without relative paths, are output. If you just specify the
8301 @option{^-M^/DEPENDENCIES_LIST^}
8302 switch, dependencies of the GNAT internal system files are omitted. This
8303 is typically what you want. If you also specify
8304 the @option{^-a^/ALL_FILES^} switch,
8305 dependencies of the GNAT internal files are also listed. Note that
8306 dependencies of the objects in external Ada libraries (see switch
8307 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
8310 @item ^-n^/DO_OBJECT_CHECK^
8311 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@code{gnatmake})
8312 Don't compile, bind, or link. Checks if all objects are up to date.
8313 If they are not, the full name of the first file that needs to be
8314 recompiled is printed.
8315 Repeated use of this option, followed by compiling the indicated source
8316 file, will eventually result in recompiling all required units.
8318 @item ^-o ^/EXECUTABLE=^@var{exec_name}
8319 @cindex @option{^-o^/EXECUTABLE^} (@code{gnatmake})
8320 Output executable name. The name of the final executable program will be
8321 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
8322 name for the executable will be the name of the input file in appropriate form
8323 for an executable file on the host system.
8325 This switch cannot be used when invoking @code{gnatmake} with several
8328 @item ^-P^/PROJECT_FILE=^@var{project}
8329 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatmake})
8330 Use project file @var{project}. Only one such switch can be used.
8331 See @ref{gnatmake and Project Files}.
8334 @cindex @option{^-q^/QUIET^} (@code{gnatmake})
8335 Quiet. When this flag is not set, the commands carried out by
8336 @code{gnatmake} are displayed.
8338 @item ^-s^/SWITCH_CHECK/^
8339 @cindex @option{^-s^/SWITCH_CHECK^} (@code{gnatmake})
8340 Recompile if compiler switches have changed since last compilation.
8341 All compiler switches but -I and -o are taken into account in the
8343 orders between different ``first letter'' switches are ignored, but
8344 orders between same switches are taken into account. For example,
8345 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
8346 is equivalent to @option{-O -g}.
8348 This switch is recommended when Integrated Preprocessing is used.
8351 @cindex @option{^-u^/UNIQUE^} (@code{gnatmake})
8352 Unique. Recompile at most the main files. It implies -c. Combined with
8353 -f, it is equivalent to calling the compiler directly. Note that using
8354 ^-u^/UNIQUE^ with a project file and no main has a special meaning
8355 (see @ref{Project Files and Main Subprograms}).
8357 @item ^-U^/ALL_PROJECTS^
8358 @cindex @option{^-U^/ALL_PROJECTS^} (@code{gnatmake})
8359 When used without a project file or with one or several mains on the command
8360 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
8361 on the command line, all sources of all project files are checked and compiled
8362 if not up to date, and libraries are rebuilt, if necessary.
8365 @cindex @option{^-v^/REASONS^} (@code{gnatmake})
8366 Verbose. Displays the reason for all recompilations @code{gnatmake}
8367 decides are necessary.
8369 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
8370 Indicates the verbosity of the parsing of GNAT project files.
8371 See @ref{Switches Related to Project Files}.
8373 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
8374 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@code{gnatmake})
8375 Indicates that sources that are not part of any Project File may be compiled.
8376 Normally, when using Project Files, only sources that are part of a Project
8377 File may be compile. When this switch is used, a source outside of all Project
8378 Files may be compiled. The ALI file and the object file will be put in the
8379 object directory of the main Project. The compilation switches used will only
8380 be those specified on the command line.
8382 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
8383 Indicates that external variable @var{name} has the value @var{value}.
8384 The Project Manager will use this value for occurrences of
8385 @code{external(name)} when parsing the project file.
8386 See @ref{Switches Related to Project Files}.
8389 @cindex @option{^-z^/NOMAIN^} (@code{gnatmake})
8390 No main subprogram. Bind and link the program even if the unit name
8391 given on the command line is a package name. The resulting executable
8392 will execute the elaboration routines of the package and its closure,
8393 then the finalization routines.
8396 @cindex @option{^-g^/DEBUG^} (@code{gnatmake})
8397 Enable debugging. This switch is simply passed to the compiler and to the
8403 @item @code{gcc} @asis{switches}
8405 Any uppercase or multi-character switch that is not a @code{gnatmake} switch
8406 is passed to @code{gcc} (e.g. @option{-O}, @option{-gnato,} etc.)
8409 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
8410 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
8411 automatically treated as a compiler switch, and passed on to all
8412 compilations that are carried out.
8417 Source and library search path switches:
8421 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
8422 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatmake})
8423 When looking for source files also look in directory @var{dir}.
8424 The order in which source files search is undertaken is
8425 described in @ref{Search Paths and the Run-Time Library (RTL)}.
8427 @item ^-aL^/SKIP_MISSING=^@var{dir}
8428 @cindex @option{^-aL^/SKIP_MISSING^} (@code{gnatmake})
8429 Consider @var{dir} as being an externally provided Ada library.
8430 Instructs @code{gnatmake} to skip compilation units whose @file{.ALI}
8431 files have been located in directory @var{dir}. This allows you to have
8432 missing bodies for the units in @var{dir} and to ignore out of date bodies
8433 for the same units. You still need to specify
8434 the location of the specs for these units by using the switches
8435 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
8436 or @option{^-I^/SEARCH=^@var{dir}}.
8437 Note: this switch is provided for compatibility with previous versions
8438 of @code{gnatmake}. The easier method of causing standard libraries
8439 to be excluded from consideration is to write-protect the corresponding
8442 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
8443 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatmake})
8444 When searching for library and object files, look in directory
8445 @var{dir}. The order in which library files are searched is described in
8446 @ref{Search Paths for gnatbind}.
8448 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
8449 @cindex Search paths, for @code{gnatmake}
8450 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@code{gnatmake})
8451 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
8452 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8454 @item ^-I^/SEARCH=^@var{dir}
8455 @cindex @option{^-I^/SEARCH^} (@code{gnatmake})
8456 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
8457 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8459 @item ^-I-^/NOCURRENT_DIRECTORY^
8460 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatmake})
8461 @cindex Source files, suppressing search
8462 Do not look for source files in the directory containing the source
8463 file named in the command line.
8464 Do not look for ALI or object files in the directory
8465 where @code{gnatmake} was invoked.
8467 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
8468 @cindex @option{^-L^/LIBRARY_SEARCH^} (@code{gnatmake})
8469 @cindex Linker libraries
8470 Add directory @var{dir} to the list of directories in which the linker
8471 will search for libraries. This is equivalent to
8472 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
8474 Furthermore, under Windows, the sources pointed to by the libraries path
8475 set in the registry are not searched for.
8479 @cindex @option{-nostdinc} (@code{gnatmake})
8480 Do not look for source files in the system default directory.
8483 @cindex @option{-nostdlib} (@code{gnatmake})
8484 Do not look for library files in the system default directory.
8486 @item --RTS=@var{rts-path}
8487 @cindex @option{--RTS} (@code{gnatmake})
8488 Specifies the default location of the runtime library. GNAT looks for the
8490 in the following directories, and stops as soon as a valid runtime is found
8491 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
8492 @file{ada_object_path} present):
8495 @item <current directory>/$rts_path
8497 @item <default-search-dir>/$rts_path
8499 @item <default-search-dir>/rts-$rts_path
8503 The selected path is handled like a normal RTS path.
8507 @node Mode Switches for gnatmake
8508 @section Mode Switches for @code{gnatmake}
8511 The mode switches (referred to as @code{mode_switches}) allow the
8512 inclusion of switches that are to be passed to the compiler itself, the
8513 binder or the linker. The effect of a mode switch is to cause all
8514 subsequent switches up to the end of the switch list, or up to the next
8515 mode switch, to be interpreted as switches to be passed on to the
8516 designated component of GNAT.
8520 @item -cargs @var{switches}
8521 @cindex @option{-cargs} (@code{gnatmake})
8522 Compiler switches. Here @var{switches} is a list of switches
8523 that are valid switches for @code{gcc}. They will be passed on to
8524 all compile steps performed by @code{gnatmake}.
8526 @item -bargs @var{switches}
8527 @cindex @option{-bargs} (@code{gnatmake})
8528 Binder switches. Here @var{switches} is a list of switches
8529 that are valid switches for @code{gnatbind}. They will be passed on to
8530 all bind steps performed by @code{gnatmake}.
8532 @item -largs @var{switches}
8533 @cindex @option{-largs} (@code{gnatmake})
8534 Linker switches. Here @var{switches} is a list of switches
8535 that are valid switches for @code{gnatlink}. They will be passed on to
8536 all link steps performed by @code{gnatmake}.
8538 @item -margs @var{switches}
8539 @cindex @option{-margs} (@code{gnatmake})
8540 Make switches. The switches are directly interpreted by @code{gnatmake},
8541 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
8545 @node Notes on the Command Line
8546 @section Notes on the Command Line
8549 This section contains some additional useful notes on the operation
8550 of the @code{gnatmake} command.
8554 @cindex Recompilation, by @code{gnatmake}
8555 If @code{gnatmake} finds no ALI files, it recompiles the main program
8556 and all other units required by the main program.
8557 This means that @code{gnatmake}
8558 can be used for the initial compile, as well as during subsequent steps of
8559 the development cycle.
8562 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
8563 is a subunit or body of a generic unit, @code{gnatmake} recompiles
8564 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
8568 In @code{gnatmake} the switch @option{^-I^/SEARCH^}
8569 is used to specify both source and
8570 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8571 instead if you just want to specify
8572 source paths only and @option{^-aO^/OBJECT_SEARCH^}
8573 if you want to specify library paths
8577 @code{gnatmake} will ignore any files whose ALI file is write-protected.
8578 This may conveniently be used to exclude standard libraries from
8579 consideration and in particular it means that the use of the
8580 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
8581 unless @option{^-a^/ALL_FILES^} is also specified.
8584 @code{gnatmake} has been designed to make the use of Ada libraries
8585 particularly convenient. Assume you have an Ada library organized
8586 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
8587 of your Ada compilation units,
8588 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
8589 specs of these units, but no bodies. Then to compile a unit
8590 stored in @code{main.adb}, which uses this Ada library you would just type
8594 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
8597 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
8598 /SKIP_MISSING=@i{[OBJ_DIR]} main
8603 Using @code{gnatmake} along with the
8604 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
8605 switch provides a mechanism for avoiding unnecessary rcompilations. Using
8607 you can update the comments/format of your
8608 source files without having to recompile everything. Note, however, that
8609 adding or deleting lines in a source files may render its debugging
8610 info obsolete. If the file in question is a spec, the impact is rather
8611 limited, as that debugging info will only be useful during the
8612 elaboration phase of your program. For bodies the impact can be more
8613 significant. In all events, your debugger will warn you if a source file
8614 is more recent than the corresponding object, and alert you to the fact
8615 that the debugging information may be out of date.
8618 @node How gnatmake Works
8619 @section How @code{gnatmake} Works
8622 Generally @code{gnatmake} automatically performs all necessary
8623 recompilations and you don't need to worry about how it works. However,
8624 it may be useful to have some basic understanding of the @code{gnatmake}
8625 approach and in particular to understand how it uses the results of
8626 previous compilations without incorrectly depending on them.
8628 First a definition: an object file is considered @dfn{up to date} if the
8629 corresponding ALI file exists and if all the source files listed in the
8630 dependency section of this ALI file have time stamps matching those in
8631 the ALI file. This means that neither the source file itself nor any
8632 files that it depends on have been modified, and hence there is no need
8633 to recompile this file.
8635 @code{gnatmake} works by first checking if the specified main unit is up
8636 to date. If so, no compilations are required for the main unit. If not,
8637 @code{gnatmake} compiles the main program to build a new ALI file that
8638 reflects the latest sources. Then the ALI file of the main unit is
8639 examined to find all the source files on which the main program depends,
8640 and @code{gnatmake} recursively applies the above procedure on all these files.
8642 This process ensures that @code{gnatmake} only trusts the dependencies
8643 in an existing ALI file if they are known to be correct. Otherwise it
8644 always recompiles to determine a new, guaranteed accurate set of
8645 dependencies. As a result the program is compiled ``upside down'' from what may
8646 be more familiar as the required order of compilation in some other Ada
8647 systems. In particular, clients are compiled before the units on which
8648 they depend. The ability of GNAT to compile in any order is critical in
8649 allowing an order of compilation to be chosen that guarantees that
8650 @code{gnatmake} will recompute a correct set of new dependencies if
8653 When invoking @code{gnatmake} with several @var{file_names}, if a unit is
8654 imported by several of the executables, it will be recompiled at most once.
8656 Note: when using non-standard naming conventions
8657 (See @ref{Using Other File Names}), changing through a configuration pragmas
8658 file the version of a source and invoking @code{gnatmake} to recompile may
8659 have no effect, if the previous version of the source is still accessible
8660 by @code{gnatmake}. It may be necessary to use the switch ^-f^/FORCE_COMPILE^.
8662 @node Examples of gnatmake Usage
8663 @section Examples of @code{gnatmake} Usage
8666 @item gnatmake hello.adb
8667 Compile all files necessary to bind and link the main program
8668 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
8669 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
8671 @item gnatmake main1 main2 main3
8672 Compile all files necessary to bind and link the main programs
8673 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
8674 (containing unit @code{Main2}) and @file{main3.adb}
8675 (containing unit @code{Main3}) and bind and link the resulting object files
8676 to generate three executable files @file{^main1^MAIN1.EXE^},
8677 @file{^main2^MAIN2.EXE^}
8678 and @file{^main3^MAIN3.EXE^}.
8681 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
8685 @item gnatmake Main_Unit /QUIET
8686 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
8687 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
8689 Compile all files necessary to bind and link the main program unit
8690 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
8691 be done with optimization level 2 and the order of elaboration will be
8692 listed by the binder. @code{gnatmake} will operate in quiet mode, not
8693 displaying commands it is executing.
8696 @c *************************
8697 @node Improving Performance
8698 @chapter Improving Performance
8699 @cindex Improving performance
8702 This chapter presents several topics related to program performance.
8703 It first describes some of the tradeoffs that need to be considered
8704 and some of the techniques for making your program run faster.
8705 It then documents the @command{gnatelim} tool, which can reduce
8706 the size of program executables.
8710 * Performance Considerations::
8711 * Reducing the Size of Ada Executables with gnatelim::
8715 @c *****************************
8716 @node Performance Considerations
8717 @section Performance Considerations
8720 The GNAT system provides a number of options that allow a trade-off
8725 performance of the generated code
8728 speed of compilation
8731 minimization of dependences and recompilation
8734 the degree of run-time checking.
8738 The defaults (if no options are selected) aim at improving the speed
8739 of compilation and minimizing dependences, at the expense of performance
8740 of the generated code:
8747 no inlining of subprogram calls
8750 all run-time checks enabled except overflow and elaboration checks
8754 These options are suitable for most program development purposes. This
8755 chapter describes how you can modify these choices, and also provides
8756 some guidelines on debugging optimized code.
8759 * Controlling Run-Time Checks::
8760 * Use of Restrictions::
8761 * Optimization Levels::
8762 * Debugging Optimized Code::
8763 * Inlining of Subprograms::
8764 * Optimization and Strict Aliasing::
8766 * Coverage Analysis::
8770 @node Controlling Run-Time Checks
8771 @subsection Controlling Run-Time Checks
8774 By default, GNAT generates all run-time checks, except arithmetic overflow
8775 checking for integer operations and checks for access before elaboration on
8776 subprogram calls. The latter are not required in default mode, because all
8777 necessary checking is done at compile time.
8778 @cindex @option{-gnatp} (@code{gcc})
8779 @cindex @option{-gnato} (@code{gcc})
8780 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
8781 be modified. @xref{Run-Time Checks}.
8783 Our experience is that the default is suitable for most development
8786 We treat integer overflow specially because these
8787 are quite expensive and in our experience are not as important as other
8788 run-time checks in the development process. Note that division by zero
8789 is not considered an overflow check, and divide by zero checks are
8790 generated where required by default.
8792 Elaboration checks are off by default, and also not needed by default, since
8793 GNAT uses a static elaboration analysis approach that avoids the need for
8794 run-time checking. This manual contains a full chapter discussing the issue
8795 of elaboration checks, and if the default is not satisfactory for your use,
8796 you should read this chapter.
8798 For validity checks, the minimal checks required by the Ada Reference
8799 Manual (for case statements and assignments to array elements) are on
8800 by default. These can be suppressed by use of the @option{-gnatVn} switch.
8801 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
8802 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
8803 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
8804 are also suppressed entirely if @option{-gnatp} is used.
8806 @cindex Overflow checks
8807 @cindex Checks, overflow
8810 @cindex pragma Suppress
8811 @cindex pragma Unsuppress
8812 Note that the setting of the switches controls the default setting of
8813 the checks. They may be modified using either @code{pragma Suppress} (to
8814 remove checks) or @code{pragma Unsuppress} (to add back suppressed
8815 checks) in the program source.
8817 @node Use of Restrictions
8818 @subsection Use of Restrictions
8821 The use of pragma Restrictions allows you to control which features are
8822 permitted in your program. Apart from the obvious point that if you avoid
8823 relatively expensive features like finalization (enforceable by the use
8824 of pragma Restrictions (No_Finalization), the use of this pragma does not
8825 affect the generated code in most cases.
8827 One notable exception to this rule is that the possibility of task abort
8828 results in some distributed overhead, particularly if finalization or
8829 exception handlers are used. The reason is that certain sections of code
8830 have to be marked as non-abortable.
8832 If you use neither the @code{abort} statement, nor asynchronous transfer
8833 of control (@code{select .. then abort}), then this distributed overhead
8834 is removed, which may have a general positive effect in improving
8835 overall performance. Especially code involving frequent use of tasking
8836 constructs and controlled types will show much improved performance.
8837 The relevant restrictions pragmas are
8840 pragma Restrictions (No_Abort_Statements);
8841 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
8845 It is recommended that these restriction pragmas be used if possible. Note
8846 that this also means that you can write code without worrying about the
8847 possibility of an immediate abort at any point.
8849 @node Optimization Levels
8850 @subsection Optimization Levels
8851 @cindex @option{^-O^/OPTIMIZE^} (@code{gcc})
8854 The default is optimization off. This results in the fastest compile
8855 times, but GNAT makes absolutely no attempt to optimize, and the
8856 generated programs are considerably larger and slower than when
8857 optimization is enabled. You can use the
8859 @option{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
8862 @code{OPTIMIZE} qualifier
8864 to @code{gcc} to control the optimization level:
8867 @item ^-O0^/OPTIMIZE=NONE^
8868 No optimization (the default);
8869 generates unoptimized code but has
8870 the fastest compilation time.
8872 @item ^-O1^/OPTIMIZE=SOME^
8873 Medium level optimization;
8874 optimizes reasonably well but does not
8875 degrade compilation time significantly.
8877 @item ^-O2^/OPTIMIZE=ALL^
8879 @itemx /OPTIMIZE=DEVELOPMENT
8882 generates highly optimized code and has
8883 the slowest compilation time.
8885 @item ^-O3^/OPTIMIZE=INLINING^
8886 Full optimization as in @option{-O2},
8887 and also attempts automatic inlining of small
8888 subprograms within a unit (@pxref{Inlining of Subprograms}).
8892 Higher optimization levels perform more global transformations on the
8893 program and apply more expensive analysis algorithms in order to generate
8894 faster and more compact code. The price in compilation time, and the
8895 resulting improvement in execution time,
8896 both depend on the particular application and the hardware environment.
8897 You should experiment to find the best level for your application.
8899 Since the precise set of optimizations done at each level will vary from
8900 release to release (and sometime from target to target), it is best to think
8901 of the optimization settings in general terms.
8902 The @cite{Using GNU GCC} manual contains details about
8903 ^the @option{-O} settings and a number of @option{-f} options that^how to^
8904 individually enable or disable specific optimizations.
8906 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
8907 been tested extensively at all optimization levels. There are some bugs
8908 which appear only with optimization turned on, but there have also been
8909 bugs which show up only in @emph{unoptimized} code. Selecting a lower
8910 level of optimization does not improve the reliability of the code
8911 generator, which in practice is highly reliable at all optimization
8914 Note regarding the use of @option{-O3}: The use of this optimization level
8915 is generally discouraged with GNAT, since it often results in larger
8916 executables which run more slowly. See further discussion of this point
8917 in @pxref{Inlining of Subprograms}.
8919 @node Debugging Optimized Code
8920 @subsection Debugging Optimized Code
8921 @cindex Debugging optimized code
8922 @cindex Optimization and debugging
8925 Although it is possible to do a reasonable amount of debugging at
8927 non-zero optimization levels,
8928 the higher the level the more likely that
8931 @option{/OPTIMIZE} settings other than @code{NONE},
8932 such settings will make it more likely that
8934 source-level constructs will have been eliminated by optimization.
8935 For example, if a loop is strength-reduced, the loop
8936 control variable may be completely eliminated and thus cannot be
8937 displayed in the debugger.
8938 This can only happen at @option{-O2} or @option{-O3}.
8939 Explicit temporary variables that you code might be eliminated at
8940 ^level^setting^ @option{-O1} or higher.
8942 The use of the @option{^-g^/DEBUG^} switch,
8943 @cindex @option{^-g^/DEBUG^} (@code{gcc})
8944 which is needed for source-level debugging,
8945 affects the size of the program executable on disk,
8946 and indeed the debugging information can be quite large.
8947 However, it has no effect on the generated code (and thus does not
8948 degrade performance)
8950 Since the compiler generates debugging tables for a compilation unit before
8951 it performs optimizations, the optimizing transformations may invalidate some
8952 of the debugging data. You therefore need to anticipate certain
8953 anomalous situations that may arise while debugging optimized code.
8954 These are the most common cases:
8958 @i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next}
8960 the PC bouncing back and forth in the code. This may result from any of
8961 the following optimizations:
8965 @i{Common subexpression elimination:} using a single instance of code for a
8966 quantity that the source computes several times. As a result you
8967 may not be able to stop on what looks like a statement.
8970 @i{Invariant code motion:} moving an expression that does not change within a
8971 loop, to the beginning of the loop.
8974 @i{Instruction scheduling:} moving instructions so as to
8975 overlap loads and stores (typically) with other code, or in
8976 general to move computations of values closer to their uses. Often
8977 this causes you to pass an assignment statement without the assignment
8978 happening and then later bounce back to the statement when the
8979 value is actually needed. Placing a breakpoint on a line of code
8980 and then stepping over it may, therefore, not always cause all the
8981 expected side-effects.
8985 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
8986 two identical pieces of code are merged and the program counter suddenly
8987 jumps to a statement that is not supposed to be executed, simply because
8988 it (and the code following) translates to the same thing as the code
8989 that @emph{was} supposed to be executed. This effect is typically seen in
8990 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
8991 a @code{break} in a C @code{^switch^switch^} statement.
8994 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
8995 There are various reasons for this effect:
8999 In a subprogram prologue, a parameter may not yet have been moved to its
9003 A variable may be dead, and its register re-used. This is
9004 probably the most common cause.
9007 As mentioned above, the assignment of a value to a variable may
9011 A variable may be eliminated entirely by value propagation or
9012 other means. In this case, GCC may incorrectly generate debugging
9013 information for the variable
9017 In general, when an unexpected value appears for a local variable or parameter
9018 you should first ascertain if that value was actually computed by
9019 your program, as opposed to being incorrectly reported by the debugger.
9021 array elements in an object designated by an access value
9022 are generally less of a problem, once you have ascertained that the access
9024 Typically, this means checking variables in the preceding code and in the
9025 calling subprogram to verify that the value observed is explainable from other
9026 values (one must apply the procedure recursively to those
9027 other values); or re-running the code and stopping a little earlier
9028 (perhaps before the call) and stepping to better see how the variable obtained
9029 the value in question; or continuing to step @emph{from} the point of the
9030 strange value to see if code motion had simply moved the variable's
9035 In light of such anomalies, a recommended technique is to use @option{-O0}
9036 early in the software development cycle, when extensive debugging capabilities
9037 are most needed, and then move to @option{-O1} and later @option{-O2} as
9038 the debugger becomes less critical.
9039 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
9040 a release management issue.
9042 Note that if you use @option{-g} you can then use the @command{strip} program
9043 on the resulting executable,
9044 which removes both debugging information and global symbols.
9047 @node Inlining of Subprograms
9048 @subsection Inlining of Subprograms
9051 A call to a subprogram in the current unit is inlined if all the
9052 following conditions are met:
9056 The optimization level is at least @option{-O1}.
9059 The called subprogram is suitable for inlining: It must be small enough
9060 and not contain nested subprograms or anything else that @code{gcc}
9061 cannot support in inlined subprograms.
9064 The call occurs after the definition of the body of the subprogram.
9067 @cindex pragma Inline
9069 Either @code{pragma Inline} applies to the subprogram or it is
9070 small and automatic inlining (optimization level @option{-O3}) is
9075 Calls to subprograms in @code{with}'ed units are normally not inlined.
9076 To achieve this level of inlining, the following conditions must all be
9081 The optimization level is at least @option{-O1}.
9084 The called subprogram is suitable for inlining: It must be small enough
9085 and not contain nested subprograms or anything else @code{gcc} cannot
9086 support in inlined subprograms.
9089 The call appears in a body (not in a package spec).
9092 There is a @code{pragma Inline} for the subprogram.
9095 @cindex @option{-gnatn} (@code{gcc})
9096 The @option{^-gnatn^/INLINE^} switch
9097 is used in the @code{gcc} command line
9100 Note that specifying the @option{-gnatn} switch causes additional
9101 compilation dependencies. Consider the following:
9103 @smallexample @c ada
9123 With the default behavior (no @option{-gnatn} switch specified), the
9124 compilation of the @code{Main} procedure depends only on its own source,
9125 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
9126 means that editing the body of @code{R} does not require recompiling
9129 On the other hand, the call @code{R.Q} is not inlined under these
9130 circumstances. If the @option{-gnatn} switch is present when @code{Main}
9131 is compiled, the call will be inlined if the body of @code{Q} is small
9132 enough, but now @code{Main} depends on the body of @code{R} in
9133 @file{r.adb} as well as on the spec. This means that if this body is edited,
9134 the main program must be recompiled. Note that this extra dependency
9135 occurs whether or not the call is in fact inlined by @code{gcc}.
9137 The use of front end inlining with @option{-gnatN} generates similar
9138 additional dependencies.
9140 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@code{gcc})
9141 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
9142 can be used to prevent
9143 all inlining. This switch overrides all other conditions and ensures
9144 that no inlining occurs. The extra dependences resulting from
9145 @option{-gnatn} will still be active, even if
9146 this switch is used to suppress the resulting inlining actions.
9148 Note regarding the use of @option{-O3}: There is no difference in inlining
9149 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
9150 pragma @code{Inline} assuming the use of @option{-gnatn}
9151 or @option{-gnatN} (the switches that activate inlining). If you have used
9152 pragma @code{Inline} in appropriate cases, then it is usually much better
9153 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
9154 in this case only has the effect of inlining subprograms you did not
9155 think should be inlined. We often find that the use of @option{-O3} slows
9156 down code by performing excessive inlining, leading to increased instruction
9157 cache pressure from the increased code size. So the bottom line here is
9158 that you should not automatically assume that @option{-O3} is better than
9159 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
9160 it actually improves performance.
9162 @node Optimization and Strict Aliasing
9163 @subsection Optimization and Strict Aliasing
9165 @cindex Strict Aliasing
9166 @cindex No_Strict_Aliasing
9169 The strong typing capabilities of Ada allow an optimizer to generate
9170 efficient code in situations where other languages would be forced to
9171 make worst case assumptions preventing such optimizations. Consider
9172 the following example:
9174 @smallexample @c ada
9177 type Int1 is new Integer;
9178 type Int2 is new Integer;
9179 type Int1A is access Int1;
9180 type Int2A is access Int2;
9187 for J in Data'Range loop
9188 if Data (J) = Int1V.all then
9189 Int2V.all := Int2V.all + 1;
9198 In this example, since the variable @code{Int1V} can only access objects
9199 of type @code{Int1}, and @code{Int2V} can only access objects of type
9200 @code{Int2}, there is no possibility that the assignment to
9201 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
9202 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
9203 for all iterations of the loop and avoid the extra memory reference
9204 required to dereference it each time through the loop.
9206 This kind of optimziation, called strict aliasing analysis, is
9207 triggered by specifying an optimization level of @option{-O2} or
9208 higher and allows @code{GNAT} to generate more efficient code
9209 when access values are involved.
9211 However, although this optimization is always correct in terms of
9212 the formal semantics of the Ada Reference Manual, difficulties can
9213 arise if features like @code{Unchecked_Conversion} are used to break
9214 the typing system. Consider the following complete program example:
9216 @smallexample @c ada
9219 type int1 is new integer;
9220 type int2 is new integer;
9221 type a1 is access int1;
9222 type a2 is access int2;
9227 function to_a2 (Input : a1) return a2;
9230 with Unchecked_Conversion;
9232 function to_a2 (Input : a1) return a2 is
9234 new Unchecked_Conversion (a1, a2);
9236 return to_a2u (Input);
9242 with Text_IO; use Text_IO;
9244 v1 : a1 := new int1;
9245 v2 : a2 := to_a2 (v1);
9249 put_line (int1'image (v1.all));
9255 This program prints out 0 in @code{-O0} or @code{-O1}
9256 mode, but it prints out 1 in @code{-O2} mode. That's
9257 because in strict aliasing mode, the compiler can and
9258 does assume that the assignment to @code{v2.all} could not
9259 affect the value of @code{v1.all}, since different types
9262 This behavior is not a case of non-conformance with the standard, since
9263 the Ada RM specifies that an unchecked conversion where the resulting
9264 bit pattern is not a correct value of the target type can result in an
9265 abnormal value and attempting to reference an abnormal value makes the
9266 execution of a program erroneous. That's the case here since the result
9267 does not point to an object of type @code{int2}. This means that the
9268 effect is entirely unpredictable.
9270 However, although that explanation may satisfy a language
9271 lawyer, in practice an applications programmer expects an
9272 unchecked conversion involving pointers to create true
9273 aliases and the behavior of printing 1 seems plain wrong.
9274 In this case, the strict aliasing optimization is unwelcome.
9276 Indeed the compiler recognizes this possibility, and the
9277 unchecked conversion generates a warning:
9280 p2.adb:5:07: warning: possible aliasing problem with type "a2"
9281 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
9282 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
9286 Unfortunately the problem is recognized when compiling the body of
9287 package @code{p2}, but the actual "bad" code is generated while
9288 compiling the body of @code{m} and this latter compilation does not see
9289 the suspicious @code{Unchecked_Conversion}.
9291 As implied by the warning message, there are approaches you can use to
9292 avoid the unwanted strict aliasing optimization in a case like this.
9294 One possibility is to simply avoid the use of @code{-O2}, but
9295 that is a bit drastic, since it throws away a number of useful
9296 optimizations that do not involve strict aliasing assumptions.
9298 A less drastic approach is to compile the program using the
9299 option @code{-fno-strict-aliasing}. Actually it is only the
9300 unit containing the dereferencing of the suspicious pointer
9301 that needs to be compiled. So in this case, if we compile
9302 unit @code{m} with this switch, then we get the expected
9303 value of zero printed. Analyzing which units might need
9304 the switch can be painful, so a more reasonable approach
9305 is to compile the entire program with options @code{-O2}
9306 and @code{-fno-strict-aliasing}. If the performance is
9307 satisfactory with this combination of options, then the
9308 advantage is that the entire issue of possible "wrong"
9309 optimization due to strict aliasing is avoided.
9311 To avoid the use of compiler switches, the configuration
9312 pragma @code{No_Strict_Aliasing} with no parameters may be
9313 used to specify that for all access types, the strict
9314 aliasing optimization should be suppressed.
9316 However, these approaches are still overkill, in that they causes
9317 all manipulations of all access values to be deoptimized. A more
9318 refined approach is to concentrate attention on the specific
9319 access type identified as problematic.
9321 First, if a careful analysis of uses of the pointer shows
9322 that there are no possible problematic references, then
9323 the warning can be suppressed by bracketing the
9324 instantiation of @code{Unchecked_Conversion} to turn
9327 @smallexample @c ada
9328 pragma Warnings (Off);
9330 new Unchecked_Conversion (a1, a2);
9331 pragma Warnings (On);
9335 Of course that approach is not appropriate for this particular
9336 example, since indeed there is a problematic reference. In this
9337 case we can take one of two other approaches.
9339 The first possibility is to move the instantiation of unchecked
9340 conversion to the unit in which the type is declared. In
9341 this example, we would move the instantiation of
9342 @code{Unchecked_Conversion} from the body of package
9343 @code{p2} to the spec of package @code{p1}. Now the
9344 warning disappears. That's because any use of the
9345 access type knows there is a suspicious unchecked
9346 conversion, and the strict aliasing optimization
9347 is automatically suppressed for the type.
9349 If it is not practical to move the unchecked conversion to the same unit
9350 in which the destination access type is declared (perhaps because the
9351 source type is not visible in that unit), you may use pragma
9352 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
9353 same declarative sequence as the declaration of the access type:
9355 @smallexample @c ada
9356 type a2 is access int2;
9357 pragma No_Strict_Aliasing (a2);
9361 Here again, the compiler now knows that the strict aliasing optimization
9362 should be suppressed for any reference to type @code{a2} and the
9363 expected behavior is obtained.
9365 Finally, note that although the compiler can generate warnings for
9366 simple cases of unchecked conversions, there are tricker and more
9367 indirect ways of creating type incorrect aliases which the compiler
9368 cannot detect. Examples are the use of address overlays and unchecked
9369 conversions involving composite types containing access types as
9370 components. In such cases, no warnings are generated, but there can
9371 still be aliasing problems. One safe coding practice is to forbid the
9372 use of address clauses for type overlaying, and to allow unchecked
9373 conversion only for primitive types. This is not really a significant
9374 restriction since any possible desired effect can be achieved by
9375 unchecked conversion of access values.
9378 @node Coverage Analysis
9379 @subsection Coverage Analysis
9382 GNAT supports the Digital Performance Coverage Analyzer (PCA), which allows
9383 the user to determine the distribution of execution time across a program,
9384 @pxref{Profiling} for details of usage.
9387 @node Reducing the Size of Ada Executables with gnatelim
9388 @section Reducing the Size of Ada Executables with @code{gnatelim}
9392 This section describes @command{gnatelim}, a tool which detects unused
9393 subprograms and helps the compiler to create a smaller executable for your
9398 * Running gnatelim::
9399 * Correcting the List of Eliminate Pragmas::
9400 * Making Your Executables Smaller::
9401 * Summary of the gnatelim Usage Cycle::
9404 @node About gnatelim
9405 @subsection About @code{gnatelim}
9408 When a program shares a set of Ada
9409 packages with other programs, it may happen that this program uses
9410 only a fraction of the subprograms defined in these packages. The code
9411 created for these unused subprograms increases the size of the executable.
9413 @code{gnatelim} tracks unused subprograms in an Ada program and
9414 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
9415 subprograms that are declared but never called. By placing the list of
9416 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
9417 recompiling your program, you may decrease the size of its executable,
9418 because the compiler will not generate the code for 'eliminated' subprograms.
9419 See GNAT Reference Manual for more information about this pragma.
9421 @code{gnatelim} needs as its input data the name of the main subprogram
9422 and a bind file for a main subprogram.
9424 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
9425 the main subprogram. @code{gnatelim} can work with both Ada and C
9426 bind files; when both are present, it uses the Ada bind file.
9427 The following commands will build the program and create the bind file:
9430 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
9431 $ gnatbind main_prog
9434 Note that @code{gnatelim} needs neither object nor ALI files.
9436 @node Running gnatelim
9437 @subsection Running @code{gnatelim}
9440 @code{gnatelim} has the following command-line interface:
9443 $ gnatelim [options] name
9447 @code{name} should be a name of a source file that contains the main subprogram
9448 of a program (partition).
9450 @code{gnatelim} has the following switches:
9455 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
9456 Quiet mode: by default @code{gnatelim} outputs to the standard error
9457 stream the number of program units left to be processed. This option turns
9461 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
9462 Verbose mode: @code{gnatelim} version information is printed as Ada
9463 comments to the standard output stream. Also, in addition to the number of
9464 program units left @code{gnatelim} will output the name of the current unit
9468 @cindex @option{^-a^/ALL^} (@command{gnatelim})
9469 Also look for subprograms from the GNAT run time that can be eliminated. Note
9470 that when @file{gnat.adc} is produced using this switch, the entire program
9471 must be recompiled with switch @option{^-a^/ALL_FILES^} to @code{gnatmake}.
9473 @item ^-I^/INCLUDE_DIRS=^@var{dir}
9474 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
9475 When looking for source files also look in directory @var{dir}. Specifying
9476 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
9477 sources in the current directory.
9479 @item ^-b^/BIND_FILE=^@var{bind_file}
9480 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
9481 Specifies @var{bind_file} as the bind file to process. If not set, the name
9482 of the bind file is computed from the full expanded Ada name
9483 of a main subprogram.
9485 @item ^-C^/CONFIG_FILE=^@var{config_file}
9486 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
9487 Specifies a file @var{config_file} that contains configuration pragmas. The
9488 file must be specified with full path.
9490 @item ^--GCC^/COMPILER^=@var{compiler_name}
9491 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
9492 Instructs @code{gnatelim} to use specific @code{gcc} compiler instead of one
9493 available on the path.
9495 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
9496 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
9497 Instructs @code{gnatelim} to use specific @code{gnatmake} instead of one
9498 available on the path.
9502 @code{gnatelim} sends its output to the standard output stream, and all the
9503 tracing and debug information is sent to the standard error stream.
9504 In order to produce a proper GNAT configuration file
9505 @file{gnat.adc}, redirection must be used:
9509 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
9512 $ gnatelim main_prog.adb > gnat.adc
9521 $ gnatelim main_prog.adb >> gnat.adc
9525 in order to append the @code{gnatelim} output to the existing contents of
9529 @node Correcting the List of Eliminate Pragmas
9530 @subsection Correcting the List of Eliminate Pragmas
9533 In some rare cases @code{gnatelim} may try to eliminate
9534 subprograms that are actually called in the program. In this case, the
9535 compiler will generate an error message of the form:
9538 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
9542 You will need to manually remove the wrong @code{Eliminate} pragmas from
9543 the @file{gnat.adc} file. You should recompile your program
9544 from scratch after that, because you need a consistent @file{gnat.adc} file
9545 during the entire compilation.
9547 @node Making Your Executables Smaller
9548 @subsection Making Your Executables Smaller
9551 In order to get a smaller executable for your program you now have to
9552 recompile the program completely with the new @file{gnat.adc} file
9553 created by @code{gnatelim} in your current directory:
9556 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9560 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
9561 recompile everything
9562 with the set of pragmas @code{Eliminate} that you have obtained with
9563 @command{gnatelim}).
9565 Be aware that the set of @code{Eliminate} pragmas is specific to each
9566 program. It is not recommended to merge sets of @code{Eliminate}
9567 pragmas created for different programs in one @file{gnat.adc} file.
9569 @node Summary of the gnatelim Usage Cycle
9570 @subsection Summary of the gnatelim Usage Cycle
9573 Here is a quick summary of the steps to be taken in order to reduce
9574 the size of your executables with @code{gnatelim}. You may use
9575 other GNAT options to control the optimization level,
9576 to produce the debugging information, to set search path, etc.
9583 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
9584 $ gnatbind main_prog
9588 Generate a list of @code{Eliminate} pragmas
9591 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
9594 $ gnatelim main_prog >[>] gnat.adc
9599 Recompile the application
9602 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9607 @c ********************************
9608 @node Renaming Files Using gnatchop
9609 @chapter Renaming Files Using @code{gnatchop}
9613 This chapter discusses how to handle files with multiple units by using
9614 the @code{gnatchop} utility. This utility is also useful in renaming
9615 files to meet the standard GNAT default file naming conventions.
9618 * Handling Files with Multiple Units::
9619 * Operating gnatchop in Compilation Mode::
9620 * Command Line for gnatchop::
9621 * Switches for gnatchop::
9622 * Examples of gnatchop Usage::
9625 @node Handling Files with Multiple Units
9626 @section Handling Files with Multiple Units
9629 The basic compilation model of GNAT requires that a file submitted to the
9630 compiler have only one unit and there be a strict correspondence
9631 between the file name and the unit name.
9633 The @code{gnatchop} utility allows both of these rules to be relaxed,
9634 allowing GNAT to process files which contain multiple compilation units
9635 and files with arbitrary file names. @code{gnatchop}
9636 reads the specified file and generates one or more output files,
9637 containing one unit per file. The unit and the file name correspond,
9638 as required by GNAT.
9640 If you want to permanently restructure a set of ``foreign'' files so that
9641 they match the GNAT rules, and do the remaining development using the
9642 GNAT structure, you can simply use @command{gnatchop} once, generate the
9643 new set of files and work with them from that point on.
9645 Alternatively, if you want to keep your files in the ``foreign'' format,
9646 perhaps to maintain compatibility with some other Ada compilation
9647 system, you can set up a procedure where you use @command{gnatchop} each
9648 time you compile, regarding the source files that it writes as temporary
9649 files that you throw away.
9651 @node Operating gnatchop in Compilation Mode
9652 @section Operating gnatchop in Compilation Mode
9655 The basic function of @code{gnatchop} is to take a file with multiple units
9656 and split it into separate files. The boundary between files is reasonably
9657 clear, except for the issue of comments and pragmas. In default mode, the
9658 rule is that any pragmas between units belong to the previous unit, except
9659 that configuration pragmas always belong to the following unit. Any comments
9660 belong to the following unit. These rules
9661 almost always result in the right choice of
9662 the split point without needing to mark it explicitly and most users will
9663 find this default to be what they want. In this default mode it is incorrect to
9664 submit a file containing only configuration pragmas, or one that ends in
9665 configuration pragmas, to @code{gnatchop}.
9667 However, using a special option to activate ``compilation mode'',
9669 can perform another function, which is to provide exactly the semantics
9670 required by the RM for handling of configuration pragmas in a compilation.
9671 In the absence of configuration pragmas (at the main file level), this
9672 option has no effect, but it causes such configuration pragmas to be handled
9673 in a quite different manner.
9675 First, in compilation mode, if @code{gnatchop} is given a file that consists of
9676 only configuration pragmas, then this file is appended to the
9677 @file{gnat.adc} file in the current directory. This behavior provides
9678 the required behavior described in the RM for the actions to be taken
9679 on submitting such a file to the compiler, namely that these pragmas
9680 should apply to all subsequent compilations in the same compilation
9681 environment. Using GNAT, the current directory, possibly containing a
9682 @file{gnat.adc} file is the representation
9683 of a compilation environment. For more information on the
9684 @file{gnat.adc} file, see the section on handling of configuration
9685 pragmas @pxref{Handling of Configuration Pragmas}.
9687 Second, in compilation mode, if @code{gnatchop}
9688 is given a file that starts with
9689 configuration pragmas, and contains one or more units, then these
9690 configuration pragmas are prepended to each of the chopped files. This
9691 behavior provides the required behavior described in the RM for the
9692 actions to be taken on compiling such a file, namely that the pragmas
9693 apply to all units in the compilation, but not to subsequently compiled
9696 Finally, if configuration pragmas appear between units, they are appended
9697 to the previous unit. This results in the previous unit being illegal,
9698 since the compiler does not accept configuration pragmas that follow
9699 a unit. This provides the required RM behavior that forbids configuration
9700 pragmas other than those preceding the first compilation unit of a
9703 For most purposes, @code{gnatchop} will be used in default mode. The
9704 compilation mode described above is used only if you need exactly
9705 accurate behavior with respect to compilations, and you have files
9706 that contain multiple units and configuration pragmas. In this
9707 circumstance the use of @code{gnatchop} with the compilation mode
9708 switch provides the required behavior, and is for example the mode
9709 in which GNAT processes the ACVC tests.
9711 @node Command Line for gnatchop
9712 @section Command Line for @code{gnatchop}
9715 The @code{gnatchop} command has the form:
9718 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
9723 The only required argument is the file name of the file to be chopped.
9724 There are no restrictions on the form of this file name. The file itself
9725 contains one or more Ada units, in normal GNAT format, concatenated
9726 together. As shown, more than one file may be presented to be chopped.
9728 When run in default mode, @code{gnatchop} generates one output file in
9729 the current directory for each unit in each of the files.
9731 @var{directory}, if specified, gives the name of the directory to which
9732 the output files will be written. If it is not specified, all files are
9733 written to the current directory.
9735 For example, given a
9736 file called @file{hellofiles} containing
9738 @smallexample @c ada
9743 with Text_IO; use Text_IO;
9756 $ gnatchop ^hellofiles^HELLOFILES.^
9760 generates two files in the current directory, one called
9761 @file{hello.ads} containing the single line that is the procedure spec,
9762 and the other called @file{hello.adb} containing the remaining text. The
9763 original file is not affected. The generated files can be compiled in
9767 When gnatchop is invoked on a file that is empty or that contains only empty
9768 lines and/or comments, gnatchop will not fail, but will not produce any
9771 For example, given a
9772 file called @file{toto.txt} containing
9774 @smallexample @c ada
9786 $ gnatchop ^toto.txt^TOT.TXT^
9790 will not produce any new file and will result in the following warnings:
9793 toto.txt:1:01: warning: empty file, contains no compilation units
9794 no compilation units found
9795 no source files written
9798 @node Switches for gnatchop
9799 @section Switches for @code{gnatchop}
9802 @command{gnatchop} recognizes the following switches:
9807 @item ^-c^/COMPILATION^
9808 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
9809 Causes @code{gnatchop} to operate in compilation mode, in which
9810 configuration pragmas are handled according to strict RM rules. See
9811 previous section for a full description of this mode.
9815 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
9816 used to parse the given file. Not all @code{xxx} options make sense,
9817 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
9818 process a source file that uses Latin-2 coding for identifiers.
9822 Causes @code{gnatchop} to generate a brief help summary to the standard
9823 output file showing usage information.
9825 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
9826 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
9827 Limit generated file names to the specified number @code{mm}
9829 This is useful if the
9830 resulting set of files is required to be interoperable with systems
9831 which limit the length of file names.
9833 If no value is given, or
9834 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
9835 a default of 39, suitable for OpenVMS Alpha
9839 No space is allowed between the @option{-k} and the numeric value. The numeric
9840 value may be omitted in which case a default of @option{-k8},
9842 with DOS-like file systems, is used. If no @option{-k} switch
9844 there is no limit on the length of file names.
9847 @item ^-p^/PRESERVE^
9848 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
9849 Causes the file ^modification^creation^ time stamp of the input file to be
9850 preserved and used for the time stamp of the output file(s). This may be
9851 useful for preserving coherency of time stamps in an environment where
9852 @code{gnatchop} is used as part of a standard build process.
9855 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
9856 Causes output of informational messages indicating the set of generated
9857 files to be suppressed. Warnings and error messages are unaffected.
9859 @item ^-r^/REFERENCE^
9860 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
9861 @findex Source_Reference
9862 Generate @code{Source_Reference} pragmas. Use this switch if the output
9863 files are regarded as temporary and development is to be done in terms
9864 of the original unchopped file. This switch causes
9865 @code{Source_Reference} pragmas to be inserted into each of the
9866 generated files to refers back to the original file name and line number.
9867 The result is that all error messages refer back to the original
9869 In addition, the debugging information placed into the object file (when
9870 the @option{^-g^/DEBUG^} switch of @code{gcc} or @code{gnatmake} is specified)
9871 also refers back to this original file so that tools like profilers and
9872 debuggers will give information in terms of the original unchopped file.
9874 If the original file to be chopped itself contains
9875 a @code{Source_Reference}
9876 pragma referencing a third file, then gnatchop respects
9877 this pragma, and the generated @code{Source_Reference} pragmas
9878 in the chopped file refer to the original file, with appropriate
9879 line numbers. This is particularly useful when @code{gnatchop}
9880 is used in conjunction with @code{gnatprep} to compile files that
9881 contain preprocessing statements and multiple units.
9884 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
9885 Causes @code{gnatchop} to operate in verbose mode. The version
9886 number and copyright notice are output, as well as exact copies of
9887 the gnat1 commands spawned to obtain the chop control information.
9889 @item ^-w^/OVERWRITE^
9890 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
9891 Overwrite existing file names. Normally @code{gnatchop} regards it as a
9892 fatal error if there is already a file with the same name as a
9893 file it would otherwise output, in other words if the files to be
9894 chopped contain duplicated units. This switch bypasses this
9895 check, and causes all but the last instance of such duplicated
9896 units to be skipped.
9900 @cindex @option{--GCC=} (@code{gnatchop})
9901 Specify the path of the GNAT parser to be used. When this switch is used,
9902 no attempt is made to add the prefix to the GNAT parser executable.
9906 @node Examples of gnatchop Usage
9907 @section Examples of @code{gnatchop} Usage
9911 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
9914 @item gnatchop -w hello_s.ada prerelease/files
9917 Chops the source file @file{hello_s.ada}. The output files will be
9918 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
9920 files with matching names in that directory (no files in the current
9921 directory are modified).
9923 @item gnatchop ^archive^ARCHIVE.^
9924 Chops the source file @file{^archive^ARCHIVE.^}
9925 into the current directory. One
9926 useful application of @code{gnatchop} is in sending sets of sources
9927 around, for example in email messages. The required sources are simply
9928 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
9930 @code{gnatchop} is used at the other end to reconstitute the original
9933 @item gnatchop file1 file2 file3 direc
9934 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
9935 the resulting files in the directory @file{direc}. Note that if any units
9936 occur more than once anywhere within this set of files, an error message
9937 is generated, and no files are written. To override this check, use the
9938 @option{^-w^/OVERWRITE^} switch,
9939 in which case the last occurrence in the last file will
9940 be the one that is output, and earlier duplicate occurrences for a given
9941 unit will be skipped.
9944 @node Configuration Pragmas
9945 @chapter Configuration Pragmas
9946 @cindex Configuration pragmas
9947 @cindex Pragmas, configuration
9950 In Ada 95, configuration pragmas include those pragmas described as
9951 such in the Ada 95 Reference Manual, as well as
9952 implementation-dependent pragmas that are configuration pragmas. See the
9953 individual descriptions of pragmas in the GNAT Reference Manual for
9954 details on these additional GNAT-specific configuration pragmas. Most
9955 notably, the pragma @code{Source_File_Name}, which allows
9956 specifying non-default names for source files, is a configuration
9957 pragma. The following is a complete list of configuration pragmas
9958 recognized by @code{GNAT}:
9971 External_Name_Casing
9972 Float_Representation
9981 Propagate_Exceptions
9986 Restrictions_Warnings
9991 Task_Dispatching_Policy
10000 * Handling of Configuration Pragmas::
10001 * The Configuration Pragmas Files::
10004 @node Handling of Configuration Pragmas
10005 @section Handling of Configuration Pragmas
10007 Configuration pragmas may either appear at the start of a compilation
10008 unit, in which case they apply only to that unit, or they may apply to
10009 all compilations performed in a given compilation environment.
10011 GNAT also provides the @code{gnatchop} utility to provide an automatic
10012 way to handle configuration pragmas following the semantics for
10013 compilations (that is, files with multiple units), described in the RM.
10014 See section @pxref{Operating gnatchop in Compilation Mode} for details.
10015 However, for most purposes, it will be more convenient to edit the
10016 @file{gnat.adc} file that contains configuration pragmas directly,
10017 as described in the following section.
10019 @node The Configuration Pragmas Files
10020 @section The Configuration Pragmas Files
10021 @cindex @file{gnat.adc}
10024 In GNAT a compilation environment is defined by the current
10025 directory at the time that a compile command is given. This current
10026 directory is searched for a file whose name is @file{gnat.adc}. If
10027 this file is present, it is expected to contain one or more
10028 configuration pragmas that will be applied to the current compilation.
10029 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
10032 Configuration pragmas may be entered into the @file{gnat.adc} file
10033 either by running @code{gnatchop} on a source file that consists only of
10034 configuration pragmas, or more conveniently by
10035 direct editing of the @file{gnat.adc} file, which is a standard format
10038 In addition to @file{gnat.adc}, one additional file containing configuration
10039 pragmas may be applied to the current compilation using the switch
10040 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
10041 contains only configuration pragmas. These configuration pragmas are
10042 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
10043 is present and switch @option{-gnatA} is not used).
10045 It is allowed to specify several switches @option{-gnatec}, however only
10046 the last one on the command line will be taken into account.
10048 If you are using project file, a separate mechanism is provided using
10049 project attributes, see @ref{Specifying Configuration Pragmas} for more
10053 Of special interest to GNAT OpenVMS Alpha is the following
10054 configuration pragma:
10056 @smallexample @c ada
10058 pragma Extend_System (Aux_DEC);
10063 In the presence of this pragma, GNAT adds to the definition of the
10064 predefined package SYSTEM all the additional types and subprograms that are
10065 defined in DEC Ada. See @pxref{Compatibility with DEC Ada} for details.
10068 @node Handling Arbitrary File Naming Conventions Using gnatname
10069 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
10070 @cindex Arbitrary File Naming Conventions
10073 * Arbitrary File Naming Conventions::
10074 * Running gnatname::
10075 * Switches for gnatname::
10076 * Examples of gnatname Usage::
10079 @node Arbitrary File Naming Conventions
10080 @section Arbitrary File Naming Conventions
10083 The GNAT compiler must be able to know the source file name of a compilation
10084 unit. When using the standard GNAT default file naming conventions
10085 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
10086 does not need additional information.
10089 When the source file names do not follow the standard GNAT default file naming
10090 conventions, the GNAT compiler must be given additional information through
10091 a configuration pragmas file (see @ref{Configuration Pragmas})
10093 When the non standard file naming conventions are well-defined,
10094 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
10095 (see @ref{Alternative File Naming Schemes}) may be sufficient. However,
10096 if the file naming conventions are irregular or arbitrary, a number
10097 of pragma @code{Source_File_Name} for individual compilation units
10099 To help maintain the correspondence between compilation unit names and
10100 source file names within the compiler,
10101 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
10104 @node Running gnatname
10105 @section Running @code{gnatname}
10108 The usual form of the @code{gnatname} command is
10111 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
10115 All of the arguments are optional. If invoked without any argument,
10116 @code{gnatname} will display its usage.
10119 When used with at least one naming pattern, @code{gnatname} will attempt to
10120 find all the compilation units in files that follow at least one of the
10121 naming patterns. To find these compilation units,
10122 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
10126 One or several Naming Patterns may be given as arguments to @code{gnatname}.
10127 Each Naming Pattern is enclosed between double quotes.
10128 A Naming Pattern is a regular expression similar to the wildcard patterns
10129 used in file names by the Unix shells or the DOS prompt.
10132 Examples of Naming Patterns are
10141 For a more complete description of the syntax of Naming Patterns,
10142 see the second kind of regular expressions described in @file{g-regexp.ads}
10143 (the ``Glob'' regular expressions).
10146 When invoked with no switches, @code{gnatname} will create a configuration
10147 pragmas file @file{gnat.adc} in the current working directory, with pragmas
10148 @code{Source_File_Name} for each file that contains a valid Ada unit.
10150 @node Switches for gnatname
10151 @section Switches for @code{gnatname}
10154 Switches for @code{gnatname} must precede any specified Naming Pattern.
10157 You may specify any of the following switches to @code{gnatname}:
10162 @item ^-c^/CONFIG_FILE=^@file{file}
10163 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
10164 Create a configuration pragmas file @file{file} (instead of the default
10167 There may be zero, one or more space between @option{-c} and
10170 @file{file} may include directory information. @file{file} must be
10171 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
10172 When a switch @option{^-c^/CONFIG_FILE^} is
10173 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
10175 @item ^-d^/SOURCE_DIRS=^@file{dir}
10176 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
10177 Look for source files in directory @file{dir}. There may be zero, one or more
10178 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
10179 When a switch @option{^-d^/SOURCE_DIRS^}
10180 is specified, the current working directory will not be searched for source
10181 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
10182 or @option{^-D^/DIR_FILES^} switch.
10183 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
10184 If @file{dir} is a relative path, it is relative to the directory of
10185 the configuration pragmas file specified with switch
10186 @option{^-c^/CONFIG_FILE^},
10187 or to the directory of the project file specified with switch
10188 @option{^-P^/PROJECT_FILE^} or,
10189 if neither switch @option{^-c^/CONFIG_FILE^}
10190 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
10191 current working directory. The directory
10192 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
10194 @item ^-D^/DIRS_FILE=^@file{file}
10195 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
10196 Look for source files in all directories listed in text file @file{file}.
10197 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
10199 @file{file} must be an existing, readable text file.
10200 Each non empty line in @file{file} must be a directory.
10201 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
10202 switches @option{^-d^/SOURCE_DIRS^} as there are non empty lines in
10205 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
10206 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
10207 Foreign patterns. Using this switch, it is possible to add sources of languages
10208 other than Ada to the list of sources of a project file.
10209 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
10212 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
10215 will look for Ada units in all files with the @file{.ada} extension,
10216 and will add to the list of file for project @file{prj.gpr} the C files
10217 with extension ".^c^C^".
10220 @cindex @option{^-h^/HELP^} (@code{gnatname})
10221 Output usage (help) information. The output is written to @file{stdout}.
10223 @item ^-P^/PROJECT_FILE=^@file{proj}
10224 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
10225 Create or update project file @file{proj}. There may be zero, one or more space
10226 between @option{-P} and @file{proj}. @file{proj} may include directory
10227 information. @file{proj} must be writable.
10228 There may be only one switch @option{^-P^/PROJECT_FILE^}.
10229 When a switch @option{^-P^/PROJECT_FILE^} is specified,
10230 no switch @option{^-c^/CONFIG_FILE^} may be specified.
10232 @item ^-v^/VERBOSE^
10233 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
10234 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
10235 This includes name of the file written, the name of the directories to search
10236 and, for each file in those directories whose name matches at least one of
10237 the Naming Patterns, an indication of whether the file contains a unit,
10238 and if so the name of the unit.
10240 @item ^-v -v^/VERBOSE /VERBOSE^
10241 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
10242 Very Verbose mode. In addition to the output produced in verbose mode,
10243 for each file in the searched directories whose name matches none of
10244 the Naming Patterns, an indication is given that there is no match.
10246 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
10247 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
10248 Excluded patterns. Using this switch, it is possible to exclude some files
10249 that would match the name patterns. For example,
10251 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
10254 will look for Ada units in all files with the @file{.ada} extension,
10255 except those whose names end with @file{_nt.ada}.
10259 @node Examples of gnatname Usage
10260 @section Examples of @code{gnatname} Usage
10264 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
10270 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
10275 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
10276 and be writable. In addition, the directory
10277 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
10278 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
10281 Note the optional spaces after @option{-c} and @option{-d}.
10286 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
10287 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
10290 $ gnatname /PROJECT_FILE=[HOME.ME]PROJ
10291 /EXCLUDED_PATTERN=*_nt_body.ada
10292 /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
10293 /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
10297 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
10298 even in conjunction with one or several switches
10299 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
10300 are used in this example.
10302 @c *****************************************
10303 @c * G N A T P r o j e c t M a n a g e r *
10304 @c *****************************************
10305 @node GNAT Project Manager
10306 @chapter GNAT Project Manager
10310 * Examples of Project Files::
10311 * Project File Syntax::
10312 * Objects and Sources in Project Files::
10313 * Importing Projects::
10314 * Project Extension::
10315 * Project Hierarchy Extension::
10316 * External References in Project Files::
10317 * Packages in Project Files::
10318 * Variables from Imported Projects::
10320 * Library Projects::
10321 * Using Third-Party Libraries through Projects::
10322 * Stand-alone Library Projects::
10323 * Switches Related to Project Files::
10324 * Tools Supporting Project Files::
10325 * An Extended Example::
10326 * Project File Complete Syntax::
10329 @c ****************
10330 @c * Introduction *
10331 @c ****************
10334 @section Introduction
10337 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
10338 you to manage complex builds involving a number of source files, directories,
10339 and compilation options for different system configurations. In particular,
10340 project files allow you to specify:
10343 The directory or set of directories containing the source files, and/or the
10344 names of the specific source files themselves
10346 The directory in which the compiler's output
10347 (@file{ALI} files, object files, tree files) is to be placed
10349 The directory in which the executable programs is to be placed
10351 ^Switch^Switch^ settings for any of the project-enabled tools
10352 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
10353 @code{gnatfind}); you can apply these settings either globally or to individual
10356 The source files containing the main subprogram(s) to be built
10358 The source programming language(s) (currently Ada and/or C)
10360 Source file naming conventions; you can specify these either globally or for
10361 individual compilation units
10368 @node Project Files
10369 @subsection Project Files
10372 Project files are written in a syntax close to that of Ada, using familiar
10373 notions such as packages, context clauses, declarations, default values,
10374 assignments, and inheritance. Finally, project files can be built
10375 hierarchically from other project files, simplifying complex system
10376 integration and project reuse.
10378 A @dfn{project} is a specific set of values for various compilation properties.
10379 The settings for a given project are described by means of
10380 a @dfn{project file}, which is a text file written in an Ada-like syntax.
10381 Property values in project files are either strings or lists of strings.
10382 Properties that are not explicitly set receive default values. A project
10383 file may interrogate the values of @dfn{external variables} (user-defined
10384 command-line switches or environment variables), and it may specify property
10385 settings conditionally, based on the value of such variables.
10387 In simple cases, a project's source files depend only on other source files
10388 in the same project, or on the predefined libraries. (@emph{Dependence} is
10390 the Ada technical sense; as in one Ada unit @code{with}ing another.) However,
10391 the Project Manager also allows more sophisticated arrangements,
10392 where the source files in one project depend on source files in other
10396 One project can @emph{import} other projects containing needed source files.
10398 You can organize GNAT projects in a hierarchy: a @emph{child} project
10399 can extend a @emph{parent} project, inheriting the parent's source files and
10400 optionally overriding any of them with alternative versions
10404 More generally, the Project Manager lets you structure large development
10405 efforts into hierarchical subsystems, where build decisions are delegated
10406 to the subsystem level, and thus different compilation environments
10407 (^switch^switch^ settings) used for different subsystems.
10409 The Project Manager is invoked through the
10410 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
10411 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
10413 There may be zero, one or more spaces between @option{-P} and
10414 @option{@emph{projectfile}}.
10416 If you want to define (on the command line) an external variable that is
10417 queried by the project file, you must use the
10418 @option{^-X^/EXTERNAT_REFERENCE=^@emph{vbl}=@emph{value}} switch.
10419 The Project Manager parses and interprets the project file, and drives the
10420 invoked tool based on the project settings.
10422 The Project Manager supports a wide range of development strategies,
10423 for systems of all sizes. Here are some typical practices that are
10427 Using a common set of source files, but generating object files in different
10428 directories via different ^switch^switch^ settings
10430 Using a mostly-shared set of source files, but with different versions of
10435 The destination of an executable can be controlled inside a project file
10436 using the @option{^-o^-o^}
10438 In the absence of such a ^switch^switch^ either inside
10439 the project file or on the command line, any executable files generated by
10440 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
10441 in the project file. If no @code{Exec_Dir} is specified, they will be placed
10442 in the object directory of the project.
10444 You can use project files to achieve some of the effects of a source
10445 versioning system (for example, defining separate projects for
10446 the different sets of sources that comprise different releases) but the
10447 Project Manager is independent of any source configuration management tools
10448 that might be used by the developers.
10450 The next section introduces the main features of GNAT's project facility
10451 through a sequence of examples; subsequent sections will present the syntax
10452 and semantics in more detail. A more formal description of the project
10453 facility appears in the GNAT Reference Manual.
10455 @c *****************************
10456 @c * Examples of Project Files *
10457 @c *****************************
10459 @node Examples of Project Files
10460 @section Examples of Project Files
10462 This section illustrates some of the typical uses of project files and
10463 explains their basic structure and behavior.
10466 * Common Sources with Different ^Switches^Switches^ and Directories::
10467 * Using External Variables::
10468 * Importing Other Projects::
10469 * Extending a Project::
10472 @node Common Sources with Different ^Switches^Switches^ and Directories
10473 @subsection Common Sources with Different ^Switches^Switches^ and Directories
10477 * Specifying the Object Directory::
10478 * Specifying the Exec Directory::
10479 * Project File Packages::
10480 * Specifying ^Switch^Switch^ Settings::
10481 * Main Subprograms::
10482 * Executable File Names::
10483 * Source File Naming Conventions::
10484 * Source Language(s)::
10488 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
10489 @file{proc.adb} are in the @file{/common} directory. The file
10490 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
10491 package @code{Pack}. We want to compile these source files under two sets
10492 of ^switches^switches^:
10495 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
10496 and the @option{^-gnata^-gnata^},
10497 @option{^-gnato^-gnato^},
10498 and @option{^-gnatE^-gnatE^} switches to the
10499 compiler; the compiler's output is to appear in @file{/common/debug}
10501 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
10502 to the compiler; the compiler's output is to appear in @file{/common/release}
10506 The GNAT project files shown below, respectively @file{debug.gpr} and
10507 @file{release.gpr} in the @file{/common} directory, achieve these effects.
10520 ^/common/debug^[COMMON.DEBUG]^
10525 ^/common/release^[COMMON.RELEASE]^
10530 Here are the corresponding project files:
10532 @smallexample @c projectfile
10535 for Object_Dir use "debug";
10536 for Main use ("proc");
10539 for ^Default_Switches^Default_Switches^ ("Ada")
10541 for Executable ("proc.adb") use "proc1";
10546 package Compiler is
10547 for ^Default_Switches^Default_Switches^ ("Ada")
10548 use ("-fstack-check",
10551 "^-gnatE^-gnatE^");
10557 @smallexample @c projectfile
10560 for Object_Dir use "release";
10561 for Exec_Dir use ".";
10562 for Main use ("proc");
10564 package Compiler is
10565 for ^Default_Switches^Default_Switches^ ("Ada")
10573 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
10574 insensitive), and analogously the project defined by @file{release.gpr} is
10575 @code{"Release"}. For consistency the file should have the same name as the
10576 project, and the project file's extension should be @code{"gpr"}. These
10577 conventions are not required, but a warning is issued if they are not followed.
10579 If the current directory is @file{^/temp^[TEMP]^}, then the command
10581 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
10585 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
10586 as well as the @code{^proc1^PROC1.EXE^} executable,
10587 using the ^switch^switch^ settings defined in the project file.
10589 Likewise, the command
10591 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
10595 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
10596 and the @code{^proc^PROC.EXE^}
10597 executable in @file{^/common^[COMMON]^},
10598 using the ^switch^switch^ settings from the project file.
10601 @unnumberedsubsubsec Source Files
10604 If a project file does not explicitly specify a set of source directories or
10605 a set of source files, then by default the project's source files are the
10606 Ada source files in the project file directory. Thus @file{pack.ads},
10607 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
10609 @node Specifying the Object Directory
10610 @unnumberedsubsubsec Specifying the Object Directory
10613 Several project properties are modeled by Ada-style @emph{attributes};
10614 a property is defined by supplying the equivalent of an Ada attribute
10615 definition clause in the project file.
10616 A project's object directory is another such a property; the corresponding
10617 attribute is @code{Object_Dir}, and its value is also a string expression,
10618 specified either as absolute or relative. In the later case,
10619 it is relative to the project file directory. Thus the compiler's
10620 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
10621 (for the @code{Debug} project)
10622 and to @file{^/common/release^[COMMON.RELEASE]^}
10623 (for the @code{Release} project).
10624 If @code{Object_Dir} is not specified, then the default is the project file
10627 @node Specifying the Exec Directory
10628 @unnumberedsubsubsec Specifying the Exec Directory
10631 A project's exec directory is another property; the corresponding
10632 attribute is @code{Exec_Dir}, and its value is also a string expression,
10633 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
10634 then the default is the object directory (which may also be the project file
10635 directory if attribute @code{Object_Dir} is not specified). Thus the executable
10636 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
10637 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
10638 and in @file{^/common^[COMMON]^} for the @code{Release} project.
10640 @node Project File Packages
10641 @unnumberedsubsubsec Project File Packages
10644 A GNAT tool that is integrated with the Project Manager is modeled by a
10645 corresponding package in the project file. In the example above,
10646 The @code{Debug} project defines the packages @code{Builder}
10647 (for @command{gnatmake}) and @code{Compiler};
10648 the @code{Release} project defines only the @code{Compiler} package.
10650 The Ada-like package syntax is not to be taken literally. Although packages in
10651 project files bear a surface resemblance to packages in Ada source code, the
10652 notation is simply a way to convey a grouping of properties for a named
10653 entity. Indeed, the package names permitted in project files are restricted
10654 to a predefined set, corresponding to the project-aware tools, and the contents
10655 of packages are limited to a small set of constructs.
10656 The packages in the example above contain attribute definitions.
10658 @node Specifying ^Switch^Switch^ Settings
10659 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
10662 ^Switch^Switch^ settings for a project-aware tool can be specified through
10663 attributes in the package that corresponds to the tool.
10664 The example above illustrates one of the relevant attributes,
10665 @code{^Default_Switches^Default_Switches^}, which is defined in packages
10666 in both project files.
10667 Unlike simple attributes like @code{Source_Dirs},
10668 @code{^Default_Switches^Default_Switches^} is
10669 known as an @emph{associative array}. When you define this attribute, you must
10670 supply an ``index'' (a literal string), and the effect of the attribute
10671 definition is to set the value of the array at the specified index.
10672 For the @code{^Default_Switches^Default_Switches^} attribute,
10673 the index is a programming language (in our case, Ada),
10674 and the value specified (after @code{use}) must be a list
10675 of string expressions.
10677 The attributes permitted in project files are restricted to a predefined set.
10678 Some may appear at project level, others in packages.
10679 For any attribute that is an associative array, the index must always be a
10680 literal string, but the restrictions on this string (e.g., a file name or a
10681 language name) depend on the individual attribute.
10682 Also depending on the attribute, its specified value will need to be either a
10683 string or a string list.
10685 In the @code{Debug} project, we set the switches for two tools,
10686 @command{gnatmake} and the compiler, and thus we include the two corresponding
10687 packages; each package defines the @code{^Default_Switches^Default_Switches^}
10688 attribute with index @code{"Ada"}.
10689 Note that the package corresponding to
10690 @command{gnatmake} is named @code{Builder}. The @code{Release} project is
10691 similar, but only includes the @code{Compiler} package.
10693 In project @code{Debug} above, the ^switches^switches^ starting with
10694 @option{-gnat} that are specified in package @code{Compiler}
10695 could have been placed in package @code{Builder}, since @command{gnatmake}
10696 transmits all such ^switches^switches^ to the compiler.
10698 @node Main Subprograms
10699 @unnumberedsubsubsec Main Subprograms
10702 One of the specifiable properties of a project is a list of files that contain
10703 main subprograms. This property is captured in the @code{Main} attribute,
10704 whose value is a list of strings. If a project defines the @code{Main}
10705 attribute, it is not necessary to identify the main subprogram(s) when
10706 invoking @command{gnatmake} (see @ref{gnatmake and Project Files}).
10708 @node Executable File Names
10709 @unnumberedsubsubsec Executable File Names
10712 By default, the executable file name corresponding to a main source is
10713 deduced from the main source file name. Through the attributes
10714 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
10715 it is possible to change this default.
10716 In project @code{Debug} above, the executable file name
10717 for main source @file{^proc.adb^PROC.ADB^} is
10718 @file{^proc1^PROC1.EXE^}.
10719 Attribute @code{Executable_Suffix}, when specified, may change the suffix
10720 of the the executable files, when no attribute @code{Executable} applies:
10721 its value replace the platform-specific executable suffix.
10722 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
10723 specify a non default executable file name when several mains are built at once
10724 in a single @command{gnatmake} command.
10726 @node Source File Naming Conventions
10727 @unnumberedsubsubsec Source File Naming Conventions
10730 Since the project files above do not specify any source file naming
10731 conventions, the GNAT defaults are used. The mechanism for defining source
10732 file naming conventions -- a package named @code{Naming} --
10733 is described below (@pxref{Naming Schemes}).
10735 @node Source Language(s)
10736 @unnumberedsubsubsec Source Language(s)
10739 Since the project files do not specify a @code{Languages} attribute, by
10740 default the GNAT tools assume that the language of the project file is Ada.
10741 More generally, a project can comprise source files
10742 in Ada, C, and/or other languages.
10744 @node Using External Variables
10745 @subsection Using External Variables
10748 Instead of supplying different project files for debug and release, we can
10749 define a single project file that queries an external variable (set either
10750 on the command line or via an ^environment variable^logical name^) in order to
10751 conditionally define the appropriate settings. Again, assume that the
10752 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
10753 located in directory @file{^/common^[COMMON]^}. The following project file,
10754 @file{build.gpr}, queries the external variable named @code{STYLE} and
10755 defines an object directory and ^switch^switch^ settings based on whether
10756 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
10757 the default is @code{"deb"}.
10759 @smallexample @c projectfile
10762 for Main use ("proc");
10764 type Style_Type is ("deb", "rel");
10765 Style : Style_Type := external ("STYLE", "deb");
10769 for Object_Dir use "debug";
10772 for Object_Dir use "release";
10773 for Exec_Dir use ".";
10782 for ^Default_Switches^Default_Switches^ ("Ada")
10784 for Executable ("proc") use "proc1";
10793 package Compiler is
10797 for ^Default_Switches^Default_Switches^ ("Ada")
10798 use ("^-gnata^-gnata^",
10800 "^-gnatE^-gnatE^");
10803 for ^Default_Switches^Default_Switches^ ("Ada")
10814 @code{Style_Type} is an example of a @emph{string type}, which is the project
10815 file analog of an Ada enumeration type but whose components are string literals
10816 rather than identifiers. @code{Style} is declared as a variable of this type.
10818 The form @code{external("STYLE", "deb")} is known as an
10819 @emph{external reference}; its first argument is the name of an
10820 @emph{external variable}, and the second argument is a default value to be
10821 used if the external variable doesn't exist. You can define an external
10822 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
10823 or you can use ^an environment variable^a logical name^
10824 as an external variable.
10826 Each @code{case} construct is expanded by the Project Manager based on the
10827 value of @code{Style}. Thus the command
10830 gnatmake -P/common/build.gpr -XSTYLE=deb
10836 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
10841 is equivalent to the @command{gnatmake} invocation using the project file
10842 @file{debug.gpr} in the earlier example. So is the command
10844 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
10848 since @code{"deb"} is the default for @code{STYLE}.
10854 gnatmake -P/common/build.gpr -XSTYLE=rel
10860 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
10865 is equivalent to the @command{gnatmake} invocation using the project file
10866 @file{release.gpr} in the earlier example.
10868 @node Importing Other Projects
10869 @subsection Importing Other Projects
10872 A compilation unit in a source file in one project may depend on compilation
10873 units in source files in other projects. To compile this unit under
10874 control of a project file, the
10875 dependent project must @emph{import} the projects containing the needed source
10877 This effect is obtained using syntax similar to an Ada @code{with} clause,
10878 but where @code{with}ed entities are strings that denote project files.
10880 As an example, suppose that the two projects @code{GUI_Proj} and
10881 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
10882 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
10883 and @file{^/comm^[COMM]^}, respectively.
10884 Suppose that the source files for @code{GUI_Proj} are
10885 @file{gui.ads} and @file{gui.adb}, and that the source files for
10886 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
10887 files is located in its respective project file directory. Schematically:
10906 We want to develop an application in directory @file{^/app^[APP]^} that
10907 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
10908 the corresponding project files (e.g. the ^switch^switch^ settings
10909 and object directory).
10910 Skeletal code for a main procedure might be something like the following:
10912 @smallexample @c ada
10915 procedure App_Main is
10924 Here is a project file, @file{app_proj.gpr}, that achieves the desired
10927 @smallexample @c projectfile
10929 with "/gui/gui_proj", "/comm/comm_proj";
10930 project App_Proj is
10931 for Main use ("app_main");
10937 Building an executable is achieved through the command:
10939 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
10942 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
10943 in the directory where @file{app_proj.gpr} resides.
10945 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
10946 (as illustrated above) the @code{with} clause can omit the extension.
10948 Our example specified an absolute path for each imported project file.
10949 Alternatively, the directory name of an imported object can be omitted
10953 The imported project file is in the same directory as the importing project
10956 You have defined ^an environment variable^a logical name^
10957 that includes the directory containing
10958 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
10959 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
10960 directory names separated by colons (semicolons on Windows).
10964 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
10965 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
10968 @smallexample @c projectfile
10970 with "gui_proj", "comm_proj";
10971 project App_Proj is
10972 for Main use ("app_main");
10978 Importing other projects can create ambiguities.
10979 For example, the same unit might be present in different imported projects, or
10980 it might be present in both the importing project and in an imported project.
10981 Both of these conditions are errors. Note that in the current version of
10982 the Project Manager, it is illegal to have an ambiguous unit even if the
10983 unit is never referenced by the importing project. This restriction may be
10984 relaxed in a future release.
10986 @node Extending a Project
10987 @subsection Extending a Project
10990 In large software systems it is common to have multiple
10991 implementations of a common interface; in Ada terms, multiple versions of a
10992 package body for the same specification. For example, one implementation
10993 might be safe for use in tasking programs, while another might only be used
10994 in sequential applications. This can be modeled in GNAT using the concept
10995 of @emph{project extension}. If one project (the ``child'') @emph{extends}
10996 another project (the ``parent'') then by default all source files of the
10997 parent project are inherited by the child, but the child project can
10998 override any of the parent's source files with new versions, and can also
10999 add new files. This facility is the project analog of a type extension in
11000 Object-Oriented Programming. Project hierarchies are permitted (a child
11001 project may be the parent of yet another project), and a project that
11002 inherits one project can also import other projects.
11004 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
11005 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
11006 @file{pack.adb}, and @file{proc.adb}:
11019 Note that the project file can simply be empty (that is, no attribute or
11020 package is defined):
11022 @smallexample @c projectfile
11024 project Seq_Proj is
11030 implying that its source files are all the Ada source files in the project
11033 Suppose we want to supply an alternate version of @file{pack.adb}, in
11034 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
11035 @file{pack.ads} and @file{proc.adb}. We can define a project
11036 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
11040 ^/tasking^[TASKING]^
11046 project Tasking_Proj extends "/seq/seq_proj" is
11052 The version of @file{pack.adb} used in a build depends on which project file
11055 Note that we could have obtained the desired behavior using project import
11056 rather than project inheritance; a @code{base} project would contain the
11057 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
11058 import @code{base} and add @file{pack.adb}, and likewise a tasking project
11059 would import @code{base} and add a different version of @file{pack.adb}. The
11060 choice depends on whether other sources in the original project need to be
11061 overridden. If they do, then project extension is necessary, otherwise,
11062 importing is sufficient.
11065 In a project file that extends another project file, it is possible to
11066 indicate that an inherited source is not part of the sources of the extending
11067 project. This is necessary sometimes when a package spec has been overloaded
11068 and no longer requires a body: in this case, it is necessary to indicate that
11069 the inherited body is not part of the sources of the project, otherwise there
11070 will be a compilation error when compiling the spec.
11072 For that purpose, the attribute @code{Locally_Removed_Files} is used.
11073 Its value is a string list: a list of file names.
11075 @smallexample @c @projectfile
11076 project B extends "a" is
11077 for Source_Files use ("pkg.ads");
11078 -- New spec of Pkg does not need a completion
11079 for Locally_Removed_Files use ("pkg.adb");
11083 Attribute @code{Locally_Removed_Files} may also be used to check if a source
11084 is still needed: if it is possible to build using @code{gnatmake} when such
11085 a source is put in attribute @code{Locally_Removed_Files} of a project P, then
11086 it is possible to remove the source completely from a system that includes
11089 @c ***********************
11090 @c * Project File Syntax *
11091 @c ***********************
11093 @node Project File Syntax
11094 @section Project File Syntax
11103 * Associative Array Attributes::
11104 * case Constructions::
11108 This section describes the structure of project files.
11110 A project may be an @emph{independent project}, entirely defined by a single
11111 project file. Any Ada source file in an independent project depends only
11112 on the predefined library and other Ada source files in the same project.
11115 A project may also @dfn{depend on} other projects, in either or both of
11116 the following ways:
11118 @item It may import any number of projects
11119 @item It may extend at most one other project
11123 The dependence relation is a directed acyclic graph (the subgraph reflecting
11124 the ``extends'' relation is a tree).
11126 A project's @dfn{immediate sources} are the source files directly defined by
11127 that project, either implicitly by residing in the project file's directory,
11128 or explicitly through any of the source-related attributes described below.
11129 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
11130 of @var{proj} together with the immediate sources (unless overridden) of any
11131 project on which @var{proj} depends (either directly or indirectly).
11134 @subsection Basic Syntax
11137 As seen in the earlier examples, project files have an Ada-like syntax.
11138 The minimal project file is:
11139 @smallexample @c projectfile
11148 The identifier @code{Empty} is the name of the project.
11149 This project name must be present after the reserved
11150 word @code{end} at the end of the project file, followed by a semi-colon.
11152 Any name in a project file, such as the project name or a variable name,
11153 has the same syntax as an Ada identifier.
11155 The reserved words of project files are the Ada reserved words plus
11156 @code{extends}, @code{external}, and @code{project}. Note that the only Ada
11157 reserved words currently used in project file syntax are:
11185 Comments in project files have the same syntax as in Ada, two consecutives
11186 hyphens through the end of the line.
11189 @subsection Packages
11192 A project file may contain @emph{packages}. The name of a package must be one
11193 of the identifiers from the following list. A package
11194 with a given name may only appear once in a project file. Package names are
11195 case insensitive. The following package names are legal:
11211 @code{Cross_Reference}
11215 @code{Pretty_Printer}
11225 @code{Language_Processing}
11229 In its simplest form, a package may be empty:
11231 @smallexample @c projectfile
11241 A package may contain @emph{attribute declarations},
11242 @emph{variable declarations} and @emph{case constructions}, as will be
11245 When there is ambiguity between a project name and a package name,
11246 the name always designates the project. To avoid possible confusion, it is
11247 always a good idea to avoid naming a project with one of the
11248 names allowed for packages or any name that starts with @code{gnat}.
11251 @subsection Expressions
11254 An @emph{expression} is either a @emph{string expression} or a
11255 @emph{string list expression}.
11257 A @emph{string expression} is either a @emph{simple string expression} or a
11258 @emph{compound string expression}.
11260 A @emph{simple string expression} is one of the following:
11262 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
11263 @item A string-valued variable reference (see @ref{Variables})
11264 @item A string-valued attribute reference (see @ref{Attributes})
11265 @item An external reference (see @ref{External References in Project Files})
11269 A @emph{compound string expression} is a concatenation of string expressions,
11270 using the operator @code{"&"}
11272 Path & "/" & File_Name & ".ads"
11276 A @emph{string list expression} is either a
11277 @emph{simple string list expression} or a
11278 @emph{compound string list expression}.
11280 A @emph{simple string list expression} is one of the following:
11282 @item A parenthesized list of zero or more string expressions,
11283 separated by commas
11285 File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
11288 @item A string list-valued variable reference
11289 @item A string list-valued attribute reference
11293 A @emph{compound string list expression} is the concatenation (using
11294 @code{"&"}) of a simple string list expression and an expression. Note that
11295 each term in a compound string list expression, except the first, may be
11296 either a string expression or a string list expression.
11298 @smallexample @c projectfile
11300 File_Name_List := () & File_Name; -- One string in this list
11301 Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
11303 Big_List := File_Name_List & Extended_File_Name_List;
11304 -- Concatenation of two string lists: three strings
11305 Illegal_List := "gnat.adc" & Extended_File_Name_List;
11306 -- Illegal: must start with a string list
11311 @subsection String Types
11314 A @emph{string type declaration} introduces a discrete set of string literals.
11315 If a string variable is declared to have this type, its value
11316 is restricted to the given set of literals.
11318 Here is an example of a string type declaration:
11320 @smallexample @c projectfile
11321 type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
11325 Variables of a string type are called @emph{typed variables}; all other
11326 variables are called @emph{untyped variables}. Typed variables are
11327 particularly useful in @code{case} constructions, to support conditional
11328 attribute declarations.
11329 (see @ref{case Constructions}).
11331 The string literals in the list are case sensitive and must all be different.
11332 They may include any graphic characters allowed in Ada, including spaces.
11334 A string type may only be declared at the project level, not inside a package.
11336 A string type may be referenced by its name if it has been declared in the same
11337 project file, or by an expanded name whose prefix is the name of the project
11338 in which it is declared.
11341 @subsection Variables
11344 A variable may be declared at the project file level, or within a package.
11345 Here are some examples of variable declarations:
11347 @smallexample @c projectfile
11349 This_OS : OS := external ("OS"); -- a typed variable declaration
11350 That_OS := "GNU/Linux"; -- an untyped variable declaration
11355 The syntax of a @emph{typed variable declaration} is identical to the Ada
11356 syntax for an object declaration. By contrast, the syntax of an untyped
11357 variable declaration is identical to an Ada assignment statement. In fact,
11358 variable declarations in project files have some of the characteristics of
11359 an assignment, in that successive declarations for the same variable are
11360 allowed. Untyped variable declarations do establish the expected kind of the
11361 variable (string or string list), and successive declarations for it must
11362 respect the initial kind.
11365 A string variable declaration (typed or untyped) declares a variable
11366 whose value is a string. This variable may be used as a string expression.
11367 @smallexample @c projectfile
11368 File_Name := "readme.txt";
11369 Saved_File_Name := File_Name & ".saved";
11373 A string list variable declaration declares a variable whose value is a list
11374 of strings. The list may contain any number (zero or more) of strings.
11376 @smallexample @c projectfile
11378 List_With_One_Element := ("^-gnaty^-gnaty^");
11379 List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
11380 Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
11381 "pack2.ada", "util_.ada", "util.ada");
11385 The same typed variable may not be declared more than once at project level,
11386 and it may not be declared more than once in any package; it is in effect
11389 The same untyped variable may be declared several times. Declarations are
11390 elaborated in the order in which they appear, so the new value replaces
11391 the old one, and any subsequent reference to the variable uses the new value.
11392 However, as noted above, if a variable has been declared as a string, all
11394 declarations must give it a string value. Similarly, if a variable has
11395 been declared as a string list, all subsequent declarations
11396 must give it a string list value.
11398 A @emph{variable reference} may take several forms:
11401 @item The simple variable name, for a variable in the current package (if any)
11402 or in the current project
11403 @item An expanded name, whose prefix is a context name.
11407 A @emph{context} may be one of the following:
11410 @item The name of an existing package in the current project
11411 @item The name of an imported project of the current project
11412 @item The name of an ancestor project (i.e., a project extended by the current
11413 project, either directly or indirectly)
11414 @item An expanded name whose prefix is an imported/parent project name, and
11415 whose selector is a package name in that project.
11419 A variable reference may be used in an expression.
11422 @subsection Attributes
11425 A project (and its packages) may have @emph{attributes} that define
11426 the project's properties. Some attributes have values that are strings;
11427 others have values that are string lists.
11429 There are two categories of attributes: @emph{simple attributes}
11430 and @emph{associative arrays} (see @ref{Associative Array Attributes}).
11432 Legal project attribute names, and attribute names for each legal package are
11433 listed below. Attributes names are case-insensitive.
11435 The following attributes are defined on projects (all are simple attributes):
11437 @multitable @columnfractions .4 .3
11438 @item @emph{Attribute Name}
11440 @item @code{Source_Files}
11442 @item @code{Source_Dirs}
11444 @item @code{Source_List_File}
11446 @item @code{Object_Dir}
11448 @item @code{Exec_Dir}
11450 @item @code{Locally_Removed_Files}
11454 @item @code{Languages}
11456 @item @code{Main_Language}
11458 @item @code{Library_Dir}
11460 @item @code{Library_Name}
11462 @item @code{Library_Kind}
11464 @item @code{Library_Version}
11466 @item @code{Library_Interface}
11468 @item @code{Library_Auto_Init}
11470 @item @code{Library_Options}
11472 @item @code{Library_GCC}
11477 The following attributes are defined for package @code{Naming}
11478 (see @ref{Naming Schemes}):
11480 @multitable @columnfractions .4 .2 .2 .2
11481 @item Attribute Name @tab Category @tab Index @tab Value
11482 @item @code{Spec_Suffix}
11483 @tab associative array
11486 @item @code{Body_Suffix}
11487 @tab associative array
11490 @item @code{Separate_Suffix}
11491 @tab simple attribute
11494 @item @code{Casing}
11495 @tab simple attribute
11498 @item @code{Dot_Replacement}
11499 @tab simple attribute
11503 @tab associative array
11507 @tab associative array
11510 @item @code{Specification_Exceptions}
11511 @tab associative array
11514 @item @code{Implementation_Exceptions}
11515 @tab associative array
11521 The following attributes are defined for packages @code{Builder},
11522 @code{Compiler}, @code{Binder},
11523 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
11524 (see @ref{^Switches^Switches^ and Project Files}).
11526 @multitable @columnfractions .4 .2 .2 .2
11527 @item Attribute Name @tab Category @tab Index @tab Value
11528 @item @code{^Default_Switches^Default_Switches^}
11529 @tab associative array
11532 @item @code{^Switches^Switches^}
11533 @tab associative array
11539 In addition, package @code{Compiler} has a single string attribute
11540 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
11541 string attribute @code{Global_Configuration_Pragmas}.
11544 Each simple attribute has a default value: the empty string (for string-valued
11545 attributes) and the empty list (for string list-valued attributes).
11547 An attribute declaration defines a new value for an attribute.
11549 Examples of simple attribute declarations:
11551 @smallexample @c projectfile
11552 for Object_Dir use "objects";
11553 for Source_Dirs use ("units", "test/drivers");
11557 The syntax of a @dfn{simple attribute declaration} is similar to that of an
11558 attribute definition clause in Ada.
11560 Attributes references may be appear in expressions.
11561 The general form for such a reference is @code{<entity>'<attribute>}:
11562 Associative array attributes are functions. Associative
11563 array attribute references must have an argument that is a string literal.
11567 @smallexample @c projectfile
11569 Naming'Dot_Replacement
11570 Imported_Project'Source_Dirs
11571 Imported_Project.Naming'Casing
11572 Builder'^Default_Switches^Default_Switches^("Ada")
11576 The prefix of an attribute may be:
11578 @item @code{project} for an attribute of the current project
11579 @item The name of an existing package of the current project
11580 @item The name of an imported project
11581 @item The name of a parent project that is extended by the current project
11582 @item An expanded name whose prefix is imported/parent project name,
11583 and whose selector is a package name
11588 @smallexample @c projectfile
11591 for Source_Dirs use project'Source_Dirs & "units";
11592 for Source_Dirs use project'Source_Dirs & "test/drivers"
11598 In the first attribute declaration, initially the attribute @code{Source_Dirs}
11599 has the default value: an empty string list. After this declaration,
11600 @code{Source_Dirs} is a string list of one element: @code{"units"}.
11601 After the second attribute declaration @code{Source_Dirs} is a string list of
11602 two elements: @code{"units"} and @code{"test/drivers"}.
11604 Note: this example is for illustration only. In practice,
11605 the project file would contain only one attribute declaration:
11607 @smallexample @c projectfile
11608 for Source_Dirs use ("units", "test/drivers");
11611 @node Associative Array Attributes
11612 @subsection Associative Array Attributes
11615 Some attributes are defined as @emph{associative arrays}. An associative
11616 array may be regarded as a function that takes a string as a parameter
11617 and delivers a string or string list value as its result.
11619 Here are some examples of single associative array attribute associations:
11621 @smallexample @c projectfile
11622 for Body ("main") use "Main.ada";
11623 for ^Switches^Switches^ ("main.ada")
11625 "^-gnatv^-gnatv^");
11626 for ^Switches^Switches^ ("main.ada")
11627 use Builder'^Switches^Switches^ ("main.ada")
11632 Like untyped variables and simple attributes, associative array attributes
11633 may be declared several times. Each declaration supplies a new value for the
11634 attribute, and replaces the previous setting.
11637 An associative array attribute may be declared as a full associative array
11638 declaration, with the value of the same attribute in an imported or extended
11641 @smallexample @c projectfile
11643 for Default_Switches use Default.Builder'Default_Switches;
11648 In this example, @code{Default} must be either an project imported by the
11649 current project, or the project that the current project extends. If the
11650 attribute is in a package (in this case, in package @code{Builder}), the same
11651 package needs to be specified.
11654 A full associative array declaration replaces any other declaration for the
11655 attribute, including other full associative array declaration. Single
11656 associative array associations may be declare after a full associative
11657 declaration, modifying the value for a single association of the attribute.
11659 @node case Constructions
11660 @subsection @code{case} Constructions
11663 A @code{case} construction is used in a project file to effect conditional
11665 Here is a typical example:
11667 @smallexample @c projectfile
11670 type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
11672 OS : OS_Type := external ("OS", "GNU/Linux");
11676 package Compiler is
11678 when "GNU/Linux" | "Unix" =>
11679 for ^Default_Switches^Default_Switches^ ("Ada")
11680 use ("^-gnath^-gnath^");
11682 for ^Default_Switches^Default_Switches^ ("Ada")
11683 use ("^-gnatP^-gnatP^");
11692 The syntax of a @code{case} construction is based on the Ada case statement
11693 (although there is no @code{null} construction for empty alternatives).
11695 The case expression must a typed string variable.
11696 Each alternative comprises the reserved word @code{when}, either a list of
11697 literal strings separated by the @code{"|"} character or the reserved word
11698 @code{others}, and the @code{"=>"} token.
11699 Each literal string must belong to the string type that is the type of the
11701 An @code{others} alternative, if present, must occur last.
11703 After each @code{=>}, there are zero or more constructions. The only
11704 constructions allowed in a case construction are other case constructions and
11705 attribute declarations. String type declarations, variable declarations and
11706 package declarations are not allowed.
11708 The value of the case variable is often given by an external reference
11709 (see @ref{External References in Project Files}).
11711 @c ****************************************
11712 @c * Objects and Sources in Project Files *
11713 @c ****************************************
11715 @node Objects and Sources in Project Files
11716 @section Objects and Sources in Project Files
11719 * Object Directory::
11721 * Source Directories::
11722 * Source File Names::
11726 Each project has exactly one object directory and one or more source
11727 directories. The source directories must contain at least one source file,
11728 unless the project file explicitly specifies that no source files are present
11729 (see @ref{Source File Names}).
11731 @node Object Directory
11732 @subsection Object Directory
11735 The object directory for a project is the directory containing the compiler's
11736 output (such as @file{ALI} files and object files) for the project's immediate
11739 The object directory is given by the value of the attribute @code{Object_Dir}
11740 in the project file.
11742 @smallexample @c projectfile
11743 for Object_Dir use "objects";
11747 The attribute @var{Object_Dir} has a string value, the path name of the object
11748 directory. The path name may be absolute or relative to the directory of the
11749 project file. This directory must already exist, and be readable and writable.
11751 By default, when the attribute @code{Object_Dir} is not given an explicit value
11752 or when its value is the empty string, the object directory is the same as the
11753 directory containing the project file.
11755 @node Exec Directory
11756 @subsection Exec Directory
11759 The exec directory for a project is the directory containing the executables
11760 for the project's main subprograms.
11762 The exec directory is given by the value of the attribute @code{Exec_Dir}
11763 in the project file.
11765 @smallexample @c projectfile
11766 for Exec_Dir use "executables";
11770 The attribute @var{Exec_Dir} has a string value, the path name of the exec
11771 directory. The path name may be absolute or relative to the directory of the
11772 project file. This directory must already exist, and be writable.
11774 By default, when the attribute @code{Exec_Dir} is not given an explicit value
11775 or when its value is the empty string, the exec directory is the same as the
11776 object directory of the project file.
11778 @node Source Directories
11779 @subsection Source Directories
11782 The source directories of a project are specified by the project file
11783 attribute @code{Source_Dirs}.
11785 This attribute's value is a string list. If the attribute is not given an
11786 explicit value, then there is only one source directory, the one where the
11787 project file resides.
11789 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
11792 @smallexample @c projectfile
11793 for Source_Dirs use ();
11797 indicates that the project contains no source files.
11799 Otherwise, each string in the string list designates one or more
11800 source directories.
11802 @smallexample @c projectfile
11803 for Source_Dirs use ("sources", "test/drivers");
11807 If a string in the list ends with @code{"/**"}, then the directory whose path
11808 name precedes the two asterisks, as well as all its subdirectories
11809 (recursively), are source directories.
11811 @smallexample @c projectfile
11812 for Source_Dirs use ("/system/sources/**");
11816 Here the directory @code{/system/sources} and all of its subdirectories
11817 (recursively) are source directories.
11819 To specify that the source directories are the directory of the project file
11820 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
11821 @smallexample @c projectfile
11822 for Source_Dirs use ("./**");
11826 Each of the source directories must exist and be readable.
11828 @node Source File Names
11829 @subsection Source File Names
11832 In a project that contains source files, their names may be specified by the
11833 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
11834 (a string). Source file names never include any directory information.
11836 If the attribute @code{Source_Files} is given an explicit value, then each
11837 element of the list is a source file name.
11839 @smallexample @c projectfile
11840 for Source_Files use ("main.adb");
11841 for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
11845 If the attribute @code{Source_Files} is not given an explicit value,
11846 but the attribute @code{Source_List_File} is given a string value,
11847 then the source file names are contained in the text file whose path name
11848 (absolute or relative to the directory of the project file) is the
11849 value of the attribute @code{Source_List_File}.
11851 Each line in the file that is not empty or is not a comment
11852 contains a source file name.
11854 @smallexample @c projectfile
11855 for Source_List_File use "source_list.txt";
11859 By default, if neither the attribute @code{Source_Files} nor the attribute
11860 @code{Source_List_File} is given an explicit value, then each file in the
11861 source directories that conforms to the project's naming scheme
11862 (see @ref{Naming Schemes}) is an immediate source of the project.
11864 A warning is issued if both attributes @code{Source_Files} and
11865 @code{Source_List_File} are given explicit values. In this case, the attribute
11866 @code{Source_Files} prevails.
11868 Each source file name must be the name of one existing source file
11869 in one of the source directories.
11871 A @code{Source_Files} attribute whose value is an empty list
11872 indicates that there are no source files in the project.
11874 If the order of the source directories is known statically, that is if
11875 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
11876 be several files with the same source file name. In this case, only the file
11877 in the first directory is considered as an immediate source of the project
11878 file. If the order of the source directories is not known statically, it is
11879 an error to have several files with the same source file name.
11881 Projects can be specified to have no Ada source
11882 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
11883 list, or the @code{"Ada"} may be absent from @code{Languages}:
11885 @smallexample @c projectfile
11886 for Source_Dirs use ();
11887 for Source_Files use ();
11888 for Languages use ("C", "C++");
11892 Otherwise, a project must contain at least one immediate source.
11894 Projects with no source files are useful as template packages
11895 (see @ref{Packages in Project Files}) for other projects; in particular to
11896 define a package @code{Naming} (see @ref{Naming Schemes}).
11898 @c ****************************
11899 @c * Importing Projects *
11900 @c ****************************
11902 @node Importing Projects
11903 @section Importing Projects
11906 An immediate source of a project P may depend on source files that
11907 are neither immediate sources of P nor in the predefined library.
11908 To get this effect, P must @emph{import} the projects that contain the needed
11911 @smallexample @c projectfile
11913 with "project1", "utilities.gpr";
11914 with "/namings/apex.gpr";
11921 As can be seen in this example, the syntax for importing projects is similar
11922 to the syntax for importing compilation units in Ada. However, project files
11923 use literal strings instead of names, and the @code{with} clause identifies
11924 project files rather than packages.
11926 Each literal string is the file name or path name (absolute or relative) of a
11927 project file. If a string is simply a file name, with no path, then its
11928 location is determined by the @emph{project path}:
11932 If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} exists,
11933 then the project path includes all the directories in this
11934 ^environment variable^logical name^, plus the directory of the project file.
11937 If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} does not
11938 exist, then the project path contains only one directory, namely the one where
11939 the project file is located.
11943 If a relative pathname is used, as in
11945 @smallexample @c projectfile
11950 then the path is relative to the directory where the importing project file is
11951 located. Any symbolic link will be fully resolved in the directory
11952 of the importing project file before the imported project file is examined.
11954 If the @code{with}'ed project file name does not have an extension,
11955 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
11956 then the file name as specified in the @code{with} clause (no extension) will
11957 be used. In the above example, if a file @code{project1.gpr} is found, then it
11958 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
11959 then it will be used; if neither file exists, this is an error.
11961 A warning is issued if the name of the project file does not match the
11962 name of the project; this check is case insensitive.
11964 Any source file that is an immediate source of the imported project can be
11965 used by the immediate sources of the importing project, transitively. Thus
11966 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
11967 sources of @code{A} may depend on the immediate sources of @code{C}, even if
11968 @code{A} does not import @code{C} explicitly. However, this is not recommended,
11969 because if and when @code{B} ceases to import @code{C}, some sources in
11970 @code{A} will no longer compile.
11972 A side effect of this capability is that normally cyclic dependencies are not
11973 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
11974 is not allowed to import @code{A}. However, there are cases when cyclic
11975 dependencies would be beneficial. For these cases, another form of import
11976 between projects exists, the @code{limited with}: a project @code{A} that
11977 imports a project @code{B} with a straigh @code{with} may also be imported,
11978 directly or indirectly, by @code{B} on the condition that imports from @code{B}
11979 to @code{A} include at least one @code{limited with}.
11981 @smallexample @c 0projectfile
11987 limited with "../a/a.gpr";
11995 limited with "../a/a.gpr";
12001 In the above legal example, there are two project cycles:
12004 @item A -> C -> D -> A
12008 In each of these cycle there is one @code{limited with}: import of @code{A}
12009 from @code{B} and import of @code{A} from @code{D}.
12011 The difference between straight @code{with} and @code{limited with} is that
12012 the name of a project imported with a @code{limited with} cannot be used in the
12013 project that imports it. In particular, its packages cannot be renamed and
12014 its variables cannot be referred to.
12016 An exception to the above rules for @code{limited with} is that for the main
12017 project specified to @command{gnatmake} or to the @command{GNAT} driver a
12018 @code{limited with} is equivalent to a straight @code{with}. For example,
12019 in the example above, projects @code{B} and @code{D} could not be main
12020 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
12021 each have a @code{limited with} that is the only one in a cycle of importing
12024 @c *********************
12025 @c * Project Extension *
12026 @c *********************
12028 @node Project Extension
12029 @section Project Extension
12032 During development of a large system, it is sometimes necessary to use
12033 modified versions of some of the source files, without changing the original
12034 sources. This can be achieved through the @emph{project extension} facility.
12036 @smallexample @c projectfile
12037 project Modified_Utilities extends "/baseline/utilities.gpr" is ...
12041 A project extension declaration introduces an extending project
12042 (the @emph{child}) and a project being extended (the @emph{parent}).
12044 By default, a child project inherits all the sources of its parent.
12045 However, inherited sources can be overridden: a unit in a parent is hidden
12046 by a unit of the same name in the child.
12048 Inherited sources are considered to be sources (but not immediate sources)
12049 of the child project; see @ref{Project File Syntax}.
12051 An inherited source file retains any switches specified in the parent project.
12053 For example if the project @code{Utilities} contains the specification and the
12054 body of an Ada package @code{Util_IO}, then the project
12055 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
12056 The original body of @code{Util_IO} will not be considered in program builds.
12057 However, the package specification will still be found in the project
12060 A child project can have only one parent but it may import any number of other
12063 A project is not allowed to import directly or indirectly at the same time a
12064 child project and any of its ancestors.
12066 @c *******************************
12067 @c * Project Hierarchy Extension *
12068 @c *******************************
12070 @node Project Hierarchy Extension
12071 @section Project Hierarchy Extension
12074 When extending a large system spanning multiple projects, it is often
12075 inconvenient to extend every project in the hierarchy that is impacted by a
12076 small change introduced. In such cases, it is possible to create a virtual
12077 extension of entire hierarchy using @code{extends all} relationship.
12079 When the project is extended using @code{extends all} inheritance, all projects
12080 that are imported by it, both directly and indirectly, are considered virtually
12081 extended. That is, the Project Manager creates "virtual projects"
12082 that extend every project in the hierarchy; all these virtual projects have
12083 no sources of their own and have as object directory the object directory of
12084 the root of "extending all" project.
12086 It is possible to explicitly extend one or more projects in the hierarchy
12087 in order to modify the sources. These extending projects must be imported by
12088 the "extending all" project, which will replace the corresponding virtual
12089 projects with the explicit ones.
12091 When building such a project hierarchy extension, the Project Manager will
12092 ensure that both modified sources and sources in virtual extending projects
12093 that depend on them, are recompiled.
12095 By means of example, consider the following hierarchy of projects.
12099 project A, containing package P1
12101 project B importing A and containing package P2 which depends on P1
12103 project C importing B and containing package P3 which depends on P2
12107 We want to modify packages P1 and P3.
12109 This project hierarchy will need to be extended as follows:
12113 Create project A1 that extends A, placing modified P1 there:
12115 @smallexample @c 0projectfile
12116 project A1 extends "(...)/A" is
12121 Create project C1 that "extends all" C and imports A1, placing modified
12124 @smallexample @c 0projectfile
12126 project C1 extends all "(...)/C" is
12131 When you build project C1, your entire modified project space will be
12132 recompiled, including the virtual project B1 that has been impacted by the
12133 "extending all" inheritance of project C.
12135 Note that if a Library Project in the hierarchy is virtually extended,
12136 the virtual project that extends the Library Project is not a Library Project.
12138 @c ****************************************
12139 @c * External References in Project Files *
12140 @c ****************************************
12142 @node External References in Project Files
12143 @section External References in Project Files
12146 A project file may contain references to external variables; such references
12147 are called @emph{external references}.
12149 An external variable is either defined as part of the environment (an
12150 environment variable in Unix, for example) or else specified on the command
12151 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
12152 If both, then the command line value is used.
12154 The value of an external reference is obtained by means of the built-in
12155 function @code{external}, which returns a string value.
12156 This function has two forms:
12158 @item @code{external (external_variable_name)}
12159 @item @code{external (external_variable_name, default_value)}
12163 Each parameter must be a string literal. For example:
12165 @smallexample @c projectfile
12167 external ("OS", "GNU/Linux")
12171 In the form with one parameter, the function returns the value of
12172 the external variable given as parameter. If this name is not present in the
12173 environment, the function returns an empty string.
12175 In the form with two string parameters, the second argument is
12176 the value returned when the variable given as the first argument is not
12177 present in the environment. In the example above, if @code{"OS"} is not
12178 the name of ^an environment variable^a logical name^ and is not passed on
12179 the command line, then the returned value is @code{"GNU/Linux"}.
12181 An external reference may be part of a string expression or of a string
12182 list expression, and can therefore appear in a variable declaration or
12183 an attribute declaration.
12185 @smallexample @c projectfile
12187 type Mode_Type is ("Debug", "Release");
12188 Mode : Mode_Type := external ("MODE");
12195 @c *****************************
12196 @c * Packages in Project Files *
12197 @c *****************************
12199 @node Packages in Project Files
12200 @section Packages in Project Files
12203 A @emph{package} defines the settings for project-aware tools within a
12205 For each such tool one can declare a package; the names for these
12206 packages are preset (see @ref{Packages}).
12207 A package may contain variable declarations, attribute declarations, and case
12210 @smallexample @c projectfile
12213 package Builder is -- used by gnatmake
12214 for ^Default_Switches^Default_Switches^ ("Ada")
12223 The syntax of package declarations mimics that of package in Ada.
12225 Most of the packages have an attribute
12226 @code{^Default_Switches^Default_Switches^}.
12227 This attribute is an associative array, and its value is a string list.
12228 The index of the associative array is the name of a programming language (case
12229 insensitive). This attribute indicates the ^switch^switch^
12230 or ^switches^switches^ to be used
12231 with the corresponding tool.
12233 Some packages also have another attribute, @code{^Switches^Switches^},
12234 an associative array whose value is a string list.
12235 The index is the name of a source file.
12236 This attribute indicates the ^switch^switch^
12237 or ^switches^switches^ to be used by the corresponding
12238 tool when dealing with this specific file.
12240 Further information on these ^switch^switch^-related attributes is found in
12241 @ref{^Switches^Switches^ and Project Files}.
12243 A package may be declared as a @emph{renaming} of another package; e.g., from
12244 the project file for an imported project.
12246 @smallexample @c projectfile
12248 with "/global/apex.gpr";
12250 package Naming renames Apex.Naming;
12257 Packages that are renamed in other project files often come from project files
12258 that have no sources: they are just used as templates. Any modification in the
12259 template will be reflected automatically in all the project files that rename
12260 a package from the template.
12262 In addition to the tool-oriented packages, you can also declare a package
12263 named @code{Naming} to establish specialized source file naming conventions
12264 (see @ref{Naming Schemes}).
12266 @c ************************************
12267 @c * Variables from Imported Projects *
12268 @c ************************************
12270 @node Variables from Imported Projects
12271 @section Variables from Imported Projects
12274 An attribute or variable defined in an imported or parent project can
12275 be used in expressions in the importing / extending project.
12276 Such an attribute or variable is denoted by an expanded name whose prefix
12277 is either the name of the project or the expanded name of a package within
12280 @smallexample @c projectfile
12283 project Main extends "base" is
12284 Var1 := Imported.Var;
12285 Var2 := Base.Var & ".new";
12290 for ^Default_Switches^Default_Switches^ ("Ada")
12291 use Imported.Builder.Ada_^Switches^Switches^ &
12292 "^-gnatg^-gnatg^" &
12298 package Compiler is
12299 for ^Default_Switches^Default_Switches^ ("Ada")
12300 use Base.Compiler.Ada_^Switches^Switches^;
12311 The value of @code{Var1} is a copy of the variable @code{Var} defined
12312 in the project file @file{"imported.gpr"}
12314 the value of @code{Var2} is a copy of the value of variable @code{Var}
12315 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
12317 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12318 @code{Builder} is a string list that includes in its value a copy of the value
12319 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
12320 in project file @file{imported.gpr} plus two new elements:
12321 @option{"^-gnatg^-gnatg^"}
12322 and @option{"^-v^-v^"};
12324 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12325 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
12326 defined in the @code{Compiler} package in project file @file{base.gpr},
12327 the project being extended.
12330 @c ******************
12331 @c * Naming Schemes *
12332 @c ******************
12334 @node Naming Schemes
12335 @section Naming Schemes
12338 Sometimes an Ada software system is ported from a foreign compilation
12339 environment to GNAT, and the file names do not use the default GNAT
12340 conventions. Instead of changing all the file names (which for a variety
12341 of reasons might not be possible), you can define the relevant file
12342 naming scheme in the @code{Naming} package in your project file.
12345 Note that the use of pragmas described in @ref{Alternative
12346 File Naming Schemes} by mean of a configuration pragmas file is not
12347 supported when using project files. You must use the features described
12348 in this paragraph. You can however use specify other configuration
12349 pragmas (see @ref{Specifying Configuration Pragmas}).
12352 For example, the following
12353 package models the Apex file naming rules:
12355 @smallexample @c projectfile
12358 for Casing use "lowercase";
12359 for Dot_Replacement use ".";
12360 for Spec_Suffix ("Ada") use ".1.ada";
12361 for Body_Suffix ("Ada") use ".2.ada";
12368 For example, the following package models the DEC Ada file naming rules:
12370 @smallexample @c projectfile
12373 for Casing use "lowercase";
12374 for Dot_Replacement use "__";
12375 for Spec_Suffix ("Ada") use "_.^ada^ada^";
12376 for Body_Suffix ("Ada") use ".^ada^ada^";
12382 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
12383 names in lower case)
12387 You can define the following attributes in package @code{Naming}:
12392 This must be a string with one of the three values @code{"lowercase"},
12393 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
12396 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
12398 @item @var{Dot_Replacement}
12399 This must be a string whose value satisfies the following conditions:
12402 @item It must not be empty
12403 @item It cannot start or end with an alphanumeric character
12404 @item It cannot be a single underscore
12405 @item It cannot start with an underscore followed by an alphanumeric
12406 @item It cannot contain a dot @code{'.'} except if the entire string
12411 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
12413 @item @var{Spec_Suffix}
12414 This is an associative array (indexed by the programming language name, case
12415 insensitive) whose value is a string that must satisfy the following
12419 @item It must not be empty
12420 @item It must include at least one dot
12423 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
12424 @code{"^.ads^.ADS^"}.
12426 @item @var{Body_Suffix}
12427 This is an associative array (indexed by the programming language name, case
12428 insensitive) whose value is a string that must satisfy the following
12432 @item It must not be empty
12433 @item It must include at least one dot
12434 @item It cannot end with the same string as @code{Spec_Suffix ("Ada")}
12437 If @code{Body_Suffix ("Ada")} is not specified, then the default is
12438 @code{"^.adb^.ADB^"}.
12440 @item @var{Separate_Suffix}
12441 This must be a string whose value satisfies the same conditions as
12442 @code{Body_Suffix}.
12445 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
12446 value as @code{Body_Suffix ("Ada")}.
12450 You can use the associative array attribute @code{Spec} to define
12451 the source file name for an individual Ada compilation unit's spec. The array
12452 index must be a string literal that identifies the Ada unit (case insensitive).
12453 The value of this attribute must be a string that identifies the file that
12454 contains this unit's spec (case sensitive or insensitive depending on the
12457 @smallexample @c projectfile
12458 for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
12463 You can use the associative array attribute @code{Body} to
12464 define the source file name for an individual Ada compilation unit's body
12465 (possibly a subunit). The array index must be a string literal that identifies
12466 the Ada unit (case insensitive). The value of this attribute must be a string
12467 that identifies the file that contains this unit's body or subunit (case
12468 sensitive or insensitive depending on the operating system).
12470 @smallexample @c projectfile
12471 for Body ("MyPack.MyChild") use "mypack.mychild.body";
12475 @c ********************
12476 @c * Library Projects *
12477 @c ********************
12479 @node Library Projects
12480 @section Library Projects
12483 @emph{Library projects} are projects whose object code is placed in a library.
12484 (Note that this facility is not yet supported on all platforms)
12486 To create a library project, you need to define in its project file
12487 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
12488 Additionally, you may define the library-related attributes
12489 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
12490 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
12492 The @code{Library_Name} attribute has a string value. There is no restriction
12493 on the name of a library. It is the responsability of the developer to
12494 choose a name that will be accepted by the platform. It is recommanded to
12495 choose names that could be Ada identifiers; such names are almost guaranteed
12496 to be acceptable on all platforms.
12498 The @code{Library_Dir} attribute has a string value that designates the path
12499 (absolute or relative) of the directory where the library will reside.
12500 It must designate an existing directory, and this directory must be
12501 different from the project's object directory. It also needs to be writable.
12502 The directory should only be used for one library; the reason is that all
12503 files contained in this directory may be deleted by the Project Manager.
12505 If both @code{Library_Name} and @code{Library_Dir} are specified and
12506 are legal, then the project file defines a library project. The optional
12507 library-related attributes are checked only for such project files.
12509 The @code{Library_Kind} attribute has a string value that must be one of the
12510 following (case insensitive): @code{"static"}, @code{"dynamic"} or
12511 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
12512 attribute is not specified, the library is a static library, that is
12513 an archive of object files that can be potentially linked into an
12514 static executable. Otherwise, the library may be dynamic or
12515 relocatable, that is a library that is loaded only at the start of execution.
12517 If you need to build both a static and a dynamic library, you should use two
12518 different object directories, since in some cases some extra code needs to
12519 be generated for the latter. For such cases, it is recommended to either use
12520 two different project files, or a single one which uses external variables
12521 to indicate what kind of library should be build.
12523 The @code{Library_Version} attribute has a string value whose interpretation
12524 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
12525 used only for dynamic/relocatable libraries as the internal name of the
12526 library (the @code{"soname"}). If the library file name (built from the
12527 @code{Library_Name}) is different from the @code{Library_Version}, then the
12528 library file will be a symbolic link to the actual file whose name will be
12529 @code{Library_Version}.
12533 @smallexample @c projectfile
12539 for Library_Dir use "lib_dir";
12540 for Library_Name use "dummy";
12541 for Library_Kind use "relocatable";
12542 for Library_Version use "libdummy.so." & Version;
12549 Directory @file{lib_dir} will contain the internal library file whose name
12550 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
12551 @file{libdummy.so.1}.
12553 When @command{gnatmake} detects that a project file
12554 is a library project file, it will check all immediate sources of the project
12555 and rebuild the library if any of the sources have been recompiled.
12557 Standard project files can import library project files. In such cases,
12558 the libraries will only be rebuild if some of its sources are recompiled
12559 because they are in the closure of some other source in an importing project.
12560 Sources of the library project files that are not in such a closure will
12561 not be checked, unless the full library is checked, because one of its sources
12562 needs to be recompiled.
12564 For instance, assume the project file @code{A} imports the library project file
12565 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
12566 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
12567 @file{l2.ads}, @file{l2.adb}.
12569 If @file{l1.adb} has been modified, then the library associated with @code{L}
12570 will be rebuild when compiling all the immediate sources of @code{A} only
12571 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
12574 To be sure that all the sources in the library associated with @code{L} are
12575 up to date, and that all the sources of parject @code{A} are also up to date,
12576 the following two commands needs to be used:
12583 When a library is built or rebuilt, an attempt is made first to delete all
12584 files in the library directory.
12585 All @file{ALI} files will also be copied from the object directory to the
12586 library directory. To build executables, @command{gnatmake} will use the
12587 library rather than the individual object files.
12589 @c **********************************************
12590 @c * Using Third-Party Libraries through Projects
12591 @c **********************************************
12592 @node Using Third-Party Libraries through Projects
12593 @section Using Third-Party Libraries through Projects
12595 Whether you are exporting your own library to make it available to
12596 clients, or you are using a library provided by a third party, it is
12597 convenient to have project files that automatically set the correct
12598 command line switches for the compiler and linker.
12600 Such project files are very similar to the library project files;
12601 @xref{Library Projects}. The only difference is that you set the
12602 @code{Source_Dirs} and @code{Object_Dir} attribute so that they point to the
12603 directories where, respectively, the sources and the read-only ALI files have
12606 If you need to interface with a set of libraries, as opposed to a
12607 single one, you need to create one library project for each of the
12608 libraries. In addition, a top-level project that imports all these
12609 library projects should be provided, so that the user of your library
12610 has a single @code{with} clause to add to his own projects.
12612 For instance, let's assume you are providing two static libraries
12613 @file{liba.a} and @file{libb.a}. The user needs to link with
12614 both of these libraries. Each of these is associated with its
12615 own set of header files. Let's assume furthermore that all the
12616 header files for the two libraries have been installed in the same
12617 directory @file{headers}. The @file{ALI} files are found in the same
12618 @file{headers} directory.
12620 In this case, you should provide the following three projects:
12622 @smallexample @c projectfile
12624 with "liba", "libb";
12625 project My_Library is
12626 for Source_Dirs use ("headers");
12627 for Object_Dir use "headers";
12633 for Source_Dirs use ();
12634 for Library_Dir use "lib";
12635 for Library_Name use "a";
12636 for Library_Kind use "static";
12642 for Source_Dirs use ();
12643 for Library_Dir use "lib";
12644 for Library_Name use "b";
12645 for Library_Kind use "static";
12650 @c *******************************
12651 @c * Stand-alone Library Projects *
12652 @c *******************************
12654 @node Stand-alone Library Projects
12655 @section Stand-alone Library Projects
12658 A Stand-alone Library is a library that contains the necessary code to
12659 elaborate the Ada units that are included in the library. A Stand-alone
12660 Library is suitable to be used in an executable when the main is not
12661 in Ada. However, Stand-alone Libraries may also be used with an Ada main
12664 A Stand-alone Library Project is a Library Project where the library is
12665 a Stand-alone Library.
12667 To be a Stand-alone Library Project, in addition to the two attributes
12668 that make a project a Library Project (@code{Library_Name} and
12669 @code{Library_Dir}, see @ref{Library Projects}), the attribute
12670 @code{Library_Interface} must be defined.
12672 @smallexample @c projectfile
12674 for Library_Dir use "lib_dir";
12675 for Library_Name use "dummy";
12676 for Library_Interface use ("int1", "int1.child");
12680 Attribute @code{Library_Interface} has a non empty string list value,
12681 each string in the list designating a unit contained in an immediate source
12682 of the project file.
12684 When a Stand-alone Library is built, first the binder is invoked to build
12685 a package whose name depends on the library name
12686 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
12687 This binder-generated package includes initialization and
12688 finalization procedures whose
12689 names depend on the library name (dummyinit and dummyfinal in the example
12690 above). The object corresponding to this package is included in the library.
12692 A dynamic or relocatable Stand-alone Library is automatically initialized
12693 if automatic initialization of Stand-alone Libraries is supported on the
12694 platform and if attribute @code{Library_Auto_Init} is not specified or
12695 is specified with the value "true". A static Stand-alone Library is never
12696 automatically initialized.
12698 Single string attribute @code{Library_Auto_Init} may be specified with only
12699 two possible values: "false" or "true" (case-insensitive). Specifying
12700 "false" for attribute @code{Library_Auto_Init} will prevent automatic
12701 initialization of dynamic or relocatable libraries.
12703 When a non automatically initialized Stand-alone Library is used
12704 in an executable, its initialization procedure must be called before
12705 any service of the library is used.
12706 When the main subprogram is in Ada, it may mean that the initialization
12707 procedure has to be called during elaboration of another package.
12709 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
12710 (those that are listed in attribute @code{Library_Interface}) are copied to
12711 the Library Directory. As a consequence, only the Interface Units may be
12712 imported from Ada units outside of the library. If other units are imported,
12713 the binding phase will fail.
12715 When a Stand-Alone Library is bound, the switches that are specified in
12716 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
12717 used in the call to @command{gnatbind}.
12719 The string list attribute @code{Library_Options} may be used to specified
12720 additional switches to the call to @command{gcc} to link the library.
12722 The attribute @code{Library_Src_Dir}, may be specified for a
12723 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
12724 single string value. Its value must be the path (absolute or relative to the
12725 project directory) of an existing directory. This directory cannot be the
12726 object directory or one of the source directories, but it can be the same as
12727 the library directory. The sources of the Interface
12728 Units of the library, necessary to an Ada client of the library, will be
12729 copied to the designated directory, called Interface Copy directory.
12730 These sources includes the specs of the Interface Units, but they may also
12731 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
12732 are used, or when there is a generic units in the spec. Before the sources
12733 are copied to the Interface Copy directory, an attempt is made to delete all
12734 files in the Interface Copy directory.
12736 @c *************************************
12737 @c * Switches Related to Project Files *
12738 @c *************************************
12739 @node Switches Related to Project Files
12740 @section Switches Related to Project Files
12743 The following switches are used by GNAT tools that support project files:
12747 @item ^-P^/PROJECT_FILE=^@var{project}
12748 @cindex @option{^-P^/PROJECT_FILE^} (any tool supporting project files)
12749 Indicates the name of a project file. This project file will be parsed with
12750 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12751 if any, and using the external references indicated
12752 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12754 There may zero, one or more spaces between @option{-P} and @var{project}.
12758 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12761 Since the Project Manager parses the project file only after all the switches
12762 on the command line are checked, the order of the switches
12763 @option{^-P^/PROJECT_FILE^},
12764 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12765 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12767 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12768 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any tool supporting project files)
12769 Indicates that external variable @var{name} has the value @var{value}.
12770 The Project Manager will use this value for occurrences of
12771 @code{external(name)} when parsing the project file.
12775 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12776 put between quotes.
12784 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12785 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12786 @var{name}, only the last one is used.
12789 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12790 takes precedence over the value of the same name in the environment.
12792 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12793 @cindex @code{^-vP^/MESSAGES_PROJECT_FILE^} (any tool supporting project files)
12794 @c Previous line uses code vs option command, to stay less than 80 chars
12795 Indicates the verbosity of the parsing of GNAT project files.
12798 @option{-vP0} means Default;
12799 @option{-vP1} means Medium;
12800 @option{-vP2} means High.
12804 There are three possible options for this qualifier: DEFAULT, MEDIUM and
12809 The default is ^Default^DEFAULT^: no output for syntactically correct
12812 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12813 only the last one is used.
12817 @c **********************************
12818 @c * Tools Supporting Project Files *
12819 @c **********************************
12821 @node Tools Supporting Project Files
12822 @section Tools Supporting Project Files
12825 * gnatmake and Project Files::
12826 * The GNAT Driver and Project Files::
12828 * Glide and Project Files::
12832 @node gnatmake and Project Files
12833 @subsection gnatmake and Project Files
12836 This section covers several topics related to @command{gnatmake} and
12837 project files: defining ^switches^switches^ for @command{gnatmake}
12838 and for the tools that it invokes; specifying configuration pragmas;
12839 the use of the @code{Main} attribute; building and rebuilding library project
12843 * ^Switches^Switches^ and Project Files::
12844 * Specifying Configuration Pragmas::
12845 * Project Files and Main Subprograms::
12846 * Library Project Files::
12849 @node ^Switches^Switches^ and Project Files
12850 @subsubsection ^Switches^Switches^ and Project Files
12853 It is not currently possible to specify VMS style qualifiers in the project
12854 files; only Unix style ^switches^switches^ may be specified.
12858 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12859 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
12860 attribute, a @code{^Switches^Switches^} attribute, or both;
12861 as their names imply, these ^switch^switch^-related
12862 attributes affect the ^switches^switches^ that are used for each of these GNAT
12864 @command{gnatmake} is invoked. As will be explained below, these
12865 component-specific ^switches^switches^ precede
12866 the ^switches^switches^ provided on the @command{gnatmake} command line.
12868 The @code{^Default_Switches^Default_Switches^} attribute is an associative
12869 array indexed by language name (case insensitive) whose value is a string list.
12872 @smallexample @c projectfile
12874 package Compiler is
12875 for ^Default_Switches^Default_Switches^ ("Ada")
12876 use ("^-gnaty^-gnaty^",
12883 The @code{^Switches^Switches^} attribute is also an associative array,
12884 indexed by a file name (which may or may not be case sensitive, depending
12885 on the operating system) whose value is a string list. For example:
12887 @smallexample @c projectfile
12890 for ^Switches^Switches^ ("main1.adb")
12892 for ^Switches^Switches^ ("main2.adb")
12899 For the @code{Builder} package, the file names must designate source files
12900 for main subprograms. For the @code{Binder} and @code{Linker} packages, the
12901 file names must designate @file{ALI} or source files for main subprograms.
12902 In each case just the file name without an explicit extension is acceptable.
12904 For each tool used in a program build (@command{gnatmake}, the compiler, the
12905 binder, and the linker), the corresponding package @dfn{contributes} a set of
12906 ^switches^switches^ for each file on which the tool is invoked, based on the
12907 ^switch^switch^-related attributes defined in the package.
12908 In particular, the ^switches^switches^
12909 that each of these packages contributes for a given file @var{f} comprise:
12913 the value of attribute @code{^Switches^Switches^ (@var{f})},
12914 if it is specified in the package for the given file,
12916 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
12917 if it is specified in the package.
12921 If neither of these attributes is defined in the package, then the package does
12922 not contribute any ^switches^switches^ for the given file.
12924 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
12925 two sets, in the following order: those contributed for the file
12926 by the @code{Builder} package;
12927 and the switches passed on the command line.
12929 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12930 the ^switches^switches^ passed to the tool comprise three sets,
12931 in the following order:
12935 the applicable ^switches^switches^ contributed for the file
12936 by the @code{Builder} package in the project file supplied on the command line;
12939 those contributed for the file by the package (in the relevant project file --
12940 see below) corresponding to the tool; and
12943 the applicable switches passed on the command line.
12947 The term @emph{applicable ^switches^switches^} reflects the fact that
12948 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
12949 tools, depending on the individual ^switch^switch^.
12951 @command{gnatmake} may invoke the compiler on source files from different
12952 projects. The Project Manager will use the appropriate project file to
12953 determine the @code{Compiler} package for each source file being compiled.
12954 Likewise for the @code{Binder} and @code{Linker} packages.
12956 As an example, consider the following package in a project file:
12958 @smallexample @c projectfile
12961 package Compiler is
12962 for ^Default_Switches^Default_Switches^ ("Ada")
12964 for ^Switches^Switches^ ("a.adb")
12966 for ^Switches^Switches^ ("b.adb")
12968 "^-gnaty^-gnaty^");
12975 If @command{gnatmake} is invoked with this project file, and it needs to
12976 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12977 @file{a.adb} will be compiled with the ^switch^switch^
12978 @option{^-O1^-O1^},
12979 @file{b.adb} with ^switches^switches^
12981 and @option{^-gnaty^-gnaty^},
12982 and @file{c.adb} with @option{^-g^-g^}.
12984 The following example illustrates the ordering of the ^switches^switches^
12985 contributed by different packages:
12987 @smallexample @c projectfile
12991 for ^Switches^Switches^ ("main.adb")
12999 package Compiler is
13000 for ^Switches^Switches^ ("main.adb")
13008 If you issue the command:
13011 gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
13015 then the compiler will be invoked on @file{main.adb} with the following
13016 sequence of ^switches^switches^
13019 ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
13022 with the last @option{^-O^-O^}
13023 ^switch^switch^ having precedence over the earlier ones;
13024 several other ^switches^switches^
13025 (such as @option{^-c^-c^}) are added implicitly.
13027 The ^switches^switches^
13029 and @option{^-O1^-O1^} are contributed by package
13030 @code{Builder}, @option{^-O2^-O2^} is contributed
13031 by the package @code{Compiler}
13032 and @option{^-O0^-O0^} comes from the command line.
13034 The @option{^-g^-g^}
13035 ^switch^switch^ will also be passed in the invocation of
13036 @command{Gnatlink.}
13038 A final example illustrates switch contributions from packages in different
13041 @smallexample @c projectfile
13044 for Source_Files use ("pack.ads", "pack.adb");
13045 package Compiler is
13046 for ^Default_Switches^Default_Switches^ ("Ada")
13047 use ("^-gnata^-gnata^");
13055 for Source_Files use ("foo_main.adb", "bar_main.adb");
13057 for ^Switches^Switches^ ("foo_main.adb")
13065 -- Ada source file:
13067 procedure Foo_Main is
13075 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
13079 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
13080 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
13081 @option{^-gnato^-gnato^} (passed on the command line).
13082 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
13083 are @option{^-g^-g^} from @code{Proj4.Builder},
13084 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
13085 and @option{^-gnato^-gnato^} from the command line.
13088 When using @command{gnatmake} with project files, some ^switches^switches^ or
13089 arguments may be expressed as relative paths. As the working directory where
13090 compilation occurs may change, these relative paths are converted to absolute
13091 paths. For the ^switches^switches^ found in a project file, the relative paths
13092 are relative to the project file directory, for the switches on the command
13093 line, they are relative to the directory where @command{gnatmake} is invoked.
13094 The ^switches^switches^ for which this occurs are:
13100 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
13102 ^-o^-o^, object files specified in package @code{Linker} or after
13103 -largs on the command line). The exception to this rule is the ^switch^switch^
13104 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
13106 @node Specifying Configuration Pragmas
13107 @subsubsection Specifying Configuration Pragmas
13109 When using @command{gnatmake} with project files, if there exists a file
13110 @file{gnat.adc} that contains configuration pragmas, this file will be
13113 Configuration pragmas can be defined by means of the following attributes in
13114 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
13115 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
13117 Both these attributes are single string attributes. Their values is the path
13118 name of a file containing configuration pragmas. If a path name is relative,
13119 then it is relative to the project directory of the project file where the
13120 attribute is defined.
13122 When compiling a source, the configuration pragmas used are, in order,
13123 those listed in the file designated by attribute
13124 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
13125 project file, if it is specified, and those listed in the file designated by
13126 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
13127 the project file of the source, if it exists.
13129 @node Project Files and Main Subprograms
13130 @subsubsection Project Files and Main Subprograms
13133 When using a project file, you can invoke @command{gnatmake}
13134 with one or several main subprograms, by specifying their source files on the
13138 gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
13142 Each of these needs to be a source file of the same project, except
13143 when the switch ^-u^/UNIQUE^ is used.
13146 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
13147 same project, one of the project in the tree rooted at the project specified
13148 on the command line. The package @code{Builder} of this common project, the
13149 "main project" is the one that is considered by @command{gnatmake}.
13152 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
13153 imported directly or indirectly by the project specified on the command line.
13154 Note that if such a source file is not part of the project specified on the
13155 command line, the ^switches^switches^ found in package @code{Builder} of the
13156 project specified on the command line, if any, that are transmitted
13157 to the compiler will still be used, not those found in the project file of
13161 When using a project file, you can also invoke @command{gnatmake} without
13162 explicitly specifying any main, and the effect depends on whether you have
13163 defined the @code{Main} attribute. This attribute has a string list value,
13164 where each element in the list is the name of a source file (the file
13165 extension is optional) that contains a unit that can be a main subprogram.
13167 If the @code{Main} attribute is defined in a project file as a non-empty
13168 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
13169 line, then invoking @command{gnatmake} with this project file but without any
13170 main on the command line is equivalent to invoking @command{gnatmake} with all
13171 the file names in the @code{Main} attribute on the command line.
13174 @smallexample @c projectfile
13177 for Main use ("main1", "main2", "main3");
13183 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
13185 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
13187 When the project attribute @code{Main} is not specified, or is specified
13188 as an empty string list, or when the switch @option{-u} is used on the command
13189 line, then invoking @command{gnatmake} with no main on the command line will
13190 result in all immediate sources of the project file being checked, and
13191 potentially recompiled. Depending on the presence of the switch @option{-u},
13192 sources from other project files on which the immediate sources of the main
13193 project file depend are also checked and potentially recompiled. In other
13194 words, the @option{-u} switch is applied to all of the immediate sources of the
13197 When no main is specified on the command line and attribute @code{Main} exists
13198 and includes several mains, or when several mains are specified on the
13199 command line, the default ^switches^switches^ in package @code{Builder} will
13200 be used for all mains, even if there are specific ^switches^switches^
13201 specified for one or several mains.
13203 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
13204 the specific ^switches^switches^ for each main, if they are specified.
13206 @node Library Project Files
13207 @subsubsection Library Project Files
13210 When @command{gnatmake} is invoked with a main project file that is a library
13211 project file, it is not allowed to specify one or more mains on the command
13215 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
13216 ^-l^/ACTION=LINK^ have special meanings.
13219 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
13220 to @command{gnatmake} that @command{gnatbind} should be invoked for the
13223 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13224 to @command{gnatmake} that the binder generated file should be compiled
13225 (in the case of a stand-alone library) and that the library should be built.
13229 @node The GNAT Driver and Project Files
13230 @subsection The GNAT Driver and Project Files
13233 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13235 @command{^gnatbind^gnatbind^},
13236 @command{^gnatfind^gnatfind^},
13237 @command{^gnatlink^gnatlink^},
13238 @command{^gnatls^gnatls^},
13239 @command{^gnatelim^gnatelim^},
13240 @command{^gnatpp^gnatpp^},
13241 @command{^gnatmetric^gnatmetric^},
13242 @command{^gnatstub^gnatstub^},
13243 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
13244 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13245 They must be invoked through the @command{gnat} driver.
13247 The @command{gnat} driver is a front-end that accepts a number of commands and
13248 call the corresponding tool. It has been designed initially for VMS to convert
13249 VMS style qualifiers to Unix style switches, but it is now available to all
13250 the GNAT supported platforms.
13252 On non VMS platforms, the @command{gnat} driver accepts the following commands
13253 (case insensitive):
13257 BIND to invoke @command{^gnatbind^gnatbind^}
13259 CHOP to invoke @command{^gnatchop^gnatchop^}
13261 CLEAN to invoke @command{^gnatclean^gnatclean^}
13263 COMP or COMPILE to invoke the compiler
13265 ELIM to invoke @command{^gnatelim^gnatelim^}
13267 FIND to invoke @command{^gnatfind^gnatfind^}
13269 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
13271 LINK to invoke @command{^gnatlink^gnatlink^}
13273 LS or LIST to invoke @command{^gnatls^gnatls^}
13275 MAKE to invoke @command{^gnatmake^gnatmake^}
13277 NAME to invoke @command{^gnatname^gnatname^}
13279 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
13281 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
13283 METRIC to invoke @command{^gnatmetric^gnatmetric^}
13285 STUB to invoke @command{^gnatstub^gnatstub^}
13287 XREF to invoke @command{^gnatxref^gnatxref^}
13291 (note that the compiler is invoked using the command
13292 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
13295 On non VMS platforms, between @command{gnat} and the command, two
13296 special switches may be used:
13300 @command{-v} to display the invocation of the tool.
13302 @command{-dn} to prevent the @command{gnat} driver from removing
13303 the temporary files it has created. These temporary files are
13304 configuration files and temporary file list files.
13308 The command may be followed by switches and arguments for the invoked
13312 gnat bind -C main.ali
13318 Switches may also be put in text files, one switch per line, and the text
13319 files may be specified with their path name preceded by '@@'.
13322 gnat bind @@args.txt main.ali
13326 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
13327 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
13328 (@option{^-P^/PROJECT_FILE^},
13329 @option{^-X^/EXTERNAL_REFERENCE^} and
13330 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
13331 the switches of the invoking tool.
13334 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
13335 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
13336 the immediate sources of the specified project file.
13339 When GNAT METRIC is used with a project file, but with no source
13340 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
13341 with all the immediate sources of the specified project file and with
13342 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
13346 For each of the following commands, there is optionally a corresponding
13347 package in the main project.
13351 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
13354 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
13357 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
13360 package @code{Eliminate} for command ELIM (invoking
13361 @code{^gnatelim^gnatelim^})
13364 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
13367 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
13370 package @code{Metrics} for command METRIC
13371 (invoking @code{^gnatmetric^gnatmetric^})
13374 package @code{Pretty_Printer} for command PP or PRETTY
13375 (invoking @code{^gnatpp^gnatpp^})
13378 package @code{Gnatstub} for command STUB
13379 (invoking @code{^gnatstub^gnatstub^})
13382 package @code{Cross_Reference} for command XREF (invoking
13383 @code{^gnatxref^gnatxref^})
13388 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
13389 a simple variable with a string list value. It contains ^switches^switches^
13390 for the invocation of @code{^gnatls^gnatls^}.
13392 @smallexample @c projectfile
13396 for ^Switches^Switches^
13405 All other packages have two attribute @code{^Switches^Switches^} and
13406 @code{^Default_Switches^Default_Switches^}.
13409 @code{^Switches^Switches^} is an associated array attribute, indexed by the
13410 source file name, that has a string list value: the ^switches^switches^ to be
13411 used when the tool corresponding to the package is invoked for the specific
13415 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
13416 indexed by the programming language that has a string list value.
13417 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
13418 ^switches^switches^ for the invocation of the tool corresponding
13419 to the package, except if a specific @code{^Switches^Switches^} attribute
13420 is specified for the source file.
13422 @smallexample @c projectfile
13426 for Source_Dirs use ("./**");
13429 for ^Switches^Switches^ use
13436 package Compiler is
13437 for ^Default_Switches^Default_Switches^ ("Ada")
13438 use ("^-gnatv^-gnatv^",
13439 "^-gnatwa^-gnatwa^");
13445 for ^Default_Switches^Default_Switches^ ("Ada")
13453 for ^Default_Switches^Default_Switches^ ("Ada")
13455 for ^Switches^Switches^ ("main.adb")
13464 for ^Default_Switches^Default_Switches^ ("Ada")
13471 package Cross_Reference is
13472 for ^Default_Switches^Default_Switches^ ("Ada")
13477 end Cross_Reference;
13483 With the above project file, commands such as
13486 ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13487 ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13488 ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13489 ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13490 ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13494 will set up the environment properly and invoke the tool with the switches
13495 found in the package corresponding to the tool:
13496 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13497 except @code{^Switches^Switches^ ("main.adb")}
13498 for @code{^gnatlink^gnatlink^}.
13501 @node Glide and Project Files
13502 @subsection Glide and Project Files
13505 Glide will automatically recognize the @file{.gpr} extension for
13506 project files, and will
13507 convert them to its own internal format automatically. However, it
13508 doesn't provide a syntax-oriented editor for modifying these
13510 The project file will be loaded as text when you select the menu item
13511 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
13512 You can edit this text and save the @file{gpr} file;
13513 when you next select this project file in Glide it
13514 will be automatically reloaded.
13517 @c **********************
13518 @node An Extended Example
13519 @section An Extended Example
13522 Suppose that we have two programs, @var{prog1} and @var{prog2},
13523 whose sources are in corresponding directories. We would like
13524 to build them with a single @command{gnatmake} command, and we want to place
13525 their object files into @file{build} subdirectories of the source directories.
13526 Furthermore, we want to have to have two separate subdirectories
13527 in @file{build} -- @file{release} and @file{debug} -- which will contain
13528 the object files compiled with different set of compilation flags.
13530 In other words, we have the following structure:
13547 Here are the project files that we must place in a directory @file{main}
13548 to maintain this structure:
13552 @item We create a @code{Common} project with a package @code{Compiler} that
13553 specifies the compilation ^switches^switches^:
13558 @b{project} Common @b{is}
13560 @b{for} Source_Dirs @b{use} (); -- No source files
13564 @b{type} Build_Type @b{is} ("release", "debug");
13565 Build : Build_Type := External ("BUILD", "debug");
13568 @b{package} Compiler @b{is}
13569 @b{case} Build @b{is}
13570 @b{when} "release" =>
13571 @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13572 @b{use} ("^-O2^-O2^");
13573 @b{when} "debug" =>
13574 @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13575 @b{use} ("^-g^-g^");
13583 @item We create separate projects for the two programs:
13590 @b{project} Prog1 @b{is}
13592 @b{for} Source_Dirs @b{use} ("prog1");
13593 @b{for} Object_Dir @b{use} "prog1/build/" & Common.Build;
13595 @b{package} Compiler @b{renames} Common.Compiler;
13606 @b{project} Prog2 @b{is}
13608 @b{for} Source_Dirs @b{use} ("prog2");
13609 @b{for} Object_Dir @b{use} "prog2/build/" & Common.Build;
13611 @b{package} Compiler @b{renames} Common.Compiler;
13617 @item We create a wrapping project @code{Main}:
13626 @b{project} Main @b{is}
13628 @b{package} Compiler @b{renames} Common.Compiler;
13634 @item Finally we need to create a dummy procedure that @code{with}s (either
13635 explicitly or implicitly) all the sources of our two programs.
13640 Now we can build the programs using the command
13643 gnatmake ^-P^/PROJECT_FILE=^main dummy
13647 for the Debug mode, or
13651 gnatmake -Pmain -XBUILD=release
13657 GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
13662 for the Release mode.
13664 @c ********************************
13665 @c * Project File Complete Syntax *
13666 @c ********************************
13668 @node Project File Complete Syntax
13669 @section Project File Complete Syntax
13673 context_clause project_declaration
13679 @b{with} path_name @{ , path_name @} ;
13684 project_declaration ::=
13685 simple_project_declaration | project_extension
13687 simple_project_declaration ::=
13688 @b{project} <project_>simple_name @b{is}
13689 @{declarative_item@}
13690 @b{end} <project_>simple_name;
13692 project_extension ::=
13693 @b{project} <project_>simple_name @b{extends} path_name @b{is}
13694 @{declarative_item@}
13695 @b{end} <project_>simple_name;
13697 declarative_item ::=
13698 package_declaration |
13699 typed_string_declaration |
13700 other_declarative_item
13702 package_declaration ::=
13703 package_specification | package_renaming
13705 package_specification ::=
13706 @b{package} package_identifier @b{is}
13707 @{simple_declarative_item@}
13708 @b{end} package_identifier ;
13710 package_identifier ::=
13711 @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
13712 @code{Linker} | @code{Finder} | @code{Cross_Reference} |
13713 @code{^gnatls^gnatls^} | @code{IDE} | @code{Pretty_Printer}
13715 package_renaming ::==
13716 @b{package} package_identifier @b{renames}
13717 <project_>simple_name.package_identifier ;
13719 typed_string_declaration ::=
13720 @b{type} <typed_string_>_simple_name @b{is}
13721 ( string_literal @{, string_literal@} );
13723 other_declarative_item ::=
13724 attribute_declaration |
13725 typed_variable_declaration |
13726 variable_declaration |
13729 attribute_declaration ::=
13730 full_associative_array_declaration |
13731 @b{for} attribute_designator @b{use} expression ;
13733 full_associative_array_declaration ::=
13734 @b{for} <associative_array_attribute_>simple_name @b{use}
13735 <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
13737 attribute_designator ::=
13738 <simple_attribute_>simple_name |
13739 <associative_array_attribute_>simple_name ( string_literal )
13741 typed_variable_declaration ::=
13742 <typed_variable_>simple_name : <typed_string_>name := string_expression ;
13744 variable_declaration ::=
13745 <variable_>simple_name := expression;
13755 attribute_reference
13761 ( <string_>expression @{ , <string_>expression @} )
13764 @b{external} ( string_literal [, string_literal] )
13766 attribute_reference ::=
13767 attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
13769 attribute_prefix ::=
13771 <project_>simple_name | package_identifier |
13772 <project_>simple_name . package_identifier
13774 case_construction ::=
13775 @b{case} <typed_variable_>name @b{is}
13780 @b{when} discrete_choice_list =>
13781 @{case_construction | attribute_declaration@}
13783 discrete_choice_list ::=
13784 string_literal @{| string_literal@} |
13788 simple_name @{. simple_name@}
13791 identifier (same as Ada)
13795 @node The Cross-Referencing Tools gnatxref and gnatfind
13796 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13801 The compiler generates cross-referencing information (unless
13802 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13803 This information indicates where in the source each entity is declared and
13804 referenced. Note that entities in package Standard are not included, but
13805 entities in all other predefined units are included in the output.
13807 Before using any of these two tools, you need to compile successfully your
13808 application, so that GNAT gets a chance to generate the cross-referencing
13811 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13812 information to provide the user with the capability to easily locate the
13813 declaration and references to an entity. These tools are quite similar,
13814 the difference being that @code{gnatfind} is intended for locating
13815 definitions and/or references to a specified entity or entities, whereas
13816 @code{gnatxref} is oriented to generating a full report of all
13819 To use these tools, you must not compile your application using the
13820 @option{-gnatx} switch on the @file{gnatmake} command line
13821 (see @ref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
13822 information will not be generated.
13825 * gnatxref Switches::
13826 * gnatfind Switches::
13827 * Project Files for gnatxref and gnatfind::
13828 * Regular Expressions in gnatfind and gnatxref::
13829 * Examples of gnatxref Usage::
13830 * Examples of gnatfind Usage::
13833 @node gnatxref Switches
13834 @section @code{gnatxref} Switches
13837 The command invocation for @code{gnatxref} is:
13839 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
13846 @item sourcefile1, sourcefile2
13847 identifies the source files for which a report is to be generated. The
13848 ``with''ed units will be processed too. You must provide at least one file.
13850 These file names are considered to be regular expressions, so for instance
13851 specifying @file{source*.adb} is the same as giving every file in the current
13852 directory whose name starts with @file{source} and whose extension is
13855 You shouldn't specify any directory name, just base names. @command{gnatxref}
13856 and @command{gnatfind} will be able to locate these files by themselves using
13857 the source path. If you specify directories, no result is produced.
13862 The switches can be :
13865 @item ^-a^/ALL_FILES^
13866 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
13867 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13868 the read-only files found in the library search path. Otherwise, these files
13869 will be ignored. This option can be used to protect Gnat sources or your own
13870 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13871 much faster, and their output much smaller. Read-only here refers to access
13872 or permissions status in the file system for the current user.
13875 @cindex @option{-aIDIR} (@command{gnatxref})
13876 When looking for source files also look in directory DIR. The order in which
13877 source file search is undertaken is the same as for @file{gnatmake}.
13880 @cindex @option{-aODIR} (@command{gnatxref})
13881 When searching for library and object files, look in directory
13882 DIR. The order in which library files are searched is the same as for
13886 @cindex @option{-nostdinc} (@command{gnatxref})
13887 Do not look for sources in the system default directory.
13890 @cindex @option{-nostdlib} (@command{gnatxref})
13891 Do not look for library files in the system default directory.
13893 @item --RTS=@var{rts-path}
13894 @cindex @option{--RTS} (@command{gnatxref})
13895 Specifies the default location of the runtime library. Same meaning as the
13896 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13898 @item ^-d^/DERIVED_TYPES^
13899 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
13900 If this switch is set @code{gnatxref} will output the parent type
13901 reference for each matching derived types.
13903 @item ^-f^/FULL_PATHNAME^
13904 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
13905 If this switch is set, the output file names will be preceded by their
13906 directory (if the file was found in the search path). If this switch is
13907 not set, the directory will not be printed.
13909 @item ^-g^/IGNORE_LOCALS^
13910 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
13911 If this switch is set, information is output only for library-level
13912 entities, ignoring local entities. The use of this switch may accelerate
13913 @code{gnatfind} and @code{gnatxref}.
13916 @cindex @option{-IDIR} (@command{gnatxref})
13917 Equivalent to @samp{-aODIR -aIDIR}.
13920 @cindex @option{-pFILE} (@command{gnatxref})
13921 Specify a project file to use @xref{Project Files}. These project files are
13922 the @file{.adp} files used by Glide. If you need to use the @file{.gpr}
13923 project files, you should use gnatxref through the GNAT driver
13924 (@command{gnat xref -Pproject}).
13926 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13927 project file in the current directory.
13929 If a project file is either specified or found by the tools, then the content
13930 of the source directory and object directory lines are added as if they
13931 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13932 and @samp{^-aO^OBJECT_SEARCH^}.
13934 Output only unused symbols. This may be really useful if you give your
13935 main compilation unit on the command line, as @code{gnatxref} will then
13936 display every unused entity and 'with'ed package.
13940 Instead of producing the default output, @code{gnatxref} will generate a
13941 @file{tags} file that can be used by vi. For examples how to use this
13942 feature, see @xref{Examples of gnatxref Usage}. The tags file is output
13943 to the standard output, thus you will have to redirect it to a file.
13949 All these switches may be in any order on the command line, and may even
13950 appear after the file names. They need not be separated by spaces, thus
13951 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13952 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13954 @node gnatfind Switches
13955 @section @code{gnatfind} Switches
13958 The command line for @code{gnatfind} is:
13961 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
13970 An entity will be output only if it matches the regular expression found
13971 in @samp{pattern}, see @xref{Regular Expressions in gnatfind and gnatxref}.
13973 Omitting the pattern is equivalent to specifying @samp{*}, which
13974 will match any entity. Note that if you do not provide a pattern, you
13975 have to provide both a sourcefile and a line.
13977 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13978 for matching purposes. At the current time there is no support for
13979 8-bit codes other than Latin-1, or for wide characters in identifiers.
13982 @code{gnatfind} will look for references, bodies or declarations
13983 of symbols referenced in @file{sourcefile}, at line @samp{line}
13984 and column @samp{column}. See @pxref{Examples of gnatfind Usage}
13985 for syntax examples.
13988 is a decimal integer identifying the line number containing
13989 the reference to the entity (or entities) to be located.
13992 is a decimal integer identifying the exact location on the
13993 line of the first character of the identifier for the
13994 entity reference. Columns are numbered from 1.
13996 @item file1 file2 ...
13997 The search will be restricted to these source files. If none are given, then
13998 the search will be done for every library file in the search path.
13999 These file must appear only after the pattern or sourcefile.
14001 These file names are considered to be regular expressions, so for instance
14002 specifying 'source*.adb' is the same as giving every file in the current
14003 directory whose name starts with 'source' and whose extension is 'adb'.
14005 The location of the spec of the entity will always be displayed, even if it
14006 isn't in one of file1, file2,... The occurrences of the entity in the
14007 separate units of the ones given on the command line will also be displayed.
14009 Note that if you specify at least one file in this part, @code{gnatfind} may
14010 sometimes not be able to find the body of the subprograms...
14015 At least one of 'sourcefile' or 'pattern' has to be present on
14018 The following switches are available:
14022 @item ^-a^/ALL_FILES^
14023 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
14024 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
14025 the read-only files found in the library search path. Otherwise, these files
14026 will be ignored. This option can be used to protect Gnat sources or your own
14027 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
14028 much faster, and their output much smaller. Read-only here refers to access
14029 or permission status in the file system for the current user.
14032 @cindex @option{-aIDIR} (@command{gnatfind})
14033 When looking for source files also look in directory DIR. The order in which
14034 source file search is undertaken is the same as for @file{gnatmake}.
14037 @cindex @option{-aODIR} (@command{gnatfind})
14038 When searching for library and object files, look in directory
14039 DIR. The order in which library files are searched is the same as for
14043 @cindex @option{-nostdinc} (@command{gnatfind})
14044 Do not look for sources in the system default directory.
14047 @cindex @option{-nostdlib} (@command{gnatfind})
14048 Do not look for library files in the system default directory.
14050 @item --RTS=@var{rts-path}
14051 @cindex @option{--RTS} (@command{gnatfind})
14052 Specifies the default location of the runtime library. Same meaning as the
14053 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
14055 @item ^-d^/DERIVED_TYPE_INFORMATION^
14056 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
14057 If this switch is set, then @code{gnatfind} will output the parent type
14058 reference for each matching derived types.
14060 @item ^-e^/EXPRESSIONS^
14061 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
14062 By default, @code{gnatfind} accept the simple regular expression set for
14063 @samp{pattern}. If this switch is set, then the pattern will be
14064 considered as full Unix-style regular expression.
14066 @item ^-f^/FULL_PATHNAME^
14067 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
14068 If this switch is set, the output file names will be preceded by their
14069 directory (if the file was found in the search path). If this switch is
14070 not set, the directory will not be printed.
14072 @item ^-g^/IGNORE_LOCALS^
14073 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
14074 If this switch is set, information is output only for library-level
14075 entities, ignoring local entities. The use of this switch may accelerate
14076 @code{gnatfind} and @code{gnatxref}.
14079 @cindex @option{-IDIR} (@command{gnatfind})
14080 Equivalent to @samp{-aODIR -aIDIR}.
14083 @cindex @option{-pFILE} (@command{gnatfind})
14084 Specify a project file (@pxref{Project Files}) to use.
14085 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14086 project file in the current directory.
14088 If a project file is either specified or found by the tools, then the content
14089 of the source directory and object directory lines are added as if they
14090 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
14091 @samp{^-aO^/OBJECT_SEARCH^}.
14093 @item ^-r^/REFERENCES^
14094 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
14095 By default, @code{gnatfind} will output only the information about the
14096 declaration, body or type completion of the entities. If this switch is
14097 set, the @code{gnatfind} will locate every reference to the entities in
14098 the files specified on the command line (or in every file in the search
14099 path if no file is given on the command line).
14101 @item ^-s^/PRINT_LINES^
14102 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
14103 If this switch is set, then @code{gnatfind} will output the content
14104 of the Ada source file lines were the entity was found.
14106 @item ^-t^/TYPE_HIERARCHY^
14107 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
14108 If this switch is set, then @code{gnatfind} will output the type hierarchy for
14109 the specified type. It act like -d option but recursively from parent
14110 type to parent type. When this switch is set it is not possible to
14111 specify more than one file.
14116 All these switches may be in any order on the command line, and may even
14117 appear after the file names. They need not be separated by spaces, thus
14118 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14119 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14121 As stated previously, gnatfind will search in every directory in the
14122 search path. You can force it to look only in the current directory if
14123 you specify @code{*} at the end of the command line.
14125 @node Project Files for gnatxref and gnatfind
14126 @section Project Files for @command{gnatxref} and @command{gnatfind}
14129 Project files allow a programmer to specify how to compile its
14130 application, where to find sources, etc. These files are used
14132 primarily by the Glide Ada mode, but they can also be used
14135 @code{gnatxref} and @code{gnatfind}.
14137 A project file name must end with @file{.gpr}. If a single one is
14138 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
14139 extract the information from it. If multiple project files are found, none of
14140 them is read, and you have to use the @samp{-p} switch to specify the one
14143 The following lines can be included, even though most of them have default
14144 values which can be used in most cases.
14145 The lines can be entered in any order in the file.
14146 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
14147 each line. If you have multiple instances, only the last one is taken into
14152 [default: @code{"^./^[]^"}]
14153 specifies a directory where to look for source files. Multiple @code{src_dir}
14154 lines can be specified and they will be searched in the order they
14158 [default: @code{"^./^[]^"}]
14159 specifies a directory where to look for object and library files. Multiple
14160 @code{obj_dir} lines can be specified, and they will be searched in the order
14163 @item comp_opt=SWITCHES
14164 [default: @code{""}]
14165 creates a variable which can be referred to subsequently by using
14166 the @code{$@{comp_opt@}} notation. This is intended to store the default
14167 switches given to @command{gnatmake} and @command{gcc}.
14169 @item bind_opt=SWITCHES
14170 [default: @code{""}]
14171 creates a variable which can be referred to subsequently by using
14172 the @samp{$@{bind_opt@}} notation. This is intended to store the default
14173 switches given to @command{gnatbind}.
14175 @item link_opt=SWITCHES
14176 [default: @code{""}]
14177 creates a variable which can be referred to subsequently by using
14178 the @samp{$@{link_opt@}} notation. This is intended to store the default
14179 switches given to @command{gnatlink}.
14181 @item main=EXECUTABLE
14182 [default: @code{""}]
14183 specifies the name of the executable for the application. This variable can
14184 be referred to in the following lines by using the @samp{$@{main@}} notation.
14187 @item comp_cmd=COMMAND
14188 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
14191 @item comp_cmd=COMMAND
14192 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
14194 specifies the command used to compile a single file in the application.
14197 @item make_cmd=COMMAND
14198 [default: @code{"GNAT MAKE $@{main@}
14199 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
14200 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
14201 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
14204 @item make_cmd=COMMAND
14205 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
14206 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
14207 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
14209 specifies the command used to recompile the whole application.
14211 @item run_cmd=COMMAND
14212 [default: @code{"$@{main@}"}]
14213 specifies the command used to run the application.
14215 @item debug_cmd=COMMAND
14216 [default: @code{"gdb $@{main@}"}]
14217 specifies the command used to debug the application
14222 @command{gnatxref} and @command{gnatfind} only take into account the
14223 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
14225 @node Regular Expressions in gnatfind and gnatxref
14226 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
14229 As specified in the section about @command{gnatfind}, the pattern can be a
14230 regular expression. Actually, there are to set of regular expressions
14231 which are recognized by the program :
14234 @item globbing patterns
14235 These are the most usual regular expression. They are the same that you
14236 generally used in a Unix shell command line, or in a DOS session.
14238 Here is a more formal grammar :
14245 term ::= elmt -- matches elmt
14246 term ::= elmt elmt -- concatenation (elmt then elmt)
14247 term ::= * -- any string of 0 or more characters
14248 term ::= ? -- matches any character
14249 term ::= [char @{char@}] -- matches any character listed
14250 term ::= [char - char] -- matches any character in range
14254 @item full regular expression
14255 The second set of regular expressions is much more powerful. This is the
14256 type of regular expressions recognized by utilities such a @file{grep}.
14258 The following is the form of a regular expression, expressed in Ada
14259 reference manual style BNF is as follows
14266 regexp ::= term @{| term@} -- alternation (term or term ...)
14268 term ::= item @{item@} -- concatenation (item then item)
14270 item ::= elmt -- match elmt
14271 item ::= elmt * -- zero or more elmt's
14272 item ::= elmt + -- one or more elmt's
14273 item ::= elmt ? -- matches elmt or nothing
14276 elmt ::= nschar -- matches given character
14277 elmt ::= [nschar @{nschar@}] -- matches any character listed
14278 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
14279 elmt ::= [char - char] -- matches chars in given range
14280 elmt ::= \ char -- matches given character
14281 elmt ::= . -- matches any single character
14282 elmt ::= ( regexp ) -- parens used for grouping
14284 char ::= any character, including special characters
14285 nschar ::= any character except ()[].*+?^^^
14289 Following are a few examples :
14293 will match any of the two strings 'abcde' and 'fghi'.
14296 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
14299 will match any string which has only lowercase characters in it (and at
14300 least one character
14305 @node Examples of gnatxref Usage
14306 @section Examples of @code{gnatxref} Usage
14308 @subsection General Usage
14311 For the following examples, we will consider the following units :
14313 @smallexample @c ada
14319 3: procedure Foo (B : in Integer);
14326 1: package body Main is
14327 2: procedure Foo (B : in Integer) is
14338 2: procedure Print (B : Integer);
14347 The first thing to do is to recompile your application (for instance, in
14348 that case just by doing a @samp{gnatmake main}, so that GNAT generates
14349 the cross-referencing information.
14350 You can then issue any of the following commands:
14352 @item gnatxref main.adb
14353 @code{gnatxref} generates cross-reference information for main.adb
14354 and every unit 'with'ed by main.adb.
14356 The output would be:
14364 Decl: main.ads 3:20
14365 Body: main.adb 2:20
14366 Ref: main.adb 4:13 5:13 6:19
14369 Ref: main.adb 6:8 7:8
14379 Decl: main.ads 3:15
14380 Body: main.adb 2:15
14383 Body: main.adb 1:14
14386 Ref: main.adb 6:12 7:12
14390 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
14391 its body is in main.adb, line 1, column 14 and is not referenced any where.
14393 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
14394 it referenced in main.adb, line 6 column 12 and line 7 column 12.
14396 @item gnatxref package1.adb package2.ads
14397 @code{gnatxref} will generates cross-reference information for
14398 package1.adb, package2.ads and any other package 'with'ed by any
14404 @subsection Using gnatxref with vi
14406 @code{gnatxref} can generate a tags file output, which can be used
14407 directly from @file{vi}. Note that the standard version of @file{vi}
14408 will not work properly with overloaded symbols. Consider using another
14409 free implementation of @file{vi}, such as @file{vim}.
14412 $ gnatxref -v gnatfind.adb > tags
14416 will generate the tags file for @code{gnatfind} itself (if the sources
14417 are in the search path!).
14419 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
14420 (replacing @i{entity} by whatever you are looking for), and vi will
14421 display a new file with the corresponding declaration of entity.
14424 @node Examples of gnatfind Usage
14425 @section Examples of @code{gnatfind} Usage
14429 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
14430 Find declarations for all entities xyz referenced at least once in
14431 main.adb. The references are search in every library file in the search
14434 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
14437 The output will look like:
14439 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14440 ^directory/^[directory]^main.adb:24:10: xyz <= body
14441 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14445 that is to say, one of the entities xyz found in main.adb is declared at
14446 line 12 of main.ads (and its body is in main.adb), and another one is
14447 declared at line 45 of foo.ads
14449 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
14450 This is the same command as the previous one, instead @code{gnatfind} will
14451 display the content of the Ada source file lines.
14453 The output will look like:
14456 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14458 ^directory/^[directory]^main.adb:24:10: xyz <= body
14460 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14465 This can make it easier to find exactly the location your are looking
14468 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14469 Find references to all entities containing an x that are
14470 referenced on line 123 of main.ads.
14471 The references will be searched only in main.ads and foo.adb.
14473 @item gnatfind main.ads:123
14474 Find declarations and bodies for all entities that are referenced on
14475 line 123 of main.ads.
14477 This is the same as @code{gnatfind "*":main.adb:123}.
14479 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
14480 Find the declaration for the entity referenced at column 45 in
14481 line 123 of file main.adb in directory mydir. Note that it
14482 is usual to omit the identifier name when the column is given,
14483 since the column position identifies a unique reference.
14485 The column has to be the beginning of the identifier, and should not
14486 point to any character in the middle of the identifier.
14490 @c *********************************
14491 @node The GNAT Pretty-Printer gnatpp
14492 @chapter The GNAT Pretty-Printer @command{gnatpp}
14494 @cindex Pretty-Printer
14497 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
14498 for source reformatting / pretty-printing.
14499 It takes an Ada source file as input and generates a reformatted
14501 You can specify various style directives via switches; e.g.,
14502 identifier case conventions, rules of indentation, and comment layout.
14504 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
14505 tree for the input source and thus requires the input to be syntactically and
14506 semantically legal.
14507 If this condition is not met, @command{gnatpp} will terminate with an
14508 error message; no output file will be generated.
14510 If the compilation unit
14511 contained in the input source depends semantically upon units located
14512 outside the current directory, you have to provide the source search path
14513 when invoking @command{gnatpp}, if these units are contained in files with
14514 names that do not follow the GNAT file naming rules, you have to provide
14515 the configuration file describing the corresponding naming scheme;
14516 see the description of the @command{gnatpp}
14517 switches below. Another possibility is to use a project file and to
14518 call @command{gnatpp} through the @command{gnat} driver
14520 The @command{gnatpp} command has the form
14523 $ gnatpp [@var{switches}] @var{filename}
14530 @var{switches} is an optional sequence of switches defining such properties as
14531 the formatting rules, the source search path, and the destination for the
14535 @var{filename} is the name (including the extension) of the source file to
14536 reformat; ``wildcards'' or several file names on the same gnatpp command are
14537 allowed. The file name may contain path information; it does not have to
14538 follow the GNAT file naming rules
14542 * Switches for gnatpp::
14543 * Formatting Rules::
14546 @node Switches for gnatpp
14547 @section Switches for @command{gnatpp}
14550 The following subsections describe the various switches accepted by
14551 @command{gnatpp}, organized by category.
14554 You specify a switch by supplying a name and generally also a value.
14555 In many cases the values for a switch with a given name are incompatible with
14557 (for example the switch that controls the casing of a reserved word may have
14558 exactly one value: upper case, lower case, or
14559 mixed case) and thus exactly one such switch can be in effect for an
14560 invocation of @command{gnatpp}.
14561 If more than one is supplied, the last one is used.
14562 However, some values for the same switch are mutually compatible.
14563 You may supply several such switches to @command{gnatpp}, but then
14564 each must be specified in full, with both the name and the value.
14565 Abbreviated forms (the name appearing once, followed by each value) are
14567 For example, to set
14568 the alignment of the assignment delimiter both in declarations and in
14569 assignment statements, you must write @option{-A2A3}
14570 (or @option{-A2 -A3}), but not @option{-A23}.
14574 In many cases the set of options for a given qualifier are incompatible with
14575 each other (for example the qualifier that controls the casing of a reserved
14576 word may have exactly one option, which specifies either upper case, lower
14577 case, or mixed case), and thus exactly one such option can be in effect for
14578 an invocation of @command{gnatpp}.
14579 If more than one is supplied, the last one is used.
14580 However, some qualifiers have options that are mutually compatible,
14581 and then you may then supply several such options when invoking
14585 In most cases, it is obvious whether or not the
14586 ^values for a switch with a given name^options for a given qualifier^
14587 are compatible with each other.
14588 When the semantics might not be evident, the summaries below explicitly
14589 indicate the effect.
14592 * Alignment Control::
14594 * Construct Layout Control::
14595 * General Text Layout Control::
14596 * Other Formatting Options::
14597 * Setting the Source Search Path::
14598 * Output File Control::
14599 * Other gnatpp Switches::
14602 @node Alignment Control
14603 @subsection Alignment Control
14604 @cindex Alignment control in @command{gnatpp}
14607 Programs can be easier to read if certain constructs are vertically aligned.
14608 By default all alignments are set ON.
14609 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
14610 OFF, and then use one or more of the other
14611 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
14612 to activate alignment for specific constructs.
14615 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
14619 Set all alignments to ON
14622 @item ^-A0^/ALIGN=OFF^
14623 Set all alignments to OFF
14625 @item ^-A1^/ALIGN=COLONS^
14626 Align @code{:} in declarations
14628 @item ^-A2^/ALIGN=DECLARATIONS^
14629 Align @code{:=} in initializations in declarations
14631 @item ^-A3^/ALIGN=STATEMENTS^
14632 Align @code{:=} in assignment statements
14634 @item ^-A4^/ALIGN=ARROWS^
14635 Align @code{=>} in associations
14639 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
14642 @node Casing Control
14643 @subsection Casing Control
14644 @cindex Casing control in @command{gnatpp}
14647 @command{gnatpp} allows you to specify the casing for reserved words,
14648 pragma names, attribute designators and identifiers.
14649 For identifiers you may define a
14650 general rule for name casing but also override this rule
14651 via a set of dictionary files.
14653 Three types of casing are supported: lower case, upper case, and mixed case.
14654 Lower and upper case are self-explanatory (but since some letters in
14655 Latin1 and other GNAT-supported character sets
14656 exist only in lower-case form, an upper case conversion will have no
14658 ``Mixed case'' means that the first letter, and also each letter immediately
14659 following an underscore, are converted to their uppercase forms;
14660 all the other letters are converted to their lowercase forms.
14663 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
14664 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
14665 Attribute designators are lower case
14667 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
14668 Attribute designators are upper case
14670 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
14671 Attribute designators are mixed case (this is the default)
14673 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
14674 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
14675 Keywords (technically, these are known in Ada as @emph{reserved words}) are
14676 lower case (this is the default)
14678 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
14679 Keywords are upper case
14681 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
14682 @item ^-nD^/NAME_CASING=AS_DECLARED^
14683 Name casing for defining occurrences are as they appear in the source file
14684 (this is the default)
14686 @item ^-nU^/NAME_CASING=UPPER_CASE^
14687 Names are in upper case
14689 @item ^-nL^/NAME_CASING=LOWER_CASE^
14690 Names are in lower case
14692 @item ^-nM^/NAME_CASING=MIXED_CASE^
14693 Names are in mixed case
14695 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
14696 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
14697 Pragma names are lower case
14699 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
14700 Pragma names are upper case
14702 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
14703 Pragma names are mixed case (this is the default)
14705 @item ^-D@var{file}^/DICTIONARY=@var{file}^
14706 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
14707 Use @var{file} as a @emph{dictionary file} that defines
14708 the casing for a set of specified names,
14709 thereby overriding the effect on these names by
14710 any explicit or implicit
14711 ^-n^/NAME_CASING^ switch.
14712 To supply more than one dictionary file,
14713 use ^several @option{-D} switches^a list of files as options^.
14716 @option{gnatpp} implicitly uses a @emph{default dictionary file}
14717 to define the casing for the Ada predefined names and
14718 the names declared in the GNAT libraries.
14720 @item ^-D-^/SPECIFIC_CASING^
14721 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
14722 Do not use the default dictionary file;
14723 instead, use the casing
14724 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
14729 The structure of a dictionary file, and details on the conventions
14730 used in the default dictionary file, are defined in @ref{Name Casing}.
14732 The @option{^-D-^/SPECIFIC_CASING^} and
14733 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
14736 @node Construct Layout Control
14737 @subsection Construct Layout Control
14738 @cindex Layout control in @command{gnatpp}
14741 This group of @command{gnatpp} switches controls the layout of comments and
14742 complex syntactic constructs. See @ref{Formatting Comments}, for details
14746 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
14747 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
14748 All the comments remain unchanged
14750 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
14751 GNAT-style comment line indentation (this is the default).
14753 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
14754 Reference-manual comment line indentation.
14756 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
14757 GNAT-style comment beginning
14759 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14760 Reformat comment blocks
14762 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
14763 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
14764 GNAT-style layout (this is the default)
14766 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
14769 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
14772 @item ^-notab^/NOTABS^
14773 All the VT characters are removed from the comment text. All the HT characters
14774 are expanded with the sequences of space characters to get to the next tab
14781 The @option{-c1} and @option{-c2} switches are incompatible.
14782 The @option{-c3} and @option{-c4} switches are compatible with each other and
14783 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
14784 the other comment formatting switches.
14786 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
14791 For the @option{/COMMENTS_LAYOUT} qualifier:
14794 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
14796 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
14797 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
14801 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
14802 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
14805 @node General Text Layout Control
14806 @subsection General Text Layout Control
14809 These switches allow control over line length and indentation.
14812 @item ^-M@i{nnn}^/LINE_LENGTH_MAX=@i{nnn}^
14813 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14814 Maximum line length, @i{nnn} from 32 ..256, the default value is 79
14816 @item ^-i@i{nnn}^/INDENTATION_LEVEL=@i{nnn}^
14817 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14818 Indentation level, @i{nnn} from 1 .. 9, the default value is 3
14820 @item ^-cl@i{nnn}^/CONTINUATION_INDENT=@i{nnn}^
14821 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
14822 Indentation level for continuation lines (relative to the line being
14823 continued), @i{nnn} from 1 .. 9.
14825 value is one less then the (normal) indentation level, unless the
14826 indentation is set to 1 (in which case the default value for continuation
14827 line indentation is also 1)
14830 @node Other Formatting Options
14831 @subsection Other Formatting Options
14834 These switches control the inclusion of missing end/exit labels, and
14835 the indentation level in @b{case} statements.
14838 @item ^-e^/NO_MISSED_LABELS^
14839 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
14840 Do not insert missing end/exit labels. An end label is the name of
14841 a construct that may optionally be repeated at the end of the
14842 construct's declaration;
14843 e.g., the names of packages, subprograms, and tasks.
14844 An exit label is the name of a loop that may appear as target
14845 of an exit statement within the loop.
14846 By default, @command{gnatpp} inserts these end/exit labels when
14847 they are absent from the original source. This option suppresses such
14848 insertion, so that the formatted source reflects the original.
14850 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
14851 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
14852 Insert a Form Feed character after a pragma Page.
14854 @item ^-T@i{nnn}^/MAX_INDENT=@i{nnn}^
14855 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
14856 Do not use an additional indentation level for @b{case} alternatives
14857 and variants if there are @i{nnn} or more (the default
14859 If @i{nnn} is 0, an additional indentation level is
14860 used for @b{case} alternatives and variants regardless of their number.
14863 @node Setting the Source Search Path
14864 @subsection Setting the Source Search Path
14867 To define the search path for the input source file, @command{gnatpp}
14868 uses the same switches as the GNAT compiler, with the same effects.
14871 @item ^-I^/SEARCH=^@var{dir}
14872 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
14873 The same as the corresponding gcc switch
14875 @item ^-I-^/NOCURRENT_DIRECTORY^
14876 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
14877 The same as the corresponding gcc switch
14879 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
14880 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
14881 The same as the corresponding gcc switch
14883 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
14884 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
14885 The same as the corresponding gcc switch
14889 @node Output File Control
14890 @subsection Output File Control
14893 By default the output is sent to the file whose name is obtained by appending
14894 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
14895 (if the file with this name already exists, it is unconditionally overwritten).
14896 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
14897 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
14899 The output may be redirected by the following switches:
14902 @item ^-pipe^/STANDARD_OUTPUT^
14903 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
14904 Send the output to @code{Standard_Output}
14906 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
14907 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
14908 Write the output into @var{output_file}.
14909 If @var{output_file} already exists, @command{gnatpp} terminates without
14910 reading or processing the input file.
14912 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
14913 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
14914 Write the output into @var{output_file}, overwriting the existing file
14915 (if one is present).
14917 @item ^-r^/REPLACE^
14918 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
14919 Replace the input source file with the reformatted output, and copy the
14920 original input source into the file whose name is obtained by appending the
14921 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
14922 If a file with this name already exists, @command{gnatpp} terminates without
14923 reading or processing the input file.
14925 @item ^-rf^/OVERRIDING_REPLACE^
14926 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
14927 Like @option{^-r^/REPLACE^} except that if the file with the specified name
14928 already exists, it is overwritten.
14930 @item ^-rnb^/NO_BACKUP^
14931 @cindex @option{^-rnb^/NO_BACKUP^} (@code{gnatpp})
14932 Replace the input source file with the reformatted output without
14933 creating any backup copy of the input source.
14937 Options @option{^-pipe^/STANDARD_OUTPUT^},
14938 @option{^-o^/OUTPUT^} and
14939 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
14940 contains only one file to reformat
14942 @node Other gnatpp Switches
14943 @subsection Other @code{gnatpp} Switches
14946 The additional @command{gnatpp} switches are defined in this subsection.
14949 @item ^-files @var{filename}^/FILES=@var{output_file}^
14950 @cindex @option{^-files^/FILES^} (@code{gnatpp})
14951 Take the argument source files from the specified file. This file should be an
14952 ordinary textual file containing file names separated by spaces or
14953 line breaks. You can use this switch more then once in the same call to
14954 @command{gnatpp}. You also can combine this switch with explicit list of
14957 @item ^-v^/VERBOSE^
14958 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
14960 @command{gnatpp} generates version information and then
14961 a trace of the actions it takes to produce or obtain the ASIS tree.
14963 @item ^-w^/WARNINGS^
14964 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
14966 @command{gnatpp} generates a warning whenever it can not provide
14967 a required layout in the result source.
14970 @node Formatting Rules
14971 @section Formatting Rules
14974 The following subsections show how @command{gnatpp} treats ``white space'',
14975 comments, program layout, and name casing.
14976 They provide the detailed descriptions of the switches shown above.
14979 * White Space and Empty Lines::
14980 * Formatting Comments::
14981 * Construct Layout::
14985 @node White Space and Empty Lines
14986 @subsection White Space and Empty Lines
14989 @command{gnatpp} does not have an option to control space characters.
14990 It will add or remove spaces according to the style illustrated by the
14991 examples in the @cite{Ada Reference Manual}.
14993 The only format effectors
14994 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
14995 that will appear in the output file are platform-specific line breaks,
14996 and also format effectors within (but not at the end of) comments.
14997 In particular, each horizontal tab character that is not inside
14998 a comment will be treated as a space and thus will appear in the
14999 output file as zero or more spaces depending on
15000 the reformatting of the line in which it appears.
15001 The only exception is a Form Feed character, which is inserted after a
15002 pragma @code{Page} when @option{-ff} is set.
15004 The output file will contain no lines with trailing ``white space'' (spaces,
15007 Empty lines in the original source are preserved
15008 only if they separate declarations or statements.
15009 In such contexts, a
15010 sequence of two or more empty lines is replaced by exactly one empty line.
15011 Note that a blank line will be removed if it separates two ``comment blocks''
15012 (a comment block is a sequence of whole-line comments).
15013 In order to preserve a visual separation between comment blocks, use an
15014 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
15015 Likewise, if for some reason you wish to have a sequence of empty lines,
15016 use a sequence of empty comments instead.
15018 @node Formatting Comments
15019 @subsection Formatting Comments
15022 Comments in Ada code are of two kinds:
15025 a @emph{whole-line comment}, which appears by itself (possibly preceded by
15026 ``white space'') on a line
15029 an @emph{end-of-line comment}, which follows some other Ada lexical element
15034 The indentation of a whole-line comment is that of either
15035 the preceding or following line in
15036 the formatted source, depending on switch settings as will be described below.
15038 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
15039 between the end of the preceding Ada lexical element and the beginning
15040 of the comment as appear in the original source,
15041 unless either the comment has to be split to
15042 satisfy the line length limitation, or else the next line contains a
15043 whole line comment that is considered a continuation of this end-of-line
15044 comment (because it starts at the same position).
15046 cases, the start of the end-of-line comment is moved right to the nearest
15047 multiple of the indentation level.
15048 This may result in a ``line overflow'' (the right-shifted comment extending
15049 beyond the maximum line length), in which case the comment is split as
15052 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
15053 (GNAT-style comment line indentation)
15054 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
15055 (reference-manual comment line indentation).
15056 With reference-manual style, a whole-line comment is indented as if it
15057 were a declaration or statement at the same place
15058 (i.e., according to the indentation of the preceding line(s)).
15059 With GNAT style, a whole-line comment that is immediately followed by an
15060 @b{if} or @b{case} statement alternative, a record variant, or the reserved
15061 word @b{begin}, is indented based on the construct that follows it.
15064 @smallexample @c ada
15076 Reference-manual indentation produces:
15078 @smallexample @c ada
15090 while GNAT-style indentation produces:
15092 @smallexample @c ada
15104 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
15105 (GNAT style comment beginning) has the following
15110 For each whole-line comment that does not end with two hyphens,
15111 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
15112 to ensure that there are at least two spaces between these hyphens and the
15113 first non-blank character of the comment.
15117 For an end-of-line comment, if in the original source the next line is a
15118 whole-line comment that starts at the same position
15119 as the end-of-line comment,
15120 then the whole-line comment (and all whole-line comments
15121 that follow it and that start at the same position)
15122 will start at this position in the output file.
15125 That is, if in the original source we have:
15127 @smallexample @c ada
15130 A := B + C; -- B must be in the range Low1..High1
15131 -- C must be in the range Low2..High2
15132 --B+C will be in the range Low1+Low2..High1+High2
15138 Then in the formatted source we get
15140 @smallexample @c ada
15143 A := B + C; -- B must be in the range Low1..High1
15144 -- C must be in the range Low2..High2
15145 -- B+C will be in the range Low1+Low2..High1+High2
15151 A comment that exceeds the line length limit will be split.
15153 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
15154 the line belongs to a reformattable block, splitting the line generates a
15155 @command{gnatpp} warning.
15156 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
15157 comments may be reformatted in typical
15158 word processor style (that is, moving words between lines and putting as
15159 many words in a line as possible).
15161 @node Construct Layout
15162 @subsection Construct Layout
15165 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
15166 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
15167 layout on the one hand, and uncompact layout
15168 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
15169 can be illustrated by the following examples:
15173 @multitable @columnfractions .5 .5
15174 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
15177 @smallexample @c ada
15184 @smallexample @c ada
15193 @smallexample @c ada
15201 @smallexample @c ada
15211 @smallexample @c ada
15212 Clear : for J in 1 .. 10 loop
15217 @smallexample @c ada
15219 for J in 1 .. 10 loop
15230 GNAT style, compact layout Uncompact layout
15232 type q is record type q is
15233 a : integer; record
15234 b : integer; a : integer;
15235 end record; b : integer;
15238 Block : declare Block :
15239 A : Integer := 3; declare
15240 begin A : Integer := 3;
15242 end Block; Proc (A, A);
15245 Clear : for J in 1 .. 10 loop Clear :
15246 A (J) := 0; for J in 1 .. 10 loop
15247 end loop Clear; A (J) := 0;
15254 A further difference between GNAT style layout and compact layout is that
15255 GNAT style layout inserts empty lines as separation for
15256 compound statements, return statements and bodies.
15259 @subsection Name Casing
15262 @command{gnatpp} always converts the usage occurrence of a (simple) name to
15263 the same casing as the corresponding defining identifier.
15265 You control the casing for defining occurrences via the
15266 @option{^-n^/NAME_CASING^} switch.
15268 With @option{-nD} (``as declared'', which is the default),
15271 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
15273 defining occurrences appear exactly as in the source file
15274 where they are declared.
15275 The other ^values for this switch^options for this qualifier^ ---
15276 @option{^-nU^UPPER_CASE^},
15277 @option{^-nL^LOWER_CASE^},
15278 @option{^-nM^MIXED_CASE^} ---
15280 ^upper, lower, or mixed case, respectively^the corresponding casing^.
15281 If @command{gnatpp} changes the casing of a defining
15282 occurrence, it analogously changes the casing of all the
15283 usage occurrences of this name.
15285 If the defining occurrence of a name is not in the source compilation unit
15286 currently being processed by @command{gnatpp}, the casing of each reference to
15287 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
15288 switch (subject to the dictionary file mechanism described below).
15289 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
15291 casing for the defining occurrence of the name.
15293 Some names may need to be spelled with casing conventions that are not
15294 covered by the upper-, lower-, and mixed-case transformations.
15295 You can arrange correct casing by placing such names in a
15296 @emph{dictionary file},
15297 and then supplying a @option{^-D^/DICTIONARY^} switch.
15298 The casing of names from dictionary files overrides
15299 any @option{^-n^/NAME_CASING^} switch.
15301 To handle the casing of Ada predefined names and the names from GNAT libraries,
15302 @command{gnatpp} assumes a default dictionary file.
15303 The name of each predefined entity is spelled with the same casing as is used
15304 for the entity in the @cite{Ada Reference Manual}.
15305 The name of each entity in the GNAT libraries is spelled with the same casing
15306 as is used in the declaration of that entity.
15308 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
15309 default dictionary file.
15310 Instead, the casing for predefined and GNAT-defined names will be established
15311 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
15312 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
15313 will appear as just shown,
15314 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
15315 To ensure that even such names are rendered in uppercase,
15316 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
15317 (or else, less conveniently, place these names in upper case in a dictionary
15320 A dictionary file is
15321 a plain text file; each line in this file can be either a blank line
15322 (containing only space characters and ASCII.HT characters), an Ada comment
15323 line, or the specification of exactly one @emph{casing schema}.
15325 A casing schema is a string that has the following syntax:
15329 @var{casing_schema} ::= @var{identifier} | [*]@var{simple_identifier}[*]
15331 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
15336 (The @code{[]} metanotation stands for an optional part;
15337 see @cite{Ada Reference Manual}, Section 2.3) for the definition of the
15338 @var{identifier} lexical element and the @var{letter_or_digit} category).
15340 The casing schema string can be followed by white space and/or an Ada-style
15341 comment; any amount of white space is allowed before the string.
15343 If a dictionary file is passed as
15345 the value of a @option{-D@var{file}} switch
15348 an option to the @option{/DICTIONARY} qualifier
15351 simple name and every identifier, @command{gnatpp} checks if the dictionary
15352 defines the casing for the name or for some of its parts (the term ``subword''
15353 is used below to denote the part of a name which is delimited by ``_'' or by
15354 the beginning or end of the word and which does not contain any ``_'' inside):
15358 if the whole name is in the dictionary, @command{gnatpp} uses for this name
15359 the casing defined by the dictionary; no subwords are checked for this word
15362 for the first subword (that is, for the subword preceding the leftmost
15363 ``_''), @command{gnatpp} checks if the dictionary contains the corresponding
15364 string of the form @code{@var{simple_identifier}*}, and if it does, the
15365 casing of this @var{simple_identifier} is used for this subword
15368 for the last subword (following the rightmost ``_'') @command{gnatpp}
15369 checks if the dictionary contains the corresponding string of the form
15370 @code{*@var{simple_identifier}}, and if it does, the casing of this
15371 @var{simple_identifier} is used for this subword
15374 for every intermediate subword (surrounded by two'_') @command{gnatpp} checks
15375 if the dictionary contains the corresponding string of the form
15376 @code{*@var{simple_identifier}*}, and if it does, the casing of this
15377 simple_identifier is used for this subword
15380 if more than one dictionary file is passed as @command{gnatpp} switches, each
15381 dictionary adds new casing exceptions and overrides all the existing casing
15382 exceptions set by the previous dictionaries
15385 when @command{gnatpp} checks if the word or subword is in the dictionary,
15386 this check is not case sensitive
15390 For example, suppose we have the following source to reformat:
15392 @smallexample @c ada
15395 name1 : integer := 1;
15396 name4_name3_name2 : integer := 2;
15397 name2_name3_name4 : Boolean;
15400 name2_name3_name4 := name4_name3_name2 > name1;
15406 And suppose we have two dictionaries:
15423 If @command{gnatpp} is called with the following switches:
15427 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
15430 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
15435 then we will get the following name casing in the @command{gnatpp} output:
15437 @smallexample @c ada
15440 NAME1 : Integer := 1;
15441 Name4_NAME3_NAME2 : integer := 2;
15442 Name2_NAME3_Name4 : Boolean;
15445 Name2_NAME3_Name4 := Name4_NAME3_NAME2 > NAME1;
15450 @c *********************************
15451 @node The GNAT Metric Tool gnatmetric
15452 @chapter The GNAT Metric Tool @command{gnatmetric}
15454 @cindex Metric tool
15457 ^The @command{gnatmetric} tool^GNAT METRIC^ is an ASIS-based utility
15458 for computing various program metrics.
15459 It takes an Ada source file as input and generates a file containing the
15460 metrics data as output. Various switches control which
15461 metrics are computed and output.
15463 @command{gnatmetric} generates and uses the ASIS
15464 tree for the input source and thus requires the input to be syntactically and
15465 semantically legal.
15466 If this condition is not met, @command{gnatmetric} will generate
15467 an error message; no metric information for this file will be
15468 computed and reported.
15470 If the compilation unit contained in the input source depends semantically
15471 upon units located outside the current directory, you have to provide the
15472 source search path when invoking @command{gnatmetric}.
15473 If these units are contained in files
15474 with names that do not follow the GNAT file naming rules, you have to provide
15475 the configuration file describing the corresponding naming scheme; see the
15476 description of the @command{gnatmetric} switches below. Another possibility
15477 is to use a project file and to
15478 call @command{gnatmetric} through the @command{gnat} driver
15480 The @command{gnatmetric} command has the form
15483 $ gnatmetric [@var{switches}] @var{filename} [@var{-cargs gcc_switches}]
15490 @var{switches} specify the metrics to compute and define the destination for
15494 @var{filename} is the name (including the extension) of the source file to
15495 process; ``wildcards'' or several file names on the same @command{gnatmetric}
15496 command are allowed. The file name may contain path information; in this case
15497 it does not have to follow the GNAT file naming rules
15500 @option{-cargs gcc_switches} is a list of switches for
15501 @command{gcc}. They will be passed on to all compiler invocations made by
15502 @command{gnatmetric} to generate the ASIS trees. Here you can provide
15503 @option{-I} switches to form the source search path,
15504 and use the @var{-gnatec} switch to set the configuration file.
15508 * Switches for gnatmetric::
15511 @node Switches for gnatmetric
15512 @section Switches for @command{gnatmetric}
15515 The following subsections describe the various switches accepted by
15516 @command{gnatmetric}, organized by category.
15519 * Output Files Control::
15520 * Disable Metrics For Local Units::
15521 * Line Metrics Control::
15522 * Syntax Metrics Control::
15523 * Complexity Metrics Control::
15524 * Other gnatmetric Switches::
15527 @node Output Files Control
15528 @subsection Output File Control
15529 @cindex Output file control in @command{gnatmetric}
15532 @command{gnatmetric} has two output formats. It can generate a
15533 textual (human-readable) form, and also XML. By default only textual
15534 output is generated.
15536 When generating the output in textual form, @command{gnatmetric} creates
15537 for each Ada source file a corresponding text file
15538 containing the computed metrics. By default, this file
15539 is placed in the same directory as where the source file is located, and
15540 its name is obtained
15541 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
15544 All the output information generated in XML format is placed in a single
15545 file. By default this file is placed in the current directory and has the
15546 name ^@file{metrix.xml}^@file{METRIX$XML}^.
15548 Some of the computed metrics are summed over the units passed to
15549 @command{gnatmetric}; for example, the total number of lines of code.
15550 By default this information is sent to @file{stdout}, but a file
15551 can be specified with the @option{-og} switch.
15553 The following switches control the @command{gnatmetric} output:
15556 @cindex @option{^-x^/XML^} (@command{gnatmetric})
15558 Generate the XML output
15560 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
15561 @item ^-nt^/NO_TEXT^
15562 Do not generate the output in text form (implies @option{^-x^/XML^})
15564 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
15565 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
15566 Put textual files with detailed metrics into @var{output_dir}
15568 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
15569 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
15570 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
15571 in the name of the output file.
15573 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
15574 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
15575 Put global metrics into @var{file_name}
15577 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
15578 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
15579 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
15581 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
15582 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
15583 Use short source file names in the output
15587 @node Disable Metrics For Local Units
15588 @subsection Disable Metrics For Local Units
15589 @cindex Disable Metrics For Local Units in @command{gnatmetric}
15592 @command{gnatmetric} relies on the GNAT compilation model @minus{}
15594 unit per one source file. It computes some metrics for the whole source
15595 file (mostly ``number of lines'' metrics) and it always computes metrics for
15596 the top program unit of the corresponding compilation unit.
15598 @command{gnatmetric} considers the following constructs as program units to
15599 compute metrics for:
15603 a library item or a subunit in a compilation unit;
15606 all kinds of bodies;
15609 declarations of tasks and protected types and objects, package and generic
15610 package declarations;
15615 That is, a subprogram declaration, a generic instantiation or a renaming is
15616 considered as a program unit only if it is a library item of a compilation
15620 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
15621 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
15622 Do not compute detailed metrics for local program units
15626 @node Line Metrics Control
15627 @subsection Line Metrics Control
15628 @cindex Line metrics control in @command{gnatmetric}
15631 For any source file containing a legal compilation unit, and for any program
15632 unit, @command{gnatmetric} computes the following metrics:
15636 the total number of lines in the file;
15639 the total number of code lines (i.e., non-blank lines that are not comments)
15642 the number of comment lines
15645 the number of code lines containing end-of-line comments;
15648 the number of empty lines and lines containing only space characters and/or
15649 format effectors (blank lines)
15653 If @command{gnatmetric} is invoked on more than one source file, it sums the
15654 values of the line metrics for all the files being processed and then
15655 generates the cumulative results.
15657 By default, all the line metrics are computed and reported. You can use the
15658 following switches to select the specific line metrics to be computed and
15659 reported (if any of these parameters is set, only explicitly specified line
15660 metrics are computed).
15663 @cindex @option{^-la^/LINES_ALL^} (@command{gnatmetric})
15664 @item ^-la^/LINES_ALL^
15665 The number of all lines
15667 @cindex @option{^-lcode^/CODE_LINES^} (@command{gnatmetric})
15668 @item ^-lcode^/CODE_LINES^
15669 The number of code lines
15671 @cindex @option{^-lcomm^/COMENT_LINES^} (@command{gnatmetric})
15672 @item ^-lcomm^/COMENT_LINES^
15673 The number of comment lines
15675 @cindex @option{^-leol^/MIXED_CODE_COMMENTS^} (@command{gnatmetric})
15676 @item ^-leol^/MIXED_CODE_COMMENTS^
15677 The number of code lines containing
15678 end-of-line comments
15680 @cindex @option{^-lb^/BLANK_LINES^} (@command{gnatmetric})
15681 @item ^-lb^/BLANK_LINES^
15682 The number of blank lines
15686 @node Syntax Metrics Control
15687 @subsection Syntax Metrics Control
15688 @cindex Syntax metrics control in @command{gnatmetric}
15691 For any program unit, @command{gnatmetric} computes the total number of
15692 declarations and the total number of statements. The sum of all the statements
15693 and all the declarations is considered as @emph{LSLOC} (``Logical Source
15695 and is reported as a separate metric.
15697 For any body and any task, protected, package and generic package declaration
15698 the maximal static nesting level of nested program units is computed.
15700 @cite{Ada 95 Language Reference Manual}, 10.1(1), ``A program unit is either a
15701 package, a task unit, a protected unit, a
15702 protected entry, a generic unit, or an explicitly declared subprogram other
15703 than an enumeration literal.''
15705 For any program unit @command{gnatmetric} computes the maximal nesting level of
15706 composite syntactic constructs. This corresponds to the notion of the
15707 maximum nesting level in the GNAT built-in style checks
15708 (see @ref{Style Checking})
15710 For any library-level program unit @command{gnatmetric} additionally computes
15711 the following metrics:
15714 @item Public subprograms
15715 This metric is computed for non-private compilation units only. It is a number
15716 of the subprograms and generic subprograms declared in the given compilation
15717 unit that can be called
15718 or instantiated outside the unit. Formal generic subprograms and generic
15719 instantiations are not counted. Protected subprograms are counted in the same
15720 way as non-protected ones.
15722 @item All subprograms
15723 This metric is computed for all the library level bodies and subunits. The
15724 metric is equal to a total number of subprogram bodies in the compilation unit.
15725 Neither generic instantiations nor renamings-as-a-body nor body stubs
15726 are counted. Any subprogram body is counted, independently of its nesting
15727 level and enclosing constructs. Generic bodies and bodies of protected
15728 subprograms are counted in the same way as ``usual'' subprogram bodies.
15731 This metric is computed only for non-private package declarations and
15732 generic package declarations. It is the total number of types
15733 that can be referenced from outside this compilation unit, plus the
15734 number of types from all the visible parts of all the visible generic packages.
15735 Generic formal types are not counted.
15738 Along with counting the total number of public types, the following
15739 types are counted and reported separately:
15746 Root tagged types (abstract, non-abstract, private, non-private). Type
15747 extensions are @emph{not} counted
15750 Private types (including private extensions)
15761 This metric is computed for any compilation unit. It is equal to the total
15762 number of the declarations of different types given in the compilation unit.
15763 The private and the corresponding full type declaration are counted as one
15764 type declaration. Incomplete type declarations and generic formal types
15766 No distinction is made among different kinds of types (abstract,
15767 private etc.); the total number of types is computed and reported.
15772 By default, all the syntax metrics are computed and reported. You can use the
15773 following switches to select specific syntax metrics;
15774 if any of these is set, only the explicitly specified metrics are computed.
15777 @cindex @option{^-ed^/DECLARATION_TOTAL^} (@command{gnatmetric})
15778 @item ^-ed^/DECLARATION_TOTAL^
15779 The total number of declarations
15781 @cindex @option{^-es^/STATEMENT_TOTAL^} (@command{gnatmetric})
15782 @item ^-es^/STATEMENT_TOTAL^
15783 The total number of statements
15785 @cindex @option{^-eps^/^} (@command{gnatmetric})
15786 @item ^-eps^/INT_SUBPROGRAMS^
15787 The number of public subprograms in a compilation unit
15789 @cindex @option{^-eas^/SUBPROGRAMS_ALL^} (@command{gnatmetric})
15790 @item ^-eas^/SUBPROGRAMS_ALL^
15791 The number of all the subprograms in a compilation unit
15793 @cindex @option{^-ept^/INT_TYPES^} (@command{gnatmetric})
15794 @item ^-ept^/INT_TYPES^
15795 The number of public types in a compilation unit
15797 @cindex @option{^-eat^/TYPES_ALL^} (@command{gnatmetric})
15798 @item ^-eat^/TYPES_ALL^
15799 The number of all the types in a compilation unit
15801 @cindex @option{^-enu^/PROGRAM_NESTING_MAX^} (@command{gnatmetric})
15802 @item ^-enu^/PROGRAM_NESTING_MAX^
15803 The maximal program unit nesting level
15805 @cindex @option{^-ec^/CONSTRUCT_NESTING_MAX^} (@command{gnatmetric})
15806 @item ^-ec^/CONSTRUCT_NESTING_MAX^
15807 The maximal construct nesting level
15811 @node Complexity Metrics Control
15812 @subsection Complexity Metrics Control
15813 @cindex Complexity metrics control in @command{gnatmetric}
15816 For a program unit that is an executable body (a subprogram body (including
15817 generic bodies), task body, entry body or a package body containing
15818 its own statement sequence ) @command{gnatmetric} computes the following
15819 complexity metrics:
15823 McCabe cyclomatic complexity;
15826 McCabe essential complexity;
15829 maximal loop nesting level
15834 The McCabe complexity metrics are defined
15835 in @url{www.mccabe.com/pdf/nist235r.pdf}
15837 According to McCabe, both control statements and short-circuit control forms
15838 should be taken into account when computing cyclomatic complexity. For each
15839 body, we compute three metric values:
15843 the complexity introduced by control
15844 statements only, without taking into account short-circuit forms,
15847 the complexity introduced by short-circuit control forms only, and
15851 cyclomatic complexity, which is the sum of these two values.
15855 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
15856 the code in the exception handlers and in all the nested program units.
15858 By default, all the complexity metrics are computed and reported.
15859 For more finely-grained control you can use
15860 the following switches:
15863 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
15865 @item ^-nocc^/SUPPRESS=CYCLOMATIC_COMPLEXITY^
15866 Do not compute the McCabe Cyclomatic Complexity
15868 @item ^noec-^/SUPPRESS=ESSENTIAL_COMPLEXITY^
15869 Do not compute the Essential Complexity
15871 @item ^-nonl^/SUPPRESS=MAXIMAL_LOOP_NESTING^
15872 Do not compute maximal loop nesting level
15874 @item ^-ne^/SUPPRESS=EXITS_AS_GOTOS^
15875 Do not consider @code{exit} statements as @code{goto}s when
15876 computing Essential Complexity
15880 @node Other gnatmetric Switches
15881 @subsection Other @code{gnatmetric} Switches
15884 Additional @command{gnatmetric} switches are as follows:
15887 @item ^-files @var{filename}^/FILES=@var{filename}^
15888 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
15889 Take the argument source files from the specified file. This file should be an
15890 ordinary textual file containing file names separated by spaces or
15891 line breaks. You can use this switch more then once in the same call to
15892 @command{gnatmetric}. You also can combine this switch with
15893 an explicit list of files.
15895 @item ^-v^/VERBOSE^
15896 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
15898 @command{gnatmetric} generates version information and then
15899 a trace of sources being procesed.
15901 @item ^-dv^/DEBUG_OUTPUT^
15902 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
15904 @command{gnatmetric} generates various messages useful to understand what
15905 happens during the metrics computation
15908 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
15912 @c ***********************************
15913 @node File Name Krunching Using gnatkr
15914 @chapter File Name Krunching Using @code{gnatkr}
15918 This chapter discusses the method used by the compiler to shorten
15919 the default file names chosen for Ada units so that they do not
15920 exceed the maximum length permitted. It also describes the
15921 @code{gnatkr} utility that can be used to determine the result of
15922 applying this shortening.
15926 * Krunching Method::
15927 * Examples of gnatkr Usage::
15931 @section About @code{gnatkr}
15934 The default file naming rule in GNAT
15935 is that the file name must be derived from
15936 the unit name. The exact default rule is as follows:
15939 Take the unit name and replace all dots by hyphens.
15941 If such a replacement occurs in the
15942 second character position of a name, and the first character is
15943 ^a, g, s, or i^A, G, S, or I^ then replace the dot by the character
15944 ^~ (tilde)^$ (dollar sign)^
15945 instead of a minus.
15947 The reason for this exception is to avoid clashes
15948 with the standard names for children of System, Ada, Interfaces,
15949 and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^
15952 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
15953 switch of the compiler activates a ``krunching''
15954 circuit that limits file names to nn characters (where nn is a decimal
15955 integer). For example, using OpenVMS,
15956 where the maximum file name length is
15957 39, the value of nn is usually set to 39, but if you want to generate
15958 a set of files that would be usable if ported to a system with some
15959 different maximum file length, then a different value can be specified.
15960 The default value of 39 for OpenVMS need not be specified.
15962 The @code{gnatkr} utility can be used to determine the krunched name for
15963 a given file, when krunched to a specified maximum length.
15966 @section Using @code{gnatkr}
15969 The @code{gnatkr} command has the form
15973 $ gnatkr @var{name} [@var{length}]
15979 $ gnatkr @var{name} /COUNT=nn
15984 @var{name} is the uncrunched file name, derived from the name of the unit
15985 in the standard manner described in the previous section (i.e. in particular
15986 all dots are replaced by hyphens). The file name may or may not have an
15987 extension (defined as a suffix of the form period followed by arbitrary
15988 characters other than period). If an extension is present then it will
15989 be preserved in the output. For example, when krunching @file{hellofile.ads}
15990 to eight characters, the result will be hellofil.ads.
15992 Note: for compatibility with previous versions of @code{gnatkr} dots may
15993 appear in the name instead of hyphens, but the last dot will always be
15994 taken as the start of an extension. So if @code{gnatkr} is given an argument
15995 such as @file{Hello.World.adb} it will be treated exactly as if the first
15996 period had been a hyphen, and for example krunching to eight characters
15997 gives the result @file{hellworl.adb}.
15999 Note that the result is always all lower case (except on OpenVMS where it is
16000 all upper case). Characters of the other case are folded as required.
16002 @var{length} represents the length of the krunched name. The default
16003 when no argument is given is ^8^39^ characters. A length of zero stands for
16004 unlimited, in other words do not chop except for system files where the
16005 impled crunching length is always eight characters.
16008 The output is the krunched name. The output has an extension only if the
16009 original argument was a file name with an extension.
16011 @node Krunching Method
16012 @section Krunching Method
16015 The initial file name is determined by the name of the unit that the file
16016 contains. The name is formed by taking the full expanded name of the
16017 unit and replacing the separating dots with hyphens and
16018 using ^lowercase^uppercase^
16019 for all letters, except that a hyphen in the second character position is
16020 replaced by a ^tilde^dollar sign^ if the first character is
16021 ^a, i, g, or s^A, I, G, or S^.
16022 The extension is @code{.ads} for a
16023 specification and @code{.adb} for a body.
16024 Krunching does not affect the extension, but the file name is shortened to
16025 the specified length by following these rules:
16029 The name is divided into segments separated by hyphens, tildes or
16030 underscores and all hyphens, tildes, and underscores are
16031 eliminated. If this leaves the name short enough, we are done.
16034 If the name is too long, the longest segment is located (left-most
16035 if there are two of equal length), and shortened by dropping
16036 its last character. This is repeated until the name is short enough.
16038 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16039 to fit the name into 8 characters as required by some operating systems.
16042 our-strings-wide_fixed 22
16043 our strings wide fixed 19
16044 our string wide fixed 18
16045 our strin wide fixed 17
16046 our stri wide fixed 16
16047 our stri wide fixe 15
16048 our str wide fixe 14
16049 our str wid fixe 13
16055 Final file name: oustwifi.adb
16059 The file names for all predefined units are always krunched to eight
16060 characters. The krunching of these predefined units uses the following
16061 special prefix replacements:
16065 replaced by @file{^a^A^-}
16068 replaced by @file{^g^G^-}
16071 replaced by @file{^i^I^-}
16074 replaced by @file{^s^S^-}
16077 These system files have a hyphen in the second character position. That
16078 is why normal user files replace such a character with a
16079 ^tilde^dollar sign^, to
16080 avoid confusion with system file names.
16082 As an example of this special rule, consider
16083 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16086 ada-strings-wide_fixed 22
16087 a- strings wide fixed 18
16088 a- string wide fixed 17
16089 a- strin wide fixed 16
16090 a- stri wide fixed 15
16091 a- stri wide fixe 14
16092 a- str wide fixe 13
16098 Final file name: a-stwifi.adb
16102 Of course no file shortening algorithm can guarantee uniqueness over all
16103 possible unit names, and if file name krunching is used then it is your
16104 responsibility to ensure that no name clashes occur. The utility
16105 program @code{gnatkr} is supplied for conveniently determining the
16106 krunched name of a file.
16108 @node Examples of gnatkr Usage
16109 @section Examples of @code{gnatkr} Usage
16116 $ gnatkr very_long_unit_name.ads --> velounna.ads
16117 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
16118 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16119 $ gnatkr grandparent-parent-child --> grparchi
16121 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16122 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16125 @node Preprocessing Using gnatprep
16126 @chapter Preprocessing Using @code{gnatprep}
16130 The @code{gnatprep} utility provides
16131 a simple preprocessing capability for Ada programs.
16132 It is designed for use with GNAT, but is not dependent on any special
16137 * Switches for gnatprep::
16138 * Form of Definitions File::
16139 * Form of Input Text for gnatprep::
16142 @node Using gnatprep
16143 @section Using @code{gnatprep}
16146 To call @code{gnatprep} use
16149 $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile]
16156 is the full name of the input file, which is an Ada source
16157 file containing preprocessor directives.
16160 is the full name of the output file, which is an Ada source
16161 in standard Ada form. When used with GNAT, this file name will
16162 normally have an ads or adb suffix.
16165 is the full name of a text file containing definitions of
16166 symbols to be referenced by the preprocessor. This argument is
16167 optional, and can be replaced by the use of the @option{-D} switch.
16170 is an optional sequence of switches as described in the next section.
16173 @node Switches for gnatprep
16174 @section Switches for @code{gnatprep}
16179 @item ^-b^/BLANK_LINES^
16180 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
16181 Causes both preprocessor lines and the lines deleted by
16182 preprocessing to be replaced by blank lines in the output source file,
16183 preserving line numbers in the output file.
16185 @item ^-c^/COMMENTS^
16186 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
16187 Causes both preprocessor lines and the lines deleted
16188 by preprocessing to be retained in the output source as comments marked
16189 with the special string @code{"--! "}. This option will result in line numbers
16190 being preserved in the output file.
16192 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
16193 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
16194 Defines a new symbol, associated with value. If no value is given on the
16195 command line, then symbol is considered to be @code{True}. This switch
16196 can be used in place of a definition file.
16200 @cindex @option{/REMOVE} (@command{gnatprep})
16201 This is the default setting which causes lines deleted by preprocessing
16202 to be entirely removed from the output file.
16205 @item ^-r^/REFERENCE^
16206 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
16207 Causes a @code{Source_Reference} pragma to be generated that
16208 references the original input file, so that error messages will use
16209 the file name of this original file. The use of this switch implies
16210 that preprocessor lines are not to be removed from the file, so its
16211 use will force @option{^-b^/BLANK_LINES^} mode if
16212 @option{^-c^/COMMENTS^}
16213 has not been specified explicitly.
16215 Note that if the file to be preprocessed contains multiple units, then
16216 it will be necessary to @code{gnatchop} the output file from
16217 @code{gnatprep}. If a @code{Source_Reference} pragma is present
16218 in the preprocessed file, it will be respected by
16219 @code{gnatchop ^-r^/REFERENCE^}
16220 so that the final chopped files will correctly refer to the original
16221 input source file for @code{gnatprep}.
16223 @item ^-s^/SYMBOLS^
16224 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
16225 Causes a sorted list of symbol names and values to be
16226 listed on the standard output file.
16228 @item ^-u^/UNDEFINED^
16229 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
16230 Causes undefined symbols to be treated as having the value FALSE in the context
16231 of a preprocessor test. In the absence of this option, an undefined symbol in
16232 a @code{#if} or @code{#elsif} test will be treated as an error.
16238 Note: if neither @option{-b} nor @option{-c} is present,
16239 then preprocessor lines and
16240 deleted lines are completely removed from the output, unless -r is
16241 specified, in which case -b is assumed.
16244 @node Form of Definitions File
16245 @section Form of Definitions File
16248 The definitions file contains lines of the form
16255 where symbol is an identifier, following normal Ada (case-insensitive)
16256 rules for its syntax, and value is one of the following:
16260 Empty, corresponding to a null substitution
16262 A string literal using normal Ada syntax
16264 Any sequence of characters from the set
16265 (letters, digits, period, underline).
16269 Comment lines may also appear in the definitions file, starting with
16270 the usual @code{--},
16271 and comments may be added to the definitions lines.
16273 @node Form of Input Text for gnatprep
16274 @section Form of Input Text for @code{gnatprep}
16277 The input text may contain preprocessor conditional inclusion lines,
16278 as well as general symbol substitution sequences.
16280 The preprocessor conditional inclusion commands have the form
16285 #if @i{expression} [then]
16287 #elsif @i{expression} [then]
16289 #elsif @i{expression} [then]
16300 In this example, @i{expression} is defined by the following grammar:
16302 @i{expression} ::= <symbol>
16303 @i{expression} ::= <symbol> = "<value>"
16304 @i{expression} ::= <symbol> = <symbol>
16305 @i{expression} ::= <symbol> 'Defined
16306 @i{expression} ::= not @i{expression}
16307 @i{expression} ::= @i{expression} and @i{expression}
16308 @i{expression} ::= @i{expression} or @i{expression}
16309 @i{expression} ::= @i{expression} and then @i{expression}
16310 @i{expression} ::= @i{expression} or else @i{expression}
16311 @i{expression} ::= ( @i{expression} )
16315 For the first test (@i{expression} ::= <symbol>) the symbol must have
16316 either the value true or false, that is to say the right-hand of the
16317 symbol definition must be one of the (case-insensitive) literals
16318 @code{True} or @code{False}. If the value is true, then the
16319 corresponding lines are included, and if the value is false, they are
16322 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
16323 the symbol has been defined in the definition file or by a @option{-D}
16324 switch on the command line. Otherwise, the test is false.
16326 The equality tests are case insensitive, as are all the preprocessor lines.
16328 If the symbol referenced is not defined in the symbol definitions file,
16329 then the effect depends on whether or not switch @option{-u}
16330 is specified. If so, then the symbol is treated as if it had the value
16331 false and the test fails. If this switch is not specified, then
16332 it is an error to reference an undefined symbol. It is also an error to
16333 reference a symbol that is defined with a value other than @code{True}
16336 The use of the @code{not} operator inverts the sense of this logical test, so
16337 that the lines are included only if the symbol is not defined.
16338 The @code{then} keyword is optional as shown
16340 The @code{#} must be the first non-blank character on a line, but
16341 otherwise the format is free form. Spaces or tabs may appear between
16342 the @code{#} and the keyword. The keywords and the symbols are case
16343 insensitive as in normal Ada code. Comments may be used on a
16344 preprocessor line, but other than that, no other tokens may appear on a
16345 preprocessor line. Any number of @code{elsif} clauses can be present,
16346 including none at all. The @code{else} is optional, as in Ada.
16348 The @code{#} marking the start of a preprocessor line must be the first
16349 non-blank character on the line, i.e. it must be preceded only by
16350 spaces or horizontal tabs.
16352 Symbol substitution outside of preprocessor lines is obtained by using
16360 anywhere within a source line, except in a comment or within a
16361 string literal. The identifier
16362 following the @code{$} must match one of the symbols defined in the symbol
16363 definition file, and the result is to substitute the value of the
16364 symbol in place of @code{$symbol} in the output file.
16366 Note that although the substitution of strings within a string literal
16367 is not possible, it is possible to have a symbol whose defined value is
16368 a string literal. So instead of setting XYZ to @code{hello} and writing:
16371 Header : String := "$XYZ";
16375 you should set XYZ to @code{"hello"} and write:
16378 Header : String := $XYZ;
16382 and then the substitution will occur as desired.
16385 @node The GNAT Run-Time Library Builder gnatlbr
16386 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
16388 @cindex Library builder
16391 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
16392 supplied configuration pragmas.
16395 * Running gnatlbr::
16396 * Switches for gnatlbr::
16397 * Examples of gnatlbr Usage::
16400 @node Running gnatlbr
16401 @section Running @code{gnatlbr}
16404 The @code{gnatlbr} command has the form
16407 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
16410 @node Switches for gnatlbr
16411 @section Switches for @code{gnatlbr}
16414 @code{gnatlbr} recognizes the following switches:
16418 @item /CREATE=directory
16419 @cindex @code{/CREATE} (@code{gnatlbr})
16420 Create the new run-time library in the specified directory.
16422 @item /SET=directory
16423 @cindex @code{/SET} (@code{gnatlbr})
16424 Make the library in the specified directory the current run-time
16427 @item /DELETE=directory
16428 @cindex @code{/DELETE} (@code{gnatlbr})
16429 Delete the run-time library in the specified directory.
16432 @cindex @code{/CONFIG} (@code{gnatlbr})
16434 Use the configuration pragmas in the specified file when building
16438 Use the configuration pragmas in the specified file when compiling.
16442 @node Examples of gnatlbr Usage
16443 @section Example of @code{gnatlbr} Usage
16446 Contents of VAXFLOAT.ADC:
16447 pragma Float_Representation (VAX_Float);
16449 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
16451 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
16456 @node The GNAT Library Browser gnatls
16457 @chapter The GNAT Library Browser @code{gnatls}
16459 @cindex Library browser
16462 @code{gnatls} is a tool that outputs information about compiled
16463 units. It gives the relationship between objects, unit names and source
16464 files. It can also be used to check the source dependencies of a unit
16465 as well as various characteristics.
16469 * Switches for gnatls::
16470 * Examples of gnatls Usage::
16473 @node Running gnatls
16474 @section Running @code{gnatls}
16477 The @code{gnatls} command has the form
16480 $ gnatls switches @var{object_or_ali_file}
16484 The main argument is the list of object or @file{ali} files
16485 (@pxref{The Ada Library Information Files})
16486 for which information is requested.
16488 In normal mode, without additional option, @code{gnatls} produces a
16489 four-column listing. Each line represents information for a specific
16490 object. The first column gives the full path of the object, the second
16491 column gives the name of the principal unit in this object, the third
16492 column gives the status of the source and the fourth column gives the
16493 full path of the source representing this unit.
16494 Here is a simple example of use:
16498 ^./^[]^demo1.o demo1 DIF demo1.adb
16499 ^./^[]^demo2.o demo2 OK demo2.adb
16500 ^./^[]^hello.o h1 OK hello.adb
16501 ^./^[]^instr-child.o instr.child MOK instr-child.adb
16502 ^./^[]^instr.o instr OK instr.adb
16503 ^./^[]^tef.o tef DIF tef.adb
16504 ^./^[]^text_io_example.o text_io_example OK text_io_example.adb
16505 ^./^[]^tgef.o tgef DIF tgef.adb
16509 The first line can be interpreted as follows: the main unit which is
16511 object file @file{demo1.o} is demo1, whose main source is in
16512 @file{demo1.adb}. Furthermore, the version of the source used for the
16513 compilation of demo1 has been modified (DIF). Each source file has a status
16514 qualifier which can be:
16517 @item OK (unchanged)
16518 The version of the source file used for the compilation of the
16519 specified unit corresponds exactly to the actual source file.
16521 @item MOK (slightly modified)
16522 The version of the source file used for the compilation of the
16523 specified unit differs from the actual source file but not enough to
16524 require recompilation. If you use gnatmake with the qualifier
16525 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
16526 MOK will not be recompiled.
16528 @item DIF (modified)
16529 No version of the source found on the path corresponds to the source
16530 used to build this object.
16532 @item ??? (file not found)
16533 No source file was found for this unit.
16535 @item HID (hidden, unchanged version not first on PATH)
16536 The version of the source that corresponds exactly to the source used
16537 for compilation has been found on the path but it is hidden by another
16538 version of the same source that has been modified.
16542 @node Switches for gnatls
16543 @section Switches for @code{gnatls}
16546 @code{gnatls} recognizes the following switches:
16550 @item ^-a^/ALL_UNITS^
16551 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
16552 Consider all units, including those of the predefined Ada library.
16553 Especially useful with @option{^-d^/DEPENDENCIES^}.
16555 @item ^-d^/DEPENDENCIES^
16556 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
16557 List sources from which specified units depend on.
16559 @item ^-h^/OUTPUT=OPTIONS^
16560 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
16561 Output the list of options.
16563 @item ^-o^/OUTPUT=OBJECTS^
16564 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
16565 Only output information about object files.
16567 @item ^-s^/OUTPUT=SOURCES^
16568 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
16569 Only output information about source files.
16571 @item ^-u^/OUTPUT=UNITS^
16572 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
16573 Only output information about compilation units.
16575 @item ^-files^/FILES^=@var{file}
16576 @cindex @option{^-files^/FILES^} (@code{gnatls})
16577 Take as arguments the files listed in text file @var{file}.
16578 Text file @var{file} may contain empty lines that are ignored.
16579 Each non empty line should contain the name of an existing file.
16580 Several such switches may be specified simultaneously.
16582 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16583 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
16584 @itemx ^-I^/SEARCH=^@var{dir}
16585 @itemx ^-I-^/NOCURRENT_DIRECTORY^
16587 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
16588 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
16589 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
16590 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
16591 Source path manipulation. Same meaning as the equivalent @code{gnatmake} flags
16592 (see @ref{Switches for gnatmake}).
16594 @item --RTS=@var{rts-path}
16595 @cindex @option{--RTS} (@code{gnatls})
16596 Specifies the default location of the runtime library. Same meaning as the
16597 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
16599 @item ^-v^/OUTPUT=VERBOSE^
16600 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
16601 Verbose mode. Output the complete source, object and project paths. Do not use
16602 the default column layout but instead use long format giving as much as
16603 information possible on each requested units, including special
16604 characteristics such as:
16607 @item Preelaborable
16608 The unit is preelaborable in the Ada 95 sense.
16611 No elaboration code has been produced by the compiler for this unit.
16614 The unit is pure in the Ada 95 sense.
16616 @item Elaborate_Body
16617 The unit contains a pragma Elaborate_Body.
16620 The unit contains a pragma Remote_Types.
16622 @item Shared_Passive
16623 The unit contains a pragma Shared_Passive.
16626 This unit is part of the predefined environment and cannot be modified
16629 @item Remote_Call_Interface
16630 The unit contains a pragma Remote_Call_Interface.
16636 @node Examples of gnatls Usage
16637 @section Example of @code{gnatls} Usage
16641 Example of using the verbose switch. Note how the source and
16642 object paths are affected by the -I switch.
16645 $ gnatls -v -I.. demo1.o
16647 GNATLS 5.03w (20041123-34)
16648 Copyright 1997-2004 Free Software Foundation, Inc.
16650 Source Search Path:
16651 <Current_Directory>
16653 /home/comar/local/adainclude/
16655 Object Search Path:
16656 <Current_Directory>
16658 /home/comar/local/lib/gcc-lib/mips-sni-sysv4/2.7.2/adalib/
16660 Project Search Path:
16661 <Current_Directory>
16662 /home/comar/local/lib/gnat/
16667 Kind => subprogram body
16668 Flags => No_Elab_Code
16669 Source => demo1.adb modified
16673 The following is an example of use of the dependency list.
16674 Note the use of the -s switch
16675 which gives a straight list of source files. This can be useful for
16676 building specialized scripts.
16679 $ gnatls -d demo2.o
16680 ./demo2.o demo2 OK demo2.adb
16686 $ gnatls -d -s -a demo1.o
16688 /home/comar/local/adainclude/ada.ads
16689 /home/comar/local/adainclude/a-finali.ads
16690 /home/comar/local/adainclude/a-filico.ads
16691 /home/comar/local/adainclude/a-stream.ads
16692 /home/comar/local/adainclude/a-tags.ads
16695 /home/comar/local/adainclude/gnat.ads
16696 /home/comar/local/adainclude/g-io.ads
16698 /home/comar/local/adainclude/system.ads
16699 /home/comar/local/adainclude/s-exctab.ads
16700 /home/comar/local/adainclude/s-finimp.ads
16701 /home/comar/local/adainclude/s-finroo.ads
16702 /home/comar/local/adainclude/s-secsta.ads
16703 /home/comar/local/adainclude/s-stalib.ads
16704 /home/comar/local/adainclude/s-stoele.ads
16705 /home/comar/local/adainclude/s-stratt.ads
16706 /home/comar/local/adainclude/s-tasoli.ads
16707 /home/comar/local/adainclude/s-unstyp.ads
16708 /home/comar/local/adainclude/unchconv.ads
16714 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
16716 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
16717 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
16718 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
16719 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
16720 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
16724 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
16725 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
16727 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
16728 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
16729 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
16730 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
16731 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
16732 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
16733 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
16734 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
16735 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
16736 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
16737 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
16741 @node Cleaning Up Using gnatclean
16742 @chapter Cleaning Up Using @code{gnatclean}
16744 @cindex Cleaning tool
16747 @code{gnatclean} is a tool that allows the deletion of files produced by the
16748 compiler, binder and linker, including ALI files, object files, tree files,
16749 expanded source files, library files, interface copy source files, binder
16750 generated files and executable files.
16753 * Running gnatclean::
16754 * Switches for gnatclean::
16755 * Examples of gnatclean Usage::
16758 @node Running gnatclean
16759 @section Running @code{gnatclean}
16762 The @code{gnatclean} command has the form:
16765 $ gnatclean switches @var{names}
16769 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
16770 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
16771 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
16774 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
16775 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
16776 the linker. In informative-only mode, specified by switch
16777 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
16778 normal mode is listed, but no file is actually deleted.
16780 @node Switches for gnatclean
16781 @section Switches for @code{gnatclean}
16784 @code{gnatclean} recognizes the following switches:
16788 @item ^-c^/COMPILER_FILES_ONLY^
16789 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
16790 Only attempt to delete the files produced by the compiler, not those produced
16791 by the binder or the linker. The files that are not to be deleted are library
16792 files, interface copy files, binder generated files and executable files.
16794 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
16795 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
16796 Indicate that ALI and object files should normally be found in directory
16799 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
16800 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
16801 When using project files, if some errors or warnings are detected during
16802 parsing and verbose mode is not in effect (no use of switch
16803 ^-v^/VERBOSE^), then error lines start with the full path name of the project
16804 file, rather than its simple file name.
16807 @cindex @option{^-h^/HELP^} (@code{gnatclean})
16808 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
16810 @item ^-n^/NODELETE^
16811 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
16812 Informative-only mode. Do not delete any files. Output the list of the files
16813 that would have been deleted if this switch was not specified.
16815 @item ^-P^/PROJECT_FILE=^@var{project}
16816 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
16817 Use project file @var{project}. Only one such switch can be used.
16818 When cleaning a project file, the files produced by the compilation of the
16819 immediate sources or inherited sources of the project files are to be
16820 deleted. This is not depending on the presence or not of executable names
16821 on the command line.
16824 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
16825 Quiet output. If there are no error, do not ouuput anything, except in
16826 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
16827 (switch ^-n^/NODELETE^).
16829 @item ^-r^/RECURSIVE^
16830 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
16831 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
16832 clean all imported and extended project files, recursively. If this switch
16833 is not specified, only the files related to the main project file are to be
16834 deleted. This switch has no effect if no project file is specified.
16836 @item ^-v^/VERBOSE^
16837 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
16840 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
16841 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
16842 Indicates the verbosity of the parsing of GNAT project files.
16843 See @ref{Switches Related to Project Files}.
16845 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
16846 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
16847 Indicates that external variable @var{name} has the value @var{value}.
16848 The Project Manager will use this value for occurrences of
16849 @code{external(name)} when parsing the project file.
16850 See @ref{Switches Related to Project Files}.
16852 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16853 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
16854 When searching for ALI and object files, look in directory
16857 @item ^-I^/SEARCH=^@var{dir}
16858 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
16859 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
16861 @item ^-I-^/NOCURRENT_DIRECTORY^
16862 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
16863 @cindex Source files, suppressing search
16864 Do not look for ALI or object files in the directory
16865 where @code{gnatclean} was invoked.
16869 @node Examples of gnatclean Usage
16870 @section Examples of @code{gnatclean} Usage
16873 @node GNAT and Libraries
16874 @chapter GNAT and Libraries
16875 @cindex Library, building, installing, using
16878 This chapter describes how to build and use libraries with GNAT, and also shows
16879 how to recompile the GNAT run-time library. You should be familiar with the
16880 Project Manager facility (see @ref{GNAT Project Manager}) before reading this
16884 * Introduction to Libraries in GNAT::
16885 * General Ada Libraries::
16886 * Stand-alone Ada Libraries::
16887 * Rebuilding the GNAT Run-Time Library::
16890 @node Introduction to Libraries in GNAT
16891 @section Introduction to Libraries in GNAT
16894 A library is, conceptually, a collection of objects which does not have its
16895 own main thread of execution, but rather provides certain services to the
16896 applications that use it. A library can be either statically linked with the
16897 application, in which case its code is directly included in the application,
16898 or, on platforms that support it, be dynamically linked, in which case
16899 its code is shared by all applications making use of this library.
16901 GNAT supports both types of libraries.
16902 In the static case, the compiled code can be provided in different ways. The
16903 simplest approach is to provide directly the set of objects resulting from
16904 compilation of the library source files. Alternatively, you can group the
16905 objects into an archive using whatever commands are provided by the operating
16906 system. For the latter case, the objects are grouped into a shared library.
16908 In the GNAT environment, a library has three types of components:
16914 See @ref{The Ada Library Information Files}.
16916 Object files, an archive or a shared library.
16920 A GNAT library may expose all its source files, which is useful for
16921 documentation purposes. Alternatively, it may expose only the units needed by
16922 an external user to make use of the library. That is to say, the specs
16923 expliciting the library services along with all the units needed to compile
16924 those specs, which can include generic bodies or any body implementing an
16925 inlined routine. In the case of @emph{stand-alone libraries} those exposed
16926 units are called @emph{interface units} (see @ref{Stand-alone Ada Libraries}).
16928 All compilation units comprising an application, including those in a library,
16929 need to be elaborated in an order partially defined by Ada's semantics. GNAT
16930 computes the elaboration order from the @file{ALI} files and this is why they
16931 constitute a mandatory part of GNAT libraries. Except in the case of
16932 @emph{stand-alone libraries}, where a specific library elaboration routine is
16933 produced independantly of the application(s) using the library.
16935 @node General Ada Libraries
16936 @section General Ada Libraries
16939 * Building a library::
16940 * Installing a library::
16941 * Using a library::
16944 @node Building a library
16945 @subsection Building a library
16948 The easiest way to build a library is to use the Project Manager,
16949 which supports a special type of projects called Library Projects
16950 (see @ref{Library Projects}).
16952 A project is considered a library project, when two project-level attributes
16953 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
16954 control different aspects of library configuration, additional optional
16955 project-level attributes can be specified:
16958 This attribute controls whether the library is to be static or dynamic
16960 @item Library_Version
16961 This attribute specifies what is the library version; this value is used
16962 during dynamic linking of shared libraries to determine if the currently
16963 installed versions of the binaries are compatible.
16965 @item Library_Options
16967 These attributes specify additional low-level options to be used during
16968 library generation, and redefine the actual application used to generate
16973 The GNAT Project Manager takes full care of the library maintenance task,
16974 including recompilation of the source files for which objects do not exist
16975 or are not up to date, assembly of the library archive, and installation of
16976 the library, i.e. copying associated source, object and @file{ALI} files
16977 to the specified location.
16979 Here is a simple library project file:
16980 @smallexample @c ada
16982 for Source_Dirs use ("src1", "src2");
16983 for Object_Dir use "obj";
16984 for Library_Name use "mylib";
16985 for Library_Dir use "lib";
16986 for Library_Kind use "dynamic";
16989 and the compilation command to build and install the library:
16990 @smallexample @c ada
16991 $ gnatmake -Pmy_lib
16994 It is not entirely trivial to perform manually all the steps required to
16995 produce a library. We recommend that you use the GNAT Project Manager
16996 for this task. In special cases where this is not desired, the necessary
16997 steps are discussed below.
16999 There are various possibilities for compiling the units that make up the
17000 library: for example with a Makefile (see @ref{Using the GNU make Utility}) or
17001 with a conventional script. For simple libraries, it is also possible to create
17002 dummy main program which depends upon all the packages that comprise the
17003 interface of the library. This dummy main program can then be given to
17004 @command{gnatmake}, which will ensure that all necessary objects are built.
17006 After this task is accomplished, you should follow the standard procedure
17007 of the underlying operating system to produce the static or shared library.
17009 Here is an example of such a dummy program:
17010 @smallexample @c ada
17012 with My_Lib.Service1;
17013 with My_Lib.Service2;
17014 with My_Lib.Service3;
17015 procedure My_Lib_Dummy is
17023 Here are the generic commands that will build an archive or a shared library.
17026 # compiling the library
17027 $ gnatmake -c my_lib_dummy.adb
17029 # we don't need the dummy object itself
17030 $ rm my_lib_dummy.o my_lib_dummy.ali
17032 # create an archive with the remaining objects
17033 $ ar rc libmy_lib.a *.o
17034 # some systems may require "ranlib" to be run as well
17036 # or create a shared library
17037 $ gcc -shared -o libmy_lib.so *.o
17038 # some systems may require the code to have been compiled with -fPIC
17040 # remove the object files that are now in the library
17043 # Make the ALI files read-only so that gnatmake will not try to
17044 # regenerate the objects that are in the library
17049 Please note that the library must have a name of the form @file{libxxx.a} or
17050 @file{libxxx.so} (or @file{libxxx.dll} on Windows) in order to be accessed by
17051 the directive @option{-lxxx} at link time.
17053 @node Installing a library
17054 @subsection Installing a library
17057 When using project files, installing libraries is part of the library build
17058 process and thus, no further action is needed in order to make use of the
17059 libraries that are built as part of the general application build. A usable
17060 version of the library is installed in the directory specified by the
17061 @code{Library_Dir} attribute of the library project file.
17063 One may want to install a library in a context different from where the library
17064 is built. This is, for instance, the case of third party suppliers, who whish
17065 to distribute a library in binary form where the user is not expected to be
17066 able to recompile the library. The simplest option, in this case, is to provide
17067 project file slightly different from the one used to build the library which
17068 makes use of the @code{externally_built} attribute. For instance the project
17069 file used to build the library in the previous section can be changed into the
17070 following one when the library is installed:
17072 @smallexample @c ada
17074 for Source_Dirs use ("src1", "src2");
17075 for Library_Name use "mylib";
17076 for Library_Dir use "lib";
17077 for Library_Kind use "dynamic";
17078 for Externally_Built use "true";
17082 This project file assumes that the directories "src1", "src2" & "lib" exist in
17083 the directory containing the project file. The @code{externally_built}
17084 attribute makes it clear to the GNAT builder that it should not attempt to
17085 recompile any of the units from this library. It allows the library provider to
17086 restrict the source set to the minimum necessary for clients to make use of the
17087 library as described in the first section of this chapter. It is the
17088 responsability of the library provider to install the necessary sources, ALI
17089 files & libraries in the directories mentioned in the project file. For
17090 convenience to the user, it is recommended to install the user's library
17091 project file in a location that will be searched automatically by the GNAT
17092 builder. That is to say, any directory refernced in the @code{ADA_LIBRARY_PATH}
17093 environmenbt variable (see @ref{Importing Projects}), or in the default GNAT
17094 library location that can be queried with @code{gnatls -v} and is usually of
17095 the form $gnat_install_root/lib/gnat.
17097 When project files are not an option, it is also possible, but not recommended,
17098 to install the library so that the sources needed to use the library be on the
17099 Ada source path and the ALI files & libraries be on the Ada Object path (see
17100 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, he system
17101 administrator can place general purpose libraries in the default compiler
17102 paths, by specifying the libraries' location in the configuration files
17103 @file{ada_source_path} and @file{ada_object_path}. These configuration files
17104 must be located in the GNAT installation tree at the same place as the gcc spec
17105 file. The location of the gcc spec file can be determined as follows:
17111 The configuration files mentioned above have a simple format: each line
17112 must contain one unique directory name.
17113 Those names are added to the corresponding path
17114 in their order of appearance in the file. The names can be either absolute
17115 or relative; in the latter case, they are relative to where theses files
17118 The files @file{ada_source_path} and @file{ada_object_path} might not be
17120 GNAT installation, in which case, GNAT will look for its run-time library in
17121 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17122 objects and @file{ALI} files). When the files exist, the compiler does not
17123 look in @file{adainclude} and @file{adalib}, and thus the
17124 @file{ada_source_path} file
17125 must contain the location for the GNAT run-time sources (which can simply
17126 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17127 contain the location for the GNAT run-time objects (which can simply
17130 You can also specify a new default path to the run-time library at compilation
17131 time with the switch @option{--RTS=rts-path}. You can thus choose / change
17132 the run-time library you want your program to be compiled with. This switch is
17133 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17134 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17136 It is possible to install a library before or after the standard GNAT
17137 library, by reordering the lines in the configuration files. In general, a
17138 library must be installed before the GNAT library if it redefines
17141 @node Using a library
17142 @subsection Using a library
17144 @noindent Once again, the project facility greatly simplifies the use of
17145 libraries. In this context, using a library is just a matter of adding a
17146 @code{with} clause in the user project. For instance, to make use of the
17147 library "My_Lib" used as an examples in earlier sections, is just a matter of
17148 writing something like:
17149 @smallexample @c ada
17156 Even if you have a third-party, non-Ada library, you can still use GNAT's
17157 Project Manager facility to provide a wrapper for it. The following project for
17158 example, when @code{with}ed in your main project, will link with the
17159 third-party library @file{liba.a}:
17161 @smallexample @c projectfile
17164 for Source_Dirs use ();
17165 for Library_Dir use "lib";
17166 for Library_Name use "a";
17167 for Library_Kind use "static";
17173 In order to use an Ada library manually, you need to make sure that this
17174 library is on both your source and object path
17175 (see @ref{Search Paths and the Run-Time Library (RTL)},
17176 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17177 in an archive or a shared library, you need to specify the desired
17178 library at link time.
17180 For example, you can use the library @file{mylib} installed in
17181 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17184 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17189 This can be expressed more simply:
17194 when the following conditions are met:
17197 @file{/dir/my_lib_src} has been added by the user to the environment
17198 variable @code{ADA_INCLUDE_PATH}, or by the administrator to the file
17199 @file{ada_source_path}
17201 @file{/dir/my_lib_obj} has been added by the user to the environment
17202 variable @code{ADA_OBJECTS_PATH}, or by the administrator to the file
17203 @file{ada_object_path}
17205 a pragma @code{Linker_Options} has been added to one of the sources.
17208 @smallexample @c ada
17209 pragma Linker_Options ("-lmy_lib");
17213 @node Stand-alone Ada Libraries
17214 @section Stand-alone Ada Libraries
17215 @cindex Stand-alone library, building, using
17218 * Introduction to Stand-alone Libraries::
17219 * Building a Stand-alone Library::
17220 * Creating a Stand-alone Library to be used in a non-Ada context::
17221 * Restrictions in Stand-alone Libraries::
17224 @node Introduction to Stand-alone Libraries
17225 @subsection Introduction to Stand-alone Libraries
17228 A Stand-alone Library (SAL) is a library that contains the necessary code to
17229 elaborate the Ada units that are included in the library. In contrast with
17230 an ordinary library, which consists of all sources, objects and @file{ALI}
17232 library, a SAL may specify a restricted subset of compilation units
17233 to serve as a library interface. In this case, the fully
17234 self-sufficient set of files will normally consist of an objects
17235 archive, the sources of interface units' specs, and the @file{ALI}
17236 files of interface units.
17237 If an interface spec contains a generic unit or an inlined subprogram,
17239 source must also be provided; if the units that must be provided in the source
17240 form depend on other units, the source and @file{ALI} files of those must
17243 The main purpose of a SAL is to minimize the recompilation overhead of client
17244 applications when a new version of the library is installed. Specifically,
17245 if the interface sources have not changed, client applications do not need to
17246 be recompiled. If, furthermore, a SAL is provided in the shared form and its
17247 version, controlled by @code{Library_Version} attribute, is not changed,
17248 then the clients do not need to be relinked.
17250 SALs also allow the library providers to minimize the amount of library source
17251 text exposed to the clients. Such ``information hiding'' might be useful or
17252 necessary for various reasons.
17254 Stand-alone libraries are also well suited to be used in an executable whose
17255 main routine is not written in Ada.
17257 @node Building a Stand-alone Library
17258 @subsection Building a Stand-alone Library
17261 GNAT's Project facility provides a simple way of building and installing
17262 stand-alone libraries; see @ref{Stand-alone Library Projects}.
17263 To be a Stand-alone Library Project, in addition to the two attributes
17264 that make a project a Library Project (@code{Library_Name} and
17265 @code{Library_Dir}; see @ref{Library Projects}), the attribute
17266 @code{Library_Interface} must be defined. For example:
17268 @smallexample @c projectfile
17270 for Library_Dir use "lib_dir";
17271 for Library_Name use "dummy";
17272 for Library_Interface use ("int1", "int1.child");
17277 Attribute @code{Library_Interface} has a non empty string list value,
17278 each string in the list designating a unit contained in an immediate source
17279 of the project file.
17281 When a Stand-alone Library is built, first the binder is invoked to build
17282 a package whose name depends on the library name
17283 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
17284 This binder-generated package includes initialization and
17285 finalization procedures whose
17286 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
17288 above). The object corresponding to this package is included in the library.
17290 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
17291 calling of these procedures if a static SAL is built, or if a shared SAL
17293 with the project-level attribute @code{Library_Auto_Init} set to
17296 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
17297 (those that are listed in attribute @code{Library_Interface}) are copied to
17298 the Library Directory. As a consequence, only the Interface Units may be
17299 imported from Ada units outside of the library. If other units are imported,
17300 the binding phase will fail.
17302 The attribute @code{Library_Src_Dir} may be specified for a
17303 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
17304 single string value. Its value must be the path (absolute or relative to the
17305 project directory) of an existing directory. This directory cannot be the
17306 object directory or one of the source directories, but it can be the same as
17307 the library directory. The sources of the Interface
17308 Units of the library that are needed by an Ada client of the library will be
17309 copied to the designated directory, called the Interface Copy directory.
17310 These sources includes the specs of the Interface Units, but they may also
17311 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
17312 are used, or when there is a generic unit in the spec. Before the sources
17313 are copied to the Interface Copy directory, an attempt is made to delete all
17314 files in the Interface Copy directory.
17316 Building stand-alone libraries by hand is somewhat tedious, but for those
17317 occasions when it is necessary here are the steps that you need to perform:
17320 Compile all library sources.
17323 Invoke the binder with the switch @option{-n} (No Ada main program),
17324 with all the @file{ALI} files of the interfaces, and
17325 with the switch @option{-L} to give specific names to the @code{init}
17326 and @code{final} procedures. For example:
17328 gnatbind -n int1.ali int2.ali -Lsal1
17332 Compile the binder generated file:
17338 Link the dynamic library with all the necessary object files,
17339 indicating to the linker the names of the @code{init} (and possibly
17340 @code{final}) procedures for automatic initialization (and finalization).
17341 The built library should be placed in a directory different from
17342 the object directory.
17345 Copy the @code{ALI} files of the interface to the library directory,
17346 add in this copy an indication that it is an interface to a SAL
17347 (i.e. add a word @option{SL} on the line in the @file{ALI} file that starts
17348 with letter ``P'') and make the modified copy of the @file{ALI} file
17353 Using SALs is not different from using other libraries
17354 (see @ref{Using a library}).
17356 @node Creating a Stand-alone Library to be used in a non-Ada context
17357 @subsection Creating a Stand-alone Library to be used in a non-Ada context
17360 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
17363 The only extra step required is to ensure that library interface subprograms
17364 are compatible with the main program, by means of @code{pragma Export}
17365 or @code{pragma Convention}.
17367 Here is an example of simple library interface for use with C main program:
17369 @smallexample @c ada
17370 package Interface is
17372 procedure Do_Something;
17373 pragma Export (C, Do_Something, "do_something");
17375 procedure Do_Something_Else;
17376 pragma Export (C, Do_Something_Else, "do_something_else");
17382 On the foreign language side, you must provide a ``foreign'' view of the
17383 library interface; remember that it should contain elaboration routines in
17384 addition to interface subprograms.
17386 The example below shows the content of @code{mylib_interface.h} (note
17387 that there is no rule for the naming of this file, any name can be used)
17389 /* the library elaboration procedure */
17390 extern void mylibinit (void);
17392 /* the library finalization procedure */
17393 extern void mylibfinal (void);
17395 /* the interface exported by the library */
17396 extern void do_something (void);
17397 extern void do_something_else (void);
17401 Libraries built as explained above can be used from any program, provided
17402 that the elaboration procedures (named @code{mylibinit} in the previous
17403 example) are called before the library services are used. Any number of
17404 libraries can be used simultaneously, as long as the elaboration
17405 procedure of each library is called.
17407 Below is an example of C program that uses the @code{mylib} library.
17410 #include "mylib_interface.h"
17415 /* First, elaborate the library before using it */
17418 /* Main program, using the library exported entities */
17420 do_something_else ();
17422 /* Library finalization at the end of the program */
17429 Note that invoking any library finalization procedure generated by
17430 @code{gnatbind} shuts down the Ada run-time environment.
17432 finalization of all Ada libraries must be performed at the end of the program.
17433 No call to these libraries nor to the Ada run-time library should be made
17434 after the finalization phase.
17436 @node Restrictions in Stand-alone Libraries
17437 @subsection Restrictions in Stand-alone Libraries
17440 The pragmas listed below should be used with caution inside libraries,
17441 as they can create incompatibilities with other Ada libraries:
17443 @item pragma @code{Locking_Policy}
17444 @item pragma @code{Queuing_Policy}
17445 @item pragma @code{Task_Dispatching_Policy}
17446 @item pragma @code{Unreserve_All_Interrupts}
17450 When using a library that contains such pragmas, the user must make sure
17451 that all libraries use the same pragmas with the same values. Otherwise,
17452 @code{Program_Error} will
17453 be raised during the elaboration of the conflicting
17454 libraries. The usage of these pragmas and its consequences for the user
17455 should therefore be well documented.
17457 Similarly, the traceback in the exception occurrence mechanism should be
17458 enabled or disabled in a consistent manner across all libraries.
17459 Otherwise, Program_Error will be raised during the elaboration of the
17460 conflicting libraries.
17462 If the @code{Version} or @code{Body_Version}
17463 attributes are used inside a library, then you need to
17464 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
17465 libraries, so that version identifiers can be properly computed.
17466 In practice these attributes are rarely used, so this is unlikely
17467 to be a consideration.
17469 @node Rebuilding the GNAT Run-Time Library
17470 @section Rebuilding the GNAT Run-Time Library
17471 @cindex GNAT Run-Time Library, rebuilding
17474 It may be useful to recompile the GNAT library in various contexts, the
17475 most important one being the use of partition-wide configuration pragmas
17476 such as @code{Normalize_Scalars}. A special Makefile called
17477 @code{Makefile.adalib} is provided to that effect and can be found in
17478 the directory containing the GNAT library. The location of this
17479 directory depends on the way the GNAT environment has been installed and can
17480 be determined by means of the command:
17487 The last entry in the object search path usually contains the
17488 gnat library. This Makefile contains its own documentation and in
17489 particular the set of instructions needed to rebuild a new library and
17492 @node Using the GNU make Utility
17493 @chapter Using the GNU @code{make} Utility
17497 This chapter offers some examples of makefiles that solve specific
17498 problems. It does not explain how to write a makefile (see the GNU make
17499 documentation), nor does it try to replace the @code{gnatmake} utility
17500 (@pxref{The GNAT Make Program gnatmake}).
17502 All the examples in this section are specific to the GNU version of
17503 make. Although @code{make} is a standard utility, and the basic language
17504 is the same, these examples use some advanced features found only in
17508 * Using gnatmake in a Makefile::
17509 * Automatically Creating a List of Directories::
17510 * Generating the Command Line Switches::
17511 * Overcoming Command Line Length Limits::
17514 @node Using gnatmake in a Makefile
17515 @section Using gnatmake in a Makefile
17520 Complex project organizations can be handled in a very powerful way by
17521 using GNU make combined with gnatmake. For instance, here is a Makefile
17522 which allows you to build each subsystem of a big project into a separate
17523 shared library. Such a makefile allows you to significantly reduce the link
17524 time of very big applications while maintaining full coherence at
17525 each step of the build process.
17527 The list of dependencies are handled automatically by
17528 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
17529 the appropriate directories.
17531 Note that you should also read the example on how to automatically
17532 create the list of directories
17533 (@pxref{Automatically Creating a List of Directories})
17534 which might help you in case your project has a lot of subdirectories.
17539 @font@heightrm=cmr8
17542 ## This Makefile is intended to be used with the following directory
17544 ## - The sources are split into a series of csc (computer software components)
17545 ## Each of these csc is put in its own directory.
17546 ## Their name are referenced by the directory names.
17547 ## They will be compiled into shared library (although this would also work
17548 ## with static libraries
17549 ## - The main program (and possibly other packages that do not belong to any
17550 ## csc is put in the top level directory (where the Makefile is).
17551 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
17552 ## \_ second_csc (sources) __ lib (will contain the library)
17554 ## Although this Makefile is build for shared library, it is easy to modify
17555 ## to build partial link objects instead (modify the lines with -shared and
17558 ## With this makefile, you can change any file in the system or add any new
17559 ## file, and everything will be recompiled correctly (only the relevant shared
17560 ## objects will be recompiled, and the main program will be re-linked).
17562 # The list of computer software component for your project. This might be
17563 # generated automatically.
17566 # Name of the main program (no extension)
17569 # If we need to build objects with -fPIC, uncomment the following line
17572 # The following variable should give the directory containing libgnat.so
17573 # You can get this directory through 'gnatls -v'. This is usually the last
17574 # directory in the Object_Path.
17577 # The directories for the libraries
17578 # (This macro expands the list of CSC to the list of shared libraries, you
17579 # could simply use the expanded form :
17580 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17581 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17583 $@{MAIN@}: objects $@{LIB_DIR@}
17584 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17585 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17588 # recompile the sources
17589 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17591 # Note: In a future version of GNAT, the following commands will be simplified
17592 # by a new tool, gnatmlib
17594 mkdir -p $@{dir $@@ @}
17595 cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17596 cd $@{dir $@@ @}; cp -f ../*.ali .
17598 # The dependencies for the modules
17599 # Note that we have to force the expansion of *.o, since in some cases
17600 # make won't be able to do it itself.
17601 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17602 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17603 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17605 # Make sure all of the shared libraries are in the path before starting the
17608 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17611 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17612 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17613 $@{RM@} $@{CSC_LIST:%=%/*.o@}
17614 $@{RM@} *.o *.ali $@{MAIN@}
17617 @node Automatically Creating a List of Directories
17618 @section Automatically Creating a List of Directories
17621 In most makefiles, you will have to specify a list of directories, and
17622 store it in a variable. For small projects, it is often easier to
17623 specify each of them by hand, since you then have full control over what
17624 is the proper order for these directories, which ones should be
17627 However, in larger projects, which might involve hundreds of
17628 subdirectories, it might be more convenient to generate this list
17631 The example below presents two methods. The first one, although less
17632 general, gives you more control over the list. It involves wildcard
17633 characters, that are automatically expanded by @code{make}. Its
17634 shortcoming is that you need to explicitly specify some of the
17635 organization of your project, such as for instance the directory tree
17636 depth, whether some directories are found in a separate tree,...
17638 The second method is the most general one. It requires an external
17639 program, called @code{find}, which is standard on all Unix systems. All
17640 the directories found under a given root directory will be added to the
17646 @font@heightrm=cmr8
17649 # The examples below are based on the following directory hierarchy:
17650 # All the directories can contain any number of files
17651 # ROOT_DIRECTORY -> a -> aa -> aaa
17654 # -> b -> ba -> baa
17657 # This Makefile creates a variable called DIRS, that can be reused any time
17658 # you need this list (see the other examples in this section)
17660 # The root of your project's directory hierarchy
17664 # First method: specify explicitly the list of directories
17665 # This allows you to specify any subset of all the directories you need.
17668 DIRS := a/aa/ a/ab/ b/ba/
17671 # Second method: use wildcards
17672 # Note that the argument(s) to wildcard below should end with a '/'.
17673 # Since wildcards also return file names, we have to filter them out
17674 # to avoid duplicate directory names.
17675 # We thus use make's @code{dir} and @code{sort} functions.
17676 # It sets DIRs to the following value (note that the directories aaa and baa
17677 # are not given, unless you change the arguments to wildcard).
17678 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17681 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17682 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17685 # Third method: use an external program
17686 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17687 # This is the most complete command: it sets DIRs to the following value:
17688 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17691 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17695 @node Generating the Command Line Switches
17696 @section Generating the Command Line Switches
17699 Once you have created the list of directories as explained in the
17700 previous section (@pxref{Automatically Creating a List of Directories}),
17701 you can easily generate the command line arguments to pass to gnatmake.
17703 For the sake of completeness, this example assumes that the source path
17704 is not the same as the object path, and that you have two separate lists
17708 # see "Automatically creating a list of directories" to create
17713 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17714 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17717 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17720 @node Overcoming Command Line Length Limits
17721 @section Overcoming Command Line Length Limits
17724 One problem that might be encountered on big projects is that many
17725 operating systems limit the length of the command line. It is thus hard to give
17726 gnatmake the list of source and object directories.
17728 This example shows how you can set up environment variables, which will
17729 make @code{gnatmake} behave exactly as if the directories had been
17730 specified on the command line, but have a much higher length limit (or
17731 even none on most systems).
17733 It assumes that you have created a list of directories in your Makefile,
17734 using one of the methods presented in
17735 @ref{Automatically Creating a List of Directories}.
17736 For the sake of completeness, we assume that the object
17737 path (where the ALI files are found) is different from the sources patch.
17739 Note a small trick in the Makefile below: for efficiency reasons, we
17740 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17741 expanded immediately by @code{make}. This way we overcome the standard
17742 make behavior which is to expand the variables only when they are
17745 On Windows, if you are using the standard Windows command shell, you must
17746 replace colons with semicolons in the assignments to these variables.
17751 @font@heightrm=cmr8
17754 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
17755 # This is the same thing as putting the -I arguments on the command line.
17756 # (the equivalent of using -aI on the command line would be to define
17757 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
17758 # You can of course have different values for these variables.
17760 # Note also that we need to keep the previous values of these variables, since
17761 # they might have been set before running 'make' to specify where the GNAT
17762 # library is installed.
17764 # see "Automatically creating a list of directories" to create these
17770 space:=$@{empty@} $@{empty@}
17771 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17772 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17773 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17774 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
17775 export ADA_INCLUDE_PATH
17776 export ADA_OBJECT_PATH
17783 @node Memory Management Issues
17784 @chapter Memory Management Issues
17787 This chapter describes some useful memory pools provided in the GNAT library
17788 and in particular the GNAT Debug Pool facility, which can be used to detect
17789 incorrect uses of access values (including ``dangling references'').
17791 It also describes the @command{gnatmem} tool, which can be used to track down
17796 * Some Useful Memory Pools::
17797 * The GNAT Debug Pool Facility::
17799 * The gnatmem Tool::
17803 @node Some Useful Memory Pools
17804 @section Some Useful Memory Pools
17805 @findex Memory Pool
17806 @cindex storage, pool
17809 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
17810 storage pool. Allocations use the standard system call @code{malloc} while
17811 deallocations use the standard system call @code{free}. No reclamation is
17812 performed when the pool goes out of scope. For performance reasons, the
17813 standard default Ada allocators/deallocators do not use any explicit storage
17814 pools but if they did, they could use this storage pool without any change in
17815 behavior. That is why this storage pool is used when the user
17816 manages to make the default implicit allocator explicit as in this example:
17817 @smallexample @c ada
17818 type T1 is access Something;
17819 -- no Storage pool is defined for T2
17820 type T2 is access Something_Else;
17821 for T2'Storage_Pool use T1'Storage_Pool;
17822 -- the above is equivalent to
17823 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
17827 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
17828 pool. The allocation strategy is similar to @code{Pool_Local}'s
17829 except that the all
17830 storage allocated with this pool is reclaimed when the pool object goes out of
17831 scope. This pool provides a explicit mechanism similar to the implicit one
17832 provided by several Ada 83 compilers for allocations performed through a local
17833 access type and whose purpose was to reclaim memory when exiting the
17834 scope of a given local access. As an example, the following program does not
17835 leak memory even though it does not perform explicit deallocation:
17837 @smallexample @c ada
17838 with System.Pool_Local;
17839 procedure Pooloc1 is
17840 procedure Internal is
17841 type A is access Integer;
17842 X : System.Pool_Local.Unbounded_Reclaim_Pool;
17843 for A'Storage_Pool use X;
17846 for I in 1 .. 50 loop
17851 for I in 1 .. 100 loop
17858 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
17859 @code{Storage_Size} is specified for an access type.
17860 The whole storage for the pool is
17861 allocated at once, usually on the stack at the point where the access type is
17862 elaborated. It is automatically reclaimed when exiting the scope where the
17863 access type is defined. This package is not intended to be used directly by the
17864 user and it is implicitly used for each such declaration:
17866 @smallexample @c ada
17867 type T1 is access Something;
17868 for T1'Storage_Size use 10_000;
17872 @node The GNAT Debug Pool Facility
17873 @section The GNAT Debug Pool Facility
17875 @cindex storage, pool, memory corruption
17878 The use of unchecked deallocation and unchecked conversion can easily
17879 lead to incorrect memory references. The problems generated by such
17880 references are usually difficult to tackle because the symptoms can be
17881 very remote from the origin of the problem. In such cases, it is
17882 very helpful to detect the problem as early as possible. This is the
17883 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
17885 In order to use the GNAT specific debugging pool, the user must
17886 associate a debug pool object with each of the access types that may be
17887 related to suspected memory problems. See Ada Reference Manual 13.11.
17888 @smallexample @c ada
17889 type Ptr is access Some_Type;
17890 Pool : GNAT.Debug_Pools.Debug_Pool;
17891 for Ptr'Storage_Pool use Pool;
17895 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
17896 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
17897 allow the user to redefine allocation and deallocation strategies. They
17898 also provide a checkpoint for each dereference, through the use of
17899 the primitive operation @code{Dereference} which is implicitly called at
17900 each dereference of an access value.
17902 Once an access type has been associated with a debug pool, operations on
17903 values of the type may raise four distinct exceptions,
17904 which correspond to four potential kinds of memory corruption:
17907 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
17909 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
17911 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
17913 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
17917 For types associated with a Debug_Pool, dynamic allocation is performed using
17918 the standard GNAT allocation routine. References to all allocated chunks of
17919 memory are kept in an internal dictionary. Several deallocation strategies are
17920 provided, whereupon the user can choose to release the memory to the system,
17921 keep it allocated for further invalid access checks, or fill it with an easily
17922 recognizable pattern for debug sessions. The memory pattern is the old IBM
17923 hexadecimal convention: @code{16#DEADBEEF#}.
17925 See the documentation in the file g-debpoo.ads for more information on the
17926 various strategies.
17928 Upon each dereference, a check is made that the access value denotes a
17929 properly allocated memory location. Here is a complete example of use of
17930 @code{Debug_Pools}, that includes typical instances of memory corruption:
17931 @smallexample @c ada
17935 with Gnat.Io; use Gnat.Io;
17936 with Unchecked_Deallocation;
17937 with Unchecked_Conversion;
17938 with GNAT.Debug_Pools;
17939 with System.Storage_Elements;
17940 with Ada.Exceptions; use Ada.Exceptions;
17941 procedure Debug_Pool_Test is
17943 type T is access Integer;
17944 type U is access all T;
17946 P : GNAT.Debug_Pools.Debug_Pool;
17947 for T'Storage_Pool use P;
17949 procedure Free is new Unchecked_Deallocation (Integer, T);
17950 function UC is new Unchecked_Conversion (U, T);
17953 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
17963 Put_Line (Integer'Image(B.all));
17965 when E : others => Put_Line ("raised: " & Exception_Name (E));
17970 when E : others => Put_Line ("raised: " & Exception_Name (E));
17974 Put_Line (Integer'Image(B.all));
17976 when E : others => Put_Line ("raised: " & Exception_Name (E));
17981 when E : others => Put_Line ("raised: " & Exception_Name (E));
17984 end Debug_Pool_Test;
17988 The debug pool mechanism provides the following precise diagnostics on the
17989 execution of this erroneous program:
17992 Total allocated bytes : 0
17993 Total deallocated bytes : 0
17994 Current Water Mark: 0
17998 Total allocated bytes : 8
17999 Total deallocated bytes : 0
18000 Current Water Mark: 8
18003 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18004 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18005 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18006 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18008 Total allocated bytes : 8
18009 Total deallocated bytes : 4
18010 Current Water Mark: 4
18015 @node The gnatmem Tool
18016 @section The @command{gnatmem} Tool
18020 The @code{gnatmem} utility monitors dynamic allocation and
18021 deallocation activity in a program, and displays information about
18022 incorrect deallocations and possible sources of memory leaks.
18023 It provides three type of information:
18026 General information concerning memory management, such as the total
18027 number of allocations and deallocations, the amount of allocated
18028 memory and the high water mark, i.e. the largest amount of allocated
18029 memory in the course of program execution.
18032 Backtraces for all incorrect deallocations, that is to say deallocations
18033 which do not correspond to a valid allocation.
18036 Information on each allocation that is potentially the origin of a memory
18041 * Running gnatmem::
18042 * Switches for gnatmem::
18043 * Example of gnatmem Usage::
18046 @node Running gnatmem
18047 @subsection Running @code{gnatmem}
18050 @code{gnatmem} makes use of the output created by the special version of
18051 allocation and deallocation routines that record call information. This
18052 allows to obtain accurate dynamic memory usage history at a minimal cost to
18053 the execution speed. Note however, that @code{gnatmem} is not supported on
18054 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux x86,
18055 Solaris (sparc and x86) and Windows NT/2000/XP (x86).
18058 The @code{gnatmem} command has the form
18061 $ gnatmem [switches] user_program
18065 The program must have been linked with the instrumented version of the
18066 allocation and deallocation routines. This is done by linking with the
18067 @file{libgmem.a} library. For correct symbolic backtrace information,
18068 the user program should be compiled with debugging options
18069 @ref{Switches for gcc}. For example to build @file{my_program}:
18072 $ gnatmake -g my_program -largs -lgmem
18076 When running @file{my_program} the file @file{gmem.out} is produced. This file
18077 contains information about all allocations and deallocations done by the
18078 program. It is produced by the instrumented allocations and
18079 deallocations routines and will be used by @code{gnatmem}.
18082 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18083 examine. If the location of @file{gmem.out} file was not explicitly supplied by
18084 @code{-i} switch, gnatmem will assume that this file can be found in the
18085 current directory. For example, after you have executed @file{my_program},
18086 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18089 $ gnatmem my_program
18093 This will produce the output with the following format:
18095 *************** debut cc
18097 $ gnatmem my_program
18101 Total number of allocations : 45
18102 Total number of deallocations : 6
18103 Final Water Mark (non freed mem) : 11.29 Kilobytes
18104 High Water Mark : 11.40 Kilobytes
18109 Allocation Root # 2
18110 -------------------
18111 Number of non freed allocations : 11
18112 Final Water Mark (non freed mem) : 1.16 Kilobytes
18113 High Water Mark : 1.27 Kilobytes
18115 my_program.adb:23 my_program.alloc
18121 The first block of output gives general information. In this case, the
18122 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18123 Unchecked_Deallocation routine occurred.
18126 Subsequent paragraphs display information on all allocation roots.
18127 An allocation root is a specific point in the execution of the program
18128 that generates some dynamic allocation, such as a ``@code{@b{new}}''
18129 construct. This root is represented by an execution backtrace (or subprogram
18130 call stack). By default the backtrace depth for allocations roots is 1, so
18131 that a root corresponds exactly to a source location. The backtrace can
18132 be made deeper, to make the root more specific.
18134 @node Switches for gnatmem
18135 @subsection Switches for @code{gnatmem}
18138 @code{gnatmem} recognizes the following switches:
18143 @cindex @option{-q} (@code{gnatmem})
18144 Quiet. Gives the minimum output needed to identify the origin of the
18145 memory leaks. Omits statistical information.
18148 @cindex @var{N} (@code{gnatmem})
18149 N is an integer literal (usually between 1 and 10) which controls the
18150 depth of the backtraces defining allocation root. The default value for
18151 N is 1. The deeper the backtrace, the more precise the localization of
18152 the root. Note that the total number of roots can depend on this
18153 parameter. This parameter must be specified @emph{before} the name of the
18154 executable to be analyzed, to avoid ambiguity.
18157 @cindex @option{-b} (@code{gnatmem})
18158 This switch has the same effect as just depth parameter.
18160 @item -i @var{file}
18161 @cindex @option{-i} (@code{gnatmem})
18162 Do the @code{gnatmem} processing starting from @file{file}, rather than
18163 @file{gmem.out} in the current directory.
18166 @cindex @option{-m} (@code{gnatmem})
18167 This switch causes @code{gnatmem} to mask the allocation roots that have less
18168 than n leaks. The default value is 1. Specifying the value of 0 will allow to
18169 examine even the roots that didn't result in leaks.
18172 @cindex @option{-s} (@code{gnatmem})
18173 This switch causes @code{gnatmem} to sort the allocation roots according to the
18174 specified order of sort criteria, each identified by a single letter. The
18175 currently supported criteria are @code{n, h, w} standing respectively for
18176 number of unfreed allocations, high watermark, and final watermark
18177 corresponding to a specific root. The default order is @code{nwh}.
18181 @node Example of gnatmem Usage
18182 @subsection Example of @code{gnatmem} Usage
18185 The following example shows the use of @code{gnatmem}
18186 on a simple memory-leaking program.
18187 Suppose that we have the following Ada program:
18189 @smallexample @c ada
18192 with Unchecked_Deallocation;
18193 procedure Test_Gm is
18195 type T is array (1..1000) of Integer;
18196 type Ptr is access T;
18197 procedure Free is new Unchecked_Deallocation (T, Ptr);
18200 procedure My_Alloc is
18205 procedure My_DeAlloc is
18213 for I in 1 .. 5 loop
18214 for J in I .. 5 loop
18225 The program needs to be compiled with debugging option and linked with
18226 @code{gmem} library:
18229 $ gnatmake -g test_gm -largs -lgmem
18233 Then we execute the program as usual:
18240 Then @code{gnatmem} is invoked simply with
18246 which produces the following output (result may vary on different platforms):
18251 Total number of allocations : 18
18252 Total number of deallocations : 5
18253 Final Water Mark (non freed mem) : 53.00 Kilobytes
18254 High Water Mark : 56.90 Kilobytes
18256 Allocation Root # 1
18257 -------------------
18258 Number of non freed allocations : 11
18259 Final Water Mark (non freed mem) : 42.97 Kilobytes
18260 High Water Mark : 46.88 Kilobytes
18262 test_gm.adb:11 test_gm.my_alloc
18264 Allocation Root # 2
18265 -------------------
18266 Number of non freed allocations : 1
18267 Final Water Mark (non freed mem) : 10.02 Kilobytes
18268 High Water Mark : 10.02 Kilobytes
18270 s-secsta.adb:81 system.secondary_stack.ss_init
18272 Allocation Root # 3
18273 -------------------
18274 Number of non freed allocations : 1
18275 Final Water Mark (non freed mem) : 12 Bytes
18276 High Water Mark : 12 Bytes
18278 s-secsta.adb:181 system.secondary_stack.ss_init
18282 Note that the GNAT run time contains itself a certain number of
18283 allocations that have no corresponding deallocation,
18284 as shown here for root #2 and root
18285 #3. This is a normal behavior when the number of non freed allocations
18286 is one, it allocates dynamic data structures that the run time needs for
18287 the complete lifetime of the program. Note also that there is only one
18288 allocation root in the user program with a single line back trace:
18289 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
18290 program shows that 'My_Alloc' is called at 2 different points in the
18291 source (line 21 and line 24). If those two allocation roots need to be
18292 distinguished, the backtrace depth parameter can be used:
18295 $ gnatmem 3 test_gm
18299 which will give the following output:
18304 Total number of allocations : 18
18305 Total number of deallocations : 5
18306 Final Water Mark (non freed mem) : 53.00 Kilobytes
18307 High Water Mark : 56.90 Kilobytes
18309 Allocation Root # 1
18310 -------------------
18311 Number of non freed allocations : 10
18312 Final Water Mark (non freed mem) : 39.06 Kilobytes
18313 High Water Mark : 42.97 Kilobytes
18315 test_gm.adb:11 test_gm.my_alloc
18316 test_gm.adb:24 test_gm
18317 b_test_gm.c:52 main
18319 Allocation Root # 2
18320 -------------------
18321 Number of non freed allocations : 1
18322 Final Water Mark (non freed mem) : 10.02 Kilobytes
18323 High Water Mark : 10.02 Kilobytes
18325 s-secsta.adb:81 system.secondary_stack.ss_init
18326 s-secsta.adb:283 <system__secondary_stack___elabb>
18327 b_test_gm.c:33 adainit
18329 Allocation Root # 3
18330 -------------------
18331 Number of non freed allocations : 1
18332 Final Water Mark (non freed mem) : 3.91 Kilobytes
18333 High Water Mark : 3.91 Kilobytes
18335 test_gm.adb:11 test_gm.my_alloc
18336 test_gm.adb:21 test_gm
18337 b_test_gm.c:52 main
18339 Allocation Root # 4
18340 -------------------
18341 Number of non freed allocations : 1
18342 Final Water Mark (non freed mem) : 12 Bytes
18343 High Water Mark : 12 Bytes
18345 s-secsta.adb:181 system.secondary_stack.ss_init
18346 s-secsta.adb:283 <system__secondary_stack___elabb>
18347 b_test_gm.c:33 adainit
18351 The allocation root #1 of the first example has been split in 2 roots #1
18352 and #3 thanks to the more precise associated backtrace.
18356 @node Creating Sample Bodies Using gnatstub
18357 @chapter Creating Sample Bodies Using @command{gnatstub}
18361 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
18362 for library unit declarations.
18364 To create a body stub, @command{gnatstub} has to compile the library
18365 unit declaration. Therefore, bodies can be created only for legal
18366 library units. Moreover, if a library unit depends semantically upon
18367 units located outside the current directory, you have to provide
18368 the source search path when calling @command{gnatstub}, see the description
18369 of @command{gnatstub} switches below.
18372 * Running gnatstub::
18373 * Switches for gnatstub::
18376 @node Running gnatstub
18377 @section Running @command{gnatstub}
18380 @command{gnatstub} has the command-line interface of the form
18383 $ gnatstub [switches] filename [directory]
18390 is the name of the source file that contains a library unit declaration
18391 for which a body must be created. The file name may contain the path
18393 The file name does not have to follow the GNAT file name conventions. If the
18395 does not follow GNAT file naming conventions, the name of the body file must
18397 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
18398 If the file name follows the GNAT file naming
18399 conventions and the name of the body file is not provided,
18402 of the body file from the argument file name by replacing the @file{.ads}
18404 with the @file{.adb} suffix.
18407 indicates the directory in which the body stub is to be placed (the default
18412 is an optional sequence of switches as described in the next section
18415 @node Switches for gnatstub
18416 @section Switches for @command{gnatstub}
18422 @cindex @option{^-f^/FULL^} (@command{gnatstub})
18423 If the destination directory already contains a file with the name of the
18425 for the argument spec file, replace it with the generated body stub.
18427 @item ^-hs^/HEADER=SPEC^
18428 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
18429 Put the comment header (i.e., all the comments preceding the
18430 compilation unit) from the source of the library unit declaration
18431 into the body stub.
18433 @item ^-hg^/HEADER=GENERAL^
18434 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
18435 Put a sample comment header into the body stub.
18439 @cindex @option{-IDIR} (@command{gnatstub})
18441 @cindex @option{-I-} (@command{gnatstub})
18444 @item /NOCURRENT_DIRECTORY
18445 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
18447 ^These switches have ^This switch has^ the same meaning as in calls to
18449 ^They define ^It defines ^ the source search path in the call to
18450 @command{gcc} issued
18451 by @command{gnatstub} to compile an argument source file.
18453 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
18454 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
18455 This switch has the same meaning as in calls to @command{gcc}.
18456 It defines the additional configuration file to be passed to the call to
18457 @command{gcc} issued
18458 by @command{gnatstub} to compile an argument source file.
18460 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
18461 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
18462 (@var{n} is a non-negative integer). Set the maximum line length in the
18463 body stub to @var{n}; the default is 79. The maximum value that can be
18464 specified is 32767. Note that in the special case of configuration
18465 pragma files, the maximum is always 32767 regardless of whether or
18466 not this switch appears.
18468 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
18469 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
18470 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
18471 the generated body sample to @var{n}.
18472 The default indentation is 3.
18474 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
18475 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
18476 Order local bodies alphabetically. (By default local bodies are ordered
18477 in the same way as the corresponding local specs in the argument spec file.)
18479 @item ^-i^/INDENTATION=^@var{n}
18480 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
18481 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
18483 @item ^-k^/TREE_FILE=SAVE^
18484 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
18485 Do not remove the tree file (i.e., the snapshot of the compiler internal
18486 structures used by @command{gnatstub}) after creating the body stub.
18488 @item ^-l^/LINE_LENGTH=^@var{n}
18489 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
18490 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
18492 @item ^-o^/BODY=^@var{body-name}
18493 @cindex @option{^-o^/BODY^} (@command{gnatstub})
18494 Body file name. This should be set if the argument file name does not
18496 the GNAT file naming
18497 conventions. If this switch is omitted the default name for the body will be
18499 from the argument file name according to the GNAT file naming conventions.
18502 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
18503 Quiet mode: do not generate a confirmation when a body is
18504 successfully created, and do not generate a message when a body is not
18508 @item ^-r^/TREE_FILE=REUSE^
18509 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
18510 Reuse the tree file (if it exists) instead of creating it. Instead of
18511 creating the tree file for the library unit declaration, @command{gnatstub}
18512 tries to find it in the current directory and use it for creating
18513 a body. If the tree file is not found, no body is created. This option
18514 also implies @option{^-k^/SAVE^}, whether or not
18515 the latter is set explicitly.
18517 @item ^-t^/TREE_FILE=OVERWRITE^
18518 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
18519 Overwrite the existing tree file. If the current directory already
18520 contains the file which, according to the GNAT file naming rules should
18521 be considered as a tree file for the argument source file,
18523 will refuse to create the tree file needed to create a sample body
18524 unless this option is set.
18526 @item ^-v^/VERBOSE^
18527 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
18528 Verbose mode: generate version information.
18532 @node Other Utility Programs
18533 @chapter Other Utility Programs
18536 This chapter discusses some other utility programs available in the Ada
18540 * Using Other Utility Programs with GNAT::
18541 * The External Symbol Naming Scheme of GNAT::
18543 * Ada Mode for Glide::
18545 * Converting Ada Files to html with gnathtml::
18546 * Installing gnathtml::
18553 @node Using Other Utility Programs with GNAT
18554 @section Using Other Utility Programs with GNAT
18557 The object files generated by GNAT are in standard system format and in
18558 particular the debugging information uses this format. This means
18559 programs generated by GNAT can be used with existing utilities that
18560 depend on these formats.
18563 In general, any utility program that works with C will also often work with
18564 Ada programs generated by GNAT. This includes software utilities such as
18565 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
18569 @node The External Symbol Naming Scheme of GNAT
18570 @section The External Symbol Naming Scheme of GNAT
18573 In order to interpret the output from GNAT, when using tools that are
18574 originally intended for use with other languages, it is useful to
18575 understand the conventions used to generate link names from the Ada
18578 All link names are in all lowercase letters. With the exception of library
18579 procedure names, the mechanism used is simply to use the full expanded
18580 Ada name with dots replaced by double underscores. For example, suppose
18581 we have the following package spec:
18583 @smallexample @c ada
18594 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
18595 the corresponding link name is @code{qrs__mn}.
18597 Of course if a @code{pragma Export} is used this may be overridden:
18599 @smallexample @c ada
18604 pragma Export (Var1, C, External_Name => "var1_name");
18606 pragma Export (Var2, C, Link_Name => "var2_link_name");
18613 In this case, the link name for @var{Var1} is whatever link name the
18614 C compiler would assign for the C function @var{var1_name}. This typically
18615 would be either @var{var1_name} or @var{_var1_name}, depending on operating
18616 system conventions, but other possibilities exist. The link name for
18617 @var{Var2} is @var{var2_link_name}, and this is not operating system
18621 One exception occurs for library level procedures. A potential ambiguity
18622 arises between the required name @code{_main} for the C main program,
18623 and the name we would otherwise assign to an Ada library level procedure
18624 called @code{Main} (which might well not be the main program).
18626 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
18627 names. So if we have a library level procedure such as
18629 @smallexample @c ada
18632 procedure Hello (S : String);
18638 the external name of this procedure will be @var{_ada_hello}.
18641 @node Ada Mode for Glide
18642 @section Ada Mode for @code{Glide}
18643 @cindex Ada mode (for Glide)
18646 The Glide mode for programming in Ada (both Ada83 and Ada95) helps the
18647 user to understand and navigate existing code, and facilitates writing
18648 new code. It furthermore provides some utility functions for easier
18649 integration of standard Emacs features when programming in Ada.
18651 Its general features include:
18655 An Integrated Development Environment with functionality such as the
18660 ``Project files'' for configuration-specific aspects
18661 (e.g. directories and compilation options)
18664 Compiling and stepping through error messages.
18667 Running and debugging an applications within Glide.
18674 User configurability
18677 Some of the specific Ada mode features are:
18681 Functions for easy and quick stepping through Ada code
18684 Getting cross reference information for identifiers (e.g., finding a
18685 defining occurrence)
18688 Displaying an index menu of types and subprograms, allowing
18689 direct selection for browsing
18692 Automatic color highlighting of the various Ada entities
18695 Glide directly supports writing Ada code, via several facilities:
18699 Switching between spec and body files with possible
18700 autogeneration of body files
18703 Automatic formating of subprogram parameter lists
18706 Automatic indentation according to Ada syntax
18709 Automatic completion of identifiers
18712 Automatic (and configurable) casing of identifiers, keywords, and attributes
18715 Insertion of syntactic templates
18718 Block commenting / uncommenting
18722 For more information, please refer to the online documentation
18723 available in the @code{Glide} @result{} @code{Help} menu.
18726 @node Converting Ada Files to html with gnathtml
18727 @section Converting Ada Files to HTML with @code{gnathtml}
18730 This @code{Perl} script allows Ada source files to be browsed using
18731 standard Web browsers. For installation procedure, see the section
18732 @xref{Installing gnathtml}.
18734 Ada reserved keywords are highlighted in a bold font and Ada comments in
18735 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
18736 switch to suppress the generation of cross-referencing information, user
18737 defined variables and types will appear in a different color; you will
18738 be able to click on any identifier and go to its declaration.
18740 The command line is as follow:
18742 $ perl gnathtml.pl [switches] ada-files
18746 You can pass it as many Ada files as you want. @code{gnathtml} will generate
18747 an html file for every ada file, and a global file called @file{index.htm}.
18748 This file is an index of every identifier defined in the files.
18750 The available switches are the following ones :
18754 @cindex @option{-83} (@code{gnathtml})
18755 Only the subset on the Ada 83 keywords will be highlighted, not the full
18756 Ada 95 keywords set.
18758 @item -cc @var{color}
18759 @cindex @option{-cc} (@code{gnathtml})
18760 This option allows you to change the color used for comments. The default
18761 value is green. The color argument can be any name accepted by html.
18764 @cindex @option{-d} (@code{gnathtml})
18765 If the ada files depend on some other files (using for instance the
18766 @code{with} command, the latter will also be converted to html.
18767 Only the files in the user project will be converted to html, not the files
18768 in the run-time library itself.
18771 @cindex @option{-D} (@code{gnathtml})
18772 This command is the same as @option{-d} above, but @command{gnathtml} will
18773 also look for files in the run-time library, and generate html files for them.
18775 @item -ext @var{extension}
18776 @cindex @option{-ext} (@code{gnathtml})
18777 This option allows you to change the extension of the generated HTML files.
18778 If you do not specify an extension, it will default to @file{htm}.
18781 @cindex @option{-f} (@code{gnathtml})
18782 By default, gnathtml will generate html links only for global entities
18783 ('with'ed units, global variables and types,...). If you specify the
18784 @option{-f} on the command line, then links will be generated for local
18787 @item -l @var{number}
18788 @cindex @option{-l} (@code{gnathtml})
18789 If this switch is provided and @var{number} is not 0, then @code{gnathtml}
18790 will number the html files every @var{number} line.
18793 @cindex @option{-I} (@code{gnathtml})
18794 Specify a directory to search for library files (@file{.ALI} files) and
18795 source files. You can provide several -I switches on the command line,
18796 and the directories will be parsed in the order of the command line.
18799 @cindex @option{-o} (@code{gnathtml})
18800 Specify the output directory for html files. By default, gnathtml will
18801 saved the generated html files in a subdirectory named @file{html/}.
18803 @item -p @var{file}
18804 @cindex @option{-p} (@code{gnathtml})
18805 If you are using Emacs and the most recent Emacs Ada mode, which provides
18806 a full Integrated Development Environment for compiling, checking,
18807 running and debugging applications, you may use @file{.gpr} files
18808 to give the directories where Emacs can find sources and object files.
18810 Using this switch, you can tell gnathtml to use these files. This allows
18811 you to get an html version of your application, even if it is spread
18812 over multiple directories.
18814 @item -sc @var{color}
18815 @cindex @option{-sc} (@code{gnathtml})
18816 This option allows you to change the color used for symbol definitions.
18817 The default value is red. The color argument can be any name accepted by html.
18819 @item -t @var{file}
18820 @cindex @option{-t} (@code{gnathtml})
18821 This switch provides the name of a file. This file contains a list of
18822 file names to be converted, and the effect is exactly as though they had
18823 appeared explicitly on the command line. This
18824 is the recommended way to work around the command line length limit on some
18829 @node Installing gnathtml
18830 @section Installing @code{gnathtml}
18833 @code{Perl} needs to be installed on your machine to run this script.
18834 @code{Perl} is freely available for almost every architecture and
18835 Operating System via the Internet.
18837 On Unix systems, you may want to modify the first line of the script
18838 @code{gnathtml}, to explicitly tell the Operating system where Perl
18839 is. The syntax of this line is :
18841 #!full_path_name_to_perl
18845 Alternatively, you may run the script using the following command line:
18848 $ perl gnathtml.pl [switches] files
18857 The GNAT distribution provides an Ada 95 template for the Digital Language
18858 Sensitive Editor (LSE), a component of DECset. In order to
18859 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
18866 GNAT supports The Digital Performance Coverage Analyzer (PCA), a component
18867 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
18868 the collection phase with the /DEBUG qualifier.
18871 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
18872 $ DEFINE LIB$DEBUG PCA$COLLECTOR
18873 $ RUN/DEBUG <PROGRAM_NAME>
18878 @node Running and Debugging Ada Programs
18879 @chapter Running and Debugging Ada Programs
18883 This chapter discusses how to debug Ada programs.
18885 It applies to the Alpha OpenVMS platform;
18886 the debugger for Integrity OpenVMS is scheduled for a subsequent release.
18889 An incorrect Ada program may be handled in three ways by the GNAT compiler:
18893 The illegality may be a violation of the static semantics of Ada. In
18894 that case GNAT diagnoses the constructs in the program that are illegal.
18895 It is then a straightforward matter for the user to modify those parts of
18899 The illegality may be a violation of the dynamic semantics of Ada. In
18900 that case the program compiles and executes, but may generate incorrect
18901 results, or may terminate abnormally with some exception.
18904 When presented with a program that contains convoluted errors, GNAT
18905 itself may terminate abnormally without providing full diagnostics on
18906 the incorrect user program.
18910 * The GNAT Debugger GDB::
18912 * Introduction to GDB Commands::
18913 * Using Ada Expressions::
18914 * Calling User-Defined Subprograms::
18915 * Using the Next Command in a Function::
18918 * Debugging Generic Units::
18919 * GNAT Abnormal Termination or Failure to Terminate::
18920 * Naming Conventions for GNAT Source Files::
18921 * Getting Internal Debugging Information::
18922 * Stack Traceback::
18928 @node The GNAT Debugger GDB
18929 @section The GNAT Debugger GDB
18932 @code{GDB} is a general purpose, platform-independent debugger that
18933 can be used to debug mixed-language programs compiled with @code{GCC},
18934 and in particular is capable of debugging Ada programs compiled with
18935 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
18936 complex Ada data structures.
18938 The manual @cite{Debugging with GDB}
18940 , located in the GNU:[DOCS] directory,
18942 contains full details on the usage of @code{GDB}, including a section on
18943 its usage on programs. This manual should be consulted for full
18944 details. The section that follows is a brief introduction to the
18945 philosophy and use of @code{GDB}.
18947 When GNAT programs are compiled, the compiler optionally writes debugging
18948 information into the generated object file, including information on
18949 line numbers, and on declared types and variables. This information is
18950 separate from the generated code. It makes the object files considerably
18951 larger, but it does not add to the size of the actual executable that
18952 will be loaded into memory, and has no impact on run-time performance. The
18953 generation of debug information is triggered by the use of the
18954 ^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out
18955 the compilations. It is important to emphasize that the use of these
18956 options does not change the generated code.
18958 The debugging information is written in standard system formats that
18959 are used by many tools, including debuggers and profilers. The format
18960 of the information is typically designed to describe C types and
18961 semantics, but GNAT implements a translation scheme which allows full
18962 details about Ada types and variables to be encoded into these
18963 standard C formats. Details of this encoding scheme may be found in
18964 the file exp_dbug.ads in the GNAT source distribution. However, the
18965 details of this encoding are, in general, of no interest to a user,
18966 since @code{GDB} automatically performs the necessary decoding.
18968 When a program is bound and linked, the debugging information is
18969 collected from the object files, and stored in the executable image of
18970 the program. Again, this process significantly increases the size of
18971 the generated executable file, but it does not increase the size of
18972 the executable program itself. Furthermore, if this program is run in
18973 the normal manner, it runs exactly as if the debug information were
18974 not present, and takes no more actual memory.
18976 However, if the program is run under control of @code{GDB}, the
18977 debugger is activated. The image of the program is loaded, at which
18978 point it is ready to run. If a run command is given, then the program
18979 will run exactly as it would have if @code{GDB} were not present. This
18980 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
18981 entirely non-intrusive until a breakpoint is encountered. If no
18982 breakpoint is ever hit, the program will run exactly as it would if no
18983 debugger were present. When a breakpoint is hit, @code{GDB} accesses
18984 the debugging information and can respond to user commands to inspect
18985 variables, and more generally to report on the state of execution.
18989 @section Running GDB
18992 The debugger can be launched directly and simply from @code{glide} or
18993 through its graphical interface: @code{gvd}. It can also be used
18994 directly in text mode. Here is described the basic use of @code{GDB}
18995 in text mode. All the commands described below can be used in the
18996 @code{gvd} console window even though there is usually other more
18997 graphical ways to achieve the same goals.
19001 The command to run the graphical interface of the debugger is
19008 The command to run @code{GDB} in text mode is
19011 $ ^gdb program^$ GDB PROGRAM^
19015 where @code{^program^PROGRAM^} is the name of the executable file. This
19016 activates the debugger and results in a prompt for debugger commands.
19017 The simplest command is simply @code{run}, which causes the program to run
19018 exactly as if the debugger were not present. The following section
19019 describes some of the additional commands that can be given to @code{GDB}.
19021 @c *******************************
19022 @node Introduction to GDB Commands
19023 @section Introduction to GDB Commands
19026 @code{GDB} contains a large repertoire of commands. The manual
19027 @cite{Debugging with GDB}
19029 , located in the GNU:[DOCS] directory,
19031 includes extensive documentation on the use
19032 of these commands, together with examples of their use. Furthermore,
19033 the command @var{help} invoked from within @code{GDB} activates a simple help
19034 facility which summarizes the available commands and their options.
19035 In this section we summarize a few of the most commonly
19036 used commands to give an idea of what @code{GDB} is about. You should create
19037 a simple program with debugging information and experiment with the use of
19038 these @code{GDB} commands on the program as you read through the
19042 @item set args @var{arguments}
19043 The @var{arguments} list above is a list of arguments to be passed to
19044 the program on a subsequent run command, just as though the arguments
19045 had been entered on a normal invocation of the program. The @code{set args}
19046 command is not needed if the program does not require arguments.
19049 The @code{run} command causes execution of the program to start from
19050 the beginning. If the program is already running, that is to say if
19051 you are currently positioned at a breakpoint, then a prompt will ask
19052 for confirmation that you want to abandon the current execution and
19055 @item breakpoint @var{location}
19056 The breakpoint command sets a breakpoint, that is to say a point at which
19057 execution will halt and @code{GDB} will await further
19058 commands. @var{location} is
19059 either a line number within a file, given in the format @code{file:linenumber},
19060 or it is the name of a subprogram. If you request that a breakpoint be set on
19061 a subprogram that is overloaded, a prompt will ask you to specify on which of
19062 those subprograms you want to breakpoint. You can also
19063 specify that all of them should be breakpointed. If the program is run
19064 and execution encounters the breakpoint, then the program
19065 stops and @code{GDB} signals that the breakpoint was encountered by
19066 printing the line of code before which the program is halted.
19068 @item breakpoint exception @var{name}
19069 A special form of the breakpoint command which breakpoints whenever
19070 exception @var{name} is raised.
19071 If @var{name} is omitted,
19072 then a breakpoint will occur when any exception is raised.
19074 @item print @var{expression}
19075 This will print the value of the given expression. Most simple
19076 Ada expression formats are properly handled by @code{GDB}, so the expression
19077 can contain function calls, variables, operators, and attribute references.
19080 Continues execution following a breakpoint, until the next breakpoint or the
19081 termination of the program.
19084 Executes a single line after a breakpoint. If the next statement
19085 is a subprogram call, execution continues into (the first statement of)
19086 the called subprogram.
19089 Executes a single line. If this line is a subprogram call, executes and
19090 returns from the call.
19093 Lists a few lines around the current source location. In practice, it
19094 is usually more convenient to have a separate edit window open with the
19095 relevant source file displayed. Successive applications of this command
19096 print subsequent lines. The command can be given an argument which is a
19097 line number, in which case it displays a few lines around the specified one.
19100 Displays a backtrace of the call chain. This command is typically
19101 used after a breakpoint has occurred, to examine the sequence of calls that
19102 leads to the current breakpoint. The display includes one line for each
19103 activation record (frame) corresponding to an active subprogram.
19106 At a breakpoint, @code{GDB} can display the values of variables local
19107 to the current frame. The command @code{up} can be used to
19108 examine the contents of other active frames, by moving the focus up
19109 the stack, that is to say from callee to caller, one frame at a time.
19112 Moves the focus of @code{GDB} down from the frame currently being
19113 examined to the frame of its callee (the reverse of the previous command),
19115 @item frame @var{n}
19116 Inspect the frame with the given number. The value 0 denotes the frame
19117 of the current breakpoint, that is to say the top of the call stack.
19121 The above list is a very short introduction to the commands that
19122 @code{GDB} provides. Important additional capabilities, including conditional
19123 breakpoints, the ability to execute command sequences on a breakpoint,
19124 the ability to debug at the machine instruction level and many other
19125 features are described in detail in @cite{Debugging with GDB}.
19126 Note that most commands can be abbreviated
19127 (for example, c for continue, bt for backtrace).
19129 @node Using Ada Expressions
19130 @section Using Ada Expressions
19131 @cindex Ada expressions
19134 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
19135 extensions. The philosophy behind the design of this subset is
19139 That @code{GDB} should provide basic literals and access to operations for
19140 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19141 leaving more sophisticated computations to subprograms written into the
19142 program (which therefore may be called from @code{GDB}).
19145 That type safety and strict adherence to Ada language restrictions
19146 are not particularly important to the @code{GDB} user.
19149 That brevity is important to the @code{GDB} user.
19152 Thus, for brevity, the debugger acts as if there were
19153 implicit @code{with} and @code{use} clauses in effect for all user-written
19154 packages, thus making it unnecessary to fully qualify most names with
19155 their packages, regardless of context. Where this causes ambiguity,
19156 @code{GDB} asks the user's intent.
19158 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
19160 @node Calling User-Defined Subprograms
19161 @section Calling User-Defined Subprograms
19164 An important capability of @code{GDB} is the ability to call user-defined
19165 subprograms while debugging. This is achieved simply by entering
19166 a subprogram call statement in the form:
19169 call subprogram-name (parameters)
19173 The keyword @code{call} can be omitted in the normal case where the
19174 @code{subprogram-name} does not coincide with any of the predefined
19175 @code{GDB} commands.
19177 The effect is to invoke the given subprogram, passing it the
19178 list of parameters that is supplied. The parameters can be expressions and
19179 can include variables from the program being debugged. The
19180 subprogram must be defined
19181 at the library level within your program, and @code{GDB} will call the
19182 subprogram within the environment of your program execution (which
19183 means that the subprogram is free to access or even modify variables
19184 within your program).
19186 The most important use of this facility is in allowing the inclusion of
19187 debugging routines that are tailored to particular data structures
19188 in your program. Such debugging routines can be written to provide a suitably
19189 high-level description of an abstract type, rather than a low-level dump
19190 of its physical layout. After all, the standard
19191 @code{GDB print} command only knows the physical layout of your
19192 types, not their abstract meaning. Debugging routines can provide information
19193 at the desired semantic level and are thus enormously useful.
19195 For example, when debugging GNAT itself, it is crucial to have access to
19196 the contents of the tree nodes used to represent the program internally.
19197 But tree nodes are represented simply by an integer value (which in turn
19198 is an index into a table of nodes).
19199 Using the @code{print} command on a tree node would simply print this integer
19200 value, which is not very useful. But the PN routine (defined in file
19201 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19202 a useful high level representation of the tree node, which includes the
19203 syntactic category of the node, its position in the source, the integers
19204 that denote descendant nodes and parent node, as well as varied
19205 semantic information. To study this example in more detail, you might want to
19206 look at the body of the PN procedure in the stated file.
19208 @node Using the Next Command in a Function
19209 @section Using the Next Command in a Function
19212 When you use the @code{next} command in a function, the current source
19213 location will advance to the next statement as usual. A special case
19214 arises in the case of a @code{return} statement.
19216 Part of the code for a return statement is the ``epilog'' of the function.
19217 This is the code that returns to the caller. There is only one copy of
19218 this epilog code, and it is typically associated with the last return
19219 statement in the function if there is more than one return. In some
19220 implementations, this epilog is associated with the first statement
19223 The result is that if you use the @code{next} command from a return
19224 statement that is not the last return statement of the function you
19225 may see a strange apparent jump to the last return statement or to
19226 the start of the function. You should simply ignore this odd jump.
19227 The value returned is always that from the first return statement
19228 that was stepped through.
19230 @node Ada Exceptions
19231 @section Breaking on Ada Exceptions
19235 You can set breakpoints that trip when your program raises
19236 selected exceptions.
19239 @item break exception
19240 Set a breakpoint that trips whenever (any task in the) program raises
19243 @item break exception @var{name}
19244 Set a breakpoint that trips whenever (any task in the) program raises
19245 the exception @var{name}.
19247 @item break exception unhandled
19248 Set a breakpoint that trips whenever (any task in the) program raises an
19249 exception for which there is no handler.
19251 @item info exceptions
19252 @itemx info exceptions @var{regexp}
19253 The @code{info exceptions} command permits the user to examine all defined
19254 exceptions within Ada programs. With a regular expression, @var{regexp}, as
19255 argument, prints out only those exceptions whose name matches @var{regexp}.
19263 @code{GDB} allows the following task-related commands:
19267 This command shows a list of current Ada tasks, as in the following example:
19274 ID TID P-ID Thread Pri State Name
19275 1 8088000 0 807e000 15 Child Activation Wait main_task
19276 2 80a4000 1 80ae000 15 Accept/Select Wait b
19277 3 809a800 1 80a4800 15 Child Activation Wait a
19278 * 4 80ae800 3 80b8000 15 Running c
19282 In this listing, the asterisk before the first task indicates it to be the
19283 currently running task. The first column lists the task ID that is used
19284 to refer to tasks in the following commands.
19286 @item break @var{linespec} task @var{taskid}
19287 @itemx break @var{linespec} task @var{taskid} if @dots{}
19288 @cindex Breakpoints and tasks
19289 These commands are like the @code{break @dots{} thread @dots{}}.
19290 @var{linespec} specifies source lines.
19292 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
19293 to specify that you only want @code{GDB} to stop the program when a
19294 particular Ada task reaches this breakpoint. @var{taskid} is one of the
19295 numeric task identifiers assigned by @code{GDB}, shown in the first
19296 column of the @samp{info tasks} display.
19298 If you do not specify @samp{task @var{taskid}} when you set a
19299 breakpoint, the breakpoint applies to @emph{all} tasks of your
19302 You can use the @code{task} qualifier on conditional breakpoints as
19303 well; in this case, place @samp{task @var{taskid}} before the
19304 breakpoint condition (before the @code{if}).
19306 @item task @var{taskno}
19307 @cindex Task switching
19309 This command allows to switch to the task referred by @var{taskno}. In
19310 particular, This allows to browse the backtrace of the specified
19311 task. It is advised to switch back to the original task before
19312 continuing execution otherwise the scheduling of the program may be
19317 For more detailed information on the tasking support,
19318 see @cite{Debugging with GDB}.
19320 @node Debugging Generic Units
19321 @section Debugging Generic Units
19322 @cindex Debugging Generic Units
19326 GNAT always uses code expansion for generic instantiation. This means that
19327 each time an instantiation occurs, a complete copy of the original code is
19328 made, with appropriate substitutions of formals by actuals.
19330 It is not possible to refer to the original generic entities in
19331 @code{GDB}, but it is always possible to debug a particular instance of
19332 a generic, by using the appropriate expanded names. For example, if we have
19334 @smallexample @c ada
19339 generic package k is
19340 procedure kp (v1 : in out integer);
19344 procedure kp (v1 : in out integer) is
19350 package k1 is new k;
19351 package k2 is new k;
19353 var : integer := 1;
19366 Then to break on a call to procedure kp in the k2 instance, simply
19370 (gdb) break g.k2.kp
19374 When the breakpoint occurs, you can step through the code of the
19375 instance in the normal manner and examine the values of local variables, as for
19378 @node GNAT Abnormal Termination or Failure to Terminate
19379 @section GNAT Abnormal Termination or Failure to Terminate
19380 @cindex GNAT Abnormal Termination or Failure to Terminate
19383 When presented with programs that contain serious errors in syntax
19385 GNAT may on rare occasions experience problems in operation, such
19387 segmentation fault or illegal memory access, raising an internal
19388 exception, terminating abnormally, or failing to terminate at all.
19389 In such cases, you can activate
19390 various features of GNAT that can help you pinpoint the construct in your
19391 program that is the likely source of the problem.
19393 The following strategies are presented in increasing order of
19394 difficulty, corresponding to your experience in using GNAT and your
19395 familiarity with compiler internals.
19399 Run @code{gcc} with the @option{-gnatf}. This first
19400 switch causes all errors on a given line to be reported. In its absence,
19401 only the first error on a line is displayed.
19403 The @option{-gnatdO} switch causes errors to be displayed as soon as they
19404 are encountered, rather than after compilation is terminated. If GNAT
19405 terminates prematurely or goes into an infinite loop, the last error
19406 message displayed may help to pinpoint the culprit.
19409 Run @code{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this mode,
19410 @code{gcc} produces ongoing information about the progress of the
19411 compilation and provides the name of each procedure as code is
19412 generated. This switch allows you to find which Ada procedure was being
19413 compiled when it encountered a code generation problem.
19416 @cindex @option{-gnatdc} switch
19417 Run @code{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
19418 switch that does for the front-end what @option{^-v^VERBOSE^} does
19419 for the back end. The system prints the name of each unit,
19420 either a compilation unit or nested unit, as it is being analyzed.
19422 Finally, you can start
19423 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19424 front-end of GNAT, and can be run independently (normally it is just
19425 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
19426 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
19427 @code{where} command is the first line of attack; the variable
19428 @code{lineno} (seen by @code{print lineno}), used by the second phase of
19429 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
19430 which the execution stopped, and @code{input_file name} indicates the name of
19434 @node Naming Conventions for GNAT Source Files
19435 @section Naming Conventions for GNAT Source Files
19438 In order to examine the workings of the GNAT system, the following
19439 brief description of its organization may be helpful:
19443 Files with prefix @file{^sc^SC^} contain the lexical scanner.
19446 All files prefixed with @file{^par^PAR^} are components of the parser. The
19447 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
19448 parsing of select statements can be found in @file{par-ch9.adb}.
19451 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
19452 numbers correspond to chapters of the Ada standard. For example, all
19453 issues involving context clauses can be found in @file{sem_ch10.adb}. In
19454 addition, some features of the language require sufficient special processing
19455 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19456 dynamic dispatching, etc.
19459 All files prefixed with @file{^exp^EXP^} perform normalization and
19460 expansion of the intermediate representation (abstract syntax tree, or AST).
19461 these files use the same numbering scheme as the parser and semantics files.
19462 For example, the construction of record initialization procedures is done in
19463 @file{exp_ch3.adb}.
19466 The files prefixed with @file{^bind^BIND^} implement the binder, which
19467 verifies the consistency of the compilation, determines an order of
19468 elaboration, and generates the bind file.
19471 The files @file{atree.ads} and @file{atree.adb} detail the low-level
19472 data structures used by the front-end.
19475 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
19476 the abstract syntax tree as produced by the parser.
19479 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
19480 all entities, computed during semantic analysis.
19483 Library management issues are dealt with in files with prefix
19489 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
19490 defined in Annex A.
19495 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
19496 defined in Annex B.
19500 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
19501 both language-defined children and GNAT run-time routines.
19505 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
19506 general-purpose packages, fully documented in their specifications. All
19507 the other @file{.c} files are modifications of common @code{gcc} files.
19510 @node Getting Internal Debugging Information
19511 @section Getting Internal Debugging Information
19514 Most compilers have internal debugging switches and modes. GNAT
19515 does also, except GNAT internal debugging switches and modes are not
19516 secret. A summary and full description of all the compiler and binder
19517 debug flags are in the file @file{debug.adb}. You must obtain the
19518 sources of the compiler to see the full detailed effects of these flags.
19520 The switches that print the source of the program (reconstructed from
19521 the internal tree) are of general interest for user programs, as are the
19523 the full internal tree, and the entity table (the symbol table
19524 information). The reconstructed source provides a readable version of the
19525 program after the front-end has completed analysis and expansion,
19526 and is useful when studying the performance of specific constructs.
19527 For example, constraint checks are indicated, complex aggregates
19528 are replaced with loops and assignments, and tasking primitives
19529 are replaced with run-time calls.
19531 @node Stack Traceback
19532 @section Stack Traceback
19534 @cindex stack traceback
19535 @cindex stack unwinding
19538 Traceback is a mechanism to display the sequence of subprogram calls that
19539 leads to a specified execution point in a program. Often (but not always)
19540 the execution point is an instruction at which an exception has been raised.
19541 This mechanism is also known as @i{stack unwinding} because it obtains
19542 its information by scanning the run-time stack and recovering the activation
19543 records of all active subprograms. Stack unwinding is one of the most
19544 important tools for program debugging.
19546 The first entry stored in traceback corresponds to the deepest calling level,
19547 that is to say the subprogram currently executing the instruction
19548 from which we want to obtain the traceback.
19550 Note that there is no runtime performance penalty when stack traceback
19551 is enabled, and no exception is raised during program execution.
19554 * Non-Symbolic Traceback::
19555 * Symbolic Traceback::
19558 @node Non-Symbolic Traceback
19559 @subsection Non-Symbolic Traceback
19560 @cindex traceback, non-symbolic
19563 Note: this feature is not supported on all platforms. See
19564 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
19568 * Tracebacks From an Unhandled Exception::
19569 * Tracebacks From Exception Occurrences (non-symbolic)::
19570 * Tracebacks From Anywhere in a Program (non-symbolic)::
19573 @node Tracebacks From an Unhandled Exception
19574 @subsubsection Tracebacks From an Unhandled Exception
19577 A runtime non-symbolic traceback is a list of addresses of call instructions.
19578 To enable this feature you must use the @option{-E}
19579 @code{gnatbind}'s option. With this option a stack traceback is stored as part
19580 of exception information. You can retrieve this information using the
19581 @code{addr2line} tool.
19583 Here is a simple example:
19585 @smallexample @c ada
19591 raise Constraint_Error;
19606 $ gnatmake stb -bargs -E
19609 Execution terminated by unhandled exception
19610 Exception name: CONSTRAINT_ERROR
19612 Call stack traceback locations:
19613 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19617 As we see the traceback lists a sequence of addresses for the unhandled
19618 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19619 guess that this exception come from procedure P1. To translate these
19620 addresses into the source lines where the calls appear, the
19621 @code{addr2line} tool, described below, is invaluable. The use of this tool
19622 requires the program to be compiled with debug information.
19625 $ gnatmake -g stb -bargs -E
19628 Execution terminated by unhandled exception
19629 Exception name: CONSTRAINT_ERROR
19631 Call stack traceback locations:
19632 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19634 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19635 0x4011f1 0x77e892a4
19637 00401373 at d:/stb/stb.adb:5
19638 0040138B at d:/stb/stb.adb:10
19639 0040139C at d:/stb/stb.adb:14
19640 00401335 at d:/stb/b~stb.adb:104
19641 004011C4 at /build/.../crt1.c:200
19642 004011F1 at /build/.../crt1.c:222
19643 77E892A4 in ?? at ??:0
19647 The @code{addr2line} tool has several other useful options:
19651 to get the function name corresponding to any location
19653 @item --demangle=gnat
19654 to use the gnat decoding mode for the function names. Note that
19655 for binutils version 2.9.x the option is simply @option{--demangle}.
19659 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
19660 0x40139c 0x401335 0x4011c4 0x4011f1
19662 00401373 in stb.p1 at d:/stb/stb.adb:5
19663 0040138B in stb.p2 at d:/stb/stb.adb:10
19664 0040139C in stb at d:/stb/stb.adb:14
19665 00401335 in main at d:/stb/b~stb.adb:104
19666 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
19667 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
19671 From this traceback we can see that the exception was raised in
19672 @file{stb.adb} at line 5, which was reached from a procedure call in
19673 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
19674 which contains the call to the main program.
19675 @pxref{Running gnatbind}. The remaining entries are assorted runtime routines,
19676 and the output will vary from platform to platform.
19678 It is also possible to use @code{GDB} with these traceback addresses to debug
19679 the program. For example, we can break at a given code location, as reported
19680 in the stack traceback:
19686 Furthermore, this feature is not implemented inside Windows DLL. Only
19687 the non-symbolic traceback is reported in this case.
19690 (gdb) break *0x401373
19691 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19695 It is important to note that the stack traceback addresses
19696 do not change when debug information is included. This is particularly useful
19697 because it makes it possible to release software without debug information (to
19698 minimize object size), get a field report that includes a stack traceback
19699 whenever an internal bug occurs, and then be able to retrieve the sequence
19700 of calls with the same program compiled with debug information.
19702 @node Tracebacks From Exception Occurrences (non-symbolic)
19703 @subsubsection Tracebacks From Exception Occurrences
19706 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
19707 The stack traceback is attached to the exception information string, and can
19708 be retrieved in an exception handler within the Ada program, by means of the
19709 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19711 @smallexample @c ada
19713 with Ada.Exceptions;
19718 use Ada.Exceptions;
19726 Text_IO.Put_Line (Exception_Information (E));
19740 This program will output:
19745 Exception name: CONSTRAINT_ERROR
19746 Message: stb.adb:12
19747 Call stack traceback locations:
19748 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19751 @node Tracebacks From Anywhere in a Program (non-symbolic)
19752 @subsubsection Tracebacks From Anywhere in a Program
19755 It is also possible to retrieve a stack traceback from anywhere in a
19756 program. For this you need to
19757 use the @code{GNAT.Traceback} API. This package includes a procedure called
19758 @code{Call_Chain} that computes a complete stack traceback, as well as useful
19759 display procedures described below. It is not necessary to use the
19760 @option{-E gnatbind} option in this case, because the stack traceback mechanism
19761 is invoked explicitly.
19764 In the following example we compute a traceback at a specific location in
19765 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
19766 convert addresses to strings:
19768 @smallexample @c ada
19770 with GNAT.Traceback;
19771 with GNAT.Debug_Utilities;
19777 use GNAT.Traceback;
19780 TB : Tracebacks_Array (1 .. 10);
19781 -- We are asking for a maximum of 10 stack frames.
19783 -- Len will receive the actual number of stack frames returned.
19785 Call_Chain (TB, Len);
19787 Text_IO.Put ("In STB.P1 : ");
19789 for K in 1 .. Len loop
19790 Text_IO.Put (Debug_Utilities.Image (TB (K)));
19811 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
19812 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
19816 You can then get further information by invoking the @code{addr2line}
19817 tool as described earlier (note that the hexadecimal addresses
19818 need to be specified in C format, with a leading ``0x'').
19820 @node Symbolic Traceback
19821 @subsection Symbolic Traceback
19822 @cindex traceback, symbolic
19825 A symbolic traceback is a stack traceback in which procedure names are
19826 associated with each code location.
19829 Note that this feature is not supported on all platforms. See
19830 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
19831 list of currently supported platforms.
19834 Note that the symbolic traceback requires that the program be compiled
19835 with debug information. If it is not compiled with debug information
19836 only the non-symbolic information will be valid.
19839 * Tracebacks From Exception Occurrences (symbolic)::
19840 * Tracebacks From Anywhere in a Program (symbolic)::
19843 @node Tracebacks From Exception Occurrences (symbolic)
19844 @subsubsection Tracebacks From Exception Occurrences
19846 @smallexample @c ada
19848 with GNAT.Traceback.Symbolic;
19854 raise Constraint_Error;
19871 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
19876 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
19879 0040149F in stb.p1 at stb.adb:8
19880 004014B7 in stb.p2 at stb.adb:13
19881 004014CF in stb.p3 at stb.adb:18
19882 004015DD in ada.stb at stb.adb:22
19883 00401461 in main at b~stb.adb:168
19884 004011C4 in __mingw_CRTStartup at crt1.c:200
19885 004011F1 in mainCRTStartup at crt1.c:222
19886 77E892A4 in ?? at ??:0
19890 In the above example the ``.\'' syntax in the @command{gnatmake} command
19891 is currently required by @command{addr2line} for files that are in
19892 the current working directory.
19893 Moreover, the exact sequence of linker options may vary from platform
19895 The above @option{-largs} section is for Windows platforms. By contrast,
19896 under Unix there is no need for the @option{-largs} section.
19897 Differences across platforms are due to details of linker implementation.
19899 @node Tracebacks From Anywhere in a Program (symbolic)
19900 @subsubsection Tracebacks From Anywhere in a Program
19903 It is possible to get a symbolic stack traceback
19904 from anywhere in a program, just as for non-symbolic tracebacks.
19905 The first step is to obtain a non-symbolic
19906 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
19907 information. Here is an example:
19909 @smallexample @c ada
19911 with GNAT.Traceback;
19912 with GNAT.Traceback.Symbolic;
19917 use GNAT.Traceback;
19918 use GNAT.Traceback.Symbolic;
19921 TB : Tracebacks_Array (1 .. 10);
19922 -- We are asking for a maximum of 10 stack frames.
19924 -- Len will receive the actual number of stack frames returned.
19926 Call_Chain (TB, Len);
19927 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
19941 @node Compatibility with DEC Ada
19942 @chapter Compatibility with DEC Ada
19943 @cindex Compatibility
19946 This section of the manual compares DEC Ada for OpenVMS Alpha and GNAT
19947 OpenVMS Alpha. GNAT achieves a high level of compatibility
19948 with DEC Ada, and it should generally be straightforward to port code
19949 from the DEC Ada environment to GNAT. However, there are a few language
19950 and implementation differences of which the user must be aware. These
19951 differences are discussed in this section. In
19952 addition, the operating environment and command structure for the
19953 compiler are different, and these differences are also discussed.
19955 Note that this discussion addresses specifically the implementation
19956 of Ada 83 for DIGITAL OpenVMS Alpha Systems. In cases where the implementation
19957 of DEC Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
19958 GNAT always follows the Alpha implementation.
19961 * Ada 95 Compatibility::
19962 * Differences in the Definition of Package System::
19963 * Language-Related Features::
19964 * The Package STANDARD::
19965 * The Package SYSTEM::
19966 * Tasking and Task-Related Features::
19967 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
19968 * Pragmas and Pragma-Related Features::
19969 * Library of Predefined Units::
19971 * Main Program Definition::
19972 * Implementation-Defined Attributes::
19973 * Compiler and Run-Time Interfacing::
19974 * Program Compilation and Library Management::
19976 * Implementation Limits::
19980 @node Ada 95 Compatibility
19981 @section Ada 95 Compatibility
19984 GNAT is an Ada 95 compiler, and DEC Ada is an Ada 83
19985 compiler. Ada 95 is almost completely upwards compatible
19986 with Ada 83, and therefore Ada 83 programs will compile
19987 and run under GNAT with
19988 no changes or only minor changes. The Ada 95 Reference
19989 Manual (ANSI/ISO/IEC-8652:1995) provides details on specific
19992 GNAT provides the switch /83 on the GNAT COMPILE command,
19993 as well as the pragma ADA_83, to force the compiler to
19994 operate in Ada 83 mode. This mode does not guarantee complete
19995 conformance to Ada 83, but in practice is sufficient to
19996 eliminate most sources of incompatibilities.
19997 In particular, it eliminates the recognition of the
19998 additional Ada 95 keywords, so that their use as identifiers
19999 in Ada83 program is legal, and handles the cases of packages
20000 with optional bodies, and generics that instantiate unconstrained
20001 types without the use of @code{(<>)}.
20003 @node Differences in the Definition of Package System
20004 @section Differences in the Definition of Package System
20007 Both the Ada 95 and Ada 83 reference manuals permit a compiler to add
20008 implementation-dependent declarations to package System. In normal mode,
20009 GNAT does not take advantage of this permission, and the version of System
20010 provided by GNAT exactly matches that in the Ada 95 Reference Manual.
20012 However, DEC Ada adds an extensive set of declarations to package System,
20013 as fully documented in the DEC Ada manuals. To minimize changes required
20014 for programs that make use of these extensions, GNAT provides the pragma
20015 Extend_System for extending the definition of package System. By using:
20017 @smallexample @c ada
20020 pragma Extend_System (Aux_DEC);
20026 The set of definitions in System is extended to include those in package
20027 @code{System.Aux_DEC}.
20028 These definitions are incorporated directly into package
20029 System, as though they had been declared there in the first place. For a
20030 list of the declarations added, see the specification of this package,
20031 which can be found in the file @code{s-auxdec.ads} in the GNAT library.
20032 The pragma Extend_System is a configuration pragma, which means that
20033 it can be placed in the file @file{gnat.adc}, so that it will automatically
20034 apply to all subsequent compilations. See the section on Configuration
20035 Pragmas for further details.
20037 An alternative approach that avoids the use of the non-standard
20038 Extend_System pragma is to add a context clause to the unit that
20039 references these facilities:
20041 @smallexample @c ada
20044 with System.Aux_DEC;
20045 use System.Aux_DEC;
20051 The effect is not quite semantically identical to incorporating
20052 the declarations directly into package @code{System},
20053 but most programs will not notice a difference
20054 unless they use prefix notation (e.g. @code{System.Integer_8})
20056 entities directly in package @code{System}.
20057 For units containing such references,
20058 the prefixes must either be removed, or the pragma @code{Extend_System}
20061 @node Language-Related Features
20062 @section Language-Related Features
20065 The following sections highlight differences in types,
20066 representations of types, operations, alignment, and
20070 * Integer Types and Representations::
20071 * Floating-Point Types and Representations::
20072 * Pragmas Float_Representation and Long_Float::
20073 * Fixed-Point Types and Representations::
20074 * Record and Array Component Alignment::
20075 * Address Clauses::
20076 * Other Representation Clauses::
20079 @node Integer Types and Representations
20080 @subsection Integer Types and Representations
20083 The set of predefined integer types is identical in DEC Ada and GNAT.
20084 Furthermore the representation of these integer types is also identical,
20085 including the capability of size clauses forcing biased representation.
20088 DEC Ada for OpenVMS Alpha systems has defined the
20089 following additional integer types in package System:
20110 When using GNAT, the first four of these types may be obtained from the
20111 standard Ada 95 package @code{Interfaces}.
20112 Alternatively, by use of the pragma
20113 @code{Extend_System}, identical
20114 declarations can be referenced directly in package @code{System}.
20115 On both GNAT and DEC Ada, the maximum integer size is 64 bits.
20117 @node Floating-Point Types and Representations
20118 @subsection Floating-Point Types and Representations
20119 @cindex Floating-Point types
20122 The set of predefined floating-point types is identical in DEC Ada and GNAT.
20123 Furthermore the representation of these floating-point
20124 types is also identical. One important difference is that the default
20125 representation for DEC Ada is VAX_Float, but the default representation
20128 Specific types may be declared to be VAX_Float or IEEE, using the pragma
20129 @code{Float_Representation} as described in the DEC Ada documentation.
20130 For example, the declarations:
20132 @smallexample @c ada
20135 type F_Float is digits 6;
20136 pragma Float_Representation (VAX_Float, F_Float);
20142 declare a type F_Float that will be represented in VAX_Float format.
20143 This set of declarations actually appears in System.Aux_DEC, which provides
20144 the full set of additional floating-point declarations provided in
20145 the DEC Ada version of package
20146 System. This and similar declarations may be accessed in a user program
20147 by using pragma @code{Extend_System}. The use of this
20148 pragma, and the related pragma @code{Long_Float} is described in further
20149 detail in the following section.
20151 @node Pragmas Float_Representation and Long_Float
20152 @subsection Pragmas Float_Representation and Long_Float
20155 DEC Ada provides the pragma @code{Float_Representation}, which
20156 acts as a program library switch to allow control over
20157 the internal representation chosen for the predefined
20158 floating-point types declared in the package @code{Standard}.
20159 The format of this pragma is as follows:
20164 @b{pragma} @code{Float_Representation}(VAX_Float | IEEE_Float);
20170 This pragma controls the representation of floating-point
20175 @code{VAX_Float} specifies that floating-point
20176 types are represented by default with the VAX hardware types
20177 F-floating, D-floating, G-floating. Note that the H-floating
20178 type is available only on DIGITAL Vax systems, and is not available
20179 in either DEC Ada or GNAT for Alpha systems.
20182 @code{IEEE_Float} specifies that floating-point
20183 types are represented by default with the IEEE single and
20184 double floating-point types.
20188 GNAT provides an identical implementation of the pragma
20189 @code{Float_Representation}, except that it functions as a
20190 configuration pragma, as defined by Ada 95. Note that the
20191 notion of configuration pragma corresponds closely to the
20192 DEC Ada notion of a program library switch.
20194 When no pragma is used in GNAT, the default is IEEE_Float, which is different
20195 from DEC Ada 83, where the default is VAX_Float. In addition, the
20196 predefined libraries in GNAT are built using IEEE_Float, so it is not
20197 advisable to change the format of numbers passed to standard library
20198 routines, and if necessary explicit type conversions may be needed.
20200 The use of IEEE_Float is recommended in GNAT since it is more efficient,
20201 and (given that it conforms to an international standard) potentially more
20202 portable. The situation in which VAX_Float may be useful is in interfacing
20203 to existing code and data that expects the use of VAX_Float. There are
20204 two possibilities here. If the requirement for the use of VAX_Float is
20205 localized, then the best approach is to use the predefined VAX_Float
20206 types in package @code{System}, as extended by
20207 @code{Extend_System}. For example, use @code{System.F_Float}
20208 to specify the 32-bit @code{F-Float} format.
20210 Alternatively, if an entire program depends heavily on the use of
20211 the @code{VAX_Float} and in particular assumes that the types in
20212 package @code{Standard} are in @code{Vax_Float} format, then it
20213 may be desirable to reconfigure GNAT to assume Vax_Float by default.
20214 This is done by using the GNAT LIBRARY command to rebuild the library, and
20215 then using the general form of the @code{Float_Representation}
20216 pragma to ensure that this default format is used throughout.
20217 The form of the GNAT LIBRARY command is:
20220 GNAT LIBRARY /CONFIG=@i{file} /CREATE=@i{directory}
20224 where @i{file} contains the new configuration pragmas
20225 and @i{directory} is the directory to be created to contain
20229 On OpenVMS systems, DEC Ada provides the pragma @code{Long_Float}
20230 to allow control over the internal representation chosen
20231 for the predefined type @code{Long_Float} and for floating-point
20232 type declarations with digits specified in the range 7 .. 15.
20233 The format of this pragma is as follows:
20235 @smallexample @c ada
20237 pragma Long_Float (D_FLOAT | G_FLOAT);
20241 @node Fixed-Point Types and Representations
20242 @subsection Fixed-Point Types and Representations
20245 On DEC Ada for OpenVMS Alpha systems, rounding is
20246 away from zero for both positive and negative numbers.
20247 Therefore, +0.5 rounds to 1 and -0.5 rounds to -1.
20249 On GNAT for OpenVMS Alpha, the results of operations
20250 on fixed-point types are in accordance with the Ada 95
20251 rules. In particular, results of operations on decimal
20252 fixed-point types are truncated.
20254 @node Record and Array Component Alignment
20255 @subsection Record and Array Component Alignment
20258 On DEC Ada for OpenVMS Alpha, all non composite components
20259 are aligned on natural boundaries. For example, 1-byte
20260 components are aligned on byte boundaries, 2-byte
20261 components on 2-byte boundaries, 4-byte components on 4-byte
20262 byte boundaries, and so on. The OpenVMS Alpha hardware
20263 runs more efficiently with naturally aligned data.
20265 ON GNAT for OpenVMS Alpha, alignment rules are compatible
20266 with DEC Ada for OpenVMS Alpha.
20268 @node Address Clauses
20269 @subsection Address Clauses
20272 In DEC Ada and GNAT, address clauses are supported for
20273 objects and imported subprograms.
20274 The predefined type @code{System.Address} is a private type
20275 in both compilers, with the same representation (it is simply
20276 a machine pointer). Addition, subtraction, and comparison
20277 operations are available in the standard Ada 95 package
20278 @code{System.Storage_Elements}, or in package @code{System}
20279 if it is extended to include @code{System.Aux_DEC} using a
20280 pragma @code{Extend_System} as previously described.
20282 Note that code that with's both this extended package @code{System}
20283 and the package @code{System.Storage_Elements} should not @code{use}
20284 both packages, or ambiguities will result. In general it is better
20285 not to mix these two sets of facilities. The Ada 95 package was
20286 designed specifically to provide the kind of features that DEC Ada
20287 adds directly to package @code{System}.
20289 GNAT is compatible with DEC Ada in its handling of address
20290 clauses, except for some limitations in
20291 the form of address clauses for composite objects with
20292 initialization. Such address clauses are easily replaced
20293 by the use of an explicitly-defined constant as described
20294 in the Ada 95 Reference Manual (13.1(22)). For example, the sequence
20297 @smallexample @c ada
20299 X, Y : Integer := Init_Func;
20300 Q : String (X .. Y) := "abc";
20302 for Q'Address use Compute_Address;
20307 will be rejected by GNAT, since the address cannot be computed at the time
20308 that Q is declared. To achieve the intended effect, write instead:
20310 @smallexample @c ada
20313 X, Y : Integer := Init_Func;
20314 Q_Address : constant Address := Compute_Address;
20315 Q : String (X .. Y) := "abc";
20317 for Q'Address use Q_Address;
20323 which will be accepted by GNAT (and other Ada 95 compilers), and is also
20324 backwards compatible with Ada 83. A fuller description of the restrictions
20325 on address specifications is found in the GNAT Reference Manual.
20327 @node Other Representation Clauses
20328 @subsection Other Representation Clauses
20331 GNAT supports in a compatible manner all the representation
20332 clauses supported by DEC Ada. In addition, it
20333 supports representation clause forms that are new in Ada 95
20334 including COMPONENT_SIZE and SIZE clauses for objects.
20336 @node The Package STANDARD
20337 @section The Package STANDARD
20340 The package STANDARD, as implemented by DEC Ada, is fully
20341 described in the Reference Manual for the Ada Programming
20342 Language (ANSI/MIL-STD-1815A-1983) and in the DEC Ada
20343 Language Reference Manual. As implemented by GNAT, the
20344 package STANDARD is described in the Ada 95 Reference
20347 In addition, DEC Ada supports the Latin-1 character set in
20348 the type CHARACTER. GNAT supports the Latin-1 character set
20349 in the type CHARACTER and also Unicode (ISO 10646 BMP) in
20350 the type WIDE_CHARACTER.
20352 The floating-point types supported by GNAT are those
20353 supported by DEC Ada, but defaults are different, and are controlled by
20354 pragmas. See @pxref{Floating-Point Types and Representations} for details.
20356 @node The Package SYSTEM
20357 @section The Package SYSTEM
20360 DEC Ada provides a system-specific version of the package
20361 SYSTEM for each platform on which the language ships.
20362 For the complete specification of the package SYSTEM, see
20363 Appendix F of the DEC Ada Language Reference Manual.
20365 On DEC Ada, the package SYSTEM includes the following conversion functions:
20367 @item TO_ADDRESS(INTEGER)
20369 @item TO_ADDRESS(UNSIGNED_LONGWORD)
20371 @item TO_ADDRESS(universal_integer)
20373 @item TO_INTEGER(ADDRESS)
20375 @item TO_UNSIGNED_LONGWORD(ADDRESS)
20377 @item Function IMPORT_VALUE return UNSIGNED_LONGWORD and the
20378 functions IMPORT_ADDRESS and IMPORT_LARGEST_VALUE
20382 By default, GNAT supplies a version of SYSTEM that matches
20383 the definition given in the Ada 95 Reference Manual.
20385 is a subset of the DIGITAL system definitions, which is as
20386 close as possible to the original definitions. The only difference
20387 is that the definition of SYSTEM_NAME is different:
20389 @smallexample @c ada
20392 type Name is (SYSTEM_NAME_GNAT);
20393 System_Name : constant Name := SYSTEM_NAME_GNAT;
20399 Also, GNAT adds the new Ada 95 declarations for
20400 BIT_ORDER and DEFAULT_BIT_ORDER.
20402 However, the use of the following pragma causes GNAT
20403 to extend the definition of package SYSTEM so that it
20404 encompasses the full set of DIGITAL-specific extensions,
20405 including the functions listed above:
20407 @smallexample @c ada
20409 pragma Extend_System (Aux_DEC);
20414 The pragma Extend_System is a configuration pragma that
20415 is most conveniently placed in the @file{gnat.adc} file. See the
20416 GNAT Reference Manual for further details.
20418 DEC Ada does not allow the recompilation of the package
20419 SYSTEM. Instead DEC Ada provides several pragmas (SYSTEM_
20420 NAME, STORAGE_UNIT, and MEMORY_SIZE) to modify values in
20421 the package SYSTEM. On OpenVMS Alpha systems, the pragma
20422 SYSTEM_NAME takes the enumeration literal OPENVMS_AXP as
20423 its single argument.
20425 GNAT does permit the recompilation of package SYSTEM using
20426 a special switch (@option{-gnatg}) and this switch can be used if
20427 it is necessary to modify the definitions in SYSTEM. GNAT does
20428 not permit the specification of SYSTEM_NAME, STORAGE_UNIT
20429 or MEMORY_SIZE by any other means.
20431 On GNAT systems, the pragma SYSTEM_NAME takes the
20432 enumeration literal SYSTEM_NAME_GNAT.
20434 The definitions provided by the use of
20436 @smallexample @c ada
20437 pragma Extend_System (AUX_Dec);
20441 are virtually identical to those provided by the DEC Ada 83 package
20442 System. One important difference is that the name of the TO_ADDRESS
20443 function for type UNSIGNED_LONGWORD is changed to TO_ADDRESS_LONG.
20444 See the GNAT Reference manual for a discussion of why this change was
20448 The version of TO_ADDRESS taking a universal integer argument is in fact
20449 an extension to Ada 83 not strictly compatible with the reference manual.
20450 In GNAT, we are constrained to be exactly compatible with the standard,
20451 and this means we cannot provide this capability. In DEC Ada 83, the
20452 point of this definition is to deal with a call like:
20454 @smallexample @c ada
20455 TO_ADDRESS (16#12777#);
20459 Normally, according to the Ada 83 standard, one would expect this to be
20460 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
20461 of TO_ADDRESS. However, in DEC Ada 83, there is no ambiguity, since the
20462 definition using universal_integer takes precedence.
20464 In GNAT, since the version with universal_integer cannot be supplied, it is
20465 not possible to be 100% compatible. Since there are many programs using
20466 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
20467 to change the name of the function in the UNSIGNED_LONGWORD case, so the
20468 declarations provided in the GNAT version of AUX_Dec are:
20470 @smallexample @c ada
20471 function To_Address (X : Integer) return Address;
20472 pragma Pure_Function (To_Address);
20474 function To_Address_Long (X : Unsigned_Longword) return Address;
20475 pragma Pure_Function (To_Address_Long);
20479 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
20480 change the name to TO_ADDRESS_LONG.
20482 @node Tasking and Task-Related Features
20483 @section Tasking and Task-Related Features
20486 The concepts relevant to a comparison of tasking on GNAT
20487 and on DEC Ada for OpenVMS Alpha systems are discussed in
20488 the following sections.
20490 For detailed information on concepts related to tasking in
20491 DEC Ada, see the DEC Ada Language Reference Manual and the
20492 relevant run-time reference manual.
20494 @node Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
20495 @section Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
20498 On OpenVMS Alpha systems, each Ada task (except a passive
20499 task) is implemented as a single stream of execution
20500 that is created and managed by the kernel. On these
20501 systems, DEC Ada tasking support is based on DECthreads,
20502 an implementation of the POSIX standard for threads.
20504 Although tasks are implemented as threads, all tasks in
20505 an Ada program are part of the same process. As a result,
20506 resources such as open files and virtual memory can be
20507 shared easily among tasks. Having all tasks in one process
20508 allows better integration with the programming environment
20509 (the shell and the debugger, for example).
20511 Also, on OpenVMS Alpha systems, DEC Ada tasks and foreign
20512 code that calls DECthreads routines can be used together.
20513 The interaction between Ada tasks and DECthreads routines
20514 can have some benefits. For example when on OpenVMS Alpha,
20515 DEC Ada can call C code that is already threaded.
20516 GNAT on OpenVMS Alpha uses the facilities of DECthreads,
20517 and Ada tasks are mapped to threads.
20520 * Assigning Task IDs::
20521 * Task IDs and Delays::
20522 * Task-Related Pragmas::
20523 * Scheduling and Task Priority::
20525 * External Interrupts::
20528 @node Assigning Task IDs
20529 @subsection Assigning Task IDs
20532 The DEC Ada Run-Time Library always assigns %TASK 1 to
20533 the environment task that executes the main program. On
20534 OpenVMS Alpha systems, %TASK 0 is often used for tasks
20535 that have been created but are not yet activated.
20537 On OpenVMS Alpha systems, task IDs are assigned at
20538 activation. On GNAT systems, task IDs are also assigned at
20539 task creation but do not have the same form or values as
20540 task ID values in DEC Ada. There is no null task, and the
20541 environment task does not have a specific task ID value.
20543 @node Task IDs and Delays
20544 @subsection Task IDs and Delays
20547 On OpenVMS Alpha systems, tasking delays are implemented
20548 using Timer System Services. The Task ID is used for the
20549 identification of the timer request (the REQIDT parameter).
20550 If Timers are used in the application take care not to use
20551 0 for the identification, because cancelling such a timer
20552 will cancel all timers and may lead to unpredictable results.
20554 @node Task-Related Pragmas
20555 @subsection Task-Related Pragmas
20558 Ada supplies the pragma TASK_STORAGE, which allows
20559 specification of the size of the guard area for a task
20560 stack. (The guard area forms an area of memory that has no
20561 read or write access and thus helps in the detection of
20562 stack overflow.) On OpenVMS Alpha systems, if the pragma
20563 TASK_STORAGE specifies a value of zero, a minimal guard
20564 area is created. In the absence of a pragma TASK_STORAGE, a default guard
20567 GNAT supplies the following task-related pragmas:
20572 This pragma appears within a task definition and
20573 applies to the task in which it appears. The argument
20574 must be of type SYSTEM.TASK_INFO.TASK_INFO_TYPE.
20578 GNAT implements pragma TASK_STORAGE in the same way as
20580 Both DEC Ada and GNAT supply the pragmas PASSIVE,
20581 SUPPRESS, and VOLATILE.
20583 @node Scheduling and Task Priority
20584 @subsection Scheduling and Task Priority
20587 DEC Ada implements the Ada language requirement that
20588 when two tasks are eligible for execution and they have
20589 different priorities, the lower priority task does not
20590 execute while the higher priority task is waiting. The DEC
20591 Ada Run-Time Library keeps a task running until either the
20592 task is suspended or a higher priority task becomes ready.
20594 On OpenVMS Alpha systems, the default strategy is round-
20595 robin with preemption. Tasks of equal priority take turns
20596 at the processor. A task is run for a certain period of
20597 time and then placed at the rear of the ready queue for
20598 its priority level.
20600 DEC Ada provides the implementation-defined pragma TIME_SLICE,
20601 which can be used to enable or disable round-robin
20602 scheduling of tasks with the same priority.
20603 See the relevant DEC Ada run-time reference manual for
20604 information on using the pragmas to control DEC Ada task
20607 GNAT follows the scheduling rules of Annex D (real-time
20608 Annex) of the Ada 95 Reference Manual. In general, this
20609 scheduling strategy is fully compatible with DEC Ada
20610 although it provides some additional constraints (as
20611 fully documented in Annex D).
20612 GNAT implements time slicing control in a manner compatible with
20613 DEC Ada 83, by means of the pragma Time_Slice, whose semantics are identical
20614 to the DEC Ada 83 pragma of the same name.
20615 Note that it is not possible to mix GNAT tasking and
20616 DEC Ada 83 tasking in the same program, since the two run times are
20619 @node The Task Stack
20620 @subsection The Task Stack
20623 In DEC Ada, a task stack is allocated each time a
20624 non passive task is activated. As soon as the task is
20625 terminated, the storage for the task stack is deallocated.
20626 If you specify a size of zero (bytes) with T'STORAGE_SIZE,
20627 a default stack size is used. Also, regardless of the size
20628 specified, some additional space is allocated for task
20629 management purposes. On OpenVMS Alpha systems, at least
20630 one page is allocated.
20632 GNAT handles task stacks in a similar manner. According to
20633 the Ada 95 rules, it provides the pragma STORAGE_SIZE as
20634 an alternative method for controlling the task stack size.
20635 The specification of the attribute T'STORAGE_SIZE is also
20636 supported in a manner compatible with DEC Ada.
20638 @node External Interrupts
20639 @subsection External Interrupts
20642 On DEC Ada, external interrupts can be associated with task entries.
20643 GNAT is compatible with DEC Ada in its handling of external interrupts.
20645 @node Pragmas and Pragma-Related Features
20646 @section Pragmas and Pragma-Related Features
20649 Both DEC Ada and GNAT supply all language-defined pragmas
20650 as specified by the Ada 83 standard. GNAT also supplies all
20651 language-defined pragmas specified in the Ada 95 Reference Manual.
20652 In addition, GNAT implements the implementation-defined pragmas
20658 @item COMMON_OBJECT
20660 @item COMPONENT_ALIGNMENT
20662 @item EXPORT_EXCEPTION
20664 @item EXPORT_FUNCTION
20666 @item EXPORT_OBJECT
20668 @item EXPORT_PROCEDURE
20670 @item EXPORT_VALUED_PROCEDURE
20672 @item FLOAT_REPRESENTATION
20676 @item IMPORT_EXCEPTION
20678 @item IMPORT_FUNCTION
20680 @item IMPORT_OBJECT
20682 @item IMPORT_PROCEDURE
20684 @item IMPORT_VALUED_PROCEDURE
20686 @item INLINE_GENERIC
20688 @item INTERFACE_NAME
20698 @item SHARE_GENERIC
20710 These pragmas are all fully implemented, with the exception of @code{Title},
20711 @code{Passive}, and @code{Share_Generic}, which are
20712 recognized, but which have no
20713 effect in GNAT. The effect of @code{Passive} may be obtained by the
20714 use of protected objects in Ada 95. In GNAT, all generics are inlined.
20716 Unlike DEC Ada, the GNAT 'EXPORT_@i{subprogram}' pragmas require
20717 a separate subprogram specification which must appear before the
20720 GNAT also supplies a number of implementation-defined pragmas as follows:
20722 @item C_PASS_BY_COPY
20724 @item EXTEND_SYSTEM
20726 @item SOURCE_FILE_NAME
20744 @item CPP_CONSTRUCTOR
20746 @item CPP_DESTRUCTOR
20756 @item LINKER_SECTION
20758 @item MACHINE_ATTRIBUTE
20762 @item PURE_FUNCTION
20764 @item SOURCE_REFERENCE
20768 @item UNCHECKED_UNION
20770 @item UNIMPLEMENTED_UNIT
20772 @item UNIVERSAL_DATA
20774 @item WEAK_EXTERNAL
20778 For full details on these GNAT implementation-defined pragmas, see
20779 the GNAT Reference Manual.
20782 * Restrictions on the Pragma INLINE::
20783 * Restrictions on the Pragma INTERFACE::
20784 * Restrictions on the Pragma SYSTEM_NAME::
20787 @node Restrictions on the Pragma INLINE
20788 @subsection Restrictions on the Pragma INLINE
20791 DEC Ada applies the following restrictions to the pragma INLINE:
20793 @item Parameters cannot be a task type.
20795 @item Function results cannot be task types, unconstrained
20796 array types, or unconstrained types with discriminants.
20798 @item Bodies cannot declare the following:
20800 @item Subprogram body or stub (imported subprogram is allowed)
20804 @item Generic declarations
20806 @item Instantiations
20810 @item Access types (types derived from access types allowed)
20812 @item Array or record types
20814 @item Dependent tasks
20816 @item Direct recursive calls of subprogram or containing
20817 subprogram, directly or via a renaming
20823 In GNAT, the only restriction on pragma INLINE is that the
20824 body must occur before the call if both are in the same
20825 unit, and the size must be appropriately small. There are
20826 no other specific restrictions which cause subprograms to
20827 be incapable of being inlined.
20829 @node Restrictions on the Pragma INTERFACE
20830 @subsection Restrictions on the Pragma INTERFACE
20833 The following lists and describes the restrictions on the
20834 pragma INTERFACE on DEC Ada and GNAT:
20836 @item Languages accepted: Ada, Bliss, C, Fortran, Default.
20837 Default is the default on OpenVMS Alpha systems.
20839 @item Parameter passing: Language specifies default
20840 mechanisms but can be overridden with an EXPORT pragma.
20843 @item Ada: Use internal Ada rules.
20845 @item Bliss, C: Parameters must be mode @code{in}; cannot be
20846 record or task type. Result cannot be a string, an
20847 array, or a record.
20849 @item Fortran: Parameters cannot be a task. Result cannot
20850 be a string, an array, or a record.
20855 GNAT is entirely upwards compatible with DEC Ada, and in addition allows
20856 record parameters for all languages.
20858 @node Restrictions on the Pragma SYSTEM_NAME
20859 @subsection Restrictions on the Pragma SYSTEM_NAME
20862 For DEC Ada for OpenVMS Alpha, the enumeration literal
20863 for the type NAME is OPENVMS_AXP. In GNAT, the enumeration
20864 literal for the type NAME is SYSTEM_NAME_GNAT.
20866 @node Library of Predefined Units
20867 @section Library of Predefined Units
20870 A library of predefined units is provided as part of the
20871 DEC Ada and GNAT implementations. DEC Ada does not provide
20872 the package MACHINE_CODE but instead recommends importing
20875 The GNAT versions of the DEC Ada Run-Time Library (ADA$PREDEFINED:)
20876 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
20877 version. During GNAT installation, the DEC Ada Predefined
20878 Library units are copied into the GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
20879 (aka DECLIB) directory and patched to remove Ada 95 incompatibilities
20880 and to make them interoperable with GNAT, @pxref{Changes to DECLIB}
20883 The GNAT RTL is contained in
20884 the GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB] (aka ADALIB) directory and
20885 the default search path is set up to find DECLIB units in preference
20886 to ADALIB units with the same name (TEXT_IO, SEQUENTIAL_IO, and DIRECT_IO,
20889 However, it is possible to change the default so that the
20890 reverse is true, or even to mix them using child package
20891 notation. The DEC Ada 83 units are available as DEC.xxx where xxx
20892 is the package name, and the Ada units are available in the
20893 standard manner defined for Ada 95, that is to say as Ada.xxx. To
20894 change the default, set ADA_INCLUDE_PATH and ADA_OBJECTS_PATH
20895 appropriately. For example, to change the default to use the Ada95
20899 $ DEFINE ADA_INCLUDE_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADAINCLUDE],-
20900 GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
20901 $ DEFINE ADA_OBJECTS_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB],-
20902 GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
20906 * Changes to DECLIB::
20909 @node Changes to DECLIB
20910 @subsection Changes to DECLIB
20913 The changes made to the DEC Ada predefined library for GNAT and Ada 95
20914 compatibility are minor and include the following:
20917 @item Adjusting the location of pragmas and record representation
20918 clauses to obey Ada 95 rules
20920 @item Adding the proper notation to generic formal parameters
20921 that take unconstrained types in instantiation
20923 @item Adding pragma ELABORATE_BODY to package specifications
20924 that have package bodies not otherwise allowed
20926 @item Occurrences of the identifier @code{"PROTECTED"} are renamed to
20928 Currently these are found only in the STARLET package spec.
20932 None of the above changes is visible to users.
20938 On OpenVMS Alpha, DEC Ada provides the following strongly-typed bindings:
20941 @item Command Language Interpreter (CLI interface)
20943 @item DECtalk Run-Time Library (DTK interface)
20945 @item Librarian utility routines (LBR interface)
20947 @item General Purpose Run-Time Library (LIB interface)
20949 @item Math Run-Time Library (MTH interface)
20951 @item National Character Set Run-Time Library (NCS interface)
20953 @item Compiled Code Support Run-Time Library (OTS interface)
20955 @item Parallel Processing Run-Time Library (PPL interface)
20957 @item Screen Management Run-Time Library (SMG interface)
20959 @item Sort Run-Time Library (SOR interface)
20961 @item String Run-Time Library (STR interface)
20963 @item STARLET System Library
20966 @item X Window System Version 11R4 and 11R5 (X, XLIB interface)
20968 @item X Windows Toolkit (XT interface)
20970 @item X/Motif Version 1.1.3 and 1.2 (XM interface)
20974 GNAT provides implementations of these DEC bindings in the DECLIB directory.
20976 The X/Motif bindings used to build DECLIB are whatever versions are in the
20977 DEC Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
20978 The build script will
20979 automatically add a pragma Linker_Options to packages @code{Xm}, @code{Xt},
20981 causing the default X/Motif sharable image libraries to be linked in. This
20982 is done via options files named @file{xm.opt}, @file{xt.opt}, and
20983 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
20985 It may be necessary to edit these options files to update or correct the
20986 library names if, for example, the newer X/Motif bindings from
20987 @file{ADA$EXAMPLES}
20988 had been (previous to installing GNAT) copied and renamed to supersede the
20989 default @file{ADA$PREDEFINED} versions.
20992 * Shared Libraries and Options Files::
20993 * Interfaces to C::
20996 @node Shared Libraries and Options Files
20997 @subsection Shared Libraries and Options Files
21000 When using the DEC Ada
21001 predefined X and Motif bindings, the linking with their sharable images is
21002 done automatically by @command{GNAT LINK}.
21003 When using other X and Motif bindings, you need
21004 to add the corresponding sharable images to the command line for
21005 @code{GNAT LINK}. When linking with shared libraries, or with
21006 @file{.OPT} files, you must
21007 also add them to the command line for @command{GNAT LINK}.
21009 A shared library to be used with GNAT is built in the same way as other
21010 libraries under VMS. The VMS Link command can be used in standard fashion.
21012 @node Interfaces to C
21013 @subsection Interfaces to C
21017 provides the following Ada types and operations:
21020 @item C types package (C_TYPES)
21022 @item C strings (C_TYPES.NULL_TERMINATED)
21024 @item Other_types (SHORT_INT)
21028 Interfacing to C with GNAT, one can use the above approach
21029 described for DEC Ada or the facilities of Annex B of
21030 the Ada 95 Reference Manual (packages INTERFACES.C,
21031 INTERFACES.C.STRINGS and INTERFACES.C.POINTERS). For more
21032 information, see the section ``Interfacing to C'' in the
21033 @cite{GNAT Reference Manual}.
21035 The @option{-gnatF} qualifier forces default and explicit
21036 @code{External_Name} parameters in pragmas Import and Export
21037 to be uppercased for compatibility with the default behavior
21038 of Compaq C. The qualifier has no effect on @code{Link_Name} parameters.
21040 @node Main Program Definition
21041 @section Main Program Definition
21044 The following section discusses differences in the
21045 definition of main programs on DEC Ada and GNAT.
21046 On DEC Ada, main programs are defined to meet the
21047 following conditions:
21049 @item Procedure with no formal parameters (returns 0 upon
21052 @item Procedure with no formal parameters (returns 42 when
21053 unhandled exceptions are raised)
21055 @item Function with no formal parameters whose returned value
21056 is of a discrete type
21058 @item Procedure with one OUT formal of a discrete type for
21059 which a specification of pragma EXPORT_VALUED_PROCEDURE is given.
21064 When declared with the pragma EXPORT_VALUED_PROCEDURE,
21065 a main function or main procedure returns a discrete
21066 value whose size is less than 64 bits (32 on VAX systems),
21067 the value is zero- or sign-extended as appropriate.
21068 On GNAT, main programs are defined as follows:
21070 @item Must be a non-generic, parameter-less subprogram that
21071 is either a procedure or function returning an Ada
21072 STANDARD.INTEGER (the predefined type)
21074 @item Cannot be a generic subprogram or an instantiation of a
21078 @node Implementation-Defined Attributes
21079 @section Implementation-Defined Attributes
21082 GNAT provides all DEC Ada implementation-defined
21085 @node Compiler and Run-Time Interfacing
21086 @section Compiler and Run-Time Interfacing
21089 DEC Ada provides the following ways to pass options to the linker
21092 @item /WAIT and /SUBMIT qualifiers
21094 @item /COMMAND qualifier
21096 @item /[NO]MAP qualifier
21098 @item /OUTPUT=file-spec
21100 @item /[NO]DEBUG and /[NO]TRACEBACK qualifiers
21104 To pass options to the linker, GNAT provides the following
21108 @item @option{/EXECUTABLE=exec-name}
21110 @item @option{/VERBOSE qualifier}
21112 @item @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK} qualifiers
21116 For more information on these switches, see
21117 @ref{Switches for gnatlink}.
21118 In DEC Ada, the command-line switch @option{/OPTIMIZE} is available
21119 to control optimization. DEC Ada also supplies the
21122 @item @code{OPTIMIZE}
21124 @item @code{INLINE}
21126 @item @code{INLINE_GENERIC}
21128 @item @code{SUPPRESS_ALL}
21130 @item @code{PASSIVE}
21134 In GNAT, optimization is controlled strictly by command
21135 line parameters, as described in the corresponding section of this guide.
21136 The DIGITAL pragmas for control of optimization are
21137 recognized but ignored.
21139 Note that in GNAT, the default is optimization off, whereas in DEC Ada 83,
21140 the default is that optimization is turned on.
21142 @node Program Compilation and Library Management
21143 @section Program Compilation and Library Management
21146 DEC Ada and GNAT provide a comparable set of commands to
21147 build programs. DEC Ada also provides a program library,
21148 which is a concept that does not exist on GNAT. Instead,
21149 GNAT provides directories of sources that are compiled as
21152 The following table summarizes
21153 the DEC Ada commands and provides
21154 equivalent GNAT commands. In this table, some GNAT
21155 equivalents reflect the fact that GNAT does not use the
21156 concept of a program library. Instead, it uses a model
21157 in which collections of source and object files are used
21158 in a manner consistent with other languages like C and
21159 Fortran. Therefore, standard system file commands are used
21160 to manipulate these elements. Those GNAT commands are marked with
21162 Note that, unlike DEC Ada, none of the GNAT commands accepts wild cards.
21165 @multitable @columnfractions .35 .65
21167 @item @emph{DEC Ada Command}
21168 @tab @emph{GNAT Equivalent / Description}
21170 @item @command{ADA}
21171 @tab @command{GNAT COMPILE}@*
21172 Invokes the compiler to compile one or more Ada source files.
21174 @item @command{ACS ATTACH}@*
21175 @tab [No equivalent]@*
21176 Switches control of terminal from current process running the program
21179 @item @command{ACS CHECK}
21180 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
21181 Forms the execution closure of one
21182 or more compiled units and checks completeness and currency.
21184 @item @command{ACS COMPILE}
21185 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21186 Forms the execution closure of one or
21187 more specified units, checks completeness and currency,
21188 identifies units that have revised source files, compiles same,
21189 and recompiles units that are or will become obsolete.
21190 Also completes incomplete generic instantiations.
21192 @item @command{ACS COPY FOREIGN}
21194 Copies a foreign object file into the program library as a
21197 @item @command{ACS COPY UNIT}
21199 Copies a compiled unit from one program library to another.
21201 @item @command{ACS CREATE LIBRARY}
21202 @tab Create /directory (*)@*
21203 Creates a program library.
21205 @item @command{ACS CREATE SUBLIBRARY}
21206 @tab Create /directory (*)@*
21207 Creates a program sublibrary.
21209 @item @command{ACS DELETE LIBRARY}
21211 Deletes a program library and its contents.
21213 @item @command{ACS DELETE SUBLIBRARY}
21215 Deletes a program sublibrary and its contents.
21217 @item @command{ACS DELETE UNIT}
21218 @tab Delete file (*)@*
21219 On OpenVMS systems, deletes one or more compiled units from
21220 the current program library.
21222 @item @command{ACS DIRECTORY}
21223 @tab Directory (*)@*
21224 On OpenVMS systems, lists units contained in the current
21227 @item @command{ACS ENTER FOREIGN}
21229 Allows the import of a foreign body as an Ada library
21230 specification and enters a reference to a pointer.
21232 @item @command{ACS ENTER UNIT}
21234 Enters a reference (pointer) from the current program library to
21235 a unit compiled into another program library.
21237 @item @command{ACS EXIT}
21238 @tab [No equivalent]@*
21239 Exits from the program library manager.
21241 @item @command{ACS EXPORT}
21243 Creates an object file that contains system-specific object code
21244 for one or more units. With GNAT, object files can simply be copied
21245 into the desired directory.
21247 @item @command{ACS EXTRACT SOURCE}
21249 Allows access to the copied source file for each Ada compilation unit
21251 @item @command{ACS HELP}
21252 @tab @command{HELP GNAT}@*
21253 Provides online help.
21255 @item @command{ACS LINK}
21256 @tab @command{GNAT LINK}@*
21257 Links an object file containing Ada units into an executable file.
21259 @item @command{ACS LOAD}
21261 Loads (partially compiles) Ada units into the program library.
21262 Allows loading a program from a collection of files into a library
21263 without knowing the relationship among units.
21265 @item @command{ACS MERGE}
21267 Merges into the current program library, one or more units from
21268 another library where they were modified.
21270 @item @command{ACS RECOMPILE}
21271 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21272 Recompiles from external or copied source files any obsolete
21273 unit in the closure. Also, completes any incomplete generic
21276 @item @command{ACS REENTER}
21277 @tab @command{GNAT MAKE}@*
21278 Reenters current references to units compiled after last entered
21279 with the @command{ACS ENTER UNIT} command.
21281 @item @command{ACS SET LIBRARY}
21282 @tab Set default (*)@*
21283 Defines a program library to be the compilation context as well
21284 as the target library for compiler output and commands in general.
21286 @item @command{ACS SET PRAGMA}
21287 @tab Edit @file{gnat.adc} (*)@*
21288 Redefines specified values of the library characteristics
21289 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
21290 and @code{Float_Representation}.
21292 @item @command{ACS SET SOURCE}
21293 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
21294 Defines the source file search list for the @command{ACS COMPILE} command.
21296 @item @command{ACS SHOW LIBRARY}
21297 @tab Directory (*)@*
21298 Lists information about one or more program libraries.
21300 @item @command{ACS SHOW PROGRAM}
21301 @tab [No equivalent]@*
21302 Lists information about the execution closure of one or
21303 more units in the program library.
21305 @item @command{ACS SHOW SOURCE}
21306 @tab Show logical @code{ADA_INCLUDE_PATH}@*
21307 Shows the source file search used when compiling units.
21309 @item @command{ACS SHOW VERSION}
21310 @tab Compile with @option{VERBOSE} option
21311 Displays the version number of the compiler and program library
21314 @item @command{ACS SPAWN}
21315 @tab [No equivalent]@*
21316 Creates a subprocess of the current process (same as @command{DCL SPAWN}
21319 @item @command{ACS VERIFY}
21320 @tab [No equivalent]@*
21321 Performs a series of consistency checks on a program library to
21322 determine whether the library structure and library files are in
21329 @section Input-Output
21332 On OpenVMS Alpha systems, DEC Ada uses OpenVMS Record
21333 Management Services (RMS) to perform operations on
21337 DEC Ada and GNAT predefine an identical set of input-
21338 output packages. To make the use of the
21339 generic TEXT_IO operations more convenient, DEC Ada
21340 provides predefined library packages that instantiate the
21341 integer and floating-point operations for the predefined
21342 integer and floating-point types as shown in the following table.
21344 @multitable @columnfractions .45 .55
21345 @item @emph{Package Name} @tab Instantiation
21347 @item @code{INTEGER_TEXT_IO}
21348 @tab @code{INTEGER_IO(INTEGER)}
21350 @item @code{SHORT_INTEGER_TEXT_IO}
21351 @tab @code{INTEGER_IO(SHORT_INTEGER)}
21353 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
21354 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
21356 @item @code{FLOAT_TEXT_IO}
21357 @tab @code{FLOAT_IO(FLOAT)}
21359 @item @code{LONG_FLOAT_TEXT_IO}
21360 @tab @code{FLOAT_IO(LONG_FLOAT)}
21364 The DEC Ada predefined packages and their operations
21365 are implemented using OpenVMS Alpha files and input-
21366 output facilities. DEC Ada supports asynchronous input-
21367 output on OpenVMS Alpha. Familiarity with the following is
21370 @item RMS file organizations and access methods
21372 @item OpenVMS file specifications and directories
21374 @item OpenVMS File Definition Language (FDL)
21378 GNAT provides I/O facilities that are completely
21379 compatible with DEC Ada. The distribution includes the
21380 standard DEC Ada versions of all I/O packages, operating
21381 in a manner compatible with DEC Ada. In particular, the
21382 following packages are by default the DEC Ada (Ada 83)
21383 versions of these packages rather than the renamings
21384 suggested in annex J of the Ada 95 Reference Manual:
21386 @item @code{TEXT_IO}
21388 @item @code{SEQUENTIAL_IO}
21390 @item @code{DIRECT_IO}
21394 The use of the standard Ada 95 syntax for child packages (for
21395 example, @code{ADA.TEXT_IO}) retrieves the Ada 95 versions of these
21396 packages, as defined in the Ada 95 Reference Manual.
21397 GNAT provides DIGITAL-compatible predefined instantiations
21398 of the @code{TEXT_IO} packages, and also
21399 provides the standard predefined instantiations required
21400 by the Ada 95 Reference Manual.
21402 For further information on how GNAT interfaces to the file
21403 system or how I/O is implemented in programs written in
21404 mixed languages, see the chapter ``Implementation of the
21405 Standard I/O'' in the @cite{GNAT Reference Manual}.
21406 This chapter covers the following:
21408 @item Standard I/O packages
21410 @item @code{FORM} strings
21412 @item @code{ADA.DIRECT_IO}
21414 @item @code{ADA.SEQUENTIAL_IO}
21416 @item @code{ADA.TEXT_IO}
21418 @item Stream pointer positioning
21420 @item Reading and writing non-regular files
21422 @item @code{GET_IMMEDIATE}
21424 @item Treating @code{TEXT_IO} files as streams
21431 @node Implementation Limits
21432 @section Implementation Limits
21435 The following table lists implementation limits for DEC Ada
21437 @multitable @columnfractions .60 .20 .20
21439 @item @emph{Compilation Parameter}
21440 @tab @emph{DEC Ada}
21444 @item In a subprogram or entry declaration, maximum number of
21445 formal parameters that are of an unconstrained record type
21450 @item Maximum identifier length (number of characters)
21455 @item Maximum number of characters in a source line
21460 @item Maximum collection size (number of bytes)
21465 @item Maximum number of discriminants for a record type
21470 @item Maximum number of formal parameters in an entry or
21471 subprogram declaration
21476 @item Maximum number of dimensions in an array type
21481 @item Maximum number of library units and subunits in a compilation.
21486 @item Maximum number of library units and subunits in an execution.
21491 @item Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
21492 or @code{PSECT_OBJECT}
21497 @item Maximum number of enumeration literals in an enumeration type
21503 @item Maximum number of lines in a source file
21508 @item Maximum number of bits in any object
21513 @item Maximum size of the static portion of a stack frame (approximate)
21523 @c **************************************
21524 @node Platform-Specific Information for the Run-Time Libraries
21525 @appendix Platform-Specific Information for the Run-Time Libraries
21526 @cindex Tasking and threads libraries
21527 @cindex Threads libraries and tasking
21528 @cindex Run-time libraries (platform-specific information)
21531 The GNAT run-time implementation
21532 may vary with respect to both the underlying threads library and
21533 the exception handling scheme.
21534 For threads support, one or more of the following are supplied:
21536 @item @b{native threads library}, a binding to the thread package from
21537 the underlying operating system
21539 @item @b{FSU threads library}, a binding to the Florida State University
21540 threads implementation, which complies fully with the requirements of Annex D
21542 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
21543 POSIX thread package
21547 For exception handling, either or both of two models are supplied:
21549 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
21550 Most programs should experience a substantial speed improvement by
21551 being compiled with a ZCX run-time.
21552 This is especially true for
21553 tasking applications or applications with many exception handlers.}
21554 @cindex Zero-Cost Exceptions
21555 @cindex ZCX (Zero-Cost Exceptions)
21556 which uses binder-generated tables that
21557 are interrogated at run time to locate a handler
21559 @item @b{setjmp / longjmp} (``SJLJ''),
21560 @cindex setjmp/longjmp Exception Model
21561 @cindex SJLJ (setjmp/longjmp Exception Model)
21562 which uses dynamically-set data to establish
21563 the set of handlers
21567 This appendix summarizes which combinations of threads and exception support
21568 are supplied on various GNAT platforms.
21569 It then shows how to select a particular library either
21570 permanently or temporarily,
21571 explains the properties of (and tradeoffs among) the various threads
21572 libraries, and provides some additional
21573 information about several specific platforms.
21576 * Summary of Run-Time Configurations::
21577 * Specifying a Run-Time Library::
21578 * Choosing between Native and FSU Threads Libraries::
21579 * Choosing the Scheduling Policy::
21580 * Solaris-Specific Considerations::
21581 * IRIX-Specific Considerations::
21582 * Linux-Specific Considerations::
21583 * AIX-Specific Considerations::
21586 @node Summary of Run-Time Configurations
21587 @section Summary of Run-Time Configurations
21589 @multitable @columnfractions .30 .70
21590 @item @b{alpha-openvms}
21591 @item @code{@ @ }@i{rts-native (default)}
21592 @item @code{@ @ @ @ }Tasking @tab native VMS threads
21593 @item @code{@ @ @ @ }Exceptions @tab ZCX
21596 @item @code{@ @ }@i{rts-native (default)}
21597 @item @code{@ @ @ @ }Tasking @tab native HP threads library
21598 @item @code{@ @ @ @ }Exceptions @tab ZCX
21600 @item @code{@ @ }@i{rts-sjlj}
21601 @item @code{@ @ @ @ }Tasking @tab native HP threads library
21602 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21604 @item @b{sparc-solaris} @tab
21605 @item @code{@ @ }@i{rts-native (default)}
21606 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
21607 @item @code{@ @ @ @ }Exceptions @tab ZCX
21609 @item @code{@ @ }@i{rts-fsu} @tab
21610 @item @code{@ @ @ @ }Tasking @tab FSU threads library
21611 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21613 @item @code{@ @ }@i{rts-m64}
21614 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
21615 @item @code{@ @ @ @ }Exceptions @tab ZCX
21616 @item @code{@ @ @ @ }Constraints @tab Use only when compiling in 64-bit mode;
21617 @item @tab Use only on Solaris 8 or later.
21618 @item @tab @xref{Building and Debugging 64-bit Applications}, for details.
21620 @item @code{@ @ }@i{rts-pthread}
21621 @item @code{@ @ @ @ }Tasking @tab pthreads library
21622 @item @code{@ @ @ @ }Exceptions @tab ZCX
21624 @item @code{@ @ }@i{rts-sjlj}
21625 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
21626 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21628 @item @b{x86-linux}
21629 @item @code{@ @ }@i{rts-native (default)}
21630 @item @code{@ @ @ @ }Tasking @tab LinuxThread library
21631 @item @code{@ @ @ @ }Exceptions @tab ZCX
21633 @item @code{@ @ }@i{rts-fsu}
21634 @item @code{@ @ @ @ }Tasking @tab FSU threads library
21635 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21637 @item @code{@ @ }@i{rts-sjlj}
21638 @item @code{@ @ @ @ }Tasking @tab LinuxThread library
21639 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21641 @item @b{x86-windows}
21642 @item @code{@ @ }@i{rts-native (default)}
21643 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
21644 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21648 @node Specifying a Run-Time Library
21649 @section Specifying a Run-Time Library
21652 The @file{adainclude} subdirectory containing the sources of the GNAT
21653 run-time library, and the @file{adalib} subdirectory containing the
21654 @file{ALI} files and the static and/or shared GNAT library, are located
21655 in the gcc target-dependent area:
21658 target=$prefix/lib/gcc-lib/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
21662 As indicated above, on some platforms several run-time libraries are supplied.
21663 These libraries are installed in the target dependent area and
21664 contain a complete source and binary subdirectory. The detailed description
21665 below explains the differences between the different libraries in terms of
21666 their thread support.
21668 The default run-time library (when GNAT is installed) is @emph{rts-native}.
21669 This default run time is selected by the means of soft links.
21670 For example on x86-linux:
21676 +--- adainclude----------+
21678 +--- adalib-----------+ |
21680 +--- rts-native | |
21682 | +--- adainclude <---+
21684 | +--- adalib <----+
21701 If the @i{rts-fsu} library is to be selected on a permanent basis,
21702 these soft links can be modified with the following commands:
21706 $ rm -f adainclude adalib
21707 $ ln -s rts-fsu/adainclude adainclude
21708 $ ln -s rts-fsu/adalib adalib
21712 Alternatively, you can specify @file{rts-fsu/adainclude} in the file
21713 @file{$target/ada_source_path} and @file{rts-fsu/adalib} in
21714 @file{$target/ada_object_path}.
21716 Selecting another run-time library temporarily can be
21717 achieved by the regular mechanism for GNAT object or source path selection:
21721 Set the environment variables:
21724 $ ADA_INCLUDE_PATH=$target/rts-fsu/adainclude:$ADA_INCLUDE_PATH
21725 $ ADA_OBJECTS_PATH=$target/rts-fsu/adalib:$ADA_OBJECTS_PATH
21726 $ export ADA_INCLUDE_PATH ADA_OBJECTS_PATH
21730 Use @option{-aI$target/rts-fsu/adainclude}
21731 and @option{-aO$target/rts-fsu/adalib}
21732 on the @command{gnatmake} command line
21735 Use the switch @option{--RTS}; e.g., @option{--RTS=fsu}
21736 @cindex @option{--RTS} option
21740 You can similarly switch to @emph{rts-sjlj}.
21742 @node Choosing between Native and FSU Threads Libraries
21743 @section Choosing between Native and FSU Threads Libraries
21744 @cindex Native threads library
21745 @cindex FSU threads library
21748 Some GNAT implementations offer a choice between
21749 native threads and FSU threads.
21753 The @emph{native threads} library correspond to the standard system threads
21754 implementation (e.g. LinuxThreads on GNU/Linux,
21755 @cindex LinuxThreads library
21756 POSIX threads on AIX, or
21757 Solaris threads on Solaris). When this option is chosen, GNAT provides
21758 a full and accurate implementation of the core language tasking model
21759 as described in Chapter 9 of the Ada Reference Manual,
21760 but might not (and probably does not) implement
21761 the exact semantics as specified in @w{Annex D} (the Real-Time Systems Annex).
21762 @cindex Annex D (Real-Time Systems Annex) compliance
21763 @cindex Real-Time Systems Annex compliance
21764 Indeed, the reason that a choice of libraries is offered
21765 on a given target is because some of the
21766 ACATS tests for @w{Annex D} fail using the native threads library.
21767 As far as possible, this library is implemented
21768 in accordance with Ada semantics (e.g., modifying priorities as required
21769 to simulate ceiling locking),
21770 but there are often slight inaccuracies, most often in the area of
21771 absolutely respecting the priority rules on a single
21773 Moreover, it is not possible in general to define the exact behavior,
21774 because the native threads implementations
21775 are not well enough documented.
21777 On systems where the @code{SCHED_FIFO} POSIX scheduling policy is supported,
21778 @cindex POSIX scheduling policies
21779 @cindex @code{SCHED_FIFO} scheduling policy
21780 native threads will provide a behavior very close to the @w{Annex D}
21781 requirements (i.e., a run-till-blocked scheduler with fixed priorities), but
21782 on some systems (in particular GNU/Linux and Solaris), you need to have root
21783 privileges to use the @code{SCHED_FIFO} policy.
21786 The @emph{FSU threads} library provides a completely accurate implementation
21788 Thus, operating with this library, GNAT is 100% compliant with both the core
21789 and all @w{Annex D}
21791 The formal validations for implementations offering
21792 a choice of threads packages are always carried out using the FSU
21797 From these considerations, it might seem that FSU threads are the
21799 but that is by no means always the case. The FSU threads package
21800 operates with all Ada tasks appearing to the system to be a single
21801 thread. This is often considerably more efficient than operating
21802 with separate threads, since for example, switching between tasks
21803 can be accomplished without the (in some cases considerable)
21804 overhead of a context switch between two system threads. However,
21805 it means that you may well lose concurrency at the system
21806 level. Notably, some system operations (such as I/O) may block all
21807 tasks in a program and not just the calling task. More
21808 significantly, the FSU threads approach likely means you cannot
21809 take advantage of multiple processors, since for this you need
21810 separate threads (or even separate processes) to operate on
21811 different processors.
21813 For most programs, the native threads library is
21814 usually the better choice. Use the FSU threads if absolute
21815 conformance to @w{Annex D} is important for your application, or if
21816 you find that the improved efficiency of FSU threads is significant to you.
21818 Note also that to take full advantage of Florist and Glade, it is highly
21819 recommended that you use native threads.
21821 @node Choosing the Scheduling Policy
21822 @section Choosing the Scheduling Policy
21825 When using a POSIX threads implementation, you have a choice of several
21826 scheduling policies: @code{SCHED_FIFO},
21827 @cindex @code{SCHED_FIFO} scheduling policy
21829 @cindex @code{SCHED_RR} scheduling policy
21830 and @code{SCHED_OTHER}.
21831 @cindex @code{SCHED_OTHER} scheduling policy
21832 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
21833 or @code{SCHED_RR} requires special (e.g., root) privileges.
21835 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
21837 @cindex @code{SCHED_FIFO} scheduling policy
21838 you can use one of the following:
21842 @code{pragma Time_Slice (0.0)}
21843 @cindex pragma Time_Slice
21845 the corresponding binder option @option{-T0}
21846 @cindex @option{-T0} option
21848 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21849 @cindex pragma Task_Dispatching_Policy
21853 To specify @code{SCHED_RR},
21854 @cindex @code{SCHED_RR} scheduling policy
21855 you should use @code{pragma Time_Slice} with a
21856 value greater than @code{0.0}, or else use the corresponding @option{-T}
21859 @node Solaris-Specific Considerations
21860 @section Solaris-Specific Considerations
21861 @cindex Solaris Sparc threads libraries
21864 This section addresses some topics related to the various threads libraries
21865 on Sparc Solaris and then provides some information on building and
21866 debugging 64-bit applications.
21869 * Solaris Threads Issues::
21870 * Building and Debugging 64-bit Applications::
21873 @node Solaris Threads Issues
21874 @subsection Solaris Threads Issues
21877 Starting with version 3.14, GNAT under Solaris comes with a new tasking
21878 run-time library based on POSIX threads --- @emph{rts-pthread}.
21879 @cindex rts-pthread threads library
21880 This run-time library has the advantage of being mostly shared across all
21881 POSIX-compliant thread implementations, and it also provides under
21882 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
21883 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
21884 and @code{PTHREAD_PRIO_PROTECT}
21885 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
21886 semantics that can be selected using the predefined pragma
21887 @code{Locking_Policy}
21888 @cindex pragma Locking_Policy (under rts-pthread)
21890 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
21891 @cindex @code{Inheritance_Locking} (under rts-pthread)
21892 @cindex @code{Ceiling_Locking} (under rts-pthread)
21894 As explained above, the native run-time library is based on the Solaris thread
21895 library (@code{libthread}) and is the default library.
21896 The FSU run-time library is based on the FSU threads.
21897 @cindex FSU threads library
21899 Starting with Solaris 2.5.1, when the Solaris threads library is used
21900 (this is the default), programs
21901 compiled with GNAT can automatically take advantage of
21902 and can thus execute on multiple processors.
21903 The user can alternatively specify a processor on which the program should run
21904 to emulate a single-processor system. The multiprocessor / uniprocessor choice
21906 setting the environment variable @code{GNAT_PROCESSOR}
21907 @cindex @code{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
21908 to one of the following:
21912 Use the default configuration (run the program on all
21913 available processors) - this is the same as having
21914 @code{GNAT_PROCESSOR} unset
21917 Let the run-time implementation choose one processor and run the program on
21920 @item 0 .. Last_Proc
21921 Run the program on the specified processor.
21922 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
21923 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
21926 @node Building and Debugging 64-bit Applications
21927 @subsection Building and Debugging 64-bit Applications
21930 In a 64-bit application, all the sources involved must be compiled with the
21931 @option{-m64} command-line option, and a specific GNAT library (compiled with
21932 this option) is required.
21933 The easiest way to build a 64bit application is to add
21934 @option{-m64 --RTS=m64} to the @command{gnatmake} flags.
21936 To debug these applications, dwarf-2 debug information is required, so you
21937 have to add @option{-gdwarf-2} to your gnatmake arguments.
21938 In addition, a special
21939 version of gdb, called @command{gdb64}, needs to be used.
21941 To summarize, building and debugging a ``Hello World'' program in 64-bit mode
21945 $ gnatmake -m64 -gdwarf-2 --RTS=m64 hello.adb
21949 @node IRIX-Specific Considerations
21950 @section IRIX-Specific Considerations
21951 @cindex IRIX thread library
21954 On SGI IRIX, the thread library depends on which compiler is used.
21955 The @emph{o32 ABI} compiler comes with a run-time library based on the
21956 user-level @code{athread}
21957 library. Thus kernel-level capabilities such as nonblocking system
21958 calls or time slicing can only be achieved reliably by specifying different
21959 @code{sprocs} via the pragma @code{Task_Info}
21960 @cindex pragma Task_Info (and IRIX threads)
21962 @code{System.Task_Info} package.
21963 @cindex @code{System.Task_Info} package (and IRIX threads)
21964 See the @cite{GNAT Reference Manual} for further information.
21966 The @emph{n32 ABI} compiler comes with a run-time library based on the
21967 kernel POSIX threads and thus does not have the limitations mentioned above.
21969 @node Linux-Specific Considerations
21970 @section Linux-Specific Considerations
21971 @cindex Linux threads libraries
21974 The default thread library under GNU/Linux has the following disadvantages
21975 compared to other native thread libraries:
21978 @item The size of the task's stack is limited to 2 megabytes.
21979 @item The signal model is not POSIX compliant, which means that to send a
21980 signal to the process, you need to send the signal to all threads,
21981 e.g. by using @code{killpg()}.
21984 @node AIX-Specific Considerations
21985 @section AIX-Specific Considerations
21986 @cindex AIX resolver library
21989 On AIX, the resolver library initializes some internal structure on
21990 the first call to @code{get*by*} functions, which are used to implement
21991 @code{GNAT.Sockets.Get_Host_By_Name} and
21992 @code{GNAT.Sockets.Get_Host_By_Addrss}.
21993 If such initialization occurs within an Ada task, and the stack size for
21994 the task is the default size, a stack overflow may occur.
21996 To avoid this overflow, the user should either ensure that the first call
21997 to @code{GNAT.Sockets.Get_Host_By_Name} or
21998 @code{GNAT.Sockets.Get_Host_By_Addrss}
21999 occurs in the environment task, or use @code{pragma Storage_Size} to
22000 specify a sufficiently large size for the stack of the task that contains
22003 @c *******************************
22004 @node Example of Binder Output File
22005 @appendix Example of Binder Output File
22008 This Appendix displays the source code for @command{gnatbind}'s output
22009 file generated for a simple ``Hello World'' program.
22010 Comments have been added for clarification purposes.
22012 @smallexample @c adanocomment
22016 -- The package is called Ada_Main unless this name is actually used
22017 -- as a unit name in the partition, in which case some other unique
22021 package ada_main is
22023 Elab_Final_Code : Integer;
22024 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
22026 -- The main program saves the parameters (argument count,
22027 -- argument values, environment pointer) in global variables
22028 -- for later access by other units including
22029 -- Ada.Command_Line.
22031 gnat_argc : Integer;
22032 gnat_argv : System.Address;
22033 gnat_envp : System.Address;
22035 -- The actual variables are stored in a library routine. This
22036 -- is useful for some shared library situations, where there
22037 -- are problems if variables are not in the library.
22039 pragma Import (C, gnat_argc);
22040 pragma Import (C, gnat_argv);
22041 pragma Import (C, gnat_envp);
22043 -- The exit status is similarly an external location
22045 gnat_exit_status : Integer;
22046 pragma Import (C, gnat_exit_status);
22048 GNAT_Version : constant String :=
22049 "GNAT Version: 3.15w (20010315)";
22050 pragma Export (C, GNAT_Version, "__gnat_version");
22052 -- This is the generated adafinal routine that performs
22053 -- finalization at the end of execution. In the case where
22054 -- Ada is the main program, this main program makes a call
22055 -- to adafinal at program termination.
22057 procedure adafinal;
22058 pragma Export (C, adafinal, "adafinal");
22060 -- This is the generated adainit routine that performs
22061 -- initialization at the start of execution. In the case
22062 -- where Ada is the main program, this main program makes
22063 -- a call to adainit at program startup.
22066 pragma Export (C, adainit, "adainit");
22068 -- This routine is called at the start of execution. It is
22069 -- a dummy routine that is used by the debugger to breakpoint
22070 -- at the start of execution.
22072 procedure Break_Start;
22073 pragma Import (C, Break_Start, "__gnat_break_start");
22075 -- This is the actual generated main program (it would be
22076 -- suppressed if the no main program switch were used). As
22077 -- required by standard system conventions, this program has
22078 -- the external name main.
22082 argv : System.Address;
22083 envp : System.Address)
22085 pragma Export (C, main, "main");
22087 -- The following set of constants give the version
22088 -- identification values for every unit in the bound
22089 -- partition. This identification is computed from all
22090 -- dependent semantic units, and corresponds to the
22091 -- string that would be returned by use of the
22092 -- Body_Version or Version attributes.
22094 type Version_32 is mod 2 ** 32;
22095 u00001 : constant Version_32 := 16#7880BEB3#;
22096 u00002 : constant Version_32 := 16#0D24CBD0#;
22097 u00003 : constant Version_32 := 16#3283DBEB#;
22098 u00004 : constant Version_32 := 16#2359F9ED#;
22099 u00005 : constant Version_32 := 16#664FB847#;
22100 u00006 : constant Version_32 := 16#68E803DF#;
22101 u00007 : constant Version_32 := 16#5572E604#;
22102 u00008 : constant Version_32 := 16#46B173D8#;
22103 u00009 : constant Version_32 := 16#156A40CF#;
22104 u00010 : constant Version_32 := 16#033DABE0#;
22105 u00011 : constant Version_32 := 16#6AB38FEA#;
22106 u00012 : constant Version_32 := 16#22B6217D#;
22107 u00013 : constant Version_32 := 16#68A22947#;
22108 u00014 : constant Version_32 := 16#18CC4A56#;
22109 u00015 : constant Version_32 := 16#08258E1B#;
22110 u00016 : constant Version_32 := 16#367D5222#;
22111 u00017 : constant Version_32 := 16#20C9ECA4#;
22112 u00018 : constant Version_32 := 16#50D32CB6#;
22113 u00019 : constant Version_32 := 16#39A8BB77#;
22114 u00020 : constant Version_32 := 16#5CF8FA2B#;
22115 u00021 : constant Version_32 := 16#2F1EB794#;
22116 u00022 : constant Version_32 := 16#31AB6444#;
22117 u00023 : constant Version_32 := 16#1574B6E9#;
22118 u00024 : constant Version_32 := 16#5109C189#;
22119 u00025 : constant Version_32 := 16#56D770CD#;
22120 u00026 : constant Version_32 := 16#02F9DE3D#;
22121 u00027 : constant Version_32 := 16#08AB6B2C#;
22122 u00028 : constant Version_32 := 16#3FA37670#;
22123 u00029 : constant Version_32 := 16#476457A0#;
22124 u00030 : constant Version_32 := 16#731E1B6E#;
22125 u00031 : constant Version_32 := 16#23C2E789#;
22126 u00032 : constant Version_32 := 16#0F1BD6A1#;
22127 u00033 : constant Version_32 := 16#7C25DE96#;
22128 u00034 : constant Version_32 := 16#39ADFFA2#;
22129 u00035 : constant Version_32 := 16#571DE3E7#;
22130 u00036 : constant Version_32 := 16#5EB646AB#;
22131 u00037 : constant Version_32 := 16#4249379B#;
22132 u00038 : constant Version_32 := 16#0357E00A#;
22133 u00039 : constant Version_32 := 16#3784FB72#;
22134 u00040 : constant Version_32 := 16#2E723019#;
22135 u00041 : constant Version_32 := 16#623358EA#;
22136 u00042 : constant Version_32 := 16#107F9465#;
22137 u00043 : constant Version_32 := 16#6843F68A#;
22138 u00044 : constant Version_32 := 16#63305874#;
22139 u00045 : constant Version_32 := 16#31E56CE1#;
22140 u00046 : constant Version_32 := 16#02917970#;
22141 u00047 : constant Version_32 := 16#6CCBA70E#;
22142 u00048 : constant Version_32 := 16#41CD4204#;
22143 u00049 : constant Version_32 := 16#572E3F58#;
22144 u00050 : constant Version_32 := 16#20729FF5#;
22145 u00051 : constant Version_32 := 16#1D4F93E8#;
22146 u00052 : constant Version_32 := 16#30B2EC3D#;
22147 u00053 : constant Version_32 := 16#34054F96#;
22148 u00054 : constant Version_32 := 16#5A199860#;
22149 u00055 : constant Version_32 := 16#0E7F912B#;
22150 u00056 : constant Version_32 := 16#5760634A#;
22151 u00057 : constant Version_32 := 16#5D851835#;
22153 -- The following Export pragmas export the version numbers
22154 -- with symbolic names ending in B (for body) or S
22155 -- (for spec) so that they can be located in a link. The
22156 -- information provided here is sufficient to track down
22157 -- the exact versions of units used in a given build.
22159 pragma Export (C, u00001, "helloB");
22160 pragma Export (C, u00002, "system__standard_libraryB");
22161 pragma Export (C, u00003, "system__standard_libraryS");
22162 pragma Export (C, u00004, "adaS");
22163 pragma Export (C, u00005, "ada__text_ioB");
22164 pragma Export (C, u00006, "ada__text_ioS");
22165 pragma Export (C, u00007, "ada__exceptionsB");
22166 pragma Export (C, u00008, "ada__exceptionsS");
22167 pragma Export (C, u00009, "gnatS");
22168 pragma Export (C, u00010, "gnat__heap_sort_aB");
22169 pragma Export (C, u00011, "gnat__heap_sort_aS");
22170 pragma Export (C, u00012, "systemS");
22171 pragma Export (C, u00013, "system__exception_tableB");
22172 pragma Export (C, u00014, "system__exception_tableS");
22173 pragma Export (C, u00015, "gnat__htableB");
22174 pragma Export (C, u00016, "gnat__htableS");
22175 pragma Export (C, u00017, "system__exceptionsS");
22176 pragma Export (C, u00018, "system__machine_state_operationsB");
22177 pragma Export (C, u00019, "system__machine_state_operationsS");
22178 pragma Export (C, u00020, "system__machine_codeS");
22179 pragma Export (C, u00021, "system__storage_elementsB");
22180 pragma Export (C, u00022, "system__storage_elementsS");
22181 pragma Export (C, u00023, "system__secondary_stackB");
22182 pragma Export (C, u00024, "system__secondary_stackS");
22183 pragma Export (C, u00025, "system__parametersB");
22184 pragma Export (C, u00026, "system__parametersS");
22185 pragma Export (C, u00027, "system__soft_linksB");
22186 pragma Export (C, u00028, "system__soft_linksS");
22187 pragma Export (C, u00029, "system__stack_checkingB");
22188 pragma Export (C, u00030, "system__stack_checkingS");
22189 pragma Export (C, u00031, "system__tracebackB");
22190 pragma Export (C, u00032, "system__tracebackS");
22191 pragma Export (C, u00033, "ada__streamsS");
22192 pragma Export (C, u00034, "ada__tagsB");
22193 pragma Export (C, u00035, "ada__tagsS");
22194 pragma Export (C, u00036, "system__string_opsB");
22195 pragma Export (C, u00037, "system__string_opsS");
22196 pragma Export (C, u00038, "interfacesS");
22197 pragma Export (C, u00039, "interfaces__c_streamsB");
22198 pragma Export (C, u00040, "interfaces__c_streamsS");
22199 pragma Export (C, u00041, "system__file_ioB");
22200 pragma Export (C, u00042, "system__file_ioS");
22201 pragma Export (C, u00043, "ada__finalizationB");
22202 pragma Export (C, u00044, "ada__finalizationS");
22203 pragma Export (C, u00045, "system__finalization_rootB");
22204 pragma Export (C, u00046, "system__finalization_rootS");
22205 pragma Export (C, u00047, "system__finalization_implementationB");
22206 pragma Export (C, u00048, "system__finalization_implementationS");
22207 pragma Export (C, u00049, "system__string_ops_concat_3B");
22208 pragma Export (C, u00050, "system__string_ops_concat_3S");
22209 pragma Export (C, u00051, "system__stream_attributesB");
22210 pragma Export (C, u00052, "system__stream_attributesS");
22211 pragma Export (C, u00053, "ada__io_exceptionsS");
22212 pragma Export (C, u00054, "system__unsigned_typesS");
22213 pragma Export (C, u00055, "system__file_control_blockS");
22214 pragma Export (C, u00056, "ada__finalization__list_controllerB");
22215 pragma Export (C, u00057, "ada__finalization__list_controllerS");
22217 -- BEGIN ELABORATION ORDER
22220 -- gnat.heap_sort_a (spec)
22221 -- gnat.heap_sort_a (body)
22222 -- gnat.htable (spec)
22223 -- gnat.htable (body)
22224 -- interfaces (spec)
22226 -- system.machine_code (spec)
22227 -- system.parameters (spec)
22228 -- system.parameters (body)
22229 -- interfaces.c_streams (spec)
22230 -- interfaces.c_streams (body)
22231 -- system.standard_library (spec)
22232 -- ada.exceptions (spec)
22233 -- system.exception_table (spec)
22234 -- system.exception_table (body)
22235 -- ada.io_exceptions (spec)
22236 -- system.exceptions (spec)
22237 -- system.storage_elements (spec)
22238 -- system.storage_elements (body)
22239 -- system.machine_state_operations (spec)
22240 -- system.machine_state_operations (body)
22241 -- system.secondary_stack (spec)
22242 -- system.stack_checking (spec)
22243 -- system.soft_links (spec)
22244 -- system.soft_links (body)
22245 -- system.stack_checking (body)
22246 -- system.secondary_stack (body)
22247 -- system.standard_library (body)
22248 -- system.string_ops (spec)
22249 -- system.string_ops (body)
22252 -- ada.streams (spec)
22253 -- system.finalization_root (spec)
22254 -- system.finalization_root (body)
22255 -- system.string_ops_concat_3 (spec)
22256 -- system.string_ops_concat_3 (body)
22257 -- system.traceback (spec)
22258 -- system.traceback (body)
22259 -- ada.exceptions (body)
22260 -- system.unsigned_types (spec)
22261 -- system.stream_attributes (spec)
22262 -- system.stream_attributes (body)
22263 -- system.finalization_implementation (spec)
22264 -- system.finalization_implementation (body)
22265 -- ada.finalization (spec)
22266 -- ada.finalization (body)
22267 -- ada.finalization.list_controller (spec)
22268 -- ada.finalization.list_controller (body)
22269 -- system.file_control_block (spec)
22270 -- system.file_io (spec)
22271 -- system.file_io (body)
22272 -- ada.text_io (spec)
22273 -- ada.text_io (body)
22275 -- END ELABORATION ORDER
22279 -- The following source file name pragmas allow the generated file
22280 -- names to be unique for different main programs. They are needed
22281 -- since the package name will always be Ada_Main.
22283 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
22284 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
22286 -- Generated package body for Ada_Main starts here
22288 package body ada_main is
22290 -- The actual finalization is performed by calling the
22291 -- library routine in System.Standard_Library.Adafinal
22293 procedure Do_Finalize;
22294 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
22301 procedure adainit is
22303 -- These booleans are set to True once the associated unit has
22304 -- been elaborated. It is also used to avoid elaborating the
22305 -- same unit twice.
22308 pragma Import (Ada, E040, "interfaces__c_streams_E");
22311 pragma Import (Ada, E008, "ada__exceptions_E");
22314 pragma Import (Ada, E014, "system__exception_table_E");
22317 pragma Import (Ada, E053, "ada__io_exceptions_E");
22320 pragma Import (Ada, E017, "system__exceptions_E");
22323 pragma Import (Ada, E024, "system__secondary_stack_E");
22326 pragma Import (Ada, E030, "system__stack_checking_E");
22329 pragma Import (Ada, E028, "system__soft_links_E");
22332 pragma Import (Ada, E035, "ada__tags_E");
22335 pragma Import (Ada, E033, "ada__streams_E");
22338 pragma Import (Ada, E046, "system__finalization_root_E");
22341 pragma Import (Ada, E048, "system__finalization_implementation_E");
22344 pragma Import (Ada, E044, "ada__finalization_E");
22347 pragma Import (Ada, E057, "ada__finalization__list_controller_E");
22350 pragma Import (Ada, E055, "system__file_control_block_E");
22353 pragma Import (Ada, E042, "system__file_io_E");
22356 pragma Import (Ada, E006, "ada__text_io_E");
22358 -- Set_Globals is a library routine that stores away the
22359 -- value of the indicated set of global values in global
22360 -- variables within the library.
22362 procedure Set_Globals
22363 (Main_Priority : Integer;
22364 Time_Slice_Value : Integer;
22365 WC_Encoding : Character;
22366 Locking_Policy : Character;
22367 Queuing_Policy : Character;
22368 Task_Dispatching_Policy : Character;
22369 Adafinal : System.Address;
22370 Unreserve_All_Interrupts : Integer;
22371 Exception_Tracebacks : Integer);
22372 @findex __gnat_set_globals
22373 pragma Import (C, Set_Globals, "__gnat_set_globals");
22375 -- SDP_Table_Build is a library routine used to build the
22376 -- exception tables. See unit Ada.Exceptions in files
22377 -- a-except.ads/adb for full details of how zero cost
22378 -- exception handling works. This procedure, the call to
22379 -- it, and the two following tables are all omitted if the
22380 -- build is in longjmp/setjump exception mode.
22382 @findex SDP_Table_Build
22383 @findex Zero Cost Exceptions
22384 procedure SDP_Table_Build
22385 (SDP_Addresses : System.Address;
22386 SDP_Count : Natural;
22387 Elab_Addresses : System.Address;
22388 Elab_Addr_Count : Natural);
22389 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22391 -- Table of Unit_Exception_Table addresses. Used for zero
22392 -- cost exception handling to build the top level table.
22394 ST : aliased constant array (1 .. 23) of System.Address := (
22396 Ada.Text_Io'UET_Address,
22397 Ada.Exceptions'UET_Address,
22398 Gnat.Heap_Sort_A'UET_Address,
22399 System.Exception_Table'UET_Address,
22400 System.Machine_State_Operations'UET_Address,
22401 System.Secondary_Stack'UET_Address,
22402 System.Parameters'UET_Address,
22403 System.Soft_Links'UET_Address,
22404 System.Stack_Checking'UET_Address,
22405 System.Traceback'UET_Address,
22406 Ada.Streams'UET_Address,
22407 Ada.Tags'UET_Address,
22408 System.String_Ops'UET_Address,
22409 Interfaces.C_Streams'UET_Address,
22410 System.File_Io'UET_Address,
22411 Ada.Finalization'UET_Address,
22412 System.Finalization_Root'UET_Address,
22413 System.Finalization_Implementation'UET_Address,
22414 System.String_Ops_Concat_3'UET_Address,
22415 System.Stream_Attributes'UET_Address,
22416 System.File_Control_Block'UET_Address,
22417 Ada.Finalization.List_Controller'UET_Address);
22419 -- Table of addresses of elaboration routines. Used for
22420 -- zero cost exception handling to make sure these
22421 -- addresses are included in the top level procedure
22424 EA : aliased constant array (1 .. 23) of System.Address := (
22425 adainit'Code_Address,
22426 Do_Finalize'Code_Address,
22427 Ada.Exceptions'Elab_Spec'Address,
22428 System.Exceptions'Elab_Spec'Address,
22429 Interfaces.C_Streams'Elab_Spec'Address,
22430 System.Exception_Table'Elab_Body'Address,
22431 Ada.Io_Exceptions'Elab_Spec'Address,
22432 System.Stack_Checking'Elab_Spec'Address,
22433 System.Soft_Links'Elab_Body'Address,
22434 System.Secondary_Stack'Elab_Body'Address,
22435 Ada.Tags'Elab_Spec'Address,
22436 Ada.Tags'Elab_Body'Address,
22437 Ada.Streams'Elab_Spec'Address,
22438 System.Finalization_Root'Elab_Spec'Address,
22439 Ada.Exceptions'Elab_Body'Address,
22440 System.Finalization_Implementation'Elab_Spec'Address,
22441 System.Finalization_Implementation'Elab_Body'Address,
22442 Ada.Finalization'Elab_Spec'Address,
22443 Ada.Finalization.List_Controller'Elab_Spec'Address,
22444 System.File_Control_Block'Elab_Spec'Address,
22445 System.File_Io'Elab_Body'Address,
22446 Ada.Text_Io'Elab_Spec'Address,
22447 Ada.Text_Io'Elab_Body'Address);
22449 -- Start of processing for adainit
22453 -- Call SDP_Table_Build to build the top level procedure
22454 -- table for zero cost exception handling (omitted in
22455 -- longjmp/setjump mode).
22457 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
22459 -- Call Set_Globals to record various information for
22460 -- this partition. The values are derived by the binder
22461 -- from information stored in the ali files by the compiler.
22463 @findex __gnat_set_globals
22465 (Main_Priority => -1,
22466 -- Priority of main program, -1 if no pragma Priority used
22468 Time_Slice_Value => -1,
22469 -- Time slice from Time_Slice pragma, -1 if none used
22471 WC_Encoding => 'b',
22472 -- Wide_Character encoding used, default is brackets
22474 Locking_Policy => ' ',
22475 -- Locking_Policy used, default of space means not
22476 -- specified, otherwise it is the first character of
22477 -- the policy name.
22479 Queuing_Policy => ' ',
22480 -- Queuing_Policy used, default of space means not
22481 -- specified, otherwise it is the first character of
22482 -- the policy name.
22484 Task_Dispatching_Policy => ' ',
22485 -- Task_Dispatching_Policy used, default of space means
22486 -- not specified, otherwise first character of the
22489 Adafinal => System.Null_Address,
22490 -- Address of Adafinal routine, not used anymore
22492 Unreserve_All_Interrupts => 0,
22493 -- Set true if pragma Unreserve_All_Interrupts was used
22495 Exception_Tracebacks => 0);
22496 -- Indicates if exception tracebacks are enabled
22498 Elab_Final_Code := 1;
22500 -- Now we have the elaboration calls for all units in the partition.
22501 -- The Elab_Spec and Elab_Body attributes generate references to the
22502 -- implicit elaboration procedures generated by the compiler for
22503 -- each unit that requires elaboration.
22506 Interfaces.C_Streams'Elab_Spec;
22510 Ada.Exceptions'Elab_Spec;
22513 System.Exception_Table'Elab_Body;
22517 Ada.Io_Exceptions'Elab_Spec;
22521 System.Exceptions'Elab_Spec;
22525 System.Stack_Checking'Elab_Spec;
22528 System.Soft_Links'Elab_Body;
22533 System.Secondary_Stack'Elab_Body;
22537 Ada.Tags'Elab_Spec;
22540 Ada.Tags'Elab_Body;
22544 Ada.Streams'Elab_Spec;
22548 System.Finalization_Root'Elab_Spec;
22552 Ada.Exceptions'Elab_Body;
22556 System.Finalization_Implementation'Elab_Spec;
22559 System.Finalization_Implementation'Elab_Body;
22563 Ada.Finalization'Elab_Spec;
22567 Ada.Finalization.List_Controller'Elab_Spec;
22571 System.File_Control_Block'Elab_Spec;
22575 System.File_Io'Elab_Body;
22579 Ada.Text_Io'Elab_Spec;
22582 Ada.Text_Io'Elab_Body;
22586 Elab_Final_Code := 0;
22594 procedure adafinal is
22603 -- main is actually a function, as in the ANSI C standard,
22604 -- defined to return the exit status. The three parameters
22605 -- are the argument count, argument values and environment
22608 @findex Main Program
22611 argv : System.Address;
22612 envp : System.Address)
22615 -- The initialize routine performs low level system
22616 -- initialization using a standard library routine which
22617 -- sets up signal handling and performs any other
22618 -- required setup. The routine can be found in file
22621 @findex __gnat_initialize
22622 procedure initialize;
22623 pragma Import (C, initialize, "__gnat_initialize");
22625 -- The finalize routine performs low level system
22626 -- finalization using a standard library routine. The
22627 -- routine is found in file a-final.c and in the standard
22628 -- distribution is a dummy routine that does nothing, so
22629 -- really this is a hook for special user finalization.
22631 @findex __gnat_finalize
22632 procedure finalize;
22633 pragma Import (C, finalize, "__gnat_finalize");
22635 -- We get to the main program of the partition by using
22636 -- pragma Import because if we try to with the unit and
22637 -- call it Ada style, then not only do we waste time
22638 -- recompiling it, but also, we don't really know the right
22639 -- switches (e.g. identifier character set) to be used
22642 procedure Ada_Main_Program;
22643 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
22645 -- Start of processing for main
22648 -- Save global variables
22654 -- Call low level system initialization
22658 -- Call our generated Ada initialization routine
22662 -- This is the point at which we want the debugger to get
22667 -- Now we call the main program of the partition
22671 -- Perform Ada finalization
22675 -- Perform low level system finalization
22679 -- Return the proper exit status
22680 return (gnat_exit_status);
22683 -- This section is entirely comments, so it has no effect on the
22684 -- compilation of the Ada_Main package. It provides the list of
22685 -- object files and linker options, as well as some standard
22686 -- libraries needed for the link. The gnatlink utility parses
22687 -- this b~hello.adb file to read these comment lines to generate
22688 -- the appropriate command line arguments for the call to the
22689 -- system linker. The BEGIN/END lines are used for sentinels for
22690 -- this parsing operation.
22692 -- The exact file names will of course depend on the environment,
22693 -- host/target and location of files on the host system.
22695 @findex Object file list
22696 -- BEGIN Object file/option list
22699 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
22700 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22701 -- END Object file/option list
22707 The Ada code in the above example is exactly what is generated by the
22708 binder. We have added comments to more clearly indicate the function
22709 of each part of the generated @code{Ada_Main} package.
22711 The code is standard Ada in all respects, and can be processed by any
22712 tools that handle Ada. In particular, it is possible to use the debugger
22713 in Ada mode to debug the generated @code{Ada_Main} package. For example,
22714 suppose that for reasons that you do not understand, your program is crashing
22715 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
22716 you can place a breakpoint on the call:
22718 @smallexample @c ada
22719 Ada.Text_Io'Elab_Body;
22723 and trace the elaboration routine for this package to find out where
22724 the problem might be (more usually of course you would be debugging
22725 elaboration code in your own application).
22727 @node Elaboration Order Handling in GNAT
22728 @appendix Elaboration Order Handling in GNAT
22729 @cindex Order of elaboration
22730 @cindex Elaboration control
22733 * Elaboration Code in Ada 95::
22734 * Checking the Elaboration Order in Ada 95::
22735 * Controlling the Elaboration Order in Ada 95::
22736 * Controlling Elaboration in GNAT - Internal Calls::
22737 * Controlling Elaboration in GNAT - External Calls::
22738 * Default Behavior in GNAT - Ensuring Safety::
22739 * Treatment of Pragma Elaborate::
22740 * Elaboration Issues for Library Tasks::
22741 * Mixing Elaboration Models::
22742 * What to Do If the Default Elaboration Behavior Fails::
22743 * Elaboration for Access-to-Subprogram Values::
22744 * Summary of Procedures for Elaboration Control::
22745 * Other Elaboration Order Considerations::
22749 This chapter describes the handling of elaboration code in Ada 95 and
22750 in GNAT, and discusses how the order of elaboration of program units can
22751 be controlled in GNAT, either automatically or with explicit programming
22754 @node Elaboration Code in Ada 95
22755 @section Elaboration Code in Ada 95
22758 Ada 95 provides rather general mechanisms for executing code at elaboration
22759 time, that is to say before the main program starts executing. Such code arises
22763 @item Initializers for variables.
22764 Variables declared at the library level, in package specs or bodies, can
22765 require initialization that is performed at elaboration time, as in:
22766 @smallexample @c ada
22768 Sqrt_Half : Float := Sqrt (0.5);
22772 @item Package initialization code
22773 Code in a @code{BEGIN-END} section at the outer level of a package body is
22774 executed as part of the package body elaboration code.
22776 @item Library level task allocators
22777 Tasks that are declared using task allocators at the library level
22778 start executing immediately and hence can execute at elaboration time.
22782 Subprogram calls are possible in any of these contexts, which means that
22783 any arbitrary part of the program may be executed as part of the elaboration
22784 code. It is even possible to write a program which does all its work at
22785 elaboration time, with a null main program, although stylistically this
22786 would usually be considered an inappropriate way to structure
22789 An important concern arises in the context of elaboration code:
22790 we have to be sure that it is executed in an appropriate order. What we
22791 have is a series of elaboration code sections, potentially one section
22792 for each unit in the program. It is important that these execute
22793 in the correct order. Correctness here means that, taking the above
22794 example of the declaration of @code{Sqrt_Half},
22795 if some other piece of
22796 elaboration code references @code{Sqrt_Half},
22797 then it must run after the
22798 section of elaboration code that contains the declaration of
22801 There would never be any order of elaboration problem if we made a rule
22802 that whenever you @code{with} a unit, you must elaborate both the spec and body
22803 of that unit before elaborating the unit doing the @code{with}'ing:
22805 @smallexample @c ada
22809 package Unit_2 is ...
22815 would require that both the body and spec of @code{Unit_1} be elaborated
22816 before the spec of @code{Unit_2}. However, a rule like that would be far too
22817 restrictive. In particular, it would make it impossible to have routines
22818 in separate packages that were mutually recursive.
22820 You might think that a clever enough compiler could look at the actual
22821 elaboration code and determine an appropriate correct order of elaboration,
22822 but in the general case, this is not possible. Consider the following
22825 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
22827 the variable @code{Sqrt_1}, which is declared in the elaboration code
22828 of the body of @code{Unit_1}:
22830 @smallexample @c ada
22832 Sqrt_1 : Float := Sqrt (0.1);
22837 The elaboration code of the body of @code{Unit_1} also contains:
22839 @smallexample @c ada
22842 if expression_1 = 1 then
22843 Q := Unit_2.Func_2;
22850 @code{Unit_2} is exactly parallel,
22851 it has a procedure @code{Func_2} that references
22852 the variable @code{Sqrt_2}, which is declared in the elaboration code of
22853 the body @code{Unit_2}:
22855 @smallexample @c ada
22857 Sqrt_2 : Float := Sqrt (0.1);
22862 The elaboration code of the body of @code{Unit_2} also contains:
22864 @smallexample @c ada
22867 if expression_2 = 2 then
22868 Q := Unit_1.Func_1;
22875 Now the question is, which of the following orders of elaboration is
22900 If you carefully analyze the flow here, you will see that you cannot tell
22901 at compile time the answer to this question.
22902 If @code{expression_1} is not equal to 1,
22903 and @code{expression_2} is not equal to 2,
22904 then either order is acceptable, because neither of the function calls is
22905 executed. If both tests evaluate to true, then neither order is acceptable
22906 and in fact there is no correct order.
22908 If one of the two expressions is true, and the other is false, then one
22909 of the above orders is correct, and the other is incorrect. For example,
22910 if @code{expression_1} = 1 and @code{expression_2} /= 2,
22911 then the call to @code{Func_2}
22912 will occur, but not the call to @code{Func_1.}
22913 This means that it is essential
22914 to elaborate the body of @code{Unit_1} before
22915 the body of @code{Unit_2}, so the first
22916 order of elaboration is correct and the second is wrong.
22918 By making @code{expression_1} and @code{expression_2}
22919 depend on input data, or perhaps
22920 the time of day, we can make it impossible for the compiler or binder
22921 to figure out which of these expressions will be true, and hence it
22922 is impossible to guarantee a safe order of elaboration at run time.
22924 @node Checking the Elaboration Order in Ada 95
22925 @section Checking the Elaboration Order in Ada 95
22928 In some languages that involve the same kind of elaboration problems,
22929 e.g. Java and C++, the programmer is expected to worry about these
22930 ordering problems himself, and it is common to
22931 write a program in which an incorrect elaboration order gives
22932 surprising results, because it references variables before they
22934 Ada 95 is designed to be a safe language, and a programmer-beware approach is
22935 clearly not sufficient. Consequently, the language provides three lines
22939 @item Standard rules
22940 Some standard rules restrict the possible choice of elaboration
22941 order. In particular, if you @code{with} a unit, then its spec is always
22942 elaborated before the unit doing the @code{with}. Similarly, a parent
22943 spec is always elaborated before the child spec, and finally
22944 a spec is always elaborated before its corresponding body.
22946 @item Dynamic elaboration checks
22947 @cindex Elaboration checks
22948 @cindex Checks, elaboration
22949 Dynamic checks are made at run time, so that if some entity is accessed
22950 before it is elaborated (typically by means of a subprogram call)
22951 then the exception (@code{Program_Error}) is raised.
22953 @item Elaboration control
22954 Facilities are provided for the programmer to specify the desired order
22958 Let's look at these facilities in more detail. First, the rules for
22959 dynamic checking. One possible rule would be simply to say that the
22960 exception is raised if you access a variable which has not yet been
22961 elaborated. The trouble with this approach is that it could require
22962 expensive checks on every variable reference. Instead Ada 95 has two
22963 rules which are a little more restrictive, but easier to check, and
22967 @item Restrictions on calls
22968 A subprogram can only be called at elaboration time if its body
22969 has been elaborated. The rules for elaboration given above guarantee
22970 that the spec of the subprogram has been elaborated before the
22971 call, but not the body. If this rule is violated, then the
22972 exception @code{Program_Error} is raised.
22974 @item Restrictions on instantiations
22975 A generic unit can only be instantiated if the body of the generic
22976 unit has been elaborated. Again, the rules for elaboration given above
22977 guarantee that the spec of the generic unit has been elaborated
22978 before the instantiation, but not the body. If this rule is
22979 violated, then the exception @code{Program_Error} is raised.
22983 The idea is that if the body has been elaborated, then any variables
22984 it references must have been elaborated; by checking for the body being
22985 elaborated we guarantee that none of its references causes any
22986 trouble. As we noted above, this is a little too restrictive, because a
22987 subprogram that has no non-local references in its body may in fact be safe
22988 to call. However, it really would be unsafe to rely on this, because
22989 it would mean that the caller was aware of details of the implementation
22990 in the body. This goes against the basic tenets of Ada.
22992 A plausible implementation can be described as follows.
22993 A Boolean variable is associated with each subprogram
22994 and each generic unit. This variable is initialized to False, and is set to
22995 True at the point body is elaborated. Every call or instantiation checks the
22996 variable, and raises @code{Program_Error} if the variable is False.
22998 Note that one might think that it would be good enough to have one Boolean
22999 variable for each package, but that would not deal with cases of trying
23000 to call a body in the same package as the call
23001 that has not been elaborated yet.
23002 Of course a compiler may be able to do enough analysis to optimize away
23003 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
23004 does such optimizations, but still the easiest conceptual model is to
23005 think of there being one variable per subprogram.
23007 @node Controlling the Elaboration Order in Ada 95
23008 @section Controlling the Elaboration Order in Ada 95
23011 In the previous section we discussed the rules in Ada 95 which ensure
23012 that @code{Program_Error} is raised if an incorrect elaboration order is
23013 chosen. This prevents erroneous executions, but we need mechanisms to
23014 specify a correct execution and avoid the exception altogether.
23015 To achieve this, Ada 95 provides a number of features for controlling
23016 the order of elaboration. We discuss these features in this section.
23018 First, there are several ways of indicating to the compiler that a given
23019 unit has no elaboration problems:
23022 @item packages that do not require a body
23023 In Ada 95, a library package that does not require a body does not permit
23024 a body. This means that if we have a such a package, as in:
23026 @smallexample @c ada
23029 package Definitions is
23031 type m is new integer;
23033 type a is array (1 .. 10) of m;
23034 type b is array (1 .. 20) of m;
23042 A package that @code{with}'s @code{Definitions} may safely instantiate
23043 @code{Definitions.Subp} because the compiler can determine that there
23044 definitely is no package body to worry about in this case
23047 @cindex pragma Pure
23049 Places sufficient restrictions on a unit to guarantee that
23050 no call to any subprogram in the unit can result in an
23051 elaboration problem. This means that the compiler does not need
23052 to worry about the point of elaboration of such units, and in
23053 particular, does not need to check any calls to any subprograms
23056 @item pragma Preelaborate
23057 @findex Preelaborate
23058 @cindex pragma Preelaborate
23059 This pragma places slightly less stringent restrictions on a unit than
23061 but these restrictions are still sufficient to ensure that there
23062 are no elaboration problems with any calls to the unit.
23064 @item pragma Elaborate_Body
23065 @findex Elaborate_Body
23066 @cindex pragma Elaborate_Body
23067 This pragma requires that the body of a unit be elaborated immediately
23068 after its spec. Suppose a unit @code{A} has such a pragma,
23069 and unit @code{B} does
23070 a @code{with} of unit @code{A}. Recall that the standard rules require
23071 the spec of unit @code{A}
23072 to be elaborated before the @code{with}'ing unit; given the pragma in
23073 @code{A}, we also know that the body of @code{A}
23074 will be elaborated before @code{B}, so
23075 that calls to @code{A} are safe and do not need a check.
23080 unlike pragma @code{Pure} and pragma @code{Preelaborate},
23082 @code{Elaborate_Body} does not guarantee that the program is
23083 free of elaboration problems, because it may not be possible
23084 to satisfy the requested elaboration order.
23085 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
23087 marks @code{Unit_1} as @code{Elaborate_Body},
23088 and not @code{Unit_2,} then the order of
23089 elaboration will be:
23101 Now that means that the call to @code{Func_1} in @code{Unit_2}
23102 need not be checked,
23103 it must be safe. But the call to @code{Func_2} in
23104 @code{Unit_1} may still fail if
23105 @code{Expression_1} is equal to 1,
23106 and the programmer must still take
23107 responsibility for this not being the case.
23109 If all units carry a pragma @code{Elaborate_Body}, then all problems are
23110 eliminated, except for calls entirely within a body, which are
23111 in any case fully under programmer control. However, using the pragma
23112 everywhere is not always possible.
23113 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
23114 we marked both of them as having pragma @code{Elaborate_Body}, then
23115 clearly there would be no possible elaboration order.
23117 The above pragmas allow a server to guarantee safe use by clients, and
23118 clearly this is the preferable approach. Consequently a good rule in
23119 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
23120 and if this is not possible,
23121 mark them as @code{Elaborate_Body} if possible.
23122 As we have seen, there are situations where neither of these
23123 three pragmas can be used.
23124 So we also provide methods for clients to control the
23125 order of elaboration of the servers on which they depend:
23128 @item pragma Elaborate (unit)
23130 @cindex pragma Elaborate
23131 This pragma is placed in the context clause, after a @code{with} clause,
23132 and it requires that the body of the named unit be elaborated before
23133 the unit in which the pragma occurs. The idea is to use this pragma
23134 if the current unit calls at elaboration time, directly or indirectly,
23135 some subprogram in the named unit.
23137 @item pragma Elaborate_All (unit)
23138 @findex Elaborate_All
23139 @cindex pragma Elaborate_All
23140 This is a stronger version of the Elaborate pragma. Consider the
23144 Unit A @code{with}'s unit B and calls B.Func in elab code
23145 Unit B @code{with}'s unit C, and B.Func calls C.Func
23149 Now if we put a pragma @code{Elaborate (B)}
23150 in unit @code{A}, this ensures that the
23151 body of @code{B} is elaborated before the call, but not the
23152 body of @code{C}, so
23153 the call to @code{C.Func} could still cause @code{Program_Error} to
23156 The effect of a pragma @code{Elaborate_All} is stronger, it requires
23157 not only that the body of the named unit be elaborated before the
23158 unit doing the @code{with}, but also the bodies of all units that the
23159 named unit uses, following @code{with} links transitively. For example,
23160 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
23162 not only that the body of @code{B} be elaborated before @code{A},
23164 body of @code{C}, because @code{B} @code{with}'s @code{C}.
23168 We are now in a position to give a usage rule in Ada 95 for avoiding
23169 elaboration problems, at least if dynamic dispatching and access to
23170 subprogram values are not used. We will handle these cases separately
23173 The rule is simple. If a unit has elaboration code that can directly or
23174 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
23175 a generic unit in a @code{with}'ed unit,
23176 then if the @code{with}'ed unit does not have
23177 pragma @code{Pure} or @code{Preelaborate}, then the client should have
23178 a pragma @code{Elaborate_All}
23179 for the @code{with}'ed unit. By following this rule a client is
23180 assured that calls can be made without risk of an exception.
23181 If this rule is not followed, then a program may be in one of four
23185 @item No order exists
23186 No order of elaboration exists which follows the rules, taking into
23187 account any @code{Elaborate}, @code{Elaborate_All},
23188 or @code{Elaborate_Body} pragmas. In
23189 this case, an Ada 95 compiler must diagnose the situation at bind
23190 time, and refuse to build an executable program.
23192 @item One or more orders exist, all incorrect
23193 One or more acceptable elaboration orders exists, and all of them
23194 generate an elaboration order problem. In this case, the binder
23195 can build an executable program, but @code{Program_Error} will be raised
23196 when the program is run.
23198 @item Several orders exist, some right, some incorrect
23199 One or more acceptable elaboration orders exists, and some of them
23200 work, and some do not. The programmer has not controlled
23201 the order of elaboration, so the binder may or may not pick one of
23202 the correct orders, and the program may or may not raise an
23203 exception when it is run. This is the worst case, because it means
23204 that the program may fail when moved to another compiler, or even
23205 another version of the same compiler.
23207 @item One or more orders exists, all correct
23208 One ore more acceptable elaboration orders exist, and all of them
23209 work. In this case the program runs successfully. This state of
23210 affairs can be guaranteed by following the rule we gave above, but
23211 may be true even if the rule is not followed.
23215 Note that one additional advantage of following our Elaborate_All rule
23216 is that the program continues to stay in the ideal (all orders OK) state
23217 even if maintenance
23218 changes some bodies of some subprograms. Conversely, if a program that does
23219 not follow this rule happens to be safe at some point, this state of affairs
23220 may deteriorate silently as a result of maintenance changes.
23222 You may have noticed that the above discussion did not mention
23223 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
23224 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
23225 code in the body makes calls to some other unit, so it is still necessary
23226 to use @code{Elaborate_All} on such units.
23228 @node Controlling Elaboration in GNAT - Internal Calls
23229 @section Controlling Elaboration in GNAT - Internal Calls
23232 In the case of internal calls, i.e. calls within a single package, the
23233 programmer has full control over the order of elaboration, and it is up
23234 to the programmer to elaborate declarations in an appropriate order. For
23237 @smallexample @c ada
23240 function One return Float;
23244 function One return Float is
23253 will obviously raise @code{Program_Error} at run time, because function
23254 One will be called before its body is elaborated. In this case GNAT will
23255 generate a warning that the call will raise @code{Program_Error}:
23261 2. function One return Float;
23263 4. Q : Float := One;
23265 >>> warning: cannot call "One" before body is elaborated
23266 >>> warning: Program_Error will be raised at run time
23269 6. function One return Float is
23282 Note that in this particular case, it is likely that the call is safe, because
23283 the function @code{One} does not access any global variables.
23284 Nevertheless in Ada 95, we do not want the validity of the check to depend on
23285 the contents of the body (think about the separate compilation case), so this
23286 is still wrong, as we discussed in the previous sections.
23288 The error is easily corrected by rearranging the declarations so that the
23289 body of One appears before the declaration containing the call
23290 (note that in Ada 95,
23291 declarations can appear in any order, so there is no restriction that
23292 would prevent this reordering, and if we write:
23294 @smallexample @c ada
23297 function One return Float;
23299 function One return Float is
23310 then all is well, no warning is generated, and no
23311 @code{Program_Error} exception
23313 Things are more complicated when a chain of subprograms is executed:
23315 @smallexample @c ada
23318 function A return Integer;
23319 function B return Integer;
23320 function C return Integer;
23322 function B return Integer is begin return A; end;
23323 function C return Integer is begin return B; end;
23327 function A return Integer is begin return 1; end;
23333 Now the call to @code{C}
23334 at elaboration time in the declaration of @code{X} is correct, because
23335 the body of @code{C} is already elaborated,
23336 and the call to @code{B} within the body of
23337 @code{C} is correct, but the call
23338 to @code{A} within the body of @code{B} is incorrect, because the body
23339 of @code{A} has not been elaborated, so @code{Program_Error}
23340 will be raised on the call to @code{A}.
23341 In this case GNAT will generate a
23342 warning that @code{Program_Error} may be
23343 raised at the point of the call. Let's look at the warning:
23349 2. function A return Integer;
23350 3. function B return Integer;
23351 4. function C return Integer;
23353 6. function B return Integer is begin return A; end;
23355 >>> warning: call to "A" before body is elaborated may
23356 raise Program_Error
23357 >>> warning: "B" called at line 7
23358 >>> warning: "C" called at line 9
23360 7. function C return Integer is begin return B; end;
23362 9. X : Integer := C;
23364 11. function A return Integer is begin return 1; end;
23374 Note that the message here says ``may raise'', instead of the direct case,
23375 where the message says ``will be raised''. That's because whether
23377 actually called depends in general on run-time flow of control.
23378 For example, if the body of @code{B} said
23380 @smallexample @c ada
23383 function B return Integer is
23385 if some-condition-depending-on-input-data then
23396 then we could not know until run time whether the incorrect call to A would
23397 actually occur, so @code{Program_Error} might
23398 or might not be raised. It is possible for a compiler to
23399 do a better job of analyzing bodies, to
23400 determine whether or not @code{Program_Error}
23401 might be raised, but it certainly
23402 couldn't do a perfect job (that would require solving the halting problem
23403 and is provably impossible), and because this is a warning anyway, it does
23404 not seem worth the effort to do the analysis. Cases in which it
23405 would be relevant are rare.
23407 In practice, warnings of either of the forms given
23408 above will usually correspond to
23409 real errors, and should be examined carefully and eliminated.
23410 In the rare case where a warning is bogus, it can be suppressed by any of
23411 the following methods:
23415 Compile with the @option{-gnatws} switch set
23418 Suppress @code{Elaboration_Check} for the called subprogram
23421 Use pragma @code{Warnings_Off} to turn warnings off for the call
23425 For the internal elaboration check case,
23426 GNAT by default generates the
23427 necessary run-time checks to ensure
23428 that @code{Program_Error} is raised if any
23429 call fails an elaboration check. Of course this can only happen if a
23430 warning has been issued as described above. The use of pragma
23431 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23432 some of these checks, meaning that it may be possible (but is not
23433 guaranteed) for a program to be able to call a subprogram whose body
23434 is not yet elaborated, without raising a @code{Program_Error} exception.
23436 @node Controlling Elaboration in GNAT - External Calls
23437 @section Controlling Elaboration in GNAT - External Calls
23440 The previous section discussed the case in which the execution of a
23441 particular thread of elaboration code occurred entirely within a
23442 single unit. This is the easy case to handle, because a programmer
23443 has direct and total control over the order of elaboration, and
23444 furthermore, checks need only be generated in cases which are rare
23445 and which the compiler can easily detect.
23446 The situation is more complex when separate compilation is taken into account.
23447 Consider the following:
23449 @smallexample @c ada
23453 function Sqrt (Arg : Float) return Float;
23456 package body Math is
23457 function Sqrt (Arg : Float) return Float is
23466 X : Float := Math.Sqrt (0.5);
23479 where @code{Main} is the main program. When this program is executed, the
23480 elaboration code must first be executed, and one of the jobs of the
23481 binder is to determine the order in which the units of a program are
23482 to be elaborated. In this case we have four units: the spec and body
23484 the spec of @code{Stuff} and the body of @code{Main}).
23485 In what order should the four separate sections of elaboration code
23488 There are some restrictions in the order of elaboration that the binder
23489 can choose. In particular, if unit U has a @code{with}
23490 for a package @code{X}, then you
23491 are assured that the spec of @code{X}
23492 is elaborated before U , but you are
23493 not assured that the body of @code{X}
23494 is elaborated before U.
23495 This means that in the above case, the binder is allowed to choose the
23506 but that's not good, because now the call to @code{Math.Sqrt}
23507 that happens during
23508 the elaboration of the @code{Stuff}
23509 spec happens before the body of @code{Math.Sqrt} is
23510 elaborated, and hence causes @code{Program_Error} exception to be raised.
23511 At first glance, one might say that the binder is misbehaving, because
23512 obviously you want to elaborate the body of something you @code{with}
23514 that is not a general rule that can be followed in all cases. Consider
23516 @smallexample @c ada
23524 package body Y is ...
23527 package body X is ...
23533 This is a common arrangement, and, apart from the order of elaboration
23534 problems that might arise in connection with elaboration code, this works fine.
23535 A rule that says that you must first elaborate the body of anything you
23536 @code{with} cannot work in this case:
23537 the body of @code{X} @code{with}'s @code{Y},
23538 which means you would have to
23539 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
23541 you have to elaborate the body of @code{X} first, but ... and we have a
23542 loop that cannot be broken.
23544 It is true that the binder can in many cases guess an order of elaboration
23545 that is unlikely to cause a @code{Program_Error}
23546 exception to be raised, and it tries to do so (in the
23547 above example of @code{Math/Stuff/Spec}, the GNAT binder will
23549 elaborate the body of @code{Math} right after its spec, so all will be well).
23551 However, a program that blindly relies on the binder to be helpful can
23552 get into trouble, as we discussed in the previous sections, so
23554 provides a number of facilities for assisting the programmer in
23555 developing programs that are robust with respect to elaboration order.
23557 @node Default Behavior in GNAT - Ensuring Safety
23558 @section Default Behavior in GNAT - Ensuring Safety
23561 The default behavior in GNAT ensures elaboration safety. In its
23562 default mode GNAT implements the
23563 rule we previously described as the right approach. Let's restate it:
23567 @emph{If a unit has elaboration code that can directly or indirectly make a
23568 call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit
23569 in a @code{with}'ed unit, then if the @code{with}'ed unit
23570 does not have pragma @code{Pure} or
23571 @code{Preelaborate}, then the client should have an
23572 @code{Elaborate_All} for the @code{with}'ed unit.}
23576 By following this rule a client is assured that calls and instantiations
23577 can be made without risk of an exception.
23579 In this mode GNAT traces all calls that are potentially made from
23580 elaboration code, and puts in any missing implicit @code{Elaborate_All}
23582 The advantage of this approach is that no elaboration problems
23583 are possible if the binder can find an elaboration order that is
23584 consistent with these implicit @code{Elaborate_All} pragmas. The
23585 disadvantage of this approach is that no such order may exist.
23587 If the binder does not generate any diagnostics, then it means that it
23588 has found an elaboration order that is guaranteed to be safe. However,
23589 the binder may still be relying on implicitly generated
23590 @code{Elaborate_All} pragmas so portability to other compilers than
23591 GNAT is not guaranteed.
23593 If it is important to guarantee portability, then the compilations should
23596 (warn on elaboration problems) switch. This will cause warning messages
23597 to be generated indicating the missing @code{Elaborate_All} pragmas.
23598 Consider the following source program:
23600 @smallexample @c ada
23605 m : integer := k.r;
23612 where it is clear that there
23613 should be a pragma @code{Elaborate_All}
23614 for unit @code{k}. An implicit pragma will be generated, and it is
23615 likely that the binder will be able to honor it. However, if you want
23616 to port this program to some other Ada compiler than GNAT.
23617 it is safer to include the pragma explicitly in the source. If this
23618 unit is compiled with the
23620 switch, then the compiler outputs a warning:
23627 3. m : integer := k.r;
23629 >>> warning: call to "r" may raise Program_Error
23630 >>> warning: missing pragma Elaborate_All for "k"
23638 and these warnings can be used as a guide for supplying manually
23639 the missing pragmas. It is usually a bad idea to use this warning
23640 option during development. That's because it will warn you when
23641 you need to put in a pragma, but cannot warn you when it is time
23642 to take it out. So the use of pragma Elaborate_All may lead to
23643 unnecessary dependencies and even false circularities.
23645 This default mode is more restrictive than the Ada Reference
23646 Manual, and it is possible to construct programs which will compile
23647 using the dynamic model described there, but will run into a
23648 circularity using the safer static model we have described.
23650 Of course any Ada compiler must be able to operate in a mode
23651 consistent with the requirements of the Ada Reference Manual,
23652 and in particular must have the capability of implementing the
23653 standard dynamic model of elaboration with run-time checks.
23655 In GNAT, this standard mode can be achieved either by the use of
23656 the @option{-gnatE} switch on the compiler (@code{gcc} or @code{gnatmake})
23657 command, or by the use of the configuration pragma:
23659 @smallexample @c ada
23660 pragma Elaboration_Checks (RM);
23664 Either approach will cause the unit affected to be compiled using the
23665 standard dynamic run-time elaboration checks described in the Ada
23666 Reference Manual. The static model is generally preferable, since it
23667 is clearly safer to rely on compile and link time checks rather than
23668 run-time checks. However, in the case of legacy code, it may be
23669 difficult to meet the requirements of the static model. This
23670 issue is further discussed in
23671 @ref{What to Do If the Default Elaboration Behavior Fails}.
23673 Note that the static model provides a strict subset of the allowed
23674 behavior and programs of the Ada Reference Manual, so if you do
23675 adhere to the static model and no circularities exist,
23676 then you are assured that your program will
23677 work using the dynamic model, providing that you remove any
23678 pragma Elaborate statements from the source.
23680 @node Treatment of Pragma Elaborate
23681 @section Treatment of Pragma Elaborate
23682 @cindex Pragma Elaborate
23685 The use of @code{pragma Elaborate}
23686 should generally be avoided in Ada 95 programs.
23687 The reason for this is that there is no guarantee that transitive calls
23688 will be properly handled. Indeed at one point, this pragma was placed
23689 in Annex J (Obsolescent Features), on the grounds that it is never useful.
23691 Now that's a bit restrictive. In practice, the case in which
23692 @code{pragma Elaborate} is useful is when the caller knows that there
23693 are no transitive calls, or that the called unit contains all necessary
23694 transitive @code{pragma Elaborate} statements, and legacy code often
23695 contains such uses.
23697 Strictly speaking the static mode in GNAT should ignore such pragmas,
23698 since there is no assurance at compile time that the necessary safety
23699 conditions are met. In practice, this would cause GNAT to be incompatible
23700 with correctly written Ada 83 code that had all necessary
23701 @code{pragma Elaborate} statements in place. Consequently, we made the
23702 decision that GNAT in its default mode will believe that if it encounters
23703 a @code{pragma Elaborate} then the programmer knows what they are doing,
23704 and it will trust that no elaboration errors can occur.
23706 The result of this decision is two-fold. First to be safe using the
23707 static mode, you should remove all @code{pragma Elaborate} statements.
23708 Second, when fixing circularities in existing code, you can selectively
23709 use @code{pragma Elaborate} statements to convince the static mode of
23710 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
23713 When using the static mode with @option{-gnatwl}, any use of
23714 @code{pragma Elaborate} will generate a warning about possible
23717 @node Elaboration Issues for Library Tasks
23718 @section Elaboration Issues for Library Tasks
23719 @cindex Library tasks, elaboration issues
23720 @cindex Elaboration of library tasks
23723 In this section we examine special elaboration issues that arise for
23724 programs that declare library level tasks.
23726 Generally the model of execution of an Ada program is that all units are
23727 elaborated, and then execution of the program starts. However, the
23728 declaration of library tasks definitely does not fit this model. The
23729 reason for this is that library tasks start as soon as they are declared
23730 (more precisely, as soon as the statement part of the enclosing package
23731 body is reached), that is to say before elaboration
23732 of the program is complete. This means that if such a task calls a
23733 subprogram, or an entry in another task, the callee may or may not be
23734 elaborated yet, and in the standard
23735 Reference Manual model of dynamic elaboration checks, you can even
23736 get timing dependent Program_Error exceptions, since there can be
23737 a race between the elaboration code and the task code.
23739 The static model of elaboration in GNAT seeks to avoid all such
23740 dynamic behavior, by being conservative, and the conservative
23741 approach in this particular case is to assume that all the code
23742 in a task body is potentially executed at elaboration time if
23743 a task is declared at the library level.
23745 This can definitely result in unexpected circularities. Consider
23746 the following example
23748 @smallexample @c ada
23754 type My_Int is new Integer;
23756 function Ident (M : My_Int) return My_Int;
23760 package body Decls is
23761 task body Lib_Task is
23767 function Ident (M : My_Int) return My_Int is
23775 procedure Put_Val (Arg : Decls.My_Int);
23779 package body Utils is
23780 procedure Put_Val (Arg : Decls.My_Int) is
23782 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23789 Decls.Lib_Task.Start;
23794 If the above example is compiled in the default static elaboration
23795 mode, then a circularity occurs. The circularity comes from the call
23796 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
23797 this call occurs in elaboration code, we need an implicit pragma
23798 @code{Elaborate_All} for @code{Utils}. This means that not only must
23799 the spec and body of @code{Utils} be elaborated before the body
23800 of @code{Decls}, but also the spec and body of any unit that is
23801 @code{with'ed} by the body of @code{Utils} must also be elaborated before
23802 the body of @code{Decls}. This is the transitive implication of
23803 pragma @code{Elaborate_All} and it makes sense, because in general
23804 the body of @code{Put_Val} might have a call to something in a
23805 @code{with'ed} unit.
23807 In this case, the body of Utils (actually its spec) @code{with's}
23808 @code{Decls}. Unfortunately this means that the body of @code{Decls}
23809 must be elaborated before itself, in case there is a call from the
23810 body of @code{Utils}.
23812 Here is the exact chain of events we are worrying about:
23816 In the body of @code{Decls} a call is made from within the body of a library
23817 task to a subprogram in the package @code{Utils}. Since this call may
23818 occur at elaboration time (given that the task is activated at elaboration
23819 time), we have to assume the worst, i.e. that the
23820 call does happen at elaboration time.
23823 This means that the body and spec of @code{Util} must be elaborated before
23824 the body of @code{Decls} so that this call does not cause an access before
23828 Within the body of @code{Util}, specifically within the body of
23829 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
23833 One such @code{with}'ed package is package @code{Decls}, so there
23834 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
23835 In fact there is such a call in this example, but we would have to
23836 assume that there was such a call even if it were not there, since
23837 we are not supposed to write the body of @code{Decls} knowing what
23838 is in the body of @code{Utils}; certainly in the case of the
23839 static elaboration model, the compiler does not know what is in
23840 other bodies and must assume the worst.
23843 This means that the spec and body of @code{Decls} must also be
23844 elaborated before we elaborate the unit containing the call, but
23845 that unit is @code{Decls}! This means that the body of @code{Decls}
23846 must be elaborated before itself, and that's a circularity.
23850 Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in
23851 the body of @code{Decls} you will get a true Ada Reference Manual
23852 circularity that makes the program illegal.
23854 In practice, we have found that problems with the static model of
23855 elaboration in existing code often arise from library tasks, so
23856 we must address this particular situation.
23858 Note that if we compile and run the program above, using the dynamic model of
23859 elaboration (that is to say use the @option{-gnatE} switch),
23860 then it compiles, binds,
23861 links, and runs, printing the expected result of 2. Therefore in some sense
23862 the circularity here is only apparent, and we need to capture
23863 the properties of this program that distinguish it from other library-level
23864 tasks that have real elaboration problems.
23866 We have four possible answers to this question:
23871 Use the dynamic model of elaboration.
23873 If we use the @option{-gnatE} switch, then as noted above, the program works.
23874 Why is this? If we examine the task body, it is apparent that the task cannot
23876 @code{accept} statement until after elaboration has been completed, because
23877 the corresponding entry call comes from the main program, not earlier.
23878 This is why the dynamic model works here. But that's really giving
23879 up on a precise analysis, and we prefer to take this approach only if we cannot
23881 problem in any other manner. So let us examine two ways to reorganize
23882 the program to avoid the potential elaboration problem.
23885 Split library tasks into separate packages.
23887 Write separate packages, so that library tasks are isolated from
23888 other declarations as much as possible. Let us look at a variation on
23891 @smallexample @c ada
23899 package body Decls1 is
23900 task body Lib_Task is
23908 type My_Int is new Integer;
23909 function Ident (M : My_Int) return My_Int;
23913 package body Decls2 is
23914 function Ident (M : My_Int) return My_Int is
23922 procedure Put_Val (Arg : Decls2.My_Int);
23926 package body Utils is
23927 procedure Put_Val (Arg : Decls2.My_Int) is
23929 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
23936 Decls1.Lib_Task.Start;
23941 All we have done is to split @code{Decls} into two packages, one
23942 containing the library task, and one containing everything else. Now
23943 there is no cycle, and the program compiles, binds, links and executes
23944 using the default static model of elaboration.
23947 Declare separate task types.
23949 A significant part of the problem arises because of the use of the
23950 single task declaration form. This means that the elaboration of
23951 the task type, and the elaboration of the task itself (i.e. the
23952 creation of the task) happen at the same time. A good rule
23953 of style in Ada 95 is to always create explicit task types. By
23954 following the additional step of placing task objects in separate
23955 packages from the task type declaration, many elaboration problems
23956 are avoided. Here is another modified example of the example program:
23958 @smallexample @c ada
23960 task type Lib_Task_Type is
23964 type My_Int is new Integer;
23966 function Ident (M : My_Int) return My_Int;
23970 package body Decls is
23971 task body Lib_Task_Type is
23977 function Ident (M : My_Int) return My_Int is
23985 procedure Put_Val (Arg : Decls.My_Int);
23989 package body Utils is
23990 procedure Put_Val (Arg : Decls.My_Int) is
23992 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23998 Lib_Task : Decls.Lib_Task_Type;
24004 Declst.Lib_Task.Start;
24009 What we have done here is to replace the @code{task} declaration in
24010 package @code{Decls} with a @code{task type} declaration. Then we
24011 introduce a separate package @code{Declst} to contain the actual
24012 task object. This separates the elaboration issues for
24013 the @code{task type}
24014 declaration, which causes no trouble, from the elaboration issues
24015 of the task object, which is also unproblematic, since it is now independent
24016 of the elaboration of @code{Utils}.
24017 This separation of concerns also corresponds to
24018 a generally sound engineering principle of separating declarations
24019 from instances. This version of the program also compiles, binds, links,
24020 and executes, generating the expected output.
24023 Use No_Entry_Calls_In_Elaboration_Code restriction.
24024 @cindex No_Entry_Calls_In_Elaboration_Code
24026 The previous two approaches described how a program can be restructured
24027 to avoid the special problems caused by library task bodies. in practice,
24028 however, such restructuring may be difficult to apply to existing legacy code,
24029 so we must consider solutions that do not require massive rewriting.
24031 Let us consider more carefully why our original sample program works
24032 under the dynamic model of elaboration. The reason is that the code
24033 in the task body blocks immediately on the @code{accept}
24034 statement. Now of course there is nothing to prohibit elaboration
24035 code from making entry calls (for example from another library level task),
24036 so we cannot tell in isolation that
24037 the task will not execute the accept statement during elaboration.
24039 However, in practice it is very unusual to see elaboration code
24040 make any entry calls, and the pattern of tasks starting
24041 at elaboration time and then immediately blocking on @code{accept} or
24042 @code{select} statements is very common. What this means is that
24043 the compiler is being too pessimistic when it analyzes the
24044 whole package body as though it might be executed at elaboration
24047 If we know that the elaboration code contains no entry calls, (a very safe
24048 assumption most of the time, that could almost be made the default
24049 behavior), then we can compile all units of the program under control
24050 of the following configuration pragma:
24053 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
24057 This pragma can be placed in the @file{gnat.adc} file in the usual
24058 manner. If we take our original unmodified program and compile it
24059 in the presence of a @file{gnat.adc} containing the above pragma,
24060 then once again, we can compile, bind, link, and execute, obtaining
24061 the expected result. In the presence of this pragma, the compiler does
24062 not trace calls in a task body, that appear after the first @code{accept}
24063 or @code{select} statement, and therefore does not report a potential
24064 circularity in the original program.
24066 The compiler will check to the extent it can that the above
24067 restriction is not violated, but it is not always possible to do a
24068 complete check at compile time, so it is important to use this
24069 pragma only if the stated restriction is in fact met, that is to say
24070 no task receives an entry call before elaboration of all units is completed.
24074 @node Mixing Elaboration Models
24075 @section Mixing Elaboration Models
24077 So far, we have assumed that the entire program is either compiled
24078 using the dynamic model or static model, ensuring consistency. It
24079 is possible to mix the two models, but rules have to be followed
24080 if this mixing is done to ensure that elaboration checks are not
24083 The basic rule is that @emph{a unit compiled with the static model cannot
24084 be @code{with'ed} by a unit compiled with the dynamic model}. The
24085 reason for this is that in the static model, a unit assumes that
24086 its clients guarantee to use (the equivalent of) pragma
24087 @code{Elaborate_All} so that no elaboration checks are required
24088 in inner subprograms, and this assumption is violated if the
24089 client is compiled with dynamic checks.
24091 The precise rule is as follows. A unit that is compiled with dynamic
24092 checks can only @code{with} a unit that meets at least one of the
24093 following criteria:
24098 The @code{with'ed} unit is itself compiled with dynamic elaboration
24099 checks (that is with the @option{-gnatE} switch.
24102 The @code{with'ed} unit is an internal GNAT implementation unit from
24103 the System, Interfaces, Ada, or GNAT hierarchies.
24106 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
24109 The @code{with'ing} unit (that is the client) has an explicit pragma
24110 @code{Elaborate_All} for the @code{with'ed} unit.
24115 If this rule is violated, that is if a unit with dynamic elaboration
24116 checks @code{with's} a unit that does not meet one of the above four
24117 criteria, then the binder (@code{gnatbind}) will issue a warning
24118 similar to that in the following example:
24121 warning: "x.ads" has dynamic elaboration checks and with's
24122 warning: "y.ads" which has static elaboration checks
24126 These warnings indicate that the rule has been violated, and that as a result
24127 elaboration checks may be missed in the resulting executable file.
24128 This warning may be suppressed using the @option{-ws} binder switch
24129 in the usual manner.
24131 One useful application of this mixing rule is in the case of a subsystem
24132 which does not itself @code{with} units from the remainder of the
24133 application. In this case, the entire subsystem can be compiled with
24134 dynamic checks to resolve a circularity in the subsystem, while
24135 allowing the main application that uses this subsystem to be compiled
24136 using the more reliable default static model.
24138 @node What to Do If the Default Elaboration Behavior Fails
24139 @section What to Do If the Default Elaboration Behavior Fails
24142 If the binder cannot find an acceptable order, it outputs detailed
24143 diagnostics. For example:
24149 error: elaboration circularity detected
24150 info: "proc (body)" must be elaborated before "pack (body)"
24151 info: reason: Elaborate_All probably needed in unit "pack (body)"
24152 info: recompile "pack (body)" with -gnatwl
24153 info: for full details
24154 info: "proc (body)"
24155 info: is needed by its spec:
24156 info: "proc (spec)"
24157 info: which is withed by:
24158 info: "pack (body)"
24159 info: "pack (body)" must be elaborated before "proc (body)"
24160 info: reason: pragma Elaborate in unit "proc (body)"
24166 In this case we have a cycle that the binder cannot break. On the one
24167 hand, there is an explicit pragma Elaborate in @code{proc} for
24168 @code{pack}. This means that the body of @code{pack} must be elaborated
24169 before the body of @code{proc}. On the other hand, there is elaboration
24170 code in @code{pack} that calls a subprogram in @code{proc}. This means
24171 that for maximum safety, there should really be a pragma
24172 Elaborate_All in @code{pack} for @code{proc} which would require that
24173 the body of @code{proc} be elaborated before the body of
24174 @code{pack}. Clearly both requirements cannot be satisfied.
24175 Faced with a circularity of this kind, you have three different options.
24178 @item Fix the program
24179 The most desirable option from the point of view of long-term maintenance
24180 is to rearrange the program so that the elaboration problems are avoided.
24181 One useful technique is to place the elaboration code into separate
24182 child packages. Another is to move some of the initialization code to
24183 explicitly called subprograms, where the program controls the order
24184 of initialization explicitly. Although this is the most desirable option,
24185 it may be impractical and involve too much modification, especially in
24186 the case of complex legacy code.
24188 @item Perform dynamic checks
24189 If the compilations are done using the
24191 (dynamic elaboration check) switch, then GNAT behaves in
24192 a quite different manner. Dynamic checks are generated for all calls
24193 that could possibly result in raising an exception. With this switch,
24194 the compiler does not generate implicit @code{Elaborate_All} pragmas.
24195 The behavior then is exactly as specified in the Ada 95 Reference Manual.
24196 The binder will generate an executable program that may or may not
24197 raise @code{Program_Error}, and then it is the programmer's job to ensure
24198 that it does not raise an exception. Note that it is important to
24199 compile all units with the switch, it cannot be used selectively.
24201 @item Suppress checks
24202 The drawback of dynamic checks is that they generate a
24203 significant overhead at run time, both in space and time. If you
24204 are absolutely sure that your program cannot raise any elaboration
24205 exceptions, and you still want to use the dynamic elaboration model,
24206 then you can use the configuration pragma
24207 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
24208 example this pragma could be placed in the @file{gnat.adc} file.
24210 @item Suppress checks selectively
24211 When you know that certain calls in elaboration code cannot possibly
24212 lead to an elaboration error, and the binder nevertheless generates warnings
24213 on those calls and inserts Elaborate_All pragmas that lead to elaboration
24214 circularities, it is possible to remove those warnings locally and obtain
24215 a program that will bind. Clearly this can be unsafe, and it is the
24216 responsibility of the programmer to make sure that the resulting program has
24217 no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can
24218 be used with different granularity to suppress warnings and break
24219 elaboration circularities:
24223 Place the pragma that names the called subprogram in the declarative part
24224 that contains the call.
24227 Place the pragma in the declarative part, without naming an entity. This
24228 disables warnings on all calls in the corresponding declarative region.
24231 Place the pragma in the package spec that declares the called subprogram,
24232 and name the subprogram. This disables warnings on all elaboration calls to
24236 Place the pragma in the package spec that declares the called subprogram,
24237 without naming any entity. This disables warnings on all elaboration calls to
24238 all subprograms declared in this spec.
24240 @item Use Pragma Elaborate
24241 As previously described in section @xref{Treatment of Pragma Elaborate},
24242 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
24243 that no elaboration checks are required on calls to the designated unit.
24244 There may be cases in which the caller knows that no transitive calls
24245 can occur, so that a @code{pragma Elaborate} will be sufficient in a
24246 case where @code{pragma Elaborate_All} would cause a circularity.
24250 These five cases are listed in order of decreasing safety, and therefore
24251 require increasing programmer care in their application. Consider the
24254 @smallexample @c adanocomment
24256 function F1 return Integer;
24261 function F2 return Integer;
24262 function Pure (x : integer) return integer;
24263 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
24264 -- pragma Suppress (Elaboration_Check); -- (4)
24268 package body Pack1 is
24269 function F1 return Integer is
24273 Val : integer := Pack2.Pure (11); -- Elab. call (1)
24276 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
24277 -- pragma Suppress(Elaboration_Check); -- (2)
24279 X1 := Pack2.F2 + 1; -- Elab. call (2)
24284 package body Pack2 is
24285 function F2 return Integer is
24289 function Pure (x : integer) return integer is
24291 return x ** 3 - 3 * x;
24295 with Pack1, Ada.Text_IO;
24298 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24301 In the absence of any pragmas, an attempt to bind this program produces
24302 the following diagnostics:
24308 error: elaboration circularity detected
24309 info: "pack1 (body)" must be elaborated before "pack1 (body)"
24310 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
24311 info: recompile "pack1 (body)" with -gnatwl for full details
24312 info: "pack1 (body)"
24313 info: must be elaborated along with its spec:
24314 info: "pack1 (spec)"
24315 info: which is withed by:
24316 info: "pack2 (body)"
24317 info: which must be elaborated along with its spec:
24318 info: "pack2 (spec)"
24319 info: which is withed by:
24320 info: "pack1 (body)"
24323 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24324 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24325 F2 is safe, even though F2 calls F1, because the call appears after the
24326 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24327 remove the warning on the call. It is also possible to use pragma (2)
24328 because there are no other potentially unsafe calls in the block.
24331 The call to @code{Pure} is safe because this function does not depend on the
24332 state of @code{Pack2}. Therefore any call to this function is safe, and it
24333 is correct to place pragma (3) in the corresponding package spec.
24336 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24337 warnings on all calls to functions declared therein. Note that this is not
24338 necessarily safe, and requires more detailed examination of the subprogram
24339 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24340 be already elaborated.
24344 It is hard to generalize on which of these four approaches should be
24345 taken. Obviously if it is possible to fix the program so that the default
24346 treatment works, this is preferable, but this may not always be practical.
24347 It is certainly simple enough to use
24349 but the danger in this case is that, even if the GNAT binder
24350 finds a correct elaboration order, it may not always do so,
24351 and certainly a binder from another Ada compiler might not. A
24352 combination of testing and analysis (for which the warnings generated
24355 switch can be useful) must be used to ensure that the program is free
24356 of errors. One switch that is useful in this testing is the
24357 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
24360 Normally the binder tries to find an order that has the best chance of
24361 of avoiding elaboration problems. With this switch, the binder
24362 plays a devil's advocate role, and tries to choose the order that
24363 has the best chance of failing. If your program works even with this
24364 switch, then it has a better chance of being error free, but this is still
24367 For an example of this approach in action, consider the C-tests (executable
24368 tests) from the ACVC suite. If these are compiled and run with the default
24369 treatment, then all but one of them succeed without generating any error
24370 diagnostics from the binder. However, there is one test that fails, and
24371 this is not surprising, because the whole point of this test is to ensure
24372 that the compiler can handle cases where it is impossible to determine
24373 a correct order statically, and it checks that an exception is indeed
24374 raised at run time.
24376 This one test must be compiled and run using the
24378 switch, and then it passes. Alternatively, the entire suite can
24379 be run using this switch. It is never wrong to run with the dynamic
24380 elaboration switch if your code is correct, and we assume that the
24381 C-tests are indeed correct (it is less efficient, but efficiency is
24382 not a factor in running the ACVC tests.)
24384 @node Elaboration for Access-to-Subprogram Values
24385 @section Elaboration for Access-to-Subprogram Values
24386 @cindex Access-to-subprogram
24389 The introduction of access-to-subprogram types in Ada 95 complicates
24390 the handling of elaboration. The trouble is that it becomes
24391 impossible to tell at compile time which procedure
24392 is being called. This means that it is not possible for the binder
24393 to analyze the elaboration requirements in this case.
24395 If at the point at which the access value is created
24396 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
24397 the body of the subprogram is
24398 known to have been elaborated, then the access value is safe, and its use
24399 does not require a check. This may be achieved by appropriate arrangement
24400 of the order of declarations if the subprogram is in the current unit,
24401 or, if the subprogram is in another unit, by using pragma
24402 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
24403 on the referenced unit.
24405 If the referenced body is not known to have been elaborated at the point
24406 the access value is created, then any use of the access value must do a
24407 dynamic check, and this dynamic check will fail and raise a
24408 @code{Program_Error} exception if the body has not been elaborated yet.
24409 GNAT will generate the necessary checks, and in addition, if the
24411 switch is set, will generate warnings that such checks are required.
24413 The use of dynamic dispatching for tagged types similarly generates
24414 a requirement for dynamic checks, and premature calls to any primitive
24415 operation of a tagged type before the body of the operation has been
24416 elaborated, will result in the raising of @code{Program_Error}.
24418 @node Summary of Procedures for Elaboration Control
24419 @section Summary of Procedures for Elaboration Control
24420 @cindex Elaboration control
24423 First, compile your program with the default options, using none of
24424 the special elaboration control switches. If the binder successfully
24425 binds your program, then you can be confident that, apart from issues
24426 raised by the use of access-to-subprogram types and dynamic dispatching,
24427 the program is free of elaboration errors. If it is important that the
24428 program be portable, then use the
24430 switch to generate warnings about missing @code{Elaborate_All}
24431 pragmas, and supply the missing pragmas.
24433 If the program fails to bind using the default static elaboration
24434 handling, then you can fix the program to eliminate the binder
24435 message, or recompile the entire program with the
24436 @option{-gnatE} switch to generate dynamic elaboration checks,
24437 and, if you are sure there really are no elaboration problems,
24438 use a global pragma @code{Suppress (Elaboration_Check)}.
24440 @node Other Elaboration Order Considerations
24441 @section Other Elaboration Order Considerations
24443 This section has been entirely concerned with the issue of finding a valid
24444 elaboration order, as defined by the Ada Reference Manual. In a case
24445 where several elaboration orders are valid, the task is to find one
24446 of the possible valid elaboration orders (and the static model in GNAT
24447 will ensure that this is achieved).
24449 The purpose of the elaboration rules in the Ada Reference Manual is to
24450 make sure that no entity is accessed before it has been elaborated. For
24451 a subprogram, this means that the spec and body must have been elaborated
24452 before the subprogram is called. For an object, this means that the object
24453 must have been elaborated before its value is read or written. A violation
24454 of either of these two requirements is an access before elaboration order,
24455 and this section has been all about avoiding such errors.
24457 In the case where more than one order of elaboration is possible, in the
24458 sense that access before elaboration errors are avoided, then any one of
24459 the orders is ``correct'' in the sense that it meets the requirements of
24460 the Ada Reference Manual, and no such error occurs.
24462 However, it may be the case for a given program, that there are
24463 constraints on the order of elaboration that come not from consideration
24464 of avoiding elaboration errors, but rather from extra-lingual logic
24465 requirements. Consider this example:
24467 @smallexample @c ada
24468 with Init_Constants;
24469 package Constants is
24474 package Init_Constants is
24475 procedure P; -- require a body
24476 end Init_Constants;
24479 package body Init_Constants is
24480 procedure P is begin null; end;
24484 end Init_Constants;
24488 Z : Integer := Constants.X + Constants.Y;
24492 with Text_IO; use Text_IO;
24495 Put_Line (Calc.Z'Img);
24500 In this example, there is more than one valid order of elaboration. For
24501 example both the following are correct orders:
24504 Init_Constants spec
24507 Init_Constants body
24512 Init_Constants spec
24513 Init_Constants body
24520 There is no language rule to prefer one or the other, both are correct
24521 from an order of elaboration point of view. But the programmatic effects
24522 of the two orders are very different. In the first, the elaboration routine
24523 of @code{Calc} initializes @code{Z} to zero, and then the main program
24524 runs with this value of zero. But in the second order, the elaboration
24525 routine of @code{Calc} runs after the body of Init_Constants has set
24526 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
24529 One could perhaps by applying pretty clever non-artificial intelligence
24530 to the situation guess that it is more likely that the second order of
24531 elaboration is the one desired, but there is no formal linguistic reason
24532 to prefer one over the other. In fact in this particular case, GNAT will
24533 prefer the second order, because of the rule that bodies are elaborated
24534 as soon as possible, but it's just luck that this is what was wanted
24535 (if indeed the second order was preferred).
24537 If the program cares about the order of elaboration routines in a case like
24538 this, it is important to specify the order required. In this particular
24539 case, that could have been achieved by adding to the spec of Calc:
24541 @smallexample @c ada
24542 pragma Elaborate_All (Constants);
24546 which requires that the body (if any) and spec of @code{Constants},
24547 as well as the body and spec of any unit @code{with}'ed by
24548 @code{Constants} be elaborated before @code{Calc} is elaborated.
24550 Clearly no automatic method can always guess which alternative you require,
24551 and if you are working with legacy code that had constraints of this kind
24552 which were not properly specified by adding @code{Elaborate} or
24553 @code{Elaborate_All} pragmas, then indeed it is possible that two different
24554 compilers can choose different orders.
24556 The @code{gnatbind}
24557 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
24558 out problems. This switch causes bodies to be elaborated as late as possible
24559 instead of as early as possible. In the example above, it would have forced
24560 the choice of the first elaboration order. If you get different results
24561 when using this switch, and particularly if one set of results is right,
24562 and one is wrong as far as you are concerned, it shows that you have some
24563 missing @code{Elaborate} pragmas. For the example above, we have the
24567 gnatmake -f -q main
24570 gnatmake -f -q main -bargs -p
24576 It is of course quite unlikely that both these results are correct, so
24577 it is up to you in a case like this to investigate the source of the
24578 difference, by looking at the two elaboration orders that are chosen,
24579 and figuring out which is correct, and then adding the necessary
24580 @code{Elaborate_All} pragmas to ensure the desired order.
24582 @node Inline Assembler
24583 @appendix Inline Assembler
24586 If you need to write low-level software that interacts directly
24587 with the hardware, Ada provides two ways to incorporate assembly
24588 language code into your program. First, you can import and invoke
24589 external routines written in assembly language, an Ada feature fully
24590 supported by GNAT. However, for small sections of code it may be simpler
24591 or more efficient to include assembly language statements directly
24592 in your Ada source program, using the facilities of the implementation-defined
24593 package @code{System.Machine_Code}, which incorporates the gcc
24594 Inline Assembler. The Inline Assembler approach offers a number of advantages,
24595 including the following:
24598 @item No need to use non-Ada tools
24599 @item Consistent interface over different targets
24600 @item Automatic usage of the proper calling conventions
24601 @item Access to Ada constants and variables
24602 @item Definition of intrinsic routines
24603 @item Possibility of inlining a subprogram comprising assembler code
24604 @item Code optimizer can take Inline Assembler code into account
24607 This chapter presents a series of examples to show you how to use
24608 the Inline Assembler. Although it focuses on the Intel x86,
24609 the general approach applies also to other processors.
24610 It is assumed that you are familiar with Ada
24611 and with assembly language programming.
24614 * Basic Assembler Syntax::
24615 * A Simple Example of Inline Assembler::
24616 * Output Variables in Inline Assembler::
24617 * Input Variables in Inline Assembler::
24618 * Inlining Inline Assembler Code::
24619 * Other Asm Functionality::
24620 * A Complete Example::
24623 @c ---------------------------------------------------------------------------
24624 @node Basic Assembler Syntax
24625 @section Basic Assembler Syntax
24628 The assembler used by GNAT and gcc is based not on the Intel assembly
24629 language, but rather on a language that descends from the AT&T Unix
24630 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
24631 The following table summarizes the main features of @emph{as} syntax
24632 and points out the differences from the Intel conventions.
24633 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
24634 pre-processor) documentation for further information.
24637 @item Register names
24638 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
24640 Intel: No extra punctuation; for example @code{eax}
24642 @item Immediate operand
24643 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
24645 Intel: No extra punctuation; for example @code{4}
24648 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
24650 Intel: No extra punctuation; for example @code{loc}
24652 @item Memory contents
24653 gcc / @emph{as}: No extra punctuation; for example @code{loc}
24655 Intel: Square brackets; for example @code{[loc]}
24657 @item Register contents
24658 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
24660 Intel: Square brackets; for example @code{[eax]}
24662 @item Hexadecimal numbers
24663 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
24665 Intel: Trailing ``h''; for example @code{A0h}
24668 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
24671 Intel: Implicit, deduced by assembler; for example @code{mov}
24673 @item Instruction repetition
24674 gcc / @emph{as}: Split into two lines; for example
24680 Intel: Keep on one line; for example @code{rep stosl}
24682 @item Order of operands
24683 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
24685 Intel: Destination first; for example @code{mov eax, 4}
24688 @c ---------------------------------------------------------------------------
24689 @node A Simple Example of Inline Assembler
24690 @section A Simple Example of Inline Assembler
24693 The following example will generate a single assembly language statement,
24694 @code{nop}, which does nothing. Despite its lack of run-time effect,
24695 the example will be useful in illustrating the basics of
24696 the Inline Assembler facility.
24698 @smallexample @c ada
24700 with System.Machine_Code; use System.Machine_Code;
24701 procedure Nothing is
24708 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
24709 here it takes one parameter, a @emph{template string} that must be a static
24710 expression and that will form the generated instruction.
24711 @code{Asm} may be regarded as a compile-time procedure that parses
24712 the template string and additional parameters (none here),
24713 from which it generates a sequence of assembly language instructions.
24715 The examples in this chapter will illustrate several of the forms
24716 for invoking @code{Asm}; a complete specification of the syntax
24717 is found in the @cite{GNAT Reference Manual}.
24719 Under the standard GNAT conventions, the @code{Nothing} procedure
24720 should be in a file named @file{nothing.adb}.
24721 You can build the executable in the usual way:
24725 However, the interesting aspect of this example is not its run-time behavior
24726 but rather the generated assembly code.
24727 To see this output, invoke the compiler as follows:
24729 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
24731 where the options are:
24735 compile only (no bind or link)
24737 generate assembler listing
24738 @item -fomit-frame-pointer
24739 do not set up separate stack frames
24741 do not add runtime checks
24744 This gives a human-readable assembler version of the code. The resulting
24745 file will have the same name as the Ada source file, but with a @code{.s}
24746 extension. In our example, the file @file{nothing.s} has the following
24751 .file "nothing.adb"
24753 ___gnu_compiled_ada:
24756 .globl __ada_nothing
24768 The assembly code you included is clearly indicated by
24769 the compiler, between the @code{#APP} and @code{#NO_APP}
24770 delimiters. The character before the 'APP' and 'NOAPP'
24771 can differ on different targets. For example, GNU/Linux uses '#APP' while
24772 on NT you will see '/APP'.
24774 If you make a mistake in your assembler code (such as using the
24775 wrong size modifier, or using a wrong operand for the instruction) GNAT
24776 will report this error in a temporary file, which will be deleted when
24777 the compilation is finished. Generating an assembler file will help
24778 in such cases, since you can assemble this file separately using the
24779 @emph{as} assembler that comes with gcc.
24781 Assembling the file using the command
24784 as @file{nothing.s}
24787 will give you error messages whose lines correspond to the assembler
24788 input file, so you can easily find and correct any mistakes you made.
24789 If there are no errors, @emph{as} will generate an object file
24790 @file{nothing.out}.
24792 @c ---------------------------------------------------------------------------
24793 @node Output Variables in Inline Assembler
24794 @section Output Variables in Inline Assembler
24797 The examples in this section, showing how to access the processor flags,
24798 illustrate how to specify the destination operands for assembly language
24801 @smallexample @c ada
24803 with Interfaces; use Interfaces;
24804 with Ada.Text_IO; use Ada.Text_IO;
24805 with System.Machine_Code; use System.Machine_Code;
24806 procedure Get_Flags is
24807 Flags : Unsigned_32;
24810 Asm ("pushfl" & LF & HT & -- push flags on stack
24811 "popl %%eax" & LF & HT & -- load eax with flags
24812 "movl %%eax, %0", -- store flags in variable
24813 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24814 Put_Line ("Flags register:" & Flags'Img);
24819 In order to have a nicely aligned assembly listing, we have separated
24820 multiple assembler statements in the Asm template string with linefeed
24821 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
24822 The resulting section of the assembly output file is:
24829 movl %eax, -40(%ebp)
24834 It would have been legal to write the Asm invocation as:
24837 Asm ("pushfl popl %%eax movl %%eax, %0")
24840 but in the generated assembler file, this would come out as:
24844 pushfl popl %eax movl %eax, -40(%ebp)
24848 which is not so convenient for the human reader.
24850 We use Ada comments
24851 at the end of each line to explain what the assembler instructions
24852 actually do. This is a useful convention.
24854 When writing Inline Assembler instructions, you need to precede each register
24855 and variable name with a percent sign. Since the assembler already requires
24856 a percent sign at the beginning of a register name, you need two consecutive
24857 percent signs for such names in the Asm template string, thus @code{%%eax}.
24858 In the generated assembly code, one of the percent signs will be stripped off.
24860 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
24861 variables: operands you later define using @code{Input} or @code{Output}
24862 parameters to @code{Asm}.
24863 An output variable is illustrated in
24864 the third statement in the Asm template string:
24868 The intent is to store the contents of the eax register in a variable that can
24869 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
24870 necessarily work, since the compiler might optimize by using a register
24871 to hold Flags, and the expansion of the @code{movl} instruction would not be
24872 aware of this optimization. The solution is not to store the result directly
24873 but rather to advise the compiler to choose the correct operand form;
24874 that is the purpose of the @code{%0} output variable.
24876 Information about the output variable is supplied in the @code{Outputs}
24877 parameter to @code{Asm}:
24879 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24882 The output is defined by the @code{Asm_Output} attribute of the target type;
24883 the general format is
24885 Type'Asm_Output (constraint_string, variable_name)
24888 The constraint string directs the compiler how
24889 to store/access the associated variable. In the example
24891 Unsigned_32'Asm_Output ("=m", Flags);
24893 the @code{"m"} (memory) constraint tells the compiler that the variable
24894 @code{Flags} should be stored in a memory variable, thus preventing
24895 the optimizer from keeping it in a register. In contrast,
24897 Unsigned_32'Asm_Output ("=r", Flags);
24899 uses the @code{"r"} (register) constraint, telling the compiler to
24900 store the variable in a register.
24902 If the constraint is preceded by the equal character (@strong{=}), it tells
24903 the compiler that the variable will be used to store data into it.
24905 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
24906 allowing the optimizer to choose whatever it deems best.
24908 There are a fairly large number of constraints, but the ones that are
24909 most useful (for the Intel x86 processor) are the following:
24915 global (i.e. can be stored anywhere)
24933 use one of eax, ebx, ecx or edx
24935 use one of eax, ebx, ecx, edx, esi or edi
24938 The full set of constraints is described in the gcc and @emph{as}
24939 documentation; note that it is possible to combine certain constraints
24940 in one constraint string.
24942 You specify the association of an output variable with an assembler operand
24943 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
24945 @smallexample @c ada
24947 Asm ("pushfl" & LF & HT & -- push flags on stack
24948 "popl %%eax" & LF & HT & -- load eax with flags
24949 "movl %%eax, %0", -- store flags in variable
24950 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24954 @code{%0} will be replaced in the expanded code by the appropriate operand,
24956 the compiler decided for the @code{Flags} variable.
24958 In general, you may have any number of output variables:
24961 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
24963 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
24964 of @code{Asm_Output} attributes
24968 @smallexample @c ada
24970 Asm ("movl %%eax, %0" & LF & HT &
24971 "movl %%ebx, %1" & LF & HT &
24973 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
24974 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
24975 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
24979 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
24980 in the Ada program.
24982 As a variation on the @code{Get_Flags} example, we can use the constraints
24983 string to direct the compiler to store the eax register into the @code{Flags}
24984 variable, instead of including the store instruction explicitly in the
24985 @code{Asm} template string:
24987 @smallexample @c ada
24989 with Interfaces; use Interfaces;
24990 with Ada.Text_IO; use Ada.Text_IO;
24991 with System.Machine_Code; use System.Machine_Code;
24992 procedure Get_Flags_2 is
24993 Flags : Unsigned_32;
24996 Asm ("pushfl" & LF & HT & -- push flags on stack
24997 "popl %%eax", -- save flags in eax
24998 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
24999 Put_Line ("Flags register:" & Flags'Img);
25005 The @code{"a"} constraint tells the compiler that the @code{Flags}
25006 variable will come from the eax register. Here is the resulting code:
25014 movl %eax,-40(%ebp)
25019 The compiler generated the store of eax into Flags after
25020 expanding the assembler code.
25022 Actually, there was no need to pop the flags into the eax register;
25023 more simply, we could just pop the flags directly into the program variable:
25025 @smallexample @c ada
25027 with Interfaces; use Interfaces;
25028 with Ada.Text_IO; use Ada.Text_IO;
25029 with System.Machine_Code; use System.Machine_Code;
25030 procedure Get_Flags_3 is
25031 Flags : Unsigned_32;
25034 Asm ("pushfl" & LF & HT & -- push flags on stack
25035 "pop %0", -- save flags in Flags
25036 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25037 Put_Line ("Flags register:" & Flags'Img);
25042 @c ---------------------------------------------------------------------------
25043 @node Input Variables in Inline Assembler
25044 @section Input Variables in Inline Assembler
25047 The example in this section illustrates how to specify the source operands
25048 for assembly language statements.
25049 The program simply increments its input value by 1:
25051 @smallexample @c ada
25053 with Interfaces; use Interfaces;
25054 with Ada.Text_IO; use Ada.Text_IO;
25055 with System.Machine_Code; use System.Machine_Code;
25056 procedure Increment is
25058 function Incr (Value : Unsigned_32) return Unsigned_32 is
25059 Result : Unsigned_32;
25062 Inputs => Unsigned_32'Asm_Input ("a", Value),
25063 Outputs => Unsigned_32'Asm_Output ("=a", Result));
25067 Value : Unsigned_32;
25071 Put_Line ("Value before is" & Value'Img);
25072 Value := Incr (Value);
25073 Put_Line ("Value after is" & Value'Img);
25078 The @code{Outputs} parameter to @code{Asm} specifies
25079 that the result will be in the eax register and that it is to be stored
25080 in the @code{Result} variable.
25082 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
25083 but with an @code{Asm_Input} attribute.
25084 The @code{"="} constraint, indicating an output value, is not present.
25086 You can have multiple input variables, in the same way that you can have more
25087 than one output variable.
25089 The parameter count (%0, %1) etc, now starts at the first input
25090 statement, and continues with the output statements.
25091 When both parameters use the same variable, the
25092 compiler will treat them as the same %n operand, which is the case here.
25094 Just as the @code{Outputs} parameter causes the register to be stored into the
25095 target variable after execution of the assembler statements, so does the
25096 @code{Inputs} parameter cause its variable to be loaded into the register
25097 before execution of the assembler statements.
25099 Thus the effect of the @code{Asm} invocation is:
25101 @item load the 32-bit value of @code{Value} into eax
25102 @item execute the @code{incl %eax} instruction
25103 @item store the contents of eax into the @code{Result} variable
25106 The resulting assembler file (with @option{-O2} optimization) contains:
25109 _increment__incr.1:
25122 @c ---------------------------------------------------------------------------
25123 @node Inlining Inline Assembler Code
25124 @section Inlining Inline Assembler Code
25127 For a short subprogram such as the @code{Incr} function in the previous
25128 section, the overhead of the call and return (creating / deleting the stack
25129 frame) can be significant, compared to the amount of code in the subprogram
25130 body. A solution is to apply Ada's @code{Inline} pragma to the subprogram,
25131 which directs the compiler to expand invocations of the subprogram at the
25132 point(s) of call, instead of setting up a stack frame for out-of-line calls.
25133 Here is the resulting program:
25135 @smallexample @c ada
25137 with Interfaces; use Interfaces;
25138 with Ada.Text_IO; use Ada.Text_IO;
25139 with System.Machine_Code; use System.Machine_Code;
25140 procedure Increment_2 is
25142 function Incr (Value : Unsigned_32) return Unsigned_32 is
25143 Result : Unsigned_32;
25146 Inputs => Unsigned_32'Asm_Input ("a", Value),
25147 Outputs => Unsigned_32'Asm_Output ("=a", Result));
25150 pragma Inline (Increment);
25152 Value : Unsigned_32;
25156 Put_Line ("Value before is" & Value'Img);
25157 Value := Increment (Value);
25158 Put_Line ("Value after is" & Value'Img);
25163 Compile the program with both optimization (@option{-O2}) and inlining
25164 enabled (@option{-gnatpn} instead of @option{-gnatp}).
25166 The @code{Incr} function is still compiled as usual, but at the
25167 point in @code{Increment} where our function used to be called:
25172 call _increment__incr.1
25177 the code for the function body directly appears:
25190 thus saving the overhead of stack frame setup and an out-of-line call.
25192 @c ---------------------------------------------------------------------------
25193 @node Other Asm Functionality
25194 @section Other @code{Asm} Functionality
25197 This section describes two important parameters to the @code{Asm}
25198 procedure: @code{Clobber}, which identifies register usage;
25199 and @code{Volatile}, which inhibits unwanted optimizations.
25202 * The Clobber Parameter::
25203 * The Volatile Parameter::
25206 @c ---------------------------------------------------------------------------
25207 @node The Clobber Parameter
25208 @subsection The @code{Clobber} Parameter
25211 One of the dangers of intermixing assembly language and a compiled language
25212 such as Ada is that the compiler needs to be aware of which registers are
25213 being used by the assembly code. In some cases, such as the earlier examples,
25214 the constraint string is sufficient to indicate register usage (e.g.,
25216 the eax register). But more generally, the compiler needs an explicit
25217 identification of the registers that are used by the Inline Assembly
25220 Using a register that the compiler doesn't know about
25221 could be a side effect of an instruction (like @code{mull}
25222 storing its result in both eax and edx).
25223 It can also arise from explicit register usage in your
25224 assembly code; for example:
25227 Asm ("movl %0, %%ebx" & LF & HT &
25229 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
25230 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
25234 where the compiler (since it does not analyze the @code{Asm} template string)
25235 does not know you are using the ebx register.
25237 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
25238 to identify the registers that will be used by your assembly code:
25242 Asm ("movl %0, %%ebx" & LF & HT &
25244 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
25245 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
25250 The Clobber parameter is a static string expression specifying the
25251 register(s) you are using. Note that register names are @emph{not} prefixed
25252 by a percent sign. Also, if more than one register is used then their names
25253 are separated by commas; e.g., @code{"eax, ebx"}
25255 The @code{Clobber} parameter has several additional uses:
25257 @item Use ``register'' name @code{cc} to indicate that flags might have changed
25258 @item Use ``register'' name @code{memory} if you changed a memory location
25261 @c ---------------------------------------------------------------------------
25262 @node The Volatile Parameter
25263 @subsection The @code{Volatile} Parameter
25264 @cindex Volatile parameter
25267 Compiler optimizations in the presence of Inline Assembler may sometimes have
25268 unwanted effects. For example, when an @code{Asm} invocation with an input
25269 variable is inside a loop, the compiler might move the loading of the input
25270 variable outside the loop, regarding it as a one-time initialization.
25272 If this effect is not desired, you can disable such optimizations by setting
25273 the @code{Volatile} parameter to @code{True}; for example:
25275 @smallexample @c ada
25277 Asm ("movl %0, %%ebx" & LF & HT &
25279 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
25280 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
25286 By default, @code{Volatile} is set to @code{False} unless there is no
25287 @code{Outputs} parameter.
25289 Although setting @code{Volatile} to @code{True} prevents unwanted
25290 optimizations, it will also disable other optimizations that might be
25291 important for efficiency. In general, you should set @code{Volatile}
25292 to @code{True} only if the compiler's optimizations have created
25295 @c ---------------------------------------------------------------------------
25296 @node A Complete Example
25297 @section A Complete Example
25300 This section contains a complete program illustrating a realistic usage
25301 of GNAT's Inline Assembler capabilities. It comprises a main procedure
25302 @code{Check_CPU} and a package @code{Intel_CPU}.
25303 The package declares a collection of functions that detect the properties
25304 of the 32-bit x86 processor that is running the program.
25305 The main procedure invokes these functions and displays the information.
25307 The Intel_CPU package could be enhanced by adding functions to
25308 detect the type of x386 co-processor, the processor caching options and
25309 special operations such as the SIMD extensions.
25311 Although the Intel_CPU package has been written for 32-bit Intel
25312 compatible CPUs, it is OS neutral. It has been tested on DOS,
25313 Windows/NT and GNU/Linux.
25316 * Check_CPU Procedure::
25317 * Intel_CPU Package Specification::
25318 * Intel_CPU Package Body::
25321 @c ---------------------------------------------------------------------------
25322 @node Check_CPU Procedure
25323 @subsection @code{Check_CPU} Procedure
25324 @cindex Check_CPU procedure
25326 @smallexample @c adanocomment
25327 ---------------------------------------------------------------------
25329 -- Uses the Intel_CPU package to identify the CPU the program is --
25330 -- running on, and some of the features it supports. --
25332 ---------------------------------------------------------------------
25334 with Intel_CPU; -- Intel CPU detection functions
25335 with Ada.Text_IO; -- Standard text I/O
25336 with Ada.Command_Line; -- To set the exit status
25338 procedure Check_CPU is
25340 Type_Found : Boolean := False;
25341 -- Flag to indicate that processor was identified
25343 Features : Intel_CPU.Processor_Features;
25344 -- The processor features
25346 Signature : Intel_CPU.Processor_Signature;
25347 -- The processor type signature
25351 -----------------------------------
25352 -- Display the program banner. --
25353 -----------------------------------
25355 Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name &
25356 ": check Intel CPU version and features, v1.0");
25357 Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever");
25358 Ada.Text_IO.New_Line;
25360 -----------------------------------------------------------------------
25361 -- We can safely start with the assumption that we are on at least --
25362 -- a x386 processor. If the CPUID instruction is present, then we --
25363 -- have a later processor type. --
25364 -----------------------------------------------------------------------
25366 if Intel_CPU.Has_CPUID = False then
25368 -- No CPUID instruction, so we assume this is indeed a x386
25369 -- processor. We can still check if it has a FP co-processor.
25370 if Intel_CPU.Has_FPU then
25371 Ada.Text_IO.Put_Line
25372 ("x386-type processor with a FP co-processor");
25374 Ada.Text_IO.Put_Line
25375 ("x386-type processor without a FP co-processor");
25376 end if; -- check for FPU
25379 Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
25382 end if; -- check for CPUID
25384 -----------------------------------------------------------------------
25385 -- If CPUID is supported, check if this is a true Intel processor, --
25386 -- if it is not, display a warning. --
25387 -----------------------------------------------------------------------
25389 if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then
25390 Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor");
25391 Ada.Text_IO.Put_Line ("*** Some information may be incorrect");
25392 end if; -- check if Intel
25394 ----------------------------------------------------------------------
25395 -- With the CPUID instruction present, we can assume at least a --
25396 -- x486 processor. If the CPUID support level is < 1 then we have --
25397 -- to leave it at that. --
25398 ----------------------------------------------------------------------
25400 if Intel_CPU.CPUID_Level < 1 then
25402 -- Ok, this is a x486 processor. we still can get the Vendor ID
25403 Ada.Text_IO.Put_Line ("x486-type processor");
25404 Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID);
25406 -- We can also check if there is a FPU present
25407 if Intel_CPU.Has_FPU then
25408 Ada.Text_IO.Put_Line ("Floating-Point support");
25410 Ada.Text_IO.Put_Line ("No Floating-Point support");
25411 end if; -- check for FPU
25414 Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
25417 end if; -- check CPUID level
25419 ---------------------------------------------------------------------
25420 -- With a CPUID level of 1 we can use the processor signature to --
25421 -- determine it's exact type. --
25422 ---------------------------------------------------------------------
25424 Signature := Intel_CPU.Signature;
25426 ----------------------------------------------------------------------
25427 -- Ok, now we go into a lot of messy comparisons to get the --
25428 -- processor type. For clarity, no attememt to try to optimize the --
25429 -- comparisons has been made. Note that since Intel_CPU does not --
25430 -- support getting cache info, we cannot distinguish between P5 --
25431 -- and Celeron types yet. --
25432 ----------------------------------------------------------------------
25435 if Signature.Processor_Type = 2#00# and
25436 Signature.Family = 2#0100# and
25437 Signature.Model = 2#0100# then
25438 Type_Found := True;
25439 Ada.Text_IO.Put_Line ("x486SL processor");
25442 -- x486DX2 Write-Back
25443 if Signature.Processor_Type = 2#00# and
25444 Signature.Family = 2#0100# and
25445 Signature.Model = 2#0111# then
25446 Type_Found := True;
25447 Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor");
25451 if Signature.Processor_Type = 2#00# and
25452 Signature.Family = 2#0100# and
25453 Signature.Model = 2#1000# then
25454 Type_Found := True;
25455 Ada.Text_IO.Put_Line ("x486DX4 processor");
25458 -- x486DX4 Overdrive
25459 if Signature.Processor_Type = 2#01# and
25460 Signature.Family = 2#0100# and
25461 Signature.Model = 2#1000# then
25462 Type_Found := True;
25463 Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor");
25466 -- Pentium (60, 66)
25467 if Signature.Processor_Type = 2#00# and
25468 Signature.Family = 2#0101# and
25469 Signature.Model = 2#0001# then
25470 Type_Found := True;
25471 Ada.Text_IO.Put_Line ("Pentium processor (60, 66)");
25474 -- Pentium (75, 90, 100, 120, 133, 150, 166, 200)
25475 if Signature.Processor_Type = 2#00# and
25476 Signature.Family = 2#0101# and
25477 Signature.Model = 2#0010# then
25478 Type_Found := True;
25479 Ada.Text_IO.Put_Line
25480 ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)");
25483 -- Pentium OverDrive (60, 66)
25484 if Signature.Processor_Type = 2#01# and
25485 Signature.Family = 2#0101# and
25486 Signature.Model = 2#0001# then
25487 Type_Found := True;
25488 Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)");
25491 -- Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200)
25492 if Signature.Processor_Type = 2#01# and
25493 Signature.Family = 2#0101# and
25494 Signature.Model = 2#0010# then
25495 Type_Found := True;
25496 Ada.Text_IO.Put_Line
25497 ("Pentium OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)");
25500 -- Pentium OverDrive processor for x486 processor-based systems
25501 if Signature.Processor_Type = 2#01# and
25502 Signature.Family = 2#0101# and
25503 Signature.Model = 2#0011# then
25504 Type_Found := True;
25505 Ada.Text_IO.Put_Line
25506 ("Pentium OverDrive processor for x486 processor-based systems");
25509 -- Pentium processor with MMX technology (166, 200)
25510 if Signature.Processor_Type = 2#00# and
25511 Signature.Family = 2#0101# and
25512 Signature.Model = 2#0100# then
25513 Type_Found := True;
25514 Ada.Text_IO.Put_Line
25515 ("Pentium processor with MMX technology (166, 200)");
25518 -- Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133)
25519 if Signature.Processor_Type = 2#01# and
25520 Signature.Family = 2#0101# and
25521 Signature.Model = 2#0100# then
25522 Type_Found := True;
25523 Ada.Text_IO.Put_Line
25524 ("Pentium OverDrive processor with MMX " &
25525 "technology for Pentium processor (75, 90, 100, 120, 133)");
25528 -- Pentium Pro processor
25529 if Signature.Processor_Type = 2#00# and
25530 Signature.Family = 2#0110# and
25531 Signature.Model = 2#0001# then
25532 Type_Found := True;
25533 Ada.Text_IO.Put_Line ("Pentium Pro processor");
25536 -- Pentium II processor, model 3
25537 if Signature.Processor_Type = 2#00# and
25538 Signature.Family = 2#0110# and
25539 Signature.Model = 2#0011# then
25540 Type_Found := True;
25541 Ada.Text_IO.Put_Line ("Pentium II processor, model 3");
25544 -- Pentium II processor, model 5 or Celeron processor
25545 if Signature.Processor_Type = 2#00# and
25546 Signature.Family = 2#0110# and
25547 Signature.Model = 2#0101# then
25548 Type_Found := True;
25549 Ada.Text_IO.Put_Line
25550 ("Pentium II processor, model 5 or Celeron processor");
25553 -- Pentium Pro OverDrive processor
25554 if Signature.Processor_Type = 2#01# and
25555 Signature.Family = 2#0110# and
25556 Signature.Model = 2#0011# then
25557 Type_Found := True;
25558 Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor");
25561 -- If no type recognized, we have an unknown. Display what
25563 if Type_Found = False then
25564 Ada.Text_IO.Put_Line ("Unknown processor");
25567 -----------------------------------------
25568 -- Display processor stepping level. --
25569 -----------------------------------------
25571 Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img);
25573 ---------------------------------
25574 -- Display vendor ID string. --
25575 ---------------------------------
25577 Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID);
25579 ------------------------------------
25580 -- Get the processors features. --
25581 ------------------------------------
25583 Features := Intel_CPU.Features;
25585 -----------------------------
25586 -- Check for a FPU unit. --
25587 -----------------------------
25589 if Features.FPU = True then
25590 Ada.Text_IO.Put_Line ("Floating-Point unit available");
25592 Ada.Text_IO.Put_Line ("no Floating-Point unit");
25593 end if; -- check for FPU
25595 --------------------------------
25596 -- List processor features. --
25597 --------------------------------
25599 Ada.Text_IO.Put_Line ("Supported features: ");
25601 -- Virtual Mode Extension
25602 if Features.VME = True then
25603 Ada.Text_IO.Put_Line (" VME - Virtual Mode Extension");
25606 -- Debugging Extension
25607 if Features.DE = True then
25608 Ada.Text_IO.Put_Line (" DE - Debugging Extension");
25611 -- Page Size Extension
25612 if Features.PSE = True then
25613 Ada.Text_IO.Put_Line (" PSE - Page Size Extension");
25616 -- Time Stamp Counter
25617 if Features.TSC = True then
25618 Ada.Text_IO.Put_Line (" TSC - Time Stamp Counter");
25621 -- Model Specific Registers
25622 if Features.MSR = True then
25623 Ada.Text_IO.Put_Line (" MSR - Model Specific Registers");
25626 -- Physical Address Extension
25627 if Features.PAE = True then
25628 Ada.Text_IO.Put_Line (" PAE - Physical Address Extension");
25631 -- Machine Check Extension
25632 if Features.MCE = True then
25633 Ada.Text_IO.Put_Line (" MCE - Machine Check Extension");
25636 -- CMPXCHG8 instruction supported
25637 if Features.CX8 = True then
25638 Ada.Text_IO.Put_Line (" CX8 - CMPXCHG8 instruction");
25641 -- on-chip APIC hardware support
25642 if Features.APIC = True then
25643 Ada.Text_IO.Put_Line (" APIC - on-chip APIC hardware support");
25646 -- Fast System Call
25647 if Features.SEP = True then
25648 Ada.Text_IO.Put_Line (" SEP - Fast System Call");
25651 -- Memory Type Range Registers
25652 if Features.MTRR = True then
25653 Ada.Text_IO.Put_Line (" MTTR - Memory Type Range Registers");
25656 -- Page Global Enable
25657 if Features.PGE = True then
25658 Ada.Text_IO.Put_Line (" PGE - Page Global Enable");
25661 -- Machine Check Architecture
25662 if Features.MCA = True then
25663 Ada.Text_IO.Put_Line (" MCA - Machine Check Architecture");
25666 -- Conditional Move Instruction Supported
25667 if Features.CMOV = True then
25668 Ada.Text_IO.Put_Line
25669 (" CMOV - Conditional Move Instruction Supported");
25672 -- Page Attribute Table
25673 if Features.PAT = True then
25674 Ada.Text_IO.Put_Line (" PAT - Page Attribute Table");
25677 -- 36-bit Page Size Extension
25678 if Features.PSE_36 = True then
25679 Ada.Text_IO.Put_Line (" PSE_36 - 36-bit Page Size Extension");
25682 -- MMX technology supported
25683 if Features.MMX = True then
25684 Ada.Text_IO.Put_Line (" MMX - MMX technology supported");
25687 -- Fast FP Save and Restore
25688 if Features.FXSR = True then
25689 Ada.Text_IO.Put_Line (" FXSR - Fast FP Save and Restore");
25692 ---------------------
25693 -- Program done. --
25694 ---------------------
25696 Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
25701 Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
25707 @c ---------------------------------------------------------------------------
25708 @node Intel_CPU Package Specification
25709 @subsection @code{Intel_CPU} Package Specification
25710 @cindex Intel_CPU package specification
25712 @smallexample @c adanocomment
25713 -------------------------------------------------------------------------
25715 -- file: intel_cpu.ads --
25717 -- ********************************************* --
25718 -- * WARNING: for 32-bit Intel processors only * --
25719 -- ********************************************* --
25721 -- This package contains a number of subprograms that are useful in --
25722 -- determining the Intel x86 CPU (and the features it supports) on --
25723 -- which the program is running. --
25725 -- The package is based upon the information given in the Intel --
25726 -- Application Note AP-485: "Intel Processor Identification and the --
25727 -- CPUID Instruction" as of April 1998. This application note can be --
25728 -- found on www.intel.com. --
25730 -- It currently deals with 32-bit processors only, will not detect --
25731 -- features added after april 1998, and does not guarantee proper --
25732 -- results on Intel-compatible processors. --
25734 -- Cache info and x386 fpu type detection are not supported. --
25736 -- This package does not use any privileged instructions, so should --
25737 -- work on any OS running on a 32-bit Intel processor. --
25739 -------------------------------------------------------------------------
25741 with Interfaces; use Interfaces;
25742 -- for using unsigned types
25744 with System.Machine_Code; use System.Machine_Code;
25745 -- for using inline assembler code
25747 with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
25748 -- for inserting control characters
25750 package Intel_CPU is
25752 ----------------------
25753 -- Processor bits --
25754 ----------------------
25756 subtype Num_Bits is Natural range 0 .. 31;
25757 -- the number of processor bits (32)
25759 --------------------------
25760 -- Processor register --
25761 --------------------------
25763 -- define a processor register type for easy access to
25764 -- the individual bits
25766 type Processor_Register is array (Num_Bits) of Boolean;
25767 pragma Pack (Processor_Register);
25768 for Processor_Register'Size use 32;
25770 -------------------------
25771 -- Unsigned register --
25772 -------------------------
25774 -- define a processor register type for easy access to
25775 -- the individual bytes
25777 type Unsigned_Register is
25785 for Unsigned_Register use
25787 L1 at 0 range 0 .. 7;
25788 H1 at 0 range 8 .. 15;
25789 L2 at 0 range 16 .. 23;
25790 H2 at 0 range 24 .. 31;
25793 for Unsigned_Register'Size use 32;
25795 ---------------------------------
25796 -- Intel processor vendor ID --
25797 ---------------------------------
25799 Intel_Processor : constant String (1 .. 12) := "GenuineIntel";
25800 -- indicates an Intel manufactured processor
25802 ------------------------------------
25803 -- Processor signature register --
25804 ------------------------------------
25806 -- a register type to hold the processor signature
25808 type Processor_Signature is
25810 Stepping : Natural range 0 .. 15;
25811 Model : Natural range 0 .. 15;
25812 Family : Natural range 0 .. 15;
25813 Processor_Type : Natural range 0 .. 3;
25814 Reserved : Natural range 0 .. 262143;
25817 for Processor_Signature use
25819 Stepping at 0 range 0 .. 3;
25820 Model at 0 range 4 .. 7;
25821 Family at 0 range 8 .. 11;
25822 Processor_Type at 0 range 12 .. 13;
25823 Reserved at 0 range 14 .. 31;
25826 for Processor_Signature'Size use 32;
25828 -----------------------------------
25829 -- Processor features register --
25830 -----------------------------------
25832 -- a processor register to hold the processor feature flags
25834 type Processor_Features is
25836 FPU : Boolean; -- floating point unit on chip
25837 VME : Boolean; -- virtual mode extension
25838 DE : Boolean; -- debugging extension
25839 PSE : Boolean; -- page size extension
25840 TSC : Boolean; -- time stamp counter
25841 MSR : Boolean; -- model specific registers
25842 PAE : Boolean; -- physical address extension
25843 MCE : Boolean; -- machine check extension
25844 CX8 : Boolean; -- cmpxchg8 instruction
25845 APIC : Boolean; -- on-chip apic hardware
25846 Res_1 : Boolean; -- reserved for extensions
25847 SEP : Boolean; -- fast system call
25848 MTRR : Boolean; -- memory type range registers
25849 PGE : Boolean; -- page global enable
25850 MCA : Boolean; -- machine check architecture
25851 CMOV : Boolean; -- conditional move supported
25852 PAT : Boolean; -- page attribute table
25853 PSE_36 : Boolean; -- 36-bit page size extension
25854 Res_2 : Natural range 0 .. 31; -- reserved for extensions
25855 MMX : Boolean; -- MMX technology supported
25856 FXSR : Boolean; -- fast FP save and restore
25857 Res_3 : Natural range 0 .. 127; -- reserved for extensions
25860 for Processor_Features use
25862 FPU at 0 range 0 .. 0;
25863 VME at 0 range 1 .. 1;
25864 DE at 0 range 2 .. 2;
25865 PSE at 0 range 3 .. 3;
25866 TSC at 0 range 4 .. 4;
25867 MSR at 0 range 5 .. 5;
25868 PAE at 0 range 6 .. 6;
25869 MCE at 0 range 7 .. 7;
25870 CX8 at 0 range 8 .. 8;
25871 APIC at 0 range 9 .. 9;
25872 Res_1 at 0 range 10 .. 10;
25873 SEP at 0 range 11 .. 11;
25874 MTRR at 0 range 12 .. 12;
25875 PGE at 0 range 13 .. 13;
25876 MCA at 0 range 14 .. 14;
25877 CMOV at 0 range 15 .. 15;
25878 PAT at 0 range 16 .. 16;
25879 PSE_36 at 0 range 17 .. 17;
25880 Res_2 at 0 range 18 .. 22;
25881 MMX at 0 range 23 .. 23;
25882 FXSR at 0 range 24 .. 24;
25883 Res_3 at 0 range 25 .. 31;
25886 for Processor_Features'Size use 32;
25888 -------------------
25890 -------------------
25892 function Has_FPU return Boolean;
25893 -- return True if a FPU is found
25894 -- use only if CPUID is not supported
25896 function Has_CPUID return Boolean;
25897 -- return True if the processor supports the CPUID instruction
25899 function CPUID_Level return Natural;
25900 -- return the CPUID support level (0, 1 or 2)
25901 -- can only be called if the CPUID instruction is supported
25903 function Vendor_ID return String;
25904 -- return the processor vendor identification string
25905 -- can only be called if the CPUID instruction is supported
25907 function Signature return Processor_Signature;
25908 -- return the processor signature
25909 -- can only be called if the CPUID instruction is supported
25911 function Features return Processor_Features;
25912 -- return the processors features
25913 -- can only be called if the CPUID instruction is supported
25917 ------------------------
25918 -- EFLAGS bit names --
25919 ------------------------
25921 ID_Flag : constant Num_Bits := 21;
25927 @c ---------------------------------------------------------------------------
25928 @node Intel_CPU Package Body
25929 @subsection @code{Intel_CPU} Package Body
25930 @cindex Intel_CPU package body
25932 @smallexample @c adanocomment
25933 package body Intel_CPU is
25935 ---------------------------
25936 -- Detect FPU presence --
25937 ---------------------------
25939 -- There is a FPU present if we can set values to the FPU Status
25940 -- and Control Words.
25942 function Has_FPU return Boolean is
25944 Register : Unsigned_16;
25945 -- processor register to store a word
25949 -- check if we can change the status word
25952 -- the assembler code
25953 "finit" & LF & HT & -- reset status word
25954 "movw $0x5A5A, %%ax" & LF & HT & -- set value status word
25955 "fnstsw %0" & LF & HT & -- save status word
25956 "movw %%ax, %0", -- store status word
25958 -- output stored in Register
25959 -- register must be a memory location
25960 Outputs => Unsigned_16'Asm_output ("=m", Register),
25962 -- tell compiler that we used eax
25965 -- if the status word is zero, there is no FPU
25966 if Register = 0 then
25967 return False; -- no status word
25968 end if; -- check status word value
25970 -- check if we can get the control word
25973 -- the assembler code
25974 "fnstcw %0", -- save the control word
25976 -- output into Register
25977 -- register must be a memory location
25978 Outputs => Unsigned_16'Asm_output ("=m", Register));
25980 -- check the relevant bits
25981 if (Register and 16#103F#) /= 16#003F# then
25982 return False; -- no control word
25983 end if; -- check control word value
25990 --------------------------------
25991 -- Detect CPUID instruction --
25992 --------------------------------
25994 -- The processor supports the CPUID instruction if it is possible
25995 -- to change the value of ID flag bit in the EFLAGS register.
25997 function Has_CPUID return Boolean is
25999 Original_Flags, Modified_Flags : Processor_Register;
26000 -- EFLAG contents before and after changing the ID flag
26004 -- try flipping the ID flag in the EFLAGS register
26007 -- the assembler code
26008 "pushfl" & LF & HT & -- push EFLAGS on stack
26009 "pop %%eax" & LF & HT & -- pop EFLAGS into eax
26010 "movl %%eax, %0" & LF & HT & -- save EFLAGS content
26011 "xor $0x200000, %%eax" & LF & HT & -- flip ID flag
26012 "push %%eax" & LF & HT & -- push EFLAGS on stack
26013 "popfl" & LF & HT & -- load EFLAGS register
26014 "pushfl" & LF & HT & -- push EFLAGS on stack
26015 "pop %1", -- save EFLAGS content
26017 -- output values, may be anything
26018 -- Original_Flags is %0
26019 -- Modified_Flags is %1
26021 (Processor_Register'Asm_output ("=g", Original_Flags),
26022 Processor_Register'Asm_output ("=g", Modified_Flags)),
26024 -- tell compiler eax is destroyed
26027 -- check if CPUID is supported
26028 if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then
26029 return True; -- ID flag was modified
26031 return False; -- ID flag unchanged
26032 end if; -- check for CPUID
26036 -------------------------------
26037 -- Get CPUID support level --
26038 -------------------------------
26040 function CPUID_Level return Natural is
26042 Level : Unsigned_32;
26043 -- returned support level
26047 -- execute CPUID, storing the results in the Level register
26050 -- the assembler code
26051 "cpuid", -- execute CPUID
26053 -- zero is stored in eax
26054 -- returning the support level in eax
26055 Inputs => Unsigned_32'Asm_input ("a", 0),
26057 -- eax is stored in Level
26058 Outputs => Unsigned_32'Asm_output ("=a", Level),
26060 -- tell compiler ebx, ecx and edx registers are destroyed
26061 Clobber => "ebx, ecx, edx");
26063 -- return the support level
26064 return Natural (Level);
26068 --------------------------------
26069 -- Get CPU Vendor ID String --
26070 --------------------------------
26072 -- The vendor ID string is returned in the ebx, ecx and edx register
26073 -- after executing the CPUID instruction with eax set to zero.
26074 -- In case of a true Intel processor the string returned is
26077 function Vendor_ID return String is
26079 Ebx, Ecx, Edx : Unsigned_Register;
26080 -- registers containing the vendor ID string
26082 Vendor_ID : String (1 .. 12);
26083 -- the vendor ID string
26087 -- execute CPUID, storing the results in the processor registers
26090 -- the assembler code
26091 "cpuid", -- execute CPUID
26093 -- zero stored in eax
26094 -- vendor ID string returned in ebx, ecx and edx
26095 Inputs => Unsigned_32'Asm_input ("a", 0),
26097 -- ebx is stored in Ebx
26098 -- ecx is stored in Ecx
26099 -- edx is stored in Edx
26100 Outputs => (Unsigned_Register'Asm_output ("=b", Ebx),
26101 Unsigned_Register'Asm_output ("=c", Ecx),
26102 Unsigned_Register'Asm_output ("=d", Edx)));
26104 -- now build the vendor ID string
26105 Vendor_ID( 1) := Character'Val (Ebx.L1);
26106 Vendor_ID( 2) := Character'Val (Ebx.H1);
26107 Vendor_ID( 3) := Character'Val (Ebx.L2);
26108 Vendor_ID( 4) := Character'Val (Ebx.H2);
26109 Vendor_ID( 5) := Character'Val (Edx.L1);
26110 Vendor_ID( 6) := Character'Val (Edx.H1);
26111 Vendor_ID( 7) := Character'Val (Edx.L2);
26112 Vendor_ID( 8) := Character'Val (Edx.H2);
26113 Vendor_ID( 9) := Character'Val (Ecx.L1);
26114 Vendor_ID(10) := Character'Val (Ecx.H1);
26115 Vendor_ID(11) := Character'Val (Ecx.L2);
26116 Vendor_ID(12) := Character'Val (Ecx.H2);
26123 -------------------------------
26124 -- Get processor signature --
26125 -------------------------------
26127 function Signature return Processor_Signature is
26129 Result : Processor_Signature;
26130 -- processor signature returned
26134 -- execute CPUID, storing the results in the Result variable
26137 -- the assembler code
26138 "cpuid", -- execute CPUID
26140 -- one is stored in eax
26141 -- processor signature returned in eax
26142 Inputs => Unsigned_32'Asm_input ("a", 1),
26144 -- eax is stored in Result
26145 Outputs => Processor_Signature'Asm_output ("=a", Result),
26147 -- tell compiler that ebx, ecx and edx are also destroyed
26148 Clobber => "ebx, ecx, edx");
26150 -- return processor signature
26155 ------------------------------
26156 -- Get processor features --
26157 ------------------------------
26159 function Features return Processor_Features is
26161 Result : Processor_Features;
26162 -- processor features returned
26166 -- execute CPUID, storing the results in the Result variable
26169 -- the assembler code
26170 "cpuid", -- execute CPUID
26172 -- one stored in eax
26173 -- processor features returned in edx
26174 Inputs => Unsigned_32'Asm_input ("a", 1),
26176 -- edx is stored in Result
26177 Outputs => Processor_Features'Asm_output ("=d", Result),
26179 -- tell compiler that ebx and ecx are also destroyed
26180 Clobber => "ebx, ecx");
26182 -- return processor signature
26189 @c END OF INLINE ASSEMBLER CHAPTER
26190 @c ===============================
26192 @c ***********************************
26193 @c * Compatibility and Porting Guide *
26194 @c ***********************************
26195 @node Compatibility and Porting Guide
26196 @appendix Compatibility and Porting Guide
26199 This chapter describes the compatibility issues that may arise between
26200 GNAT and other Ada 83 and Ada 95 compilation systems, and shows how GNAT
26201 can expedite porting
26202 applications developed in other Ada environments.
26205 * Compatibility with Ada 83::
26206 * Implementation-dependent characteristics::
26207 * Compatibility with Other Ada 95 Systems::
26208 * Representation Clauses::
26209 * Compatibility with DEC Ada 83::
26211 * Transitioning from Alpha to Integrity OpenVMS::
26215 @node Compatibility with Ada 83
26216 @section Compatibility with Ada 83
26217 @cindex Compatibility (between Ada 83 and Ada 95)
26220 Ada 95 is designed to be highly upwards compatible with Ada 83. In
26221 particular, the design intention is that the difficulties associated
26222 with moving from Ada 83 to Ada 95 should be no greater than those
26223 that occur when moving from one Ada 83 system to another.
26225 However, there are a number of points at which there are minor
26226 incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains
26227 full details of these issues,
26228 and should be consulted for a complete treatment.
26230 following subsections treat the most likely issues to be encountered.
26233 * Legal Ada 83 programs that are illegal in Ada 95::
26234 * More deterministic semantics::
26235 * Changed semantics::
26236 * Other language compatibility issues::
26239 @node Legal Ada 83 programs that are illegal in Ada 95
26240 @subsection Legal Ada 83 programs that are illegal in Ada 95
26243 @item Character literals
26244 Some uses of character literals are ambiguous. Since Ada 95 has introduced
26245 @code{Wide_Character} as a new predefined character type, some uses of
26246 character literals that were legal in Ada 83 are illegal in Ada 95.
26248 @smallexample @c ada
26249 for Char in 'A' .. 'Z' loop ... end loop;
26252 The problem is that @code{'A'} and @code{'Z'} could be from either
26253 @code{Character} or @code{Wide_Character}. The simplest correction
26254 is to make the type explicit; e.g.:
26255 @smallexample @c ada
26256 for Char in Character range 'A' .. 'Z' loop ... end loop;
26259 @item New reserved words
26260 The identifiers @code{abstract}, @code{aliased}, @code{protected},
26261 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
26262 Existing Ada 83 code using any of these identifiers must be edited to
26263 use some alternative name.
26265 @item Freezing rules
26266 The rules in Ada 95 are slightly different with regard to the point at
26267 which entities are frozen, and representation pragmas and clauses are
26268 not permitted past the freeze point. This shows up most typically in
26269 the form of an error message complaining that a representation item
26270 appears too late, and the appropriate corrective action is to move
26271 the item nearer to the declaration of the entity to which it refers.
26273 A particular case is that representation pragmas
26276 extended DEC Ada 83 compatibility pragmas such as @code{Export_Procedure})
26278 cannot be applied to a subprogram body. If necessary, a separate subprogram
26279 declaration must be introduced to which the pragma can be applied.
26281 @item Optional bodies for library packages
26282 In Ada 83, a package that did not require a package body was nevertheless
26283 allowed to have one. This lead to certain surprises in compiling large
26284 systems (situations in which the body could be unexpectedly ignored by the
26285 binder). In Ada 95, if a package does not require a body then it is not
26286 permitted to have a body. To fix this problem, simply remove a redundant
26287 body if it is empty, or, if it is non-empty, introduce a dummy declaration
26288 into the spec that makes the body required. One approach is to add a private
26289 part to the package declaration (if necessary), and define a parameterless
26290 procedure called @code{Requires_Body}, which must then be given a dummy
26291 procedure body in the package body, which then becomes required.
26292 Another approach (assuming that this does not introduce elaboration
26293 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
26294 since one effect of this pragma is to require the presence of a package body.
26296 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
26297 In Ada 95, the exception @code{Numeric_Error} is a renaming of
26298 @code{Constraint_Error}.
26299 This means that it is illegal to have separate exception handlers for
26300 the two exceptions. The fix is simply to remove the handler for the
26301 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
26302 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
26304 @item Indefinite subtypes in generics
26305 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
26306 as the actual for a generic formal private type, but then the instantiation
26307 would be illegal if there were any instances of declarations of variables
26308 of this type in the generic body. In Ada 95, to avoid this clear violation
26309 of the methodological principle known as the ``contract model'',
26310 the generic declaration explicitly indicates whether
26311 or not such instantiations are permitted. If a generic formal parameter
26312 has explicit unknown discriminants, indicated by using @code{(<>)} after the
26313 type name, then it can be instantiated with indefinite types, but no
26314 stand-alone variables can be declared of this type. Any attempt to declare
26315 such a variable will result in an illegality at the time the generic is
26316 declared. If the @code{(<>)} notation is not used, then it is illegal
26317 to instantiate the generic with an indefinite type.
26318 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
26319 It will show up as a compile time error, and
26320 the fix is usually simply to add the @code{(<>)} to the generic declaration.
26323 @node More deterministic semantics
26324 @subsection More deterministic semantics
26328 Conversions from real types to integer types round away from 0. In Ada 83
26329 the conversion Integer(2.5) could deliver either 2 or 3 as its value. This
26330 implementation freedom was intended to support unbiased rounding in
26331 statistical applications, but in practice it interfered with portability.
26332 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
26333 is required. Numeric code may be affected by this change in semantics.
26334 Note, though, that this issue is no worse than already existed in Ada 83
26335 when porting code from one vendor to another.
26338 The Real-Time Annex introduces a set of policies that define the behavior of
26339 features that were implementation dependent in Ada 83, such as the order in
26340 which open select branches are executed.
26343 @node Changed semantics
26344 @subsection Changed semantics
26347 The worst kind of incompatibility is one where a program that is legal in
26348 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
26349 possible in Ada 83. Fortunately this is extremely rare, but the one
26350 situation that you should be alert to is the change in the predefined type
26351 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
26354 @item range of @code{Character}
26355 The range of @code{Standard.Character} is now the full 256 characters
26356 of Latin-1, whereas in most Ada 83 implementations it was restricted
26357 to 128 characters. Although some of the effects of
26358 this change will be manifest in compile-time rejection of legal
26359 Ada 83 programs it is possible for a working Ada 83 program to have
26360 a different effect in Ada 95, one that was not permitted in Ada 83.
26361 As an example, the expression
26362 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
26363 delivers @code{255} as its value.
26364 In general, you should look at the logic of any
26365 character-processing Ada 83 program and see whether it needs to be adapted
26366 to work correctly with Latin-1. Note that the predefined Ada 95 API has a
26367 character handling package that may be relevant if code needs to be adapted
26368 to account for the additional Latin-1 elements.
26369 The desirable fix is to
26370 modify the program to accommodate the full character set, but in some cases
26371 it may be convenient to define a subtype or derived type of Character that
26372 covers only the restricted range.
26376 @node Other language compatibility issues
26377 @subsection Other language compatibility issues
26379 @item @option{-gnat83 switch}
26380 All implementations of GNAT provide a switch that causes GNAT to operate
26381 in Ada 83 mode. In this mode, some but not all compatibility problems
26382 of the type described above are handled automatically. For example, the
26383 new Ada 95 reserved words are treated simply as identifiers as in Ada 83.
26385 in practice, it is usually advisable to make the necessary modifications
26386 to the program to remove the need for using this switch.
26387 See @ref{Compiling Ada 83 Programs}.
26389 @item Support for removed Ada 83 pragmas and attributes
26390 A number of pragmas and attributes from Ada 83 have been removed from Ada 95,
26391 generally because they have been replaced by other mechanisms. Ada 95
26392 compilers are allowed, but not required, to implement these missing
26393 elements. In contrast with some other Ada 95 compilers, GNAT implements all
26394 such pragmas and attributes, eliminating this compatibility concern. These
26395 include @code{pragma Interface} and the floating point type attributes
26396 (@code{Emax}, @code{Mantissa}, etc.), among other items.
26399 @node Implementation-dependent characteristics
26400 @section Implementation-dependent characteristics
26402 Although the Ada language defines the semantics of each construct as
26403 precisely as practical, in some situations (for example for reasons of
26404 efficiency, or where the effect is heavily dependent on the host or target
26405 platform) the implementation is allowed some freedom. In porting Ada 83
26406 code to GNAT, you need to be aware of whether / how the existing code
26407 exercised such implementation dependencies. Such characteristics fall into
26408 several categories, and GNAT offers specific support in assisting the
26409 transition from certain Ada 83 compilers.
26412 * Implementation-defined pragmas::
26413 * Implementation-defined attributes::
26415 * Elaboration order::
26416 * Target-specific aspects::
26419 @node Implementation-defined pragmas
26420 @subsection Implementation-defined pragmas
26423 Ada compilers are allowed to supplement the language-defined pragmas, and
26424 these are a potential source of non-portability. All GNAT-defined pragmas
26425 are described in the GNAT Reference Manual, and these include several that
26426 are specifically intended to correspond to other vendors' Ada 83 pragmas.
26427 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
26429 compatibility with DEC Ada 83, GNAT supplies the pragmas
26430 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
26431 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
26432 and @code{Volatile}.
26433 Other relevant pragmas include @code{External} and @code{Link_With}.
26434 Some vendor-specific
26435 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
26437 avoiding compiler rejection of units that contain such pragmas; they are not
26438 relevant in a GNAT context and hence are not otherwise implemented.
26440 @node Implementation-defined attributes
26441 @subsection Implementation-defined attributes
26443 Analogous to pragmas, the set of attributes may be extended by an
26444 implementation. All GNAT-defined attributes are described in the
26445 @cite{GNAT Reference Manual}, and these include several that are specifically
26447 to correspond to other vendors' Ada 83 attributes. For migrating from VADS,
26448 the attribute @code{VADS_Size} may be useful. For compatibility with DEC
26449 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
26453 @subsection Libraries
26455 Vendors may supply libraries to supplement the standard Ada API. If Ada 83
26456 code uses vendor-specific libraries then there are several ways to manage
26460 If the source code for the libraries (specifications and bodies) are
26461 available, then the libraries can be migrated in the same way as the
26464 If the source code for the specifications but not the bodies are
26465 available, then you can reimplement the bodies.
26467 Some new Ada 95 features obviate the need for library support. For
26468 example most Ada 83 vendors supplied a package for unsigned integers. The
26469 Ada 95 modular type feature is the preferred way to handle this need, so
26470 instead of migrating or reimplementing the unsigned integer package it may
26471 be preferable to retrofit the application using modular types.
26474 @node Elaboration order
26475 @subsection Elaboration order
26477 The implementation can choose any elaboration order consistent with the unit
26478 dependency relationship. This freedom means that some orders can result in
26479 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
26480 to invoke a subprogram its body has been elaborated, or to instantiate a
26481 generic before the generic body has been elaborated. By default GNAT
26482 attempts to choose a safe order (one that will not encounter access before
26483 elaboration problems) by implicitly inserting Elaborate_All pragmas where
26484 needed. However, this can lead to the creation of elaboration circularities
26485 and a resulting rejection of the program by gnatbind. This issue is
26486 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
26487 In brief, there are several
26488 ways to deal with this situation:
26492 Modify the program to eliminate the circularities, e.g. by moving
26493 elaboration-time code into explicitly-invoked procedures
26495 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
26496 @code{Elaborate} pragmas, and then inhibit the generation of implicit
26497 @code{Elaborate_All}
26498 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
26499 (by selectively suppressing elaboration checks via pragma
26500 @code{Suppress(Elaboration_Check)} when it is safe to do so).
26503 @node Target-specific aspects
26504 @subsection Target-specific aspects
26506 Low-level applications need to deal with machine addresses, data
26507 representations, interfacing with assembler code, and similar issues. If
26508 such an Ada 83 application is being ported to different target hardware (for
26509 example where the byte endianness has changed) then you will need to
26510 carefully examine the program logic; the porting effort will heavily depend
26511 on the robustness of the original design. Moreover, Ada 95 is sometimes
26512 incompatible with typical Ada 83 compiler practices regarding implicit
26513 packing, the meaning of the Size attribute, and the size of access values.
26514 GNAT's approach to these issues is described in @ref{Representation Clauses}.
26516 @node Compatibility with Other Ada 95 Systems
26517 @section Compatibility with Other Ada 95 Systems
26520 Providing that programs avoid the use of implementation dependent and
26521 implementation defined features of Ada 95, as documented in the Ada 95
26522 reference manual, there should be a high degree of portability between
26523 GNAT and other Ada 95 systems. The following are specific items which
26524 have proved troublesome in moving GNAT programs to other Ada 95
26525 compilers, but do not affect porting code to GNAT@.
26528 @item Ada 83 Pragmas and Attributes
26529 Ada 95 compilers are allowed, but not required, to implement the missing
26530 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
26531 GNAT implements all such pragmas and attributes, eliminating this as
26532 a compatibility concern, but some other Ada 95 compilers reject these
26533 pragmas and attributes.
26535 @item Special-needs Annexes
26536 GNAT implements the full set of special needs annexes. At the
26537 current time, it is the only Ada 95 compiler to do so. This means that
26538 programs making use of these features may not be portable to other Ada
26539 95 compilation systems.
26541 @item Representation Clauses
26542 Some other Ada 95 compilers implement only the minimal set of
26543 representation clauses required by the Ada 95 reference manual. GNAT goes
26544 far beyond this minimal set, as described in the next section.
26547 @node Representation Clauses
26548 @section Representation Clauses
26551 The Ada 83 reference manual was quite vague in describing both the minimal
26552 required implementation of representation clauses, and also their precise
26553 effects. The Ada 95 reference manual is much more explicit, but the minimal
26554 set of capabilities required in Ada 95 is quite limited.
26556 GNAT implements the full required set of capabilities described in the
26557 Ada 95 reference manual, but also goes much beyond this, and in particular
26558 an effort has been made to be compatible with existing Ada 83 usage to the
26559 greatest extent possible.
26561 A few cases exist in which Ada 83 compiler behavior is incompatible with
26562 requirements in the Ada 95 reference manual. These are instances of
26563 intentional or accidental dependence on specific implementation dependent
26564 characteristics of these Ada 83 compilers. The following is a list of
26565 the cases most likely to arise in existing legacy Ada 83 code.
26568 @item Implicit Packing
26569 Some Ada 83 compilers allowed a Size specification to cause implicit
26570 packing of an array or record. This could cause expensive implicit
26571 conversions for change of representation in the presence of derived
26572 types, and the Ada design intends to avoid this possibility.
26573 Subsequent AI's were issued to make it clear that such implicit
26574 change of representation in response to a Size clause is inadvisable,
26575 and this recommendation is represented explicitly in the Ada 95 RM
26576 as implementation advice that is followed by GNAT@.
26577 The problem will show up as an error
26578 message rejecting the size clause. The fix is simply to provide
26579 the explicit pragma @code{Pack}, or for more fine tuned control, provide
26580 a Component_Size clause.
26582 @item Meaning of Size Attribute
26583 The Size attribute in Ada 95 for discrete types is defined as being the
26584 minimal number of bits required to hold values of the type. For example,
26585 on a 32-bit machine, the size of Natural will typically be 31 and not
26586 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and
26587 some 32 in this situation. This problem will usually show up as a compile
26588 time error, but not always. It is a good idea to check all uses of the
26589 'Size attribute when porting Ada 83 code. The GNAT specific attribute
26590 Object_Size can provide a useful way of duplicating the behavior of
26591 some Ada 83 compiler systems.
26593 @item Size of Access Types
26594 A common assumption in Ada 83 code is that an access type is in fact a pointer,
26595 and that therefore it will be the same size as a System.Address value. This
26596 assumption is true for GNAT in most cases with one exception. For the case of
26597 a pointer to an unconstrained array type (where the bounds may vary from one
26598 value of the access type to another), the default is to use a ``fat pointer'',
26599 which is represented as two separate pointers, one to the bounds, and one to
26600 the array. This representation has a number of advantages, including improved
26601 efficiency. However, it may cause some difficulties in porting existing Ada 83
26602 code which makes the assumption that, for example, pointers fit in 32 bits on
26603 a machine with 32-bit addressing.
26605 To get around this problem, GNAT also permits the use of ``thin pointers'' for
26606 access types in this case (where the designated type is an unconstrained array
26607 type). These thin pointers are indeed the same size as a System.Address value.
26608 To specify a thin pointer, use a size clause for the type, for example:
26610 @smallexample @c ada
26611 type X is access all String;
26612 for X'Size use Standard'Address_Size;
26616 which will cause the type X to be represented using a single pointer.
26617 When using this representation, the bounds are right behind the array.
26618 This representation is slightly less efficient, and does not allow quite
26619 such flexibility in the use of foreign pointers or in using the
26620 Unrestricted_Access attribute to create pointers to non-aliased objects.
26621 But for any standard portable use of the access type it will work in
26622 a functionally correct manner and allow porting of existing code.
26623 Note that another way of forcing a thin pointer representation
26624 is to use a component size clause for the element size in an array,
26625 or a record representation clause for an access field in a record.
26628 @node Compatibility with DEC Ada 83
26629 @section Compatibility with DEC Ada 83
26632 The VMS version of GNAT fully implements all the pragmas and attributes
26633 provided by DEC Ada 83, as well as providing the standard DEC Ada 83
26634 libraries, including Starlet. In addition, data layouts and parameter
26635 passing conventions are highly compatible. This means that porting
26636 existing DEC Ada 83 code to GNAT in VMS systems should be easier than
26637 most other porting efforts. The following are some of the most
26638 significant differences between GNAT and DEC Ada 83.
26641 @item Default floating-point representation
26642 In GNAT, the default floating-point format is IEEE, whereas in DEC Ada 83,
26643 it is VMS format. GNAT does implement the necessary pragmas
26644 (Long_Float, Float_Representation) for changing this default.
26647 The package System in GNAT exactly corresponds to the definition in the
26648 Ada 95 reference manual, which means that it excludes many of the
26649 DEC Ada 83 extensions. However, a separate package Aux_DEC is provided
26650 that contains the additional definitions, and a special pragma,
26651 Extend_System allows this package to be treated transparently as an
26652 extension of package System.
26655 The definitions provided by Aux_DEC are exactly compatible with those
26656 in the DEC Ada 83 version of System, with one exception.
26657 DEC Ada provides the following declarations:
26659 @smallexample @c ada
26660 TO_ADDRESS (INTEGER)
26661 TO_ADDRESS (UNSIGNED_LONGWORD)
26662 TO_ADDRESS (universal_integer)
26666 The version of TO_ADDRESS taking a universal integer argument is in fact
26667 an extension to Ada 83 not strictly compatible with the reference manual.
26668 In GNAT, we are constrained to be exactly compatible with the standard,
26669 and this means we cannot provide this capability. In DEC Ada 83, the
26670 point of this definition is to deal with a call like:
26672 @smallexample @c ada
26673 TO_ADDRESS (16#12777#);
26677 Normally, according to the Ada 83 standard, one would expect this to be
26678 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
26679 of TO_ADDRESS@. However, in DEC Ada 83, there is no ambiguity, since the
26680 definition using universal_integer takes precedence.
26682 In GNAT, since the version with universal_integer cannot be supplied, it is
26683 not possible to be 100% compatible. Since there are many programs using
26684 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
26685 to change the name of the function in the UNSIGNED_LONGWORD case, so the
26686 declarations provided in the GNAT version of AUX_Dec are:
26688 @smallexample @c ada
26689 function To_Address (X : Integer) return Address;
26690 pragma Pure_Function (To_Address);
26692 function To_Address_Long (X : Unsigned_Longword)
26694 pragma Pure_Function (To_Address_Long);
26698 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
26699 change the name to TO_ADDRESS_LONG@.
26701 @item Task_Id values
26702 The Task_Id values assigned will be different in the two systems, and GNAT
26703 does not provide a specified value for the Task_Id of the environment task,
26704 which in GNAT is treated like any other declared task.
26707 For full details on these and other less significant compatibility issues,
26708 see appendix E of the Digital publication entitled @cite{DEC Ada, Technical
26709 Overview and Comparison on DIGITAL Platforms}.
26711 For GNAT running on other than VMS systems, all the DEC Ada 83 pragmas and
26712 attributes are recognized, although only a subset of them can sensibly
26713 be implemented. The description of pragmas in this reference manual
26714 indicates whether or not they are applicable to non-VMS systems.
26718 @node Transitioning from Alpha to Integrity OpenVMS
26719 @section Transitioning from Alpha to Integrity OpenVMS
26722 * Introduction to transitioning::
26723 * Migration of 32 bit code::
26724 * Taking advantage of 64 bit addressing::
26725 * Technical details::
26728 @node Introduction to transitioning
26729 @subsection Introduction to transitioning
26732 This guide is meant to assist users of GNAT Pro
26733 for Alpha OpenVMS who are planning to transition to the IA64 architecture.
26734 GNAT Pro for Open VMS Integrity has been designed to meet
26739 Providing a full conforming implementation of the Ada 95 language
26742 Allowing maximum backward compatibility, thus easing migration of existing
26746 Supplying a path for exploiting the full IA64 address range
26750 Ada's strong typing semantics has made it
26751 impractical to have different 32-bit and 64-bit modes. As soon as
26752 one object could possibly be outside the 32-bit address space, this
26753 would make it necessary for the @code{System.Address} type to be 64 bits.
26754 In particular, this would cause inconsistencies if 32-bit code is
26755 called from 64-bit code that raises an exception.
26757 This issue has been resolved by always using 64-bit addressing
26758 at the system level, but allowing for automatic conversions between
26759 32-bit and 64-bit addresses where required. Thus users who
26760 do not currently require 64-bit addressing capabilities, can
26761 recompile their code with only minimal changes (and indeed
26762 if the code is written in portable Ada, with no assumptions about
26763 the size of the @code{Address} type, then no changes at all are necessary).
26765 this approach provides a simple, gradual upgrade path to future
26766 use of larger memories than available for 32-bit systems.
26767 Also, newly written applications or libraries will by default
26768 be fully compatible with future systems exploiting 64-bit
26769 addressing capabilities present in IA64.
26771 @ref{Migration of 32 bit code}, will focus on porting applications
26772 that do not require more than 2 GB of
26773 addressable memory. This code will be referred to as
26774 @emph{32-bit code}.
26775 For applications intending to exploit the full ia64 address space,
26776 @ref{Taking advantage of 64 bit addressing},
26777 will consider further changes that may be required.
26778 Such code is called @emph{64-bit code} in the
26779 remainder of this guide.
26782 @node Migration of 32 bit code
26783 @subsection Migration of 32-bit code
26788 * Unchecked conversions::
26789 * Predefined constants::
26790 * Single source compatibility::
26791 * Experience with source compatibility::
26794 @node Address types
26795 @subsubsection Address types
26798 To solve the problem of mixing 64-bit and 32-bit addressing,
26799 while maintaining maximum backward compatibility, the following
26800 approach has been taken:
26804 @code{System.Address} always has a size of 64 bits
26807 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
26812 Since @code{System.Short_Address} is a subtype of @code{System.Address},
26813 a @code{Short_Address}
26814 may be used where an @code{Address} is required, and vice versa, without
26815 needing explicit type conversions.
26816 By virtue of the Open VMS Integrity parameter passing conventions,
26818 and exported subprograms that have 32-bit address parameters are
26819 compatible with those that have 64-bit address parameters.
26820 (See @ref{Making code 64 bit clean}, for details.)
26822 The areas that may need attention are those where record types have
26823 been defined that contain components of the type @code{System.Address}, and
26824 where objects of this type are passed to code expecting a record layout with
26827 Different compilers on different platforms cannot be
26828 expected to represent the same type in the same way,
26829 since alignment constraints
26830 and other system-dependent properties affect the compiler's decision.
26831 For that reason, Ada code
26832 generally uses representation clauses to specify the expected
26833 layout where required.
26835 If such a representation clause uses 32 bits for a component having
26836 the type @code{System.Address}, GNAT Pro for OpenVMS Integrity will detect
26837 that error and produce a specific diagnostic message.
26838 The developer should then determine whether the representation
26839 should be 64 bits or not and make either of two changes:
26840 change the size to 64 bits and leave the type as @code{System.Address}, or
26841 leave the size as 32 bits and change the type to @code{System.Short_Address}.
26842 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
26843 required in any code setting or accessing the field; the compiler will
26844 automatically perform any needed conversions between address
26848 @subsubsection Access types
26851 By default, objects designated by access values are always
26852 allocated in the 32-bit
26853 address space. Thus legacy code will never contain
26854 any objects that are not addressable with 32-bit addresses, and
26855 the compiler will never raise exceptions as result of mixing
26856 32-bit and 64-bit addresses.
26858 However, the access values themselves are represented in 64 bits, for optimum
26859 performance and future compatibility with 64-bit code. As was
26860 the case with @code{System.Address}, the compiler will give an error message
26861 if an object or record component has a representation clause that
26862 requires the access value to fit in 32 bits. In such a situation,
26863 an explicit size clause for the access type, specifying 32 bits,
26864 will have the desired effect.
26866 General access types (declared with @code{access all}) can never be
26867 32 bits, as values of such types must be able to refer to any object
26868 of the designated type,
26869 including objects residing outside the 32-bit address range.
26870 Existing Ada 83 code will not contain such type definitions,
26871 however, since general access types were introduced in Ada 95.
26873 @node Unchecked conversions
26874 @subsubsection Unchecked conversions
26877 In the case of an @code{Unchecked_Conversion} where the source type is a
26878 64-bit access type or the type @code{System.Address}, and the target
26879 type is a 32-bit type, the compiler will generate a warning.
26880 Even though the generated code will still perform the required
26881 conversions, it is highly recommended in these cases to use
26882 respectively a 32-bit access type or @code{System.Short_Address}
26883 as the source type.
26885 @node Predefined constants
26886 @subsubsection Predefined constants
26889 The following predefined constants have changed:
26891 @multitable {@code{System.Address_Size}} {2**32} {2**64}
26892 @item @b{Constant} @tab @b{Old} @tab @b{New}
26893 @item @code{System.Word_Size} @tab 32 @tab 64
26894 @item @code{System.Memory_Size} @tab 2**32 @tab 2**64
26895 @item @code{System.Address_Size} @tab 32 @tab 64
26899 If you need to refer to the specific
26900 memory size of a 32-bit implementation, instead of the
26901 actual memory size, use @code{System.Short_Memory_Size}
26902 rather than @code{System.Memory_Size}.
26903 Similarly, references to @code{System.Address_Size} may need
26904 to be replaced by @code{System.Short_Address'Size}.
26905 The program @command{gnatfind} may be useful for locating
26906 references to the above constants, so that you can verify that they
26909 @node Single source compatibility
26910 @subsubsection Single source compatibility
26913 In order to allow the same source code to be compiled on
26914 both Alpha and IA64 platforms, GNAT Pro for Alpha/OpenVMS
26915 defines @code{System.Short_Address} and System.Short_Memory_Size
26916 as aliases of respectively @code{System.Address} and
26917 @code{System.Memory_Size}.
26918 (These aliases also leave the door open for a possible
26919 future ``upgrade'' of OpenVMS Alpha to a 64-bit address space.)
26921 @node Experience with source compatibility
26922 @subsubsection Experience with source compatibility
26925 The Security Server and STARLET provide an interesting ``test case''
26926 for source compatibility issues, since it is in such system code
26927 where assumptions about @code{Address} size might be expected to occur.
26928 Indeed, there were a small number of occasions in the Security Server
26929 file @file{jibdef.ads}
26930 where a representation clause for a record type specified
26931 32 bits for a component of type @code{Address}.
26932 All of these errors were detected by the compiler.
26933 The repair was obvious and immediate; to simply replace @code{Address} by
26934 @code{Short_Address}.
26936 In the case of STARLET, there were several record types that should
26937 have had representation clauses but did not. In these record types
26938 there was an implicit assumption that an @code{Address} value occupied
26940 These compiled without error, but their usage resulted in run-time error
26941 returns from STARLET system calls.
26942 To assist in the compile-time detection of such situations, we
26943 plan to include a switch to generate a warning message when a
26944 record component is of type @code{Address}.
26947 @c ****************************************
26948 @node Taking advantage of 64 bit addressing
26949 @subsection Taking advantage of 64-bit addressing
26952 * Making code 64 bit clean::
26953 * Allocating memory from the 64 bit storage pool::
26954 * Restrictions on use of 64 bit objects::
26955 * Using 64 bit storage pools by default::
26956 * General access types::
26957 * STARLET and other predefined libraries::
26960 @node Making code 64 bit clean
26961 @subsubsection Making code 64-bit clean
26964 In order to prevent problems that may occur when (parts of) a
26965 system start using memory outside the 32-bit address range,
26966 we recommend some additional guidelines:
26970 For imported subprograms that take parameters of the
26971 type @code{System.Address}, ensure that these subprograms can
26972 indeed handle 64-bit addresses. If not, or when in doubt,
26973 change the subprogram declaration to specify
26974 @code{System.Short_Address} instead.
26977 Resolve all warnings related to size mismatches in
26978 unchecked conversions. Failing to do so causes
26979 erroneous execution if the source object is outside
26980 the 32-bit address space.
26983 (optional) Explicitly use the 32-bit storage pool
26984 for access types used in a 32-bit context, or use
26985 generic access types where possible
26986 (see @ref{Restrictions on use of 64 bit objects}).
26990 If these rules are followed, the compiler will automatically insert
26991 any necessary checks to ensure that no addresses or access values
26992 passed to 32-bit code ever refer to objects outside the 32-bit
26994 Any attempt to do this will raise @code{Constraint_Error}.
26996 @node Allocating memory from the 64 bit storage pool
26997 @subsubsection Allocating memory from the 64-bit storage pool
27000 For any access type @code{T} that potentially requires memory allocations
27001 beyond the 32-bit address space,
27002 use the following representation clause:
27004 @smallexample @c ada
27005 for T'Storage_Pool use System.Pool_64;
27009 @node Restrictions on use of 64 bit objects
27010 @subsubsection Restrictions on use of 64-bit objects
27013 Taking the address of an object allocated from a 64-bit storage pool,
27014 and then passing this address to a subprogram expecting
27015 @code{System.Short_Address},
27016 or assigning it to a variable of type @code{Short_Address}, will cause
27017 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
27018 (see @ref{Making code 64 bit clean}), or checks are suppressed,
27019 no exception is raised and execution
27020 will become erroneous.
27022 @node Using 64 bit storage pools by default
27023 @subsubsection Using 64-bit storage pools by default
27026 In some cases it may be desirable to have the compiler allocate
27027 from 64-bit storage pools by default. This may be the case for
27028 libraries that are 64-bit clean, but may be used in both 32-bit
27029 and 64-bit contexts. For these cases the following configuration
27030 pragma may be specified:
27032 @smallexample @c ada
27033 pragma Pool_64_Default;
27037 Any code compiled in the context of this pragma will by default
27038 use the @code{System.Pool_64} storage pool. This default may be overridden
27039 for a specific access type @code{T} by the representation clause:
27041 @smallexample @c ada
27042 for T'Storage_Pool use System.Pool_32;
27046 Any object whose address may be passed to a subprogram with a
27047 @code{Short_Address} argument, or assigned to a variable of type
27048 @code{Short_Address}, needs to be allocated from this pool.
27050 @node General access types
27051 @subsubsection General access types
27054 Objects designated by access values from a
27055 general access type (declared with @code{access all}) are never allocated
27056 from a 64-bit storage pool. Code that uses general access types will
27057 accept objects allocated in either 32-bit or 64-bit address spaces,
27058 but never allocate objects outside the 32-bit address space.
27059 Using general access types ensures maximum compatibility with both
27060 32-bit and 64-bit code.
27063 @node STARLET and other predefined libraries
27064 @subsubsection STARLET and other predefined libraries
27067 All code that comes as part of GNAT is 64-bit clean, but the
27068 restrictions given in @ref{Restrictions on use of 64 bit objects},
27069 still apply. Look at the package
27070 specifications to see in which contexts objects allocated
27071 in 64-bit address space are acceptable.
27073 @node Technical details
27074 @subsection Technical details
27077 GNAT Pro for Open VMS Integrity takes advantage of the freedom given in the Ada
27078 standard with respect to the type of @code{System.Address}. Previous versions
27079 of GNAT Pro have defined this type as private and implemented it as
27082 In order to allow defining @code{System.Short_Address} as a proper subtype,
27083 and to match the implicit sign extension in parameter passing,
27084 in GNAT Pro for Open VMS Integrity, @code{System.Address} is defined as a
27085 visible (i.e., non-private) integer type.
27086 Standard operations on the type, such as the binary operators ``+'', ``-'',
27087 etc., that take @code{Address} operands and return an @code{Address} result,
27088 have been hidden by declaring these
27089 @code{abstract}, an Ada 95 feature that helps avoid the potential ambiguities
27090 that would otherwise result from overloading.
27091 (Note that, although @code{Address} is a visible integer type,
27092 good programming practice dictates against exploiting the type's
27093 integer properties such as literals, since this will compromise
27096 Defining @code{Address} as a visible integer type helps achieve
27097 maximum compatibility for existing Ada code,
27098 without sacrificing the capabilities of the IA64 architecture.
27102 @c ************************************************
27104 @node Microsoft Windows Topics
27105 @appendix Microsoft Windows Topics
27111 This chapter describes topics that are specific to the Microsoft Windows
27112 platforms (NT, 2000, and XP Professional).
27115 * Using GNAT on Windows::
27116 * Using a network installation of GNAT::
27117 * CONSOLE and WINDOWS subsystems::
27118 * Temporary Files::
27119 * Mixed-Language Programming on Windows::
27120 * Windows Calling Conventions::
27121 * Introduction to Dynamic Link Libraries (DLLs)::
27122 * Using DLLs with GNAT::
27123 * Building DLLs with GNAT::
27124 * Building DLLs with GNAT Project files::
27125 * Building DLLs with gnatdll::
27126 * GNAT and Windows Resources::
27127 * Debugging a DLL::
27128 * GNAT and COM/DCOM Objects::
27131 @node Using GNAT on Windows
27132 @section Using GNAT on Windows
27135 One of the strengths of the GNAT technology is that its tool set
27136 (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
27137 @code{gdb} debugger, etc.) is used in the same way regardless of the
27140 On Windows this tool set is complemented by a number of Microsoft-specific
27141 tools that have been provided to facilitate interoperability with Windows
27142 when this is required. With these tools:
27147 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
27151 You can use any Dynamically Linked Library (DLL) in your Ada code (both
27152 relocatable and non-relocatable DLLs are supported).
27155 You can build Ada DLLs for use in other applications. These applications
27156 can be written in a language other than Ada (e.g., C, C++, etc). Again both
27157 relocatable and non-relocatable Ada DLLs are supported.
27160 You can include Windows resources in your Ada application.
27163 You can use or create COM/DCOM objects.
27167 Immediately below are listed all known general GNAT-for-Windows restrictions.
27168 Other restrictions about specific features like Windows Resources and DLLs
27169 are listed in separate sections below.
27174 It is not possible to use @code{GetLastError} and @code{SetLastError}
27175 when tasking, protected records, or exceptions are used. In these
27176 cases, in order to implement Ada semantics, the GNAT run-time system
27177 calls certain Win32 routines that set the last error variable to 0 upon
27178 success. It should be possible to use @code{GetLastError} and
27179 @code{SetLastError} when tasking, protected record, and exception
27180 features are not used, but it is not guaranteed to work.
27183 It is not possible to link against Microsoft libraries except for
27184 import libraries. The library must be built to be compatible with
27185 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
27186 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
27187 not be compatible with the GNAT runtime. Even if the library is
27188 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
27191 When the compilation environment is located on FAT32 drives, users may
27192 experience recompilations of the source files that have not changed if
27193 Daylight Saving Time (DST) state has changed since the last time files
27194 were compiled. NTFS drives do not have this problem.
27197 No components of the GNAT toolset use any entries in the Windows
27198 registry. The only entries that can be created are file associations and
27199 PATH settings, provided the user has chosen to create them at installation
27200 time, as well as some minimal book-keeping information needed to correctly
27201 uninstall or integrate different GNAT products.
27204 @node Using a network installation of GNAT
27205 @section Using a network installation of GNAT
27208 Make sure the system on which GNAT is installed is accessible from the
27209 current machine, i.e. the install location is shared over the network.
27210 Shared resources are accessed on Windows by means of UNC paths, which
27211 have the format @code{\\server\sharename\path}
27213 In order to use such a network installation, simply add the UNC path of the
27214 @file{bin} directory of your GNAT installation in front of your PATH. For
27215 example, if GNAT is installed in @file{\GNAT} directory of a share location
27216 called @file{c-drive} on a machine @file{LOKI}, the following command will
27219 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
27221 Be aware that every compilation using the network installation results in the
27222 transfer of large amounts of data across the network and will likely cause
27223 serious performance penalty.
27225 @node CONSOLE and WINDOWS subsystems
27226 @section CONSOLE and WINDOWS subsystems
27227 @cindex CONSOLE Subsystem
27228 @cindex WINDOWS Subsystem
27232 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
27233 (which is the default subsystem) will always create a console when
27234 launching the application. This is not something desirable when the
27235 application has a Windows GUI. To get rid of this console the
27236 application must be using the @code{WINDOWS} subsystem. To do so
27237 the @option{-mwindows} linker option must be specified.
27240 $ gnatmake winprog -largs -mwindows
27243 @node Temporary Files
27244 @section Temporary Files
27245 @cindex Temporary files
27248 It is possible to control where temporary files gets created by setting
27249 the TMP environment variable. The file will be created:
27252 @item Under the directory pointed to by the TMP environment variable if
27253 this directory exists.
27255 @item Under c:\temp, if the TMP environment variable is not set (or not
27256 pointing to a directory) and if this directory exists.
27258 @item Under the current working directory otherwise.
27262 This allows you to determine exactly where the temporary
27263 file will be created. This is particularly useful in networked
27264 environments where you may not have write access to some
27267 @node Mixed-Language Programming on Windows
27268 @section Mixed-Language Programming on Windows
27271 Developing pure Ada applications on Windows is no different than on
27272 other GNAT-supported platforms. However, when developing or porting an
27273 application that contains a mix of Ada and C/C++, the choice of your
27274 Windows C/C++ development environment conditions your overall
27275 interoperability strategy.
27277 If you use @code{gcc} to compile the non-Ada part of your application,
27278 there are no Windows-specific restrictions that affect the overall
27279 interoperability with your Ada code. If you plan to use
27280 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
27281 the following limitations:
27285 You cannot link your Ada code with an object or library generated with
27286 Microsoft tools if these use the @code{.tls} section (Thread Local
27287 Storage section) since the GNAT linker does not yet support this section.
27290 You cannot link your Ada code with an object or library generated with
27291 Microsoft tools if these use I/O routines other than those provided in
27292 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
27293 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
27294 libraries can cause a conflict with @code{msvcrt.dll} services. For
27295 instance Visual C++ I/O stream routines conflict with those in
27300 If you do want to use the Microsoft tools for your non-Ada code and hit one
27301 of the above limitations, you have two choices:
27305 Encapsulate your non Ada code in a DLL to be linked with your Ada
27306 application. In this case, use the Microsoft or whatever environment to
27307 build the DLL and use GNAT to build your executable
27308 (@pxref{Using DLLs with GNAT}).
27311 Or you can encapsulate your Ada code in a DLL to be linked with the
27312 other part of your application. In this case, use GNAT to build the DLL
27313 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
27314 environment to build your executable.
27317 @node Windows Calling Conventions
27318 @section Windows Calling Conventions
27323 * C Calling Convention::
27324 * Stdcall Calling Convention::
27325 * DLL Calling Convention::
27329 When a subprogram @code{F} (caller) calls a subprogram @code{G}
27330 (callee), there are several ways to push @code{G}'s parameters on the
27331 stack and there are several possible scenarios to clean up the stack
27332 upon @code{G}'s return. A calling convention is an agreed upon software
27333 protocol whereby the responsibilities between the caller (@code{F}) and
27334 the callee (@code{G}) are clearly defined. Several calling conventions
27335 are available for Windows:
27339 @code{C} (Microsoft defined)
27342 @code{Stdcall} (Microsoft defined)
27345 @code{DLL} (GNAT specific)
27348 @node C Calling Convention
27349 @subsection @code{C} Calling Convention
27352 This is the default calling convention used when interfacing to C/C++
27353 routines compiled with either @code{gcc} or Microsoft Visual C++.
27355 In the @code{C} calling convention subprogram parameters are pushed on the
27356 stack by the caller from right to left. The caller itself is in charge of
27357 cleaning up the stack after the call. In addition, the name of a routine
27358 with @code{C} calling convention is mangled by adding a leading underscore.
27360 The name to use on the Ada side when importing (or exporting) a routine
27361 with @code{C} calling convention is the name of the routine. For
27362 instance the C function:
27365 int get_val (long);
27369 should be imported from Ada as follows:
27371 @smallexample @c ada
27373 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27374 pragma Import (C, Get_Val, External_Name => "get_val");
27379 Note that in this particular case the @code{External_Name} parameter could
27380 have been omitted since, when missing, this parameter is taken to be the
27381 name of the Ada entity in lower case. When the @code{Link_Name} parameter
27382 is missing, as in the above example, this parameter is set to be the
27383 @code{External_Name} with a leading underscore.
27385 When importing a variable defined in C, you should always use the @code{C}
27386 calling convention unless the object containing the variable is part of a
27387 DLL (in which case you should use the @code{DLL} calling convention,
27388 @pxref{DLL Calling Convention}).
27390 @node Stdcall Calling Convention
27391 @subsection @code{Stdcall} Calling Convention
27394 This convention, which was the calling convention used for Pascal
27395 programs, is used by Microsoft for all the routines in the Win32 API for
27396 efficiency reasons. It must be used to import any routine for which this
27397 convention was specified.
27399 In the @code{Stdcall} calling convention subprogram parameters are pushed
27400 on the stack by the caller from right to left. The callee (and not the
27401 caller) is in charge of cleaning the stack on routine exit. In addition,
27402 the name of a routine with @code{Stdcall} calling convention is mangled by
27403 adding a leading underscore (as for the @code{C} calling convention) and a
27404 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
27405 bytes) of the parameters passed to the routine.
27407 The name to use on the Ada side when importing a C routine with a
27408 @code{Stdcall} calling convention is the name of the C routine. The leading
27409 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
27410 the compiler. For instance the Win32 function:
27413 @b{APIENTRY} int get_val (long);
27417 should be imported from Ada as follows:
27419 @smallexample @c ada
27421 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27422 pragma Import (Stdcall, Get_Val);
27423 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
27428 As for the @code{C} calling convention, when the @code{External_Name}
27429 parameter is missing, it is taken to be the name of the Ada entity in lower
27430 case. If instead of writing the above import pragma you write:
27432 @smallexample @c ada
27434 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27435 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
27440 then the imported routine is @code{_retrieve_val@@4}. However, if instead
27441 of specifying the @code{External_Name} parameter you specify the
27442 @code{Link_Name} as in the following example:
27444 @smallexample @c ada
27446 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27447 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
27452 then the imported routine is @code{retrieve_val@@4}, that is, there is no
27453 trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always
27454 added at the end of the @code{Link_Name} by the compiler.
27457 Note, that in some special cases a DLL's entry point name lacks a trailing
27458 @code{@@}@code{@i{nn}} while the exported name generated for a call has it.
27459 The @code{gnatdll} tool, which creates the import library for the DLL, is able
27460 to handle those cases (see the description of the switches in
27461 @pxref{Using gnatdll} section).
27463 @node DLL Calling Convention
27464 @subsection @code{DLL} Calling Convention
27467 This convention, which is GNAT-specific, must be used when you want to
27468 import in Ada a variables defined in a DLL. For functions and procedures
27469 this convention is equivalent to the @code{Stdcall} convention. As an
27470 example, if a DLL contains a variable defined as:
27477 then, to access this variable from Ada you should write:
27479 @smallexample @c ada
27481 My_Var : Interfaces.C.int;
27482 pragma Import (DLL, My_Var);
27486 The remarks concerning the @code{External_Name} and @code{Link_Name}
27487 parameters given in the previous sections equally apply to the @code{DLL}
27488 calling convention.
27490 @node Introduction to Dynamic Link Libraries (DLLs)
27491 @section Introduction to Dynamic Link Libraries (DLLs)
27495 A Dynamically Linked Library (DLL) is a library that can be shared by
27496 several applications running under Windows. A DLL can contain any number of
27497 routines and variables.
27499 One advantage of DLLs is that you can change and enhance them without
27500 forcing all the applications that depend on them to be relinked or
27501 recompiled. However, you should be aware than all calls to DLL routines are
27502 slower since, as you will understand below, such calls are indirect.
27504 To illustrate the remainder of this section, suppose that an application
27505 wants to use the services of a DLL @file{API.dll}. To use the services
27506 provided by @file{API.dll} you must statically link against the DLL or
27507 an import library which contains a jump table with an entry for each
27508 routine and variable exported by the DLL. In the Microsoft world this
27509 import library is called @file{API.lib}. When using GNAT this import
27510 library is called either @file{libAPI.a} or @file{libapi.a} (names are
27513 After you have linked your application with the DLL or the import library
27514 and you run your application, here is what happens:
27518 Your application is loaded into memory.
27521 The DLL @file{API.dll} is mapped into the address space of your
27522 application. This means that:
27526 The DLL will use the stack of the calling thread.
27529 The DLL will use the virtual address space of the calling process.
27532 The DLL will allocate memory from the virtual address space of the calling
27536 Handles (pointers) can be safely exchanged between routines in the DLL
27537 routines and routines in the application using the DLL.
27541 The entries in the jump table (from the import library @file{libAPI.a}
27542 or @file{API.lib} or automatically created when linking against a DLL)
27543 which is part of your application are initialized with the addresses
27544 of the routines and variables in @file{API.dll}.
27547 If present in @file{API.dll}, routines @code{DllMain} or
27548 @code{DllMainCRTStartup} are invoked. These routines typically contain
27549 the initialization code needed for the well-being of the routines and
27550 variables exported by the DLL.
27554 There is an additional point which is worth mentioning. In the Windows
27555 world there are two kind of DLLs: relocatable and non-relocatable
27556 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
27557 in the target application address space. If the addresses of two
27558 non-relocatable DLLs overlap and these happen to be used by the same
27559 application, a conflict will occur and the application will run
27560 incorrectly. Hence, when possible, it is always preferable to use and
27561 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
27562 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
27563 User's Guide) removes the debugging symbols from the DLL but the DLL can
27564 still be relocated.
27566 As a side note, an interesting difference between Microsoft DLLs and
27567 Unix shared libraries, is the fact that on most Unix systems all public
27568 routines are exported by default in a Unix shared library, while under
27569 Windows it is possible (but not required) to list exported routines in
27570 a definition file (@pxref{The Definition File}).
27572 @node Using DLLs with GNAT
27573 @section Using DLLs with GNAT
27576 * Creating an Ada Spec for the DLL Services::
27577 * Creating an Import Library::
27581 To use the services of a DLL, say @file{API.dll}, in your Ada application
27586 The Ada spec for the routines and/or variables you want to access in
27587 @file{API.dll}. If not available this Ada spec must be built from the C/C++
27588 header files provided with the DLL.
27591 The import library (@file{libAPI.a} or @file{API.lib}). As previously
27592 mentioned an import library is a statically linked library containing the
27593 import table which will be filled at load time to point to the actual
27594 @file{API.dll} routines. Sometimes you don't have an import library for the
27595 DLL you want to use. The following sections will explain how to build
27596 one. Note that this is optional.
27599 The actual DLL, @file{API.dll}.
27603 Once you have all the above, to compile an Ada application that uses the
27604 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
27605 you simply issue the command
27608 $ gnatmake my_ada_app -largs -lAPI
27612 The argument @option{-largs -lAPI} at the end of the @code{gnatmake} command
27613 tells the GNAT linker to look first for a library named @file{API.lib}
27614 (Microsoft-style name) and if not found for a library named @file{libAPI.a}
27615 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
27616 contains the following pragma
27618 @smallexample @c ada
27619 pragma Linker_Options ("-lAPI");
27623 you do not have to add @option{-largs -lAPI} at the end of the @code{gnatmake}
27626 If any one of the items above is missing you will have to create it
27627 yourself. The following sections explain how to do so using as an
27628 example a fictitious DLL called @file{API.dll}.
27630 @node Creating an Ada Spec for the DLL Services
27631 @subsection Creating an Ada Spec for the DLL Services
27634 A DLL typically comes with a C/C++ header file which provides the
27635 definitions of the routines and variables exported by the DLL. The Ada
27636 equivalent of this header file is a package spec that contains definitions
27637 for the imported entities. If the DLL you intend to use does not come with
27638 an Ada spec you have to generate one such spec yourself. For example if
27639 the header file of @file{API.dll} is a file @file{api.h} containing the
27640 following two definitions:
27652 then the equivalent Ada spec could be:
27654 @smallexample @c ada
27657 with Interfaces.C.Strings;
27662 function Get (Str : C.Strings.Chars_Ptr) return C.int;
27665 pragma Import (C, Get);
27666 pragma Import (DLL, Some_Var);
27673 Note that a variable is @strong{always imported with a DLL convention}. A
27674 function can have @code{C}, @code{Stdcall} or @code{DLL} convention. For
27675 subprograms, the @code{DLL} convention is a synonym of @code{Stdcall}
27676 (@pxref{Windows Calling Conventions}).
27678 @node Creating an Import Library
27679 @subsection Creating an Import Library
27680 @cindex Import library
27683 * The Definition File::
27684 * GNAT-Style Import Library::
27685 * Microsoft-Style Import Library::
27689 If a Microsoft-style import library @file{API.lib} or a GNAT-style
27690 import library @file{libAPI.a} is available with @file{API.dll} you
27691 can skip this section. You can also skip this section if
27692 @file{API.dll} is built with GNU tools as in this case it is possible
27693 to link directly against the DLL. Otherwise read on.
27695 @node The Definition File
27696 @subsubsection The Definition File
27697 @cindex Definition file
27701 As previously mentioned, and unlike Unix systems, the list of symbols
27702 that are exported from a DLL must be provided explicitly in Windows.
27703 The main goal of a definition file is precisely that: list the symbols
27704 exported by a DLL. A definition file (usually a file with a @code{.def}
27705 suffix) has the following structure:
27711 [DESCRIPTION @i{string}]
27721 @item LIBRARY @i{name}
27722 This section, which is optional, gives the name of the DLL.
27724 @item DESCRIPTION @i{string}
27725 This section, which is optional, gives a description string that will be
27726 embedded in the import library.
27729 This section gives the list of exported symbols (procedures, functions or
27730 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
27731 section of @file{API.def} looks like:
27745 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
27746 (@pxref{Windows Calling Conventions}) for a Stdcall
27747 calling convention function in the exported symbols list.
27750 There can actually be other sections in a definition file, but these
27751 sections are not relevant to the discussion at hand.
27753 @node GNAT-Style Import Library
27754 @subsubsection GNAT-Style Import Library
27757 To create a static import library from @file{API.dll} with the GNAT tools
27758 you should proceed as follows:
27762 Create the definition file @file{API.def} (@pxref{The Definition File}).
27763 For that use the @code{dll2def} tool as follows:
27766 $ dll2def API.dll > API.def
27770 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
27771 to standard output the list of entry points in the DLL. Note that if
27772 some routines in the DLL have the @code{Stdcall} convention
27773 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
27774 suffix then you'll have to edit @file{api.def} to add it, and specify
27775 @code{-k} to @code{gnatdll} when creating the import library.
27778 Here are some hints to find the right @code{@@}@i{nn} suffix.
27782 If you have the Microsoft import library (.lib), it is possible to get
27783 the right symbols by using Microsoft @code{dumpbin} tool (see the
27784 corresponding Microsoft documentation for further details).
27787 $ dumpbin /exports api.lib
27791 If you have a message about a missing symbol at link time the compiler
27792 tells you what symbol is expected. You just have to go back to the
27793 definition file and add the right suffix.
27797 Build the import library @code{libAPI.a}, using @code{gnatdll}
27798 (@pxref{Using gnatdll}) as follows:
27801 $ gnatdll -e API.def -d API.dll
27805 @code{gnatdll} takes as input a definition file @file{API.def} and the
27806 name of the DLL containing the services listed in the definition file
27807 @file{API.dll}. The name of the static import library generated is
27808 computed from the name of the definition file as follows: if the
27809 definition file name is @i{xyz}@code{.def}, the import library name will
27810 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
27811 @option{-e} could have been removed because the name of the definition
27812 file (before the ``@code{.def}'' suffix) is the same as the name of the
27813 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
27816 @node Microsoft-Style Import Library
27817 @subsubsection Microsoft-Style Import Library
27820 With GNAT you can either use a GNAT-style or Microsoft-style import
27821 library. A Microsoft import library is needed only if you plan to make an
27822 Ada DLL available to applications developed with Microsoft
27823 tools (@pxref{Mixed-Language Programming on Windows}).
27825 To create a Microsoft-style import library for @file{API.dll} you
27826 should proceed as follows:
27830 Create the definition file @file{API.def} from the DLL. For this use either
27831 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
27832 tool (see the corresponding Microsoft documentation for further details).
27835 Build the actual import library using Microsoft's @code{lib} utility:
27838 $ lib -machine:IX86 -def:API.def -out:API.lib
27842 If you use the above command the definition file @file{API.def} must
27843 contain a line giving the name of the DLL:
27850 See the Microsoft documentation for further details about the usage of
27854 @node Building DLLs with GNAT
27855 @section Building DLLs with GNAT
27856 @cindex DLLs, building
27859 This section explain how to build DLLs using the GNAT built-in DLL
27860 support. With the following procedure it is straight forward to build
27861 and use DLLs with GNAT.
27865 @item building object files
27867 The first step is to build all objects files that are to be included
27868 into the DLL. This is done by using the standard @code{gnatmake} tool.
27870 @item building the DLL
27872 To build the DLL you must use @code{gcc}'s @code{-shared}
27873 option. It is quite simple to use this method:
27876 $ gcc -shared -o api.dll obj1.o obj2.o ...
27879 It is important to note that in this case all symbols found in the
27880 object files are automatically exported. It is possible to restrict
27881 the set of symbols to export by passing to @code{gcc} a definition
27882 file, @pxref{The Definition File}. For example:
27885 $ gcc -shared -o api.dll api.def obj1.o obj2.o ...
27888 If you use a definition file you must export the elaboration procedures
27889 for every package that required one. Elaboration procedures are named
27890 using the package name followed by "_E".
27892 @item preparing DLL to be used
27894 For the DLL to be used by client programs the bodies must be hidden
27895 from it and the .ali set with read-only attribute. This is very important
27896 otherwise GNAT will recompile all packages and will not actually use
27897 the code in the DLL. For example:
27901 $ copy *.ads *.ali api.dll apilib
27902 $ attrib +R apilib\*.ali
27907 At this point it is possible to use the DLL by directly linking
27908 against it. Note that you must use the GNAT shared runtime when using
27909 GNAT shared libraries. This is achieved by using @code{-shared} binder's
27913 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
27916 @node Building DLLs with GNAT Project files
27917 @section Building DLLs with GNAT Project files
27918 @cindex DLLs, building
27921 There is nothing specific to Windows in this area. @pxref{Library Projects}.
27923 @node Building DLLs with gnatdll
27924 @section Building DLLs with gnatdll
27925 @cindex DLLs, building
27928 * Limitations When Using Ada DLLs from Ada::
27929 * Exporting Ada Entities::
27930 * Ada DLLs and Elaboration::
27931 * Ada DLLs and Finalization::
27932 * Creating a Spec for Ada DLLs::
27933 * Creating the Definition File::
27938 Note that it is prefered to use the built-in GNAT DLL support
27939 (@pxref{Building DLLs with GNAT}) or GNAT Project files
27940 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
27942 This section explains how to build DLLs containing Ada code using
27943 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
27944 remainder of this section.
27946 The steps required to build an Ada DLL that is to be used by Ada as well as
27947 non-Ada applications are as follows:
27951 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
27952 @code{Stdcall} calling convention to avoid any Ada name mangling for the
27953 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
27954 skip this step if you plan to use the Ada DLL only from Ada applications.
27957 Your Ada code must export an initialization routine which calls the routine
27958 @code{adainit} generated by @code{gnatbind} to perform the elaboration of
27959 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
27960 routine exported by the Ada DLL must be invoked by the clients of the DLL
27961 to initialize the DLL.
27964 When useful, the DLL should also export a finalization routine which calls
27965 routine @code{adafinal} generated by @code{gnatbind} to perform the
27966 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
27967 The finalization routine exported by the Ada DLL must be invoked by the
27968 clients of the DLL when the DLL services are no further needed.
27971 You must provide a spec for the services exported by the Ada DLL in each
27972 of the programming languages to which you plan to make the DLL available.
27975 You must provide a definition file listing the exported entities
27976 (@pxref{The Definition File}).
27979 Finally you must use @code{gnatdll} to produce the DLL and the import
27980 library (@pxref{Using gnatdll}).
27984 Note that a relocatable DLL stripped using the @code{strip} binutils
27985 tool will not be relocatable anymore. To build a DLL without debug
27986 information pass @code{-largs -s} to @code{gnatdll}.
27988 @node Limitations When Using Ada DLLs from Ada
27989 @subsection Limitations When Using Ada DLLs from Ada
27992 When using Ada DLLs from Ada applications there is a limitation users
27993 should be aware of. Because on Windows the GNAT run time is not in a DLL of
27994 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
27995 each Ada DLL includes the services of the GNAT run time that are necessary
27996 to the Ada code inside the DLL. As a result, when an Ada program uses an
27997 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
27998 one in the main program.
28000 It is therefore not possible to exchange GNAT run-time objects between the
28001 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
28002 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
28005 It is completely safe to exchange plain elementary, array or record types,
28006 Windows object handles, etc.
28008 @node Exporting Ada Entities
28009 @subsection Exporting Ada Entities
28010 @cindex Export table
28013 Building a DLL is a way to encapsulate a set of services usable from any
28014 application. As a result, the Ada entities exported by a DLL should be
28015 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
28016 any Ada name mangling. Please note that the @code{Stdcall} convention
28017 should only be used for subprograms, not for variables. As an example here
28018 is an Ada package @code{API}, spec and body, exporting two procedures, a
28019 function, and a variable:
28021 @smallexample @c ada
28024 with Interfaces.C; use Interfaces;
28026 Count : C.int := 0;
28027 function Factorial (Val : C.int) return C.int;
28029 procedure Initialize_API;
28030 procedure Finalize_API;
28031 -- Initialization & Finalization routines. More in the next section.
28033 pragma Export (C, Initialize_API);
28034 pragma Export (C, Finalize_API);
28035 pragma Export (C, Count);
28036 pragma Export (C, Factorial);
28042 @smallexample @c ada
28045 package body API is
28046 function Factorial (Val : C.int) return C.int is
28049 Count := Count + 1;
28050 for K in 1 .. Val loop
28056 procedure Initialize_API is
28058 pragma Import (C, Adainit);
28061 end Initialize_API;
28063 procedure Finalize_API is
28064 procedure Adafinal;
28065 pragma Import (C, Adafinal);
28075 If the Ada DLL you are building will only be used by Ada applications
28076 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
28077 convention. As an example, the previous package could be written as
28080 @smallexample @c ada
28084 Count : Integer := 0;
28085 function Factorial (Val : Integer) return Integer;
28087 procedure Initialize_API;
28088 procedure Finalize_API;
28089 -- Initialization and Finalization routines.
28095 @smallexample @c ada
28098 package body API is
28099 function Factorial (Val : Integer) return Integer is
28100 Fact : Integer := 1;
28102 Count := Count + 1;
28103 for K in 1 .. Val loop
28110 -- The remainder of this package body is unchanged.
28117 Note that if you do not export the Ada entities with a @code{C} or
28118 @code{Stdcall} convention you will have to provide the mangled Ada names
28119 in the definition file of the Ada DLL
28120 (@pxref{Creating the Definition File}).
28122 @node Ada DLLs and Elaboration
28123 @subsection Ada DLLs and Elaboration
28124 @cindex DLLs and elaboration
28127 The DLL that you are building contains your Ada code as well as all the
28128 routines in the Ada library that are needed by it. The first thing a
28129 user of your DLL must do is elaborate the Ada code
28130 (@pxref{Elaboration Order Handling in GNAT}).
28132 To achieve this you must export an initialization routine
28133 (@code{Initialize_API} in the previous example), which must be invoked
28134 before using any of the DLL services. This elaboration routine must call
28135 the Ada elaboration routine @code{adainit} generated by the GNAT binder
28136 (@pxref{Binding with Non-Ada Main Programs}). See the body of
28137 @code{Initialize_Api} for an example. Note that the GNAT binder is
28138 automatically invoked during the DLL build process by the @code{gnatdll}
28139 tool (@pxref{Using gnatdll}).
28141 When a DLL is loaded, Windows systematically invokes a routine called
28142 @code{DllMain}. It would therefore be possible to call @code{adainit}
28143 directly from @code{DllMain} without having to provide an explicit
28144 initialization routine. Unfortunately, it is not possible to call
28145 @code{adainit} from the @code{DllMain} if your program has library level
28146 tasks because access to the @code{DllMain} entry point is serialized by
28147 the system (that is, only a single thread can execute ``through'' it at a
28148 time), which means that the GNAT run time will deadlock waiting for the
28149 newly created task to complete its initialization.
28151 @node Ada DLLs and Finalization
28152 @subsection Ada DLLs and Finalization
28153 @cindex DLLs and finalization
28156 When the services of an Ada DLL are no longer needed, the client code should
28157 invoke the DLL finalization routine, if available. The DLL finalization
28158 routine is in charge of releasing all resources acquired by the DLL. In the
28159 case of the Ada code contained in the DLL, this is achieved by calling
28160 routine @code{adafinal} generated by the GNAT binder
28161 (@pxref{Binding with Non-Ada Main Programs}).
28162 See the body of @code{Finalize_Api} for an
28163 example. As already pointed out the GNAT binder is automatically invoked
28164 during the DLL build process by the @code{gnatdll} tool
28165 (@pxref{Using gnatdll}).
28167 @node Creating a Spec for Ada DLLs
28168 @subsection Creating a Spec for Ada DLLs
28171 To use the services exported by the Ada DLL from another programming
28172 language (e.g. C), you have to translate the specs of the exported Ada
28173 entities in that language. For instance in the case of @code{API.dll},
28174 the corresponding C header file could look like:
28179 extern int *_imp__count;
28180 #define count (*_imp__count)
28181 int factorial (int);
28187 It is important to understand that when building an Ada DLL to be used by
28188 other Ada applications, you need two different specs for the packages
28189 contained in the DLL: one for building the DLL and the other for using
28190 the DLL. This is because the @code{DLL} calling convention is needed to
28191 use a variable defined in a DLL, but when building the DLL, the variable
28192 must have either the @code{Ada} or @code{C} calling convention. As an
28193 example consider a DLL comprising the following package @code{API}:
28195 @smallexample @c ada
28199 Count : Integer := 0;
28201 -- Remainder of the package omitted.
28208 After producing a DLL containing package @code{API}, the spec that
28209 must be used to import @code{API.Count} from Ada code outside of the
28212 @smallexample @c ada
28217 pragma Import (DLL, Count);
28223 @node Creating the Definition File
28224 @subsection Creating the Definition File
28227 The definition file is the last file needed to build the DLL. It lists
28228 the exported symbols. As an example, the definition file for a DLL
28229 containing only package @code{API} (where all the entities are exported
28230 with a @code{C} calling convention) is:
28245 If the @code{C} calling convention is missing from package @code{API},
28246 then the definition file contains the mangled Ada names of the above
28247 entities, which in this case are:
28256 api__initialize_api
28261 @node Using gnatdll
28262 @subsection Using @code{gnatdll}
28266 * gnatdll Example::
28267 * gnatdll behind the Scenes::
28272 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
28273 and non-Ada sources that make up your DLL have been compiled.
28274 @code{gnatdll} is actually in charge of two distinct tasks: build the
28275 static import library for the DLL and the actual DLL. The form of the
28276 @code{gnatdll} command is
28280 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
28285 where @i{list-of-files} is a list of ALI and object files. The object
28286 file list must be the exact list of objects corresponding to the non-Ada
28287 sources whose services are to be included in the DLL. The ALI file list
28288 must be the exact list of ALI files for the corresponding Ada sources
28289 whose services are to be included in the DLL. If @i{list-of-files} is
28290 missing, only the static import library is generated.
28293 You may specify any of the following switches to @code{gnatdll}:
28296 @item -a[@var{address}]
28297 @cindex @option{-a} (@code{gnatdll})
28298 Build a non-relocatable DLL at @var{address}. If @var{address} is not
28299 specified the default address @var{0x11000000} will be used. By default,
28300 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
28301 advise the reader to build relocatable DLL.
28303 @item -b @var{address}
28304 @cindex @option{-b} (@code{gnatdll})
28305 Set the relocatable DLL base address. By default the address is
28308 @item -bargs @var{opts}
28309 @cindex @option{-bargs} (@code{gnatdll})
28310 Binder options. Pass @var{opts} to the binder.
28312 @item -d @var{dllfile}
28313 @cindex @option{-d} (@code{gnatdll})
28314 @var{dllfile} is the name of the DLL. This switch must be present for
28315 @code{gnatdll} to do anything. The name of the generated import library is
28316 obtained algorithmically from @var{dllfile} as shown in the following
28317 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
28318 @code{libxyz.a}. The name of the definition file to use (if not specified
28319 by option @option{-e}) is obtained algorithmically from @var{dllfile}
28320 as shown in the following example:
28321 if @var{dllfile} is @code{xyz.dll}, the definition
28322 file used is @code{xyz.def}.
28324 @item -e @var{deffile}
28325 @cindex @option{-e} (@code{gnatdll})
28326 @var{deffile} is the name of the definition file.
28329 @cindex @option{-g} (@code{gnatdll})
28330 Generate debugging information. This information is stored in the object
28331 file and copied from there to the final DLL file by the linker,
28332 where it can be read by the debugger. You must use the
28333 @option{-g} switch if you plan on using the debugger or the symbolic
28337 @cindex @option{-h} (@code{gnatdll})
28338 Help mode. Displays @code{gnatdll} switch usage information.
28341 @cindex @option{-I} (@code{gnatdll})
28342 Direct @code{gnatdll} to search the @var{dir} directory for source and
28343 object files needed to build the DLL.
28344 (@pxref{Search Paths and the Run-Time Library (RTL)}).
28347 @cindex @option{-k} (@code{gnatdll})
28348 Removes the @code{@@}@i{nn} suffix from the import library's exported
28349 names, but keeps them for the link names. You must specify this
28350 option if you want to use a @code{Stdcall} function in a DLL for which
28351 the @code{@@}@i{nn} suffix has been removed. This is the case for most
28352 of the Windows NT DLL for example. This option has no effect when
28353 @option{-n} option is specified.
28355 @item -l @var{file}
28356 @cindex @option{-l} (@code{gnatdll})
28357 The list of ALI and object files used to build the DLL are listed in
28358 @var{file}, instead of being given in the command line. Each line in
28359 @var{file} contains the name of an ALI or object file.
28362 @cindex @option{-n} (@code{gnatdll})
28363 No Import. Do not create the import library.
28366 @cindex @option{-q} (@code{gnatdll})
28367 Quiet mode. Do not display unnecessary messages.
28370 @cindex @option{-v} (@code{gnatdll})
28371 Verbose mode. Display extra information.
28373 @item -largs @var{opts}
28374 @cindex @option{-largs} (@code{gnatdll})
28375 Linker options. Pass @var{opts} to the linker.
28378 @node gnatdll Example
28379 @subsubsection @code{gnatdll} Example
28382 As an example the command to build a relocatable DLL from @file{api.adb}
28383 once @file{api.adb} has been compiled and @file{api.def} created is
28386 $ gnatdll -d api.dll api.ali
28390 The above command creates two files: @file{libapi.a} (the import
28391 library) and @file{api.dll} (the actual DLL). If you want to create
28392 only the DLL, just type:
28395 $ gnatdll -d api.dll -n api.ali
28399 Alternatively if you want to create just the import library, type:
28402 $ gnatdll -d api.dll
28405 @node gnatdll behind the Scenes
28406 @subsubsection @code{gnatdll} behind the Scenes
28409 This section details the steps involved in creating a DLL. @code{gnatdll}
28410 does these steps for you. Unless you are interested in understanding what
28411 goes on behind the scenes, you should skip this section.
28413 We use the previous example of a DLL containing the Ada package @code{API},
28414 to illustrate the steps necessary to build a DLL. The starting point is a
28415 set of objects that will make up the DLL and the corresponding ALI
28416 files. In the case of this example this means that @file{api.o} and
28417 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
28422 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
28423 the information necessary to generate relocation information for the
28429 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
28434 In addition to the base file, the @code{gnatlink} command generates an
28435 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
28436 asks @code{gnatlink} to generate the routines @code{DllMain} and
28437 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
28438 is loaded into memory.
28441 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
28442 export table (@file{api.exp}). The export table contains the relocation
28443 information in a form which can be used during the final link to ensure
28444 that the Windows loader is able to place the DLL anywhere in memory.
28448 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28449 --output-exp api.exp
28454 @code{gnatdll} builds the base file using the new export table. Note that
28455 @code{gnatbind} must be called once again since the binder generated file
28456 has been deleted during the previous call to @code{gnatlink}.
28461 $ gnatlink api -o api.jnk api.exp -mdll
28462 -Wl,--base-file,api.base
28467 @code{gnatdll} builds the new export table using the new base file and
28468 generates the DLL import library @file{libAPI.a}.
28472 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28473 --output-exp api.exp --output-lib libAPI.a
28478 Finally @code{gnatdll} builds the relocatable DLL using the final export
28484 $ gnatlink api api.exp -o api.dll -mdll
28489 @node Using dlltool
28490 @subsubsection Using @code{dlltool}
28493 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
28494 DLLs and static import libraries. This section summarizes the most
28495 common @code{dlltool} switches. The form of the @code{dlltool} command
28499 $ dlltool [@var{switches}]
28503 @code{dlltool} switches include:
28506 @item --base-file @var{basefile}
28507 @cindex @option{--base-file} (@command{dlltool})
28508 Read the base file @var{basefile} generated by the linker. This switch
28509 is used to create a relocatable DLL.
28511 @item --def @var{deffile}
28512 @cindex @option{--def} (@command{dlltool})
28513 Read the definition file.
28515 @item --dllname @var{name}
28516 @cindex @option{--dllname} (@command{dlltool})
28517 Gives the name of the DLL. This switch is used to embed the name of the
28518 DLL in the static import library generated by @code{dlltool} with switch
28519 @option{--output-lib}.
28522 @cindex @option{-k} (@command{dlltool})
28523 Kill @code{@@}@i{nn} from exported names
28524 (@pxref{Windows Calling Conventions}
28525 for a discussion about @code{Stdcall}-style symbols.
28528 @cindex @option{--help} (@command{dlltool})
28529 Prints the @code{dlltool} switches with a concise description.
28531 @item --output-exp @var{exportfile}
28532 @cindex @option{--output-exp} (@command{dlltool})
28533 Generate an export file @var{exportfile}. The export file contains the
28534 export table (list of symbols in the DLL) and is used to create the DLL.
28536 @item --output-lib @i{libfile}
28537 @cindex @option{--output-lib} (@command{dlltool})
28538 Generate a static import library @var{libfile}.
28541 @cindex @option{-v} (@command{dlltool})
28544 @item --as @i{assembler-name}
28545 @cindex @option{--as} (@command{dlltool})
28546 Use @i{assembler-name} as the assembler. The default is @code{as}.
28549 @node GNAT and Windows Resources
28550 @section GNAT and Windows Resources
28551 @cindex Resources, windows
28554 * Building Resources::
28555 * Compiling Resources::
28556 * Using Resources::
28560 Resources are an easy way to add Windows specific objects to your
28561 application. The objects that can be added as resources include:
28590 This section explains how to build, compile and use resources.
28592 @node Building Resources
28593 @subsection Building Resources
28594 @cindex Resources, building
28597 A resource file is an ASCII file. By convention resource files have an
28598 @file{.rc} extension.
28599 The easiest way to build a resource file is to use Microsoft tools
28600 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
28601 @code{dlgedit.exe} to build dialogs.
28602 It is always possible to build an @file{.rc} file yourself by writing a
28605 It is not our objective to explain how to write a resource file. A
28606 complete description of the resource script language can be found in the
28607 Microsoft documentation.
28609 @node Compiling Resources
28610 @subsection Compiling Resources
28613 @cindex Resources, compiling
28616 This section describes how to build a GNAT-compatible (COFF) object file
28617 containing the resources. This is done using the Resource Compiler
28618 @code{windres} as follows:
28621 $ windres -i myres.rc -o myres.o
28625 By default @code{windres} will run @code{gcc} to preprocess the @file{.rc}
28626 file. You can specify an alternate preprocessor (usually named
28627 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
28628 parameter. A list of all possible options may be obtained by entering
28629 the command @code{windres} @option{--help}.
28631 It is also possible to use the Microsoft resource compiler @code{rc.exe}
28632 to produce a @file{.res} file (binary resource file). See the
28633 corresponding Microsoft documentation for further details. In this case
28634 you need to use @code{windres} to translate the @file{.res} file to a
28635 GNAT-compatible object file as follows:
28638 $ windres -i myres.res -o myres.o
28641 @node Using Resources
28642 @subsection Using Resources
28643 @cindex Resources, using
28646 To include the resource file in your program just add the
28647 GNAT-compatible object file for the resource(s) to the linker
28648 arguments. With @code{gnatmake} this is done by using the @option{-largs}
28652 $ gnatmake myprog -largs myres.o
28655 @node Debugging a DLL
28656 @section Debugging a DLL
28657 @cindex DLL debugging
28660 * Program and DLL Both Built with GCC/GNAT::
28661 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
28665 Debugging a DLL is similar to debugging a standard program. But
28666 we have to deal with two different executable parts: the DLL and the
28667 program that uses it. We have the following four possibilities:
28671 The program and the DLL are built with @code{GCC/GNAT}.
28673 The program is built with foreign tools and the DLL is built with
28676 The program is built with @code{GCC/GNAT} and the DLL is built with
28682 In this section we address only cases one and two above.
28683 There is no point in trying to debug
28684 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
28685 information in it. To do so you must use a debugger compatible with the
28686 tools suite used to build the DLL.
28688 @node Program and DLL Both Built with GCC/GNAT
28689 @subsection Program and DLL Both Built with GCC/GNAT
28692 This is the simplest case. Both the DLL and the program have @code{GDB}
28693 compatible debugging information. It is then possible to break anywhere in
28694 the process. Let's suppose here that the main procedure is named
28695 @code{ada_main} and that in the DLL there is an entry point named
28699 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
28700 program must have been built with the debugging information (see GNAT -g
28701 switch). Here are the step-by-step instructions for debugging it:
28704 @item Launch @code{GDB} on the main program.
28710 @item Break on the main procedure and run the program.
28713 (gdb) break ada_main
28718 This step is required to be able to set a breakpoint inside the DLL. As long
28719 as the program is not run, the DLL is not loaded. This has the
28720 consequence that the DLL debugging information is also not loaded, so it is not
28721 possible to set a breakpoint in the DLL.
28723 @item Set a breakpoint inside the DLL
28726 (gdb) break ada_dll
28733 At this stage a breakpoint is set inside the DLL. From there on
28734 you can use the standard approach to debug the whole program
28735 (@pxref{Running and Debugging Ada Programs}).
28737 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
28738 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
28741 * Debugging the DLL Directly::
28742 * Attaching to a Running Process::
28746 In this case things are slightly more complex because it is not possible to
28747 start the main program and then break at the beginning to load the DLL and the
28748 associated DLL debugging information. It is not possible to break at the
28749 beginning of the program because there is no @code{GDB} debugging information,
28750 and therefore there is no direct way of getting initial control. This
28751 section addresses this issue by describing some methods that can be used
28752 to break somewhere in the DLL to debug it.
28755 First suppose that the main procedure is named @code{main} (this is for
28756 example some C code built with Microsoft Visual C) and that there is a
28757 DLL named @code{test.dll} containing an Ada entry point named
28761 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
28762 been built with debugging information (see GNAT -g option).
28764 @node Debugging the DLL Directly
28765 @subsubsection Debugging the DLL Directly
28769 Launch the debugger on the DLL.
28775 @item Set a breakpoint on a DLL subroutine.
28778 (gdb) break ada_dll
28782 Specify the executable file to @code{GDB}.
28785 (gdb) exec-file main.exe
28796 This will run the program until it reaches the breakpoint that has been
28797 set. From that point you can use the standard way to debug a program
28798 as described in (@pxref{Running and Debugging Ada Programs}).
28803 It is also possible to debug the DLL by attaching to a running process.
28805 @node Attaching to a Running Process
28806 @subsubsection Attaching to a Running Process
28807 @cindex DLL debugging, attach to process
28810 With @code{GDB} it is always possible to debug a running process by
28811 attaching to it. It is possible to debug a DLL this way. The limitation
28812 of this approach is that the DLL must run long enough to perform the
28813 attach operation. It may be useful for instance to insert a time wasting
28814 loop in the code of the DLL to meet this criterion.
28818 @item Launch the main program @file{main.exe}.
28824 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
28825 that the process PID for @file{main.exe} is 208.
28833 @item Attach to the running process to be debugged.
28839 @item Load the process debugging information.
28842 (gdb) symbol-file main.exe
28845 @item Break somewhere in the DLL.
28848 (gdb) break ada_dll
28851 @item Continue process execution.
28860 This last step will resume the process execution, and stop at
28861 the breakpoint we have set. From there you can use the standard
28862 approach to debug a program as described in
28863 (@pxref{Running and Debugging Ada Programs}).
28865 @node GNAT and COM/DCOM Objects
28866 @section GNAT and COM/DCOM Objects
28871 This section is temporarily left blank.
28875 @c **********************************
28876 @c * GNU Free Documentation License *
28877 @c **********************************
28879 @c GNU Free Documentation License
28881 @node Index,,GNU Free Documentation License, Top
28887 @c Put table of contents at end, otherwise it precedes the "title page" in
28888 @c the .txt version
28889 @c Edit the pdf file to move the contents to the beginning, after the title