1 \input texinfo @c -*-texinfo-*-
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
6 @c GNAT DOCUMENTATION o
10 @c Copyright (C) 1992-2010, AdaCore o
12 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
14 @setfilename gnat_ugn.info
17 Copyright @copyright{} 1995-2009 Free Software Foundation,
20 Permission is granted to copy, distribute and/or modify this document
21 under the terms of the GNU Free Documentation License, Version 1.3 or
22 any later version published by the Free Software Foundation; with no
23 Invariant Sections, with no Front-Cover Texts and with no Back-Cover
24 Texts. A copy of the license is included in the section entitled
25 ``GNU Free Documentation License''.
28 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
30 @c GNAT_UGN Style Guide
32 @c 1. Always put a @noindent on the line before the first paragraph
33 @c after any of these commands:
45 @c 2. DO NOT use @example. Use @smallexample instead.
46 @c a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
47 @c context. These can interfere with the readability of the texi
48 @c source file. Instead, use one of the following annotated
49 @c @smallexample commands, and preprocess the texi file with the
50 @c ada2texi tool (which generates appropriate highlighting):
51 @c @smallexample @c ada
52 @c @smallexample @c adanocomment
53 @c @smallexample @c projectfile
54 @c b) The "@c ada" markup will result in boldface for reserved words
55 @c and italics for comments
56 @c c) The "@c adanocomment" markup will result only in boldface for
57 @c reserved words (comments are left alone)
58 @c d) The "@c projectfile" markup is like "@c ada" except that the set
59 @c of reserved words include the new reserved words for project files
61 @c 3. Each @chapter, @section, @subsection, @subsubsection, etc.
62 @c command must be preceded by two empty lines
64 @c 4. The @item command should be on a line of its own if it is in an
65 @c @itemize or @enumerate command.
67 @c 5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
70 @c 6. DO NOT put trailing spaces at the end of a line. Such spaces will
71 @c cause the document build to fail.
73 @c 7. DO NOT use @cartouche for examples that are longer than around 10 lines.
74 @c This command inhibits page breaks, so long examples in a @cartouche can
75 @c lead to large, ugly patches of empty space on a page.
77 @c NOTE: This file should be submitted to xgnatugn with either the vms flag
78 @c or the unw flag set. The unw flag covers topics for both Unix and
81 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
84 @c This flag is used where the text refers to conditions that exist when the
85 @c text was entered into the document but which may change over time.
86 @c Update the setting for the flag, and (if necessary) the text surrounding,
87 @c the references to the flag, on future doc revisions:
88 @c search for @value{NOW}.
92 @set DEFAULTLANGUAGEVERSION Ada 2005
93 @set NONDEFAULTLANGUAGEVERSION Ada 95
100 @set PLATFORM OpenVMS
105 @c The ARG is an optional argument. To be used for macro arguments in
106 @c their documentation (@defmac).
108 @r{[}@var{\varname\}@r{]}@c
110 @c Status as of November 2009:
111 @c Unfortunately texi2pdf and texi2html treat the trailing "@c"
112 @c differently, and faulty output is produced by one or the other
113 @c depending on whether the "@c" is present or absent.
114 @c As a result, the @ovar macro is not used, and all invocations
115 @c of the @ovar macro have been expanded inline.
118 @settitle @value{EDITION} User's Guide @value{PLATFORM}
119 @dircategory GNU Ada tools
121 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
124 @include gcc-common.texi
126 @setchapternewpage odd
131 @title @value{EDITION} User's Guide
135 @titlefont{@i{@value{PLATFORM}}}
141 @subtitle GNAT, The GNU Ada Compiler
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 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 * Tools Supporting Project Files::
180 * The Cross-Referencing Tools gnatxref and gnatfind::
181 * The GNAT Pretty-Printer gnatpp::
182 * The GNAT Metric Tool gnatmetric::
183 * File Name Krunching Using gnatkr::
184 * Preprocessing Using gnatprep::
185 * The GNAT Library Browser gnatls::
186 * Cleaning Up Using gnatclean::
188 * GNAT and Libraries::
189 * Using the GNU make Utility::
191 * Memory Management Issues::
192 * Stack Related Facilities::
193 * Verifying Properties Using gnatcheck::
194 * Creating Sample Bodies Using gnatstub::
195 * Generating Ada Bindings for C and C++ headers::
196 * Other Utility Programs::
197 * Running and Debugging Ada Programs::
199 * Code Coverage and Profiling::
202 * Compatibility with HP Ada::
204 * Platform-Specific Information for the Run-Time Libraries::
205 * Example of Binder Output File::
206 * Elaboration Order Handling in GNAT::
207 * Conditional Compilation::
209 * Compatibility and Porting Guide::
211 * Microsoft Windows Topics::
213 * GNU Free Documentation License::
216 --- The Detailed Node Listing ---
220 * What This Guide Contains::
221 * What You Should Know before Reading This Guide::
222 * Related Information::
225 Getting Started with GNAT
228 * Running a Simple Ada Program::
229 * Running a Program with Multiple Units::
230 * Using the gnatmake Utility::
232 * Editing with Emacs::
235 * Introduction to GPS::
238 The GNAT Compilation Model
240 * Source Representation::
241 * Foreign Language Representation::
242 * File Naming Rules::
243 * Using Other File Names::
244 * Alternative File Naming Schemes::
245 * Generating Object Files::
246 * Source Dependencies::
247 * The Ada Library Information Files::
248 * Binding an Ada Program::
249 * Mixed Language Programming::
251 * Building Mixed Ada & C++ Programs::
252 * Comparison between GNAT and C/C++ Compilation Models::
254 * Comparison between GNAT and Conventional Ada Library Models::
256 * Placement of temporary files::
259 Foreign Language Representation
262 * Other 8-Bit Codes::
263 * Wide Character Encodings::
265 Compiling Ada Programs With gcc
267 * Compiling Programs::
269 * Search Paths and the Run-Time Library (RTL)::
270 * Order of Compilation Issues::
275 * Output and Error Message Control::
276 * Warning Message Control::
277 * Debugging and Assertion Control::
278 * Validity Checking::
281 * Using gcc for Syntax Checking::
282 * Using gcc for Semantic Checking::
283 * Compiling Different Versions of Ada::
284 * Character Set Control::
285 * File Naming Control::
286 * Subprogram Inlining Control::
287 * Auxiliary Output Control::
288 * Debugging Control::
289 * Exception Handling Control::
290 * Units to Sources Mapping Files::
291 * Integrated Preprocessing::
296 Binding Ada Programs With gnatbind
299 * Switches for gnatbind::
300 * Command-Line Access::
301 * Search Paths for gnatbind::
302 * Examples of gnatbind Usage::
304 Switches for gnatbind
306 * Consistency-Checking Modes::
307 * Binder Error Message Control::
308 * Elaboration Control::
310 * Binding with Non-Ada Main Programs::
311 * Binding Programs with No Main Subprogram::
313 Linking Using gnatlink
316 * Switches for gnatlink::
318 The GNAT Make Program gnatmake
321 * Switches for gnatmake::
322 * Mode Switches for gnatmake::
323 * Notes on the Command Line::
324 * How gnatmake Works::
325 * Examples of gnatmake Usage::
327 Improving Performance
328 * Performance Considerations::
329 * Text_IO Suggestions::
330 * Reducing Size of Ada Executables with gnatelim::
331 * Reducing Size of Executables with unused subprogram/data elimination::
333 Performance Considerations
334 * Controlling Run-Time Checks::
335 * Use of Restrictions::
336 * Optimization Levels::
337 * Debugging Optimized Code::
338 * Inlining of Subprograms::
339 * Other Optimization Switches::
340 * Optimization and Strict Aliasing::
342 * Coverage Analysis::
345 Reducing Size of Ada Executables with gnatelim
348 * Processing Precompiled Libraries::
349 * Correcting the List of Eliminate Pragmas::
350 * Making Your Executables Smaller::
351 * Summary of the gnatelim Usage Cycle::
353 Reducing Size of Executables with unused subprogram/data elimination
354 * About unused subprogram/data elimination::
355 * Compilation options::
357 Renaming Files Using gnatchop
359 * Handling Files with Multiple Units::
360 * Operating gnatchop in Compilation Mode::
361 * Command Line for gnatchop::
362 * Switches for gnatchop::
363 * Examples of gnatchop Usage::
365 Configuration Pragmas
367 * Handling of Configuration Pragmas::
368 * The Configuration Pragmas Files::
370 Handling Arbitrary File Naming Conventions Using gnatname
372 * Arbitrary File Naming Conventions::
374 * Switches for gnatname::
375 * Examples of gnatname Usage::
377 The Cross-Referencing Tools gnatxref and gnatfind
379 * Switches for gnatxref::
380 * Switches for gnatfind::
381 * Project Files for gnatxref and gnatfind::
382 * Regular Expressions in gnatfind and gnatxref::
383 * Examples of gnatxref Usage::
384 * Examples of gnatfind Usage::
386 The GNAT Pretty-Printer gnatpp
388 * Switches for gnatpp::
391 The GNAT Metrics Tool gnatmetric
393 * Switches for gnatmetric::
395 File Name Krunching Using gnatkr
400 * Examples of gnatkr Usage::
402 Preprocessing Using gnatprep
403 * Preprocessing Symbols::
405 * Switches for gnatprep::
406 * Form of Definitions File::
407 * Form of Input Text for gnatprep::
409 The GNAT Library Browser gnatls
412 * Switches for gnatls::
413 * Examples of gnatls Usage::
415 Cleaning Up Using gnatclean
417 * Running gnatclean::
418 * Switches for gnatclean::
419 @c * Examples of gnatclean Usage::
425 * Introduction to Libraries in GNAT::
426 * General Ada Libraries::
427 * Stand-alone Ada Libraries::
428 * Rebuilding the GNAT Run-Time Library::
430 Using the GNU make Utility
432 * Using gnatmake in a Makefile::
433 * Automatically Creating a List of Directories::
434 * Generating the Command Line Switches::
435 * Overcoming Command Line Length Limits::
438 Memory Management Issues
440 * Some Useful Memory Pools::
441 * The GNAT Debug Pool Facility::
446 Stack Related Facilities
448 * Stack Overflow Checking::
449 * Static Stack Usage Analysis::
450 * Dynamic Stack Usage Analysis::
452 Some Useful Memory Pools
454 The GNAT Debug Pool Facility
460 * Switches for gnatmem::
461 * Example of gnatmem Usage::
464 Verifying Properties Using gnatcheck
466 * Format of the Report File::
467 * General gnatcheck Switches::
468 * gnatcheck Rule Options::
469 * Adding the Results of Compiler Checks to gnatcheck Output::
470 * Project-Wide Checks::
473 * Example of gnatcheck Usage::
475 Sample Bodies Using gnatstub
478 * Switches for gnatstub::
480 Other Utility Programs
482 * Using Other Utility Programs with GNAT::
483 * The External Symbol Naming Scheme of GNAT::
484 * Converting Ada Files to html with gnathtml::
487 Code Coverage and Profiling
489 * Code Coverage of Ada Programs using gcov::
490 * Profiling an Ada Program using gprof::
493 Running and Debugging Ada Programs
495 * The GNAT Debugger GDB::
497 * Introduction to GDB Commands::
498 * Using Ada Expressions::
499 * Calling User-Defined Subprograms::
500 * Using the Next Command in a Function::
503 * Debugging Generic Units::
504 * Remote Debugging using gdbserver::
505 * GNAT Abnormal Termination or Failure to Terminate::
506 * Naming Conventions for GNAT Source Files::
507 * Getting Internal Debugging Information::
515 Compatibility with HP Ada
517 * Ada Language Compatibility::
518 * Differences in the Definition of Package System::
519 * Language-Related Features::
520 * The Package STANDARD::
521 * The Package SYSTEM::
522 * Tasking and Task-Related Features::
523 * Pragmas and Pragma-Related Features::
524 * Library of Predefined Units::
526 * Main Program Definition::
527 * Implementation-Defined Attributes::
528 * Compiler and Run-Time Interfacing::
529 * Program Compilation and Library Management::
531 * Implementation Limits::
532 * Tools and Utilities::
534 Language-Related Features
536 * Integer Types and Representations::
537 * Floating-Point Types and Representations::
538 * Pragmas Float_Representation and Long_Float::
539 * Fixed-Point Types and Representations::
540 * Record and Array Component Alignment::
542 * Other Representation Clauses::
544 Tasking and Task-Related Features
546 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
547 * Assigning Task IDs::
548 * Task IDs and Delays::
549 * Task-Related Pragmas::
550 * Scheduling and Task Priority::
552 * External Interrupts::
554 Pragmas and Pragma-Related Features
556 * Restrictions on the Pragma INLINE::
557 * Restrictions on the Pragma INTERFACE::
558 * Restrictions on the Pragma SYSTEM_NAME::
560 Library of Predefined Units
562 * Changes to DECLIB::
566 * Shared Libraries and Options Files::
570 Platform-Specific Information for the Run-Time Libraries
572 * Summary of Run-Time Configurations::
573 * Specifying a Run-Time Library::
574 * Choosing the Scheduling Policy::
575 * Solaris-Specific Considerations::
576 * Linux-Specific Considerations::
577 * AIX-Specific Considerations::
578 * Irix-Specific Considerations::
579 * RTX-Specific Considerations::
580 * HP-UX-Specific Considerations::
582 Example of Binder Output File
584 Elaboration Order Handling in GNAT
587 * Checking the Elaboration Order::
588 * Controlling the Elaboration Order::
589 * Controlling Elaboration in GNAT - Internal Calls::
590 * Controlling Elaboration in GNAT - External Calls::
591 * Default Behavior in GNAT - Ensuring Safety::
592 * Treatment of Pragma Elaborate::
593 * Elaboration Issues for Library Tasks::
594 * Mixing Elaboration Models::
595 * What to Do If the Default Elaboration Behavior Fails::
596 * Elaboration for Access-to-Subprogram Values::
597 * Summary of Procedures for Elaboration Control::
598 * Other Elaboration Order Considerations::
600 Conditional Compilation
601 * Use of Boolean Constants::
602 * Debugging - A Special Case::
603 * Conditionalizing Declarations::
604 * Use of Alternative Implementations::
609 * Basic Assembler Syntax::
610 * A Simple Example of Inline Assembler::
611 * Output Variables in Inline Assembler::
612 * Input Variables in Inline Assembler::
613 * Inlining Inline Assembler Code::
614 * Other Asm Functionality::
616 Compatibility and Porting Guide
618 * Compatibility with Ada 83::
619 * Compatibility between Ada 95 and Ada 2005::
620 * Implementation-dependent characteristics::
622 @c This brief section is only in the non-VMS version
623 @c The complete chapter on HP Ada issues is in the VMS version
624 * Compatibility with HP Ada 83::
626 * Compatibility with Other Ada Systems::
627 * Representation Clauses::
629 * Transitioning to 64-Bit GNAT for OpenVMS::
633 Microsoft Windows Topics
635 * Using GNAT on Windows::
636 * CONSOLE and WINDOWS subsystems::
638 * Mixed-Language Programming on Windows::
639 * Windows Calling Conventions::
640 * Introduction to Dynamic Link Libraries (DLLs)::
641 * Using DLLs with GNAT::
642 * Building DLLs with GNAT::
643 * GNAT and Windows Resources::
645 * Setting Stack Size from gnatlink::
646 * Setting Heap Size from gnatlink::
653 @node About This Guide
654 @unnumbered About This Guide
658 This guide describes the use of @value{EDITION},
659 a compiler and software development toolset for the full Ada
660 programming language, implemented on OpenVMS for HP's Alpha and
661 Integrity server (I64) platforms.
664 This guide describes the use of @value{EDITION},
665 a compiler and software development
666 toolset for the full Ada programming language.
668 It documents the features of the compiler and tools, and explains
669 how to use them to build Ada applications.
671 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
672 Ada 83 compatibility mode.
673 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
674 but you can override with a compiler switch
675 (@pxref{Compiling Different Versions of Ada})
676 to explicitly specify the language version.
677 Throughout this manual, references to ``Ada'' without a year suffix
678 apply to both the Ada 95 and Ada 2005 versions of the language.
682 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
683 ``GNAT'' in the remainder of this document.
690 * What This Guide Contains::
691 * What You Should Know before Reading This Guide::
692 * Related Information::
696 @node What This Guide Contains
697 @unnumberedsec What This Guide Contains
700 This guide contains the following chapters:
704 @ref{Getting Started with GNAT}, describes how to get started compiling
705 and running Ada programs with the GNAT Ada programming environment.
707 @ref{The GNAT Compilation Model}, describes the compilation model used
711 @ref{Compiling Using gcc}, describes how to compile
712 Ada programs with @command{gcc}, the Ada compiler.
715 @ref{Binding Using gnatbind}, describes how to
716 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
720 @ref{Linking Using gnatlink},
721 describes @command{gnatlink}, a
722 program that provides for linking using the GNAT run-time library to
723 construct a program. @command{gnatlink} can also incorporate foreign language
724 object units into the executable.
727 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
728 utility that automatically determines the set of sources
729 needed by an Ada compilation unit, and executes the necessary compilations
733 @ref{Improving Performance}, shows various techniques for making your
734 Ada program run faster or take less space.
735 It discusses the effect of the compiler's optimization switch and
736 also describes the @command{gnatelim} tool and unused subprogram/data
740 @ref{Renaming Files Using gnatchop}, describes
741 @code{gnatchop}, a utility that allows you to preprocess a file that
742 contains Ada source code, and split it into one or more new files, one
743 for each compilation unit.
746 @ref{Configuration Pragmas}, describes the configuration pragmas
750 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
751 shows how to override the default GNAT file naming conventions,
752 either for an individual unit or globally.
755 @ref{GNAT Project Manager}, describes how to use project files
756 to organize large projects.
759 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
760 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
761 way to navigate through sources.
764 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
765 version of an Ada source file with control over casing, indentation,
766 comment placement, and other elements of program presentation style.
769 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
770 metrics for an Ada source file, such as the number of types and subprograms,
771 and assorted complexity measures.
774 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
775 file name krunching utility, used to handle shortened
776 file names on operating systems with a limit on the length of names.
779 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
780 preprocessor utility that allows a single source file to be used to
781 generate multiple or parameterized source files by means of macro
785 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
786 utility that displays information about compiled units, including dependences
787 on the corresponding sources files, and consistency of compilations.
790 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
791 to delete files that are produced by the compiler, binder and linker.
795 @ref{GNAT and Libraries}, describes the process of creating and using
796 Libraries with GNAT. It also describes how to recompile the GNAT run-time
800 @ref{Using the GNU make Utility}, describes some techniques for using
801 the GNAT toolset in Makefiles.
805 @ref{Memory Management Issues}, describes some useful predefined storage pools
806 and in particular the GNAT Debug Pool facility, which helps detect incorrect
809 It also describes @command{gnatmem}, a utility that monitors dynamic
810 allocation and deallocation and helps detect ``memory leaks''.
814 @ref{Stack Related Facilities}, describes some useful tools associated with
815 stack checking and analysis.
818 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
819 a utility that checks Ada code against a set of rules.
822 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
823 a utility that generates empty but compilable bodies for library units.
826 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
827 generate automatically Ada bindings from C and C++ headers.
830 @ref{Other Utility Programs}, discusses several other GNAT utilities,
831 including @code{gnathtml}.
835 @ref{Code Coverage and Profiling}, describes how to perform a structural
836 coverage and profile the execution of Ada programs.
840 @ref{Running and Debugging Ada Programs}, describes how to run and debug
845 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
846 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
847 developed by Digital Equipment Corporation and currently supported by HP.}
848 for OpenVMS Alpha. This product was formerly known as DEC Ada,
851 historical compatibility reasons, the relevant libraries still use the
856 @ref{Platform-Specific Information for the Run-Time Libraries},
857 describes the various run-time
858 libraries supported by GNAT on various platforms and explains how to
859 choose a particular library.
862 @ref{Example of Binder Output File}, shows the source code for the binder
863 output file for a sample program.
866 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
867 you deal with elaboration order issues.
870 @ref{Conditional Compilation}, describes how to model conditional compilation,
871 both with Ada in general and with GNAT facilities in particular.
874 @ref{Inline Assembler}, shows how to use the inline assembly facility
878 @ref{Compatibility and Porting Guide}, contains sections on compatibility
879 of GNAT with other Ada development environments (including Ada 83 systems),
880 to assist in porting code from those environments.
884 @ref{Microsoft Windows Topics}, presents information relevant to the
885 Microsoft Windows platform.
889 @c *************************************************
890 @node What You Should Know before Reading This Guide
891 @c *************************************************
892 @unnumberedsec What You Should Know before Reading This Guide
894 @cindex Ada 95 Language Reference Manual
895 @cindex Ada 2005 Language Reference Manual
897 This guide assumes a basic familiarity with the Ada 95 language, as
898 described in the International Standard ANSI/ISO/IEC-8652:1995, January
900 It does not require knowledge of the new features introduced by Ada 2005,
901 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
903 Both reference manuals are included in the GNAT documentation
906 @node Related Information
907 @unnumberedsec Related Information
910 For further information about related tools, refer to the following
915 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
916 Reference Manual}, which contains all reference material for the GNAT
917 implementation of Ada.
921 @cite{Using the GNAT Programming Studio}, which describes the GPS
922 Integrated Development Environment.
925 @cite{GNAT Programming Studio Tutorial}, which introduces the
926 main GPS features through examples.
930 @cite{Ada 95 Reference Manual}, which contains reference
931 material for the Ada 95 programming language.
934 @cite{Ada 2005 Reference Manual}, which contains reference
935 material for the Ada 2005 programming language.
938 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
940 in the GNU:[DOCS] directory,
942 for all details on the use of the GNU source-level debugger.
945 @xref{Top,, The extensible self-documenting text editor, emacs,
948 located in the GNU:[DOCS] directory if the EMACS kit is installed,
950 for full information on the extensible editor and programming
957 @unnumberedsec Conventions
959 @cindex Typographical conventions
962 Following are examples of the typographical and graphic conventions used
967 @code{Functions}, @command{utility program names}, @code{standard names},
971 @option{Option flags}
974 @file{File names}, @samp{button names}, and @samp{field names}.
977 @code{Variables}, @env{environment variables}, and @var{metasyntactic
984 @r{[}optional information or parameters@r{]}
987 Examples are described by text
989 and then shown this way.
994 Commands that are entered by the user are preceded in this manual by the
995 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
996 uses this sequence as a prompt, then the commands will appear exactly as
997 you see them in the manual. If your system uses some other prompt, then
998 the command will appear with the @code{$} replaced by whatever prompt
999 character you are using.
1002 Full file names are shown with the ``@code{/}'' character
1003 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1004 If you are using GNAT on a Windows platform, please note that
1005 the ``@code{\}'' character should be used instead.
1008 @c ****************************
1009 @node Getting Started with GNAT
1010 @chapter Getting Started with GNAT
1013 This chapter describes some simple ways of using GNAT to build
1014 executable Ada programs.
1016 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1017 show how to use the command line environment.
1018 @ref{Introduction to GPS}, provides a brief
1019 introduction to the GNAT Programming Studio, a visually-oriented
1020 Integrated Development Environment for GNAT.
1021 GPS offers a graphical ``look and feel'', support for development in
1022 other programming languages, comprehensive browsing features, and
1023 many other capabilities.
1024 For information on GPS please refer to
1025 @cite{Using the GNAT Programming Studio}.
1030 * Running a Simple Ada Program::
1031 * Running a Program with Multiple Units::
1032 * Using the gnatmake Utility::
1034 * Editing with Emacs::
1037 * Introduction to GPS::
1042 @section Running GNAT
1045 Three steps are needed to create an executable file from an Ada source
1050 The source file(s) must be compiled.
1052 The file(s) must be bound using the GNAT binder.
1054 All appropriate object files must be linked to produce an executable.
1058 All three steps are most commonly handled by using the @command{gnatmake}
1059 utility program that, given the name of the main program, automatically
1060 performs the necessary compilation, binding and linking steps.
1062 @node Running a Simple Ada Program
1063 @section Running a Simple Ada Program
1066 Any text editor may be used to prepare an Ada program.
1068 used, the optional Ada mode may be helpful in laying out the program.)
1070 program text is a normal text file. We will assume in our initial
1071 example that you have used your editor to prepare the following
1072 standard format text file:
1074 @smallexample @c ada
1076 with Ada.Text_IO; use Ada.Text_IO;
1079 Put_Line ("Hello WORLD!");
1085 This file should be named @file{hello.adb}.
1086 With the normal default file naming conventions, GNAT requires
1088 contain a single compilation unit whose file name is the
1090 with periods replaced by hyphens; the
1091 extension is @file{ads} for a
1092 spec and @file{adb} for a body.
1093 You can override this default file naming convention by use of the
1094 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1095 Alternatively, if you want to rename your files according to this default
1096 convention, which is probably more convenient if you will be using GNAT
1097 for all your compilations, then the @code{gnatchop} utility
1098 can be used to generate correctly-named source files
1099 (@pxref{Renaming Files Using gnatchop}).
1101 You can compile the program using the following command (@code{$} is used
1102 as the command prompt in the examples in this document):
1109 @command{gcc} is the command used to run the compiler. This compiler is
1110 capable of compiling programs in several languages, including Ada and
1111 C. It assumes that you have given it an Ada program if the file extension is
1112 either @file{.ads} or @file{.adb}, and it will then call
1113 the GNAT compiler to compile the specified file.
1116 The @option{-c} switch is required. It tells @command{gcc} to only do a
1117 compilation. (For C programs, @command{gcc} can also do linking, but this
1118 capability is not used directly for Ada programs, so the @option{-c}
1119 switch must always be present.)
1122 This compile command generates a file
1123 @file{hello.o}, which is the object
1124 file corresponding to your Ada program. It also generates
1125 an ``Ada Library Information'' file @file{hello.ali},
1126 which contains additional information used to check
1127 that an Ada program is consistent.
1128 To build an executable file,
1129 use @code{gnatbind} to bind the program
1130 and @command{gnatlink} to link it. The
1131 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1132 @file{ALI} file, but the default extension of @file{.ali} can
1133 be omitted. This means that in the most common case, the argument
1134 is simply the name of the main program:
1142 A simpler method of carrying out these steps is to use
1144 a master program that invokes all the required
1145 compilation, binding and linking tools in the correct order. In particular,
1146 @command{gnatmake} automatically recompiles any sources that have been
1147 modified since they were last compiled, or sources that depend
1148 on such modified sources, so that ``version skew'' is avoided.
1149 @cindex Version skew (avoided by @command{gnatmake})
1152 $ gnatmake hello.adb
1156 The result is an executable program called @file{hello}, which can be
1164 assuming that the current directory is on the search path
1165 for executable programs.
1168 and, if all has gone well, you will see
1175 appear in response to this command.
1177 @c ****************************************
1178 @node Running a Program with Multiple Units
1179 @section Running a Program with Multiple Units
1182 Consider a slightly more complicated example that has three files: a
1183 main program, and the spec and body of a package:
1185 @smallexample @c ada
1188 package Greetings is
1193 with Ada.Text_IO; use Ada.Text_IO;
1194 package body Greetings is
1197 Put_Line ("Hello WORLD!");
1200 procedure Goodbye is
1202 Put_Line ("Goodbye WORLD!");
1219 Following the one-unit-per-file rule, place this program in the
1220 following three separate files:
1224 spec of package @code{Greetings}
1227 body of package @code{Greetings}
1230 body of main program
1234 To build an executable version of
1235 this program, we could use four separate steps to compile, bind, and link
1236 the program, as follows:
1240 $ gcc -c greetings.adb
1246 Note that there is no required order of compilation when using GNAT.
1247 In particular it is perfectly fine to compile the main program first.
1248 Also, it is not necessary to compile package specs in the case where
1249 there is an accompanying body; you only need to compile the body. If you want
1250 to submit these files to the compiler for semantic checking and not code
1251 generation, then use the
1252 @option{-gnatc} switch:
1255 $ gcc -c greetings.ads -gnatc
1259 Although the compilation can be done in separate steps as in the
1260 above example, in practice it is almost always more convenient
1261 to use the @command{gnatmake} tool. All you need to know in this case
1262 is the name of the main program's source file. The effect of the above four
1263 commands can be achieved with a single one:
1266 $ gnatmake gmain.adb
1270 In the next section we discuss the advantages of using @command{gnatmake} in
1273 @c *****************************
1274 @node Using the gnatmake Utility
1275 @section Using the @command{gnatmake} Utility
1278 If you work on a program by compiling single components at a time using
1279 @command{gcc}, you typically keep track of the units you modify. In order to
1280 build a consistent system, you compile not only these units, but also any
1281 units that depend on the units you have modified.
1282 For example, in the preceding case,
1283 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1284 you edit @file{greetings.ads}, you must recompile both
1285 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1286 units that depend on @file{greetings.ads}.
1288 @code{gnatbind} will warn you if you forget one of these compilation
1289 steps, so that it is impossible to generate an inconsistent program as a
1290 result of forgetting to do a compilation. Nevertheless it is tedious and
1291 error-prone to keep track of dependencies among units.
1292 One approach to handle the dependency-bookkeeping is to use a
1293 makefile. However, makefiles present maintenance problems of their own:
1294 if the dependencies change as you change the program, you must make
1295 sure that the makefile is kept up-to-date manually, which is also an
1296 error-prone process.
1298 The @command{gnatmake} utility takes care of these details automatically.
1299 Invoke it using either one of the following forms:
1302 $ gnatmake gmain.adb
1303 $ gnatmake ^gmain^GMAIN^
1307 The argument is the name of the file containing the main program;
1308 you may omit the extension. @command{gnatmake}
1309 examines the environment, automatically recompiles any files that need
1310 recompiling, and binds and links the resulting set of object files,
1311 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1312 In a large program, it
1313 can be extremely helpful to use @command{gnatmake}, because working out by hand
1314 what needs to be recompiled can be difficult.
1316 Note that @command{gnatmake}
1317 takes into account all the Ada rules that
1318 establish dependencies among units. These include dependencies that result
1319 from inlining subprogram bodies, and from
1320 generic instantiation. Unlike some other
1321 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1322 found by the compiler on a previous compilation, which may possibly
1323 be wrong when sources change. @command{gnatmake} determines the exact set of
1324 dependencies from scratch each time it is run.
1327 @node Editing with Emacs
1328 @section Editing with Emacs
1332 Emacs is an extensible self-documenting text editor that is available in a
1333 separate VMSINSTAL kit.
1335 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1336 click on the Emacs Help menu and run the Emacs Tutorial.
1337 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1338 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1340 Documentation on Emacs and other tools is available in Emacs under the
1341 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1342 use the middle mouse button to select a topic (e.g.@: Emacs).
1344 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1345 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1346 get to the Emacs manual.
1347 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1350 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1351 which is sufficiently extensible to provide for a complete programming
1352 environment and shell for the sophisticated user.
1356 @node Introduction to GPS
1357 @section Introduction to GPS
1358 @cindex GPS (GNAT Programming Studio)
1359 @cindex GNAT Programming Studio (GPS)
1361 Although the command line interface (@command{gnatmake}, etc.) alone
1362 is sufficient, a graphical Interactive Development
1363 Environment can make it easier for you to compose, navigate, and debug
1364 programs. This section describes the main features of GPS
1365 (``GNAT Programming Studio''), the GNAT graphical IDE.
1366 You will see how to use GPS to build and debug an executable, and
1367 you will also learn some of the basics of the GNAT ``project'' facility.
1369 GPS enables you to do much more than is presented here;
1370 e.g., you can produce a call graph, interface to a third-party
1371 Version Control System, and inspect the generated assembly language
1373 Indeed, GPS also supports languages other than Ada.
1374 Such additional information, and an explanation of all of the GPS menu
1375 items. may be found in the on-line help, which includes
1376 a user's guide and a tutorial (these are also accessible from the GNAT
1380 * Building a New Program with GPS::
1381 * Simple Debugging with GPS::
1384 @node Building a New Program with GPS
1385 @subsection Building a New Program with GPS
1387 GPS invokes the GNAT compilation tools using information
1388 contained in a @emph{project} (also known as a @emph{project file}):
1389 a collection of properties such
1390 as source directories, identities of main subprograms, tool switches, etc.,
1391 and their associated values.
1392 See @ref{GNAT Project Manager} for details.
1393 In order to run GPS, you will need to either create a new project
1394 or else open an existing one.
1396 This section will explain how you can use GPS to create a project,
1397 to associate Ada source files with a project, and to build and run
1401 @item @emph{Creating a project}
1403 Invoke GPS, either from the command line or the platform's IDE.
1404 After it starts, GPS will display a ``Welcome'' screen with three
1409 @code{Start with default project in directory}
1412 @code{Create new project with wizard}
1415 @code{Open existing project}
1419 Select @code{Create new project with wizard} and press @code{OK}.
1420 A new window will appear. In the text box labeled with
1421 @code{Enter the name of the project to create}, type @file{sample}
1422 as the project name.
1423 In the next box, browse to choose the directory in which you
1424 would like to create the project file.
1425 After selecting an appropriate directory, press @code{Forward}.
1427 A window will appear with the title
1428 @code{Version Control System Configuration}.
1429 Simply press @code{Forward}.
1431 A window will appear with the title
1432 @code{Please select the source directories for this project}.
1433 The directory that you specified for the project file will be selected
1434 by default as the one to use for sources; simply press @code{Forward}.
1436 A window will appear with the title
1437 @code{Please select the build directory for this project}.
1438 The directory that you specified for the project file will be selected
1439 by default for object files and executables;
1440 simply press @code{Forward}.
1442 A window will appear with the title
1443 @code{Please select the main units for this project}.
1444 You will supply this information later, after creating the source file.
1445 Simply press @code{Forward} for now.
1447 A window will appear with the title
1448 @code{Please select the switches to build the project}.
1449 Press @code{Apply}. This will create a project file named
1450 @file{sample.prj} in the directory that you had specified.
1452 @item @emph{Creating and saving the source file}
1454 After you create the new project, a GPS window will appear, which is
1455 partitioned into two main sections:
1459 A @emph{Workspace area}, initially greyed out, which you will use for
1460 creating and editing source files
1463 Directly below, a @emph{Messages area}, which initially displays a
1464 ``Welcome'' message.
1465 (If the Messages area is not visible, drag its border upward to expand it.)
1469 Select @code{File} on the menu bar, and then the @code{New} command.
1470 The Workspace area will become white, and you can now
1471 enter the source program explicitly.
1472 Type the following text
1474 @smallexample @c ada
1476 with Ada.Text_IO; use Ada.Text_IO;
1479 Put_Line("Hello from GPS!");
1485 Select @code{File}, then @code{Save As}, and enter the source file name
1487 The file will be saved in the same directory you specified as the
1488 location of the default project file.
1490 @item @emph{Updating the project file}
1492 You need to add the new source file to the project.
1494 the @code{Project} menu and then @code{Edit project properties}.
1495 Click the @code{Main files} tab on the left, and then the
1497 Choose @file{hello.adb} from the list, and press @code{Open}.
1498 The project settings window will reflect this action.
1501 @item @emph{Building and running the program}
1503 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1504 and select @file{hello.adb}.
1505 The Messages window will display the resulting invocations of @command{gcc},
1506 @command{gnatbind}, and @command{gnatlink}
1507 (reflecting the default switch settings from the
1508 project file that you created) and then a ``successful compilation/build''
1511 To run the program, choose the @code{Build} menu, then @code{Run}, and
1512 select @command{hello}.
1513 An @emph{Arguments Selection} window will appear.
1514 There are no command line arguments, so just click @code{OK}.
1516 The Messages window will now display the program's output (the string
1517 @code{Hello from GPS}), and at the bottom of the GPS window a status
1518 update is displayed (@code{Run: hello}).
1519 Close the GPS window (or select @code{File}, then @code{Exit}) to
1520 terminate this GPS session.
1523 @node Simple Debugging with GPS
1524 @subsection Simple Debugging with GPS
1526 This section illustrates basic debugging techniques (setting breakpoints,
1527 examining/modifying variables, single stepping).
1530 @item @emph{Opening a project}
1532 Start GPS and select @code{Open existing project}; browse to
1533 specify the project file @file{sample.prj} that you had created in the
1536 @item @emph{Creating a source file}
1538 Select @code{File}, then @code{New}, and type in the following program:
1540 @smallexample @c ada
1542 with Ada.Text_IO; use Ada.Text_IO;
1543 procedure Example is
1544 Line : String (1..80);
1547 Put_Line("Type a line of text at each prompt; an empty line to exit");
1551 Put_Line (Line (1..N) );
1559 Select @code{File}, then @code{Save as}, and enter the file name
1562 @item @emph{Updating the project file}
1564 Add @code{Example} as a new main unit for the project:
1567 Select @code{Project}, then @code{Edit Project Properties}.
1570 Select the @code{Main files} tab, click @code{Add}, then
1571 select the file @file{example.adb} from the list, and
1573 You will see the file name appear in the list of main units
1579 @item @emph{Building/running the executable}
1581 To build the executable
1582 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1584 Run the program to see its effect (in the Messages area).
1585 Each line that you enter is displayed; an empty line will
1586 cause the loop to exit and the program to terminate.
1588 @item @emph{Debugging the program}
1590 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1591 which are required for debugging, are on by default when you create
1593 Thus unless you intentionally remove these settings, you will be able
1594 to debug any program that you develop using GPS.
1597 @item @emph{Initializing}
1599 Select @code{Debug}, then @code{Initialize}, then @file{example}
1601 @item @emph{Setting a breakpoint}
1603 After performing the initialization step, you will observe a small
1604 icon to the right of each line number.
1605 This serves as a toggle for breakpoints; clicking the icon will
1606 set a breakpoint at the corresponding line (the icon will change to
1607 a red circle with an ``x''), and clicking it again
1608 will remove the breakpoint / reset the icon.
1610 For purposes of this example, set a breakpoint at line 10 (the
1611 statement @code{Put_Line@ (Line@ (1..N));}
1613 @item @emph{Starting program execution}
1615 Select @code{Debug}, then @code{Run}. When the
1616 @code{Program Arguments} window appears, click @code{OK}.
1617 A console window will appear; enter some line of text,
1618 e.g.@: @code{abcde}, at the prompt.
1619 The program will pause execution when it gets to the
1620 breakpoint, and the corresponding line is highlighted.
1622 @item @emph{Examining a variable}
1624 Move the mouse over one of the occurrences of the variable @code{N}.
1625 You will see the value (5) displayed, in ``tool tip'' fashion.
1626 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1627 You will see information about @code{N} appear in the @code{Debugger Data}
1628 pane, showing the value as 5.
1630 @item @emph{Assigning a new value to a variable}
1632 Right click on the @code{N} in the @code{Debugger Data} pane, and
1633 select @code{Set value of N}.
1634 When the input window appears, enter the value @code{4} and click
1636 This value does not automatically appear in the @code{Debugger Data}
1637 pane; to see it, right click again on the @code{N} in the
1638 @code{Debugger Data} pane and select @code{Update value}.
1639 The new value, 4, will appear in red.
1641 @item @emph{Single stepping}
1643 Select @code{Debug}, then @code{Next}.
1644 This will cause the next statement to be executed, in this case the
1645 call of @code{Put_Line} with the string slice.
1646 Notice in the console window that the displayed string is simply
1647 @code{abcd} and not @code{abcde} which you had entered.
1648 This is because the upper bound of the slice is now 4 rather than 5.
1650 @item @emph{Removing a breakpoint}
1652 Toggle the breakpoint icon at line 10.
1654 @item @emph{Resuming execution from a breakpoint}
1656 Select @code{Debug}, then @code{Continue}.
1657 The program will reach the next iteration of the loop, and
1658 wait for input after displaying the prompt.
1659 This time, just hit the @kbd{Enter} key.
1660 The value of @code{N} will be 0, and the program will terminate.
1661 The console window will disappear.
1666 @node The GNAT Compilation Model
1667 @chapter The GNAT Compilation Model
1668 @cindex GNAT compilation model
1669 @cindex Compilation model
1672 * Source Representation::
1673 * Foreign Language Representation::
1674 * File Naming Rules::
1675 * Using Other File Names::
1676 * Alternative File Naming Schemes::
1677 * Generating Object Files::
1678 * Source Dependencies::
1679 * The Ada Library Information Files::
1680 * Binding an Ada Program::
1681 * Mixed Language Programming::
1683 * Building Mixed Ada & C++ Programs::
1684 * Comparison between GNAT and C/C++ Compilation Models::
1686 * Comparison between GNAT and Conventional Ada Library Models::
1688 * Placement of temporary files::
1693 This chapter describes the compilation model used by GNAT. Although
1694 similar to that used by other languages, such as C and C++, this model
1695 is substantially different from the traditional Ada compilation models,
1696 which are based on a library. The model is initially described without
1697 reference to the library-based model. If you have not previously used an
1698 Ada compiler, you need only read the first part of this chapter. The
1699 last section describes and discusses the differences between the GNAT
1700 model and the traditional Ada compiler models. If you have used other
1701 Ada compilers, this section will help you to understand those
1702 differences, and the advantages of the GNAT model.
1704 @node Source Representation
1705 @section Source Representation
1709 Ada source programs are represented in standard text files, using
1710 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1711 7-bit ASCII set, plus additional characters used for
1712 representing foreign languages (@pxref{Foreign Language Representation}
1713 for support of non-USA character sets). The format effector characters
1714 are represented using their standard ASCII encodings, as follows:
1719 Vertical tab, @code{16#0B#}
1723 Horizontal tab, @code{16#09#}
1727 Carriage return, @code{16#0D#}
1731 Line feed, @code{16#0A#}
1735 Form feed, @code{16#0C#}
1739 Source files are in standard text file format. In addition, GNAT will
1740 recognize a wide variety of stream formats, in which the end of
1741 physical lines is marked by any of the following sequences:
1742 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1743 in accommodating files that are imported from other operating systems.
1745 @cindex End of source file
1746 @cindex Source file, end
1748 The end of a source file is normally represented by the physical end of
1749 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1750 recognized as signalling the end of the source file. Again, this is
1751 provided for compatibility with other operating systems where this
1752 code is used to represent the end of file.
1754 Each file contains a single Ada compilation unit, including any pragmas
1755 associated with the unit. For example, this means you must place a
1756 package declaration (a package @dfn{spec}) and the corresponding body in
1757 separate files. An Ada @dfn{compilation} (which is a sequence of
1758 compilation units) is represented using a sequence of files. Similarly,
1759 you will place each subunit or child unit in a separate file.
1761 @node Foreign Language Representation
1762 @section Foreign Language Representation
1765 GNAT supports the standard character sets defined in Ada as well as
1766 several other non-standard character sets for use in localized versions
1767 of the compiler (@pxref{Character Set Control}).
1770 * Other 8-Bit Codes::
1771 * Wide Character Encodings::
1779 The basic character set is Latin-1. This character set is defined by ISO
1780 standard 8859, part 1. The lower half (character codes @code{16#00#}
1781 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper
1782 half is used to represent additional characters. These include extended letters
1783 used by European languages, such as French accents, the vowels with umlauts
1784 used in German, and the extra letter A-ring used in Swedish.
1786 @findex Ada.Characters.Latin_1
1787 For a complete list of Latin-1 codes and their encodings, see the source
1788 file of library unit @code{Ada.Characters.Latin_1} in file
1789 @file{a-chlat1.ads}.
1790 You may use any of these extended characters freely in character or
1791 string literals. In addition, the extended characters that represent
1792 letters can be used in identifiers.
1794 @node Other 8-Bit Codes
1795 @subsection Other 8-Bit Codes
1798 GNAT also supports several other 8-bit coding schemes:
1801 @item ISO 8859-2 (Latin-2)
1804 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1807 @item ISO 8859-3 (Latin-3)
1810 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1813 @item ISO 8859-4 (Latin-4)
1816 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1819 @item ISO 8859-5 (Cyrillic)
1822 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1823 lowercase equivalence.
1825 @item ISO 8859-15 (Latin-9)
1828 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1829 lowercase equivalence
1831 @item IBM PC (code page 437)
1832 @cindex code page 437
1833 This code page is the normal default for PCs in the U.S. It corresponds
1834 to the original IBM PC character set. This set has some, but not all, of
1835 the extended Latin-1 letters, but these letters do not have the same
1836 encoding as Latin-1. In this mode, these letters are allowed in
1837 identifiers with uppercase and lowercase equivalence.
1839 @item IBM PC (code page 850)
1840 @cindex code page 850
1841 This code page is a modification of 437 extended to include all the
1842 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1843 mode, all these letters are allowed in identifiers with uppercase and
1844 lowercase equivalence.
1846 @item Full Upper 8-bit
1847 Any character in the range 80-FF allowed in identifiers, and all are
1848 considered distinct. In other words, there are no uppercase and lowercase
1849 equivalences in this range. This is useful in conjunction with
1850 certain encoding schemes used for some foreign character sets (e.g.,
1851 the typical method of representing Chinese characters on the PC).
1854 No upper-half characters in the range 80-FF are allowed in identifiers.
1855 This gives Ada 83 compatibility for identifier names.
1859 For precise data on the encodings permitted, and the uppercase and lowercase
1860 equivalences that are recognized, see the file @file{csets.adb} in
1861 the GNAT compiler sources. You will need to obtain a full source release
1862 of GNAT to obtain this file.
1864 @node Wide Character Encodings
1865 @subsection Wide Character Encodings
1868 GNAT allows wide character codes to appear in character and string
1869 literals, and also optionally in identifiers, by means of the following
1870 possible encoding schemes:
1875 In this encoding, a wide character is represented by the following five
1883 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1884 characters (using uppercase letters) of the wide character code. For
1885 example, ESC A345 is used to represent the wide character with code
1887 This scheme is compatible with use of the full Wide_Character set.
1889 @item Upper-Half Coding
1890 @cindex Upper-Half Coding
1891 The wide character with encoding @code{16#abcd#} where the upper bit is on
1892 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1893 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1894 character, but is not required to be in the upper half. This method can
1895 be also used for shift-JIS or EUC, where the internal coding matches the
1898 @item Shift JIS Coding
1899 @cindex Shift JIS Coding
1900 A wide character is represented by a two-character sequence,
1902 @code{16#cd#}, with the restrictions described for upper-half encoding as
1903 described above. The internal character code is the corresponding JIS
1904 character according to the standard algorithm for Shift-JIS
1905 conversion. Only characters defined in the JIS code set table can be
1906 used with this encoding method.
1910 A wide character is represented by a two-character sequence
1912 @code{16#cd#}, with both characters being in the upper half. The internal
1913 character code is the corresponding JIS character according to the EUC
1914 encoding algorithm. Only characters defined in the JIS code set table
1915 can be used with this encoding method.
1918 A wide character is represented using
1919 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1920 10646-1/Am.2. Depending on the character value, the representation
1921 is a one, two, or three byte sequence:
1926 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1927 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1928 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1933 where the @var{xxx} bits correspond to the left-padded bits of the
1934 16-bit character value. Note that all lower half ASCII characters
1935 are represented as ASCII bytes and all upper half characters and
1936 other wide characters are represented as sequences of upper-half
1937 (The full UTF-8 scheme allows for encoding 31-bit characters as
1938 6-byte sequences, but in this implementation, all UTF-8 sequences
1939 of four or more bytes length will be treated as illegal).
1940 @item Brackets Coding
1941 In this encoding, a wide character is represented by the following eight
1949 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1950 characters (using uppercase letters) of the wide character code. For
1951 example, [``A345''] is used to represent the wide character with code
1952 @code{16#A345#}. It is also possible (though not required) to use the
1953 Brackets coding for upper half characters. For example, the code
1954 @code{16#A3#} can be represented as @code{[``A3'']}.
1956 This scheme is compatible with use of the full Wide_Character set,
1957 and is also the method used for wide character encoding in the standard
1958 ACVC (Ada Compiler Validation Capability) test suite distributions.
1963 Note: Some of these coding schemes do not permit the full use of the
1964 Ada character set. For example, neither Shift JIS, nor EUC allow the
1965 use of the upper half of the Latin-1 set.
1967 @node File Naming Rules
1968 @section File Naming Rules
1971 The default file name is determined by the name of the unit that the
1972 file contains. The name is formed by taking the full expanded name of
1973 the unit and replacing the separating dots with hyphens and using
1974 ^lowercase^uppercase^ for all letters.
1976 An exception arises if the file name generated by the above rules starts
1977 with one of the characters
1979 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
1982 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
1984 and the second character is a
1985 minus. In this case, the character ^tilde^dollar sign^ is used in place
1986 of the minus. The reason for this special rule is to avoid clashes with
1987 the standard names for child units of the packages System, Ada,
1988 Interfaces, and GNAT, which use the prefixes
1990 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
1993 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
1997 The file extension is @file{.ads} for a spec and
1998 @file{.adb} for a body. The following list shows some
1999 examples of these rules.
2006 @item arith_functions.ads
2007 Arith_Functions (package spec)
2008 @item arith_functions.adb
2009 Arith_Functions (package body)
2011 Func.Spec (child package spec)
2013 Func.Spec (child package body)
2015 Sub (subunit of Main)
2016 @item ^a~bad.adb^A$BAD.ADB^
2017 A.Bad (child package body)
2021 Following these rules can result in excessively long
2022 file names if corresponding
2023 unit names are long (for example, if child units or subunits are
2024 heavily nested). An option is available to shorten such long file names
2025 (called file name ``krunching''). This may be particularly useful when
2026 programs being developed with GNAT are to be used on operating systems
2027 with limited file name lengths. @xref{Using gnatkr}.
2029 Of course, no file shortening algorithm can guarantee uniqueness over
2030 all possible unit names; if file name krunching is used, it is your
2031 responsibility to ensure no name clashes occur. Alternatively you
2032 can specify the exact file names that you want used, as described
2033 in the next section. Finally, if your Ada programs are migrating from a
2034 compiler with a different naming convention, you can use the gnatchop
2035 utility to produce source files that follow the GNAT naming conventions.
2036 (For details @pxref{Renaming Files Using gnatchop}.)
2038 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2039 systems, case is not significant. So for example on @code{Windows XP}
2040 if the canonical name is @code{main-sub.adb}, you can use the file name
2041 @code{Main-Sub.adb} instead. However, case is significant for other
2042 operating systems, so for example, if you want to use other than
2043 canonically cased file names on a Unix system, you need to follow
2044 the procedures described in the next section.
2046 @node Using Other File Names
2047 @section Using Other File Names
2051 In the previous section, we have described the default rules used by
2052 GNAT to determine the file name in which a given unit resides. It is
2053 often convenient to follow these default rules, and if you follow them,
2054 the compiler knows without being explicitly told where to find all
2057 However, in some cases, particularly when a program is imported from
2058 another Ada compiler environment, it may be more convenient for the
2059 programmer to specify which file names contain which units. GNAT allows
2060 arbitrary file names to be used by means of the Source_File_Name pragma.
2061 The form of this pragma is as shown in the following examples:
2062 @cindex Source_File_Name pragma
2064 @smallexample @c ada
2066 pragma Source_File_Name (My_Utilities.Stacks,
2067 Spec_File_Name => "myutilst_a.ada");
2068 pragma Source_File_name (My_Utilities.Stacks,
2069 Body_File_Name => "myutilst.ada");
2074 As shown in this example, the first argument for the pragma is the unit
2075 name (in this example a child unit). The second argument has the form
2076 of a named association. The identifier
2077 indicates whether the file name is for a spec or a body;
2078 the file name itself is given by a string literal.
2080 The source file name pragma is a configuration pragma, which means that
2081 normally it will be placed in the @file{gnat.adc}
2082 file used to hold configuration
2083 pragmas that apply to a complete compilation environment.
2084 For more details on how the @file{gnat.adc} file is created and used
2085 see @ref{Handling of Configuration Pragmas}.
2086 @cindex @file{gnat.adc}
2089 GNAT allows completely arbitrary file names to be specified using the
2090 source file name pragma. However, if the file name specified has an
2091 extension other than @file{.ads} or @file{.adb} it is necessary to use
2092 a special syntax when compiling the file. The name in this case must be
2093 preceded by the special sequence @option{-x} followed by a space and the name
2094 of the language, here @code{ada}, as in:
2097 $ gcc -c -x ada peculiar_file_name.sim
2102 @command{gnatmake} handles non-standard file names in the usual manner (the
2103 non-standard file name for the main program is simply used as the
2104 argument to gnatmake). Note that if the extension is also non-standard,
2105 then it must be included in the @command{gnatmake} command, it may not
2108 @node Alternative File Naming Schemes
2109 @section Alternative File Naming Schemes
2110 @cindex File naming schemes, alternative
2113 In the previous section, we described the use of the @code{Source_File_Name}
2114 pragma to allow arbitrary names to be assigned to individual source files.
2115 However, this approach requires one pragma for each file, and especially in
2116 large systems can result in very long @file{gnat.adc} files, and also create
2117 a maintenance problem.
2119 GNAT also provides a facility for specifying systematic file naming schemes
2120 other than the standard default naming scheme previously described. An
2121 alternative scheme for naming is specified by the use of
2122 @code{Source_File_Name} pragmas having the following format:
2123 @cindex Source_File_Name pragma
2125 @smallexample @c ada
2126 pragma Source_File_Name (
2127 Spec_File_Name => FILE_NAME_PATTERN
2128 @r{[},Casing => CASING_SPEC@r{]}
2129 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2131 pragma Source_File_Name (
2132 Body_File_Name => FILE_NAME_PATTERN
2133 @r{[},Casing => CASING_SPEC@r{]}
2134 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2136 pragma Source_File_Name (
2137 Subunit_File_Name => FILE_NAME_PATTERN
2138 @r{[},Casing => CASING_SPEC@r{]}
2139 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2141 FILE_NAME_PATTERN ::= STRING_LITERAL
2142 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2146 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2147 It contains a single asterisk character, and the unit name is substituted
2148 systematically for this asterisk. The optional parameter
2149 @code{Casing} indicates
2150 whether the unit name is to be all upper-case letters, all lower-case letters,
2151 or mixed-case. If no
2152 @code{Casing} parameter is used, then the default is all
2153 ^lower-case^upper-case^.
2155 The optional @code{Dot_Replacement} string is used to replace any periods
2156 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2157 argument is used then separating dots appear unchanged in the resulting
2159 Although the above syntax indicates that the
2160 @code{Casing} argument must appear
2161 before the @code{Dot_Replacement} argument, but it
2162 is also permissible to write these arguments in the opposite order.
2164 As indicated, it is possible to specify different naming schemes for
2165 bodies, specs, and subunits. Quite often the rule for subunits is the
2166 same as the rule for bodies, in which case, there is no need to give
2167 a separate @code{Subunit_File_Name} rule, and in this case the
2168 @code{Body_File_name} rule is used for subunits as well.
2170 The separate rule for subunits can also be used to implement the rather
2171 unusual case of a compilation environment (e.g.@: a single directory) which
2172 contains a subunit and a child unit with the same unit name. Although
2173 both units cannot appear in the same partition, the Ada Reference Manual
2174 allows (but does not require) the possibility of the two units coexisting
2175 in the same environment.
2177 The file name translation works in the following steps:
2182 If there is a specific @code{Source_File_Name} pragma for the given unit,
2183 then this is always used, and any general pattern rules are ignored.
2186 If there is a pattern type @code{Source_File_Name} pragma that applies to
2187 the unit, then the resulting file name will be used if the file exists. If
2188 more than one pattern matches, the latest one will be tried first, and the
2189 first attempt resulting in a reference to a file that exists will be used.
2192 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2193 for which the corresponding file exists, then the standard GNAT default
2194 naming rules are used.
2199 As an example of the use of this mechanism, consider a commonly used scheme
2200 in which file names are all lower case, with separating periods copied
2201 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2202 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2205 @smallexample @c ada
2206 pragma Source_File_Name
2207 (Spec_File_Name => "*.1.ada");
2208 pragma Source_File_Name
2209 (Body_File_Name => "*.2.ada");
2213 The default GNAT scheme is actually implemented by providing the following
2214 default pragmas internally:
2216 @smallexample @c ada
2217 pragma Source_File_Name
2218 (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2219 pragma Source_File_Name
2220 (Body_File_Name => "*.adb", Dot_Replacement => "-");
2224 Our final example implements a scheme typically used with one of the
2225 Ada 83 compilers, where the separator character for subunits was ``__''
2226 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2227 by adding @file{.ADA}, and subunits by
2228 adding @file{.SEP}. All file names were
2229 upper case. Child units were not present of course since this was an
2230 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2231 the same double underscore separator for child units.
2233 @smallexample @c ada
2234 pragma Source_File_Name
2235 (Spec_File_Name => "*_.ADA",
2236 Dot_Replacement => "__",
2237 Casing = Uppercase);
2238 pragma Source_File_Name
2239 (Body_File_Name => "*.ADA",
2240 Dot_Replacement => "__",
2241 Casing = Uppercase);
2242 pragma Source_File_Name
2243 (Subunit_File_Name => "*.SEP",
2244 Dot_Replacement => "__",
2245 Casing = Uppercase);
2248 @node Generating Object Files
2249 @section Generating Object Files
2252 An Ada program consists of a set of source files, and the first step in
2253 compiling the program is to generate the corresponding object files.
2254 These are generated by compiling a subset of these source files.
2255 The files you need to compile are the following:
2259 If a package spec has no body, compile the package spec to produce the
2260 object file for the package.
2263 If a package has both a spec and a body, compile the body to produce the
2264 object file for the package. The source file for the package spec need
2265 not be compiled in this case because there is only one object file, which
2266 contains the code for both the spec and body of the package.
2269 For a subprogram, compile the subprogram body to produce the object file
2270 for the subprogram. The spec, if one is present, is as usual in a
2271 separate file, and need not be compiled.
2275 In the case of subunits, only compile the parent unit. A single object
2276 file is generated for the entire subunit tree, which includes all the
2280 Compile child units independently of their parent units
2281 (though, of course, the spec of all the ancestor unit must be present in order
2282 to compile a child unit).
2286 Compile generic units in the same manner as any other units. The object
2287 files in this case are small dummy files that contain at most the
2288 flag used for elaboration checking. This is because GNAT always handles generic
2289 instantiation by means of macro expansion. However, it is still necessary to
2290 compile generic units, for dependency checking and elaboration purposes.
2294 The preceding rules describe the set of files that must be compiled to
2295 generate the object files for a program. Each object file has the same
2296 name as the corresponding source file, except that the extension is
2299 You may wish to compile other files for the purpose of checking their
2300 syntactic and semantic correctness. For example, in the case where a
2301 package has a separate spec and body, you would not normally compile the
2302 spec. However, it is convenient in practice to compile the spec to make
2303 sure it is error-free before compiling clients of this spec, because such
2304 compilations will fail if there is an error in the spec.
2306 GNAT provides an option for compiling such files purely for the
2307 purposes of checking correctness; such compilations are not required as
2308 part of the process of building a program. To compile a file in this
2309 checking mode, use the @option{-gnatc} switch.
2311 @node Source Dependencies
2312 @section Source Dependencies
2315 A given object file clearly depends on the source file which is compiled
2316 to produce it. Here we are using @dfn{depends} in the sense of a typical
2317 @code{make} utility; in other words, an object file depends on a source
2318 file if changes to the source file require the object file to be
2320 In addition to this basic dependency, a given object may depend on
2321 additional source files as follows:
2325 If a file being compiled @code{with}'s a unit @var{X}, the object file
2326 depends on the file containing the spec of unit @var{X}. This includes
2327 files that are @code{with}'ed implicitly either because they are parents
2328 of @code{with}'ed child units or they are run-time units required by the
2329 language constructs used in a particular unit.
2332 If a file being compiled instantiates a library level generic unit, the
2333 object file depends on both the spec and body files for this generic
2337 If a file being compiled instantiates a generic unit defined within a
2338 package, the object file depends on the body file for the package as
2339 well as the spec file.
2343 @cindex @option{-gnatn} switch
2344 If a file being compiled contains a call to a subprogram for which
2345 pragma @code{Inline} applies and inlining is activated with the
2346 @option{-gnatn} switch, the object file depends on the file containing the
2347 body of this subprogram as well as on the file containing the spec. Note
2348 that for inlining to actually occur as a result of the use of this switch,
2349 it is necessary to compile in optimizing mode.
2351 @cindex @option{-gnatN} switch
2352 The use of @option{-gnatN} activates inlining optimization
2353 that is performed by the front end of the compiler. This inlining does
2354 not require that the code generation be optimized. Like @option{-gnatn},
2355 the use of this switch generates additional dependencies.
2357 When using a gcc-based back end (in practice this means using any version
2358 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2359 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2360 Historically front end inlining was more extensive than the gcc back end
2361 inlining, but that is no longer the case.
2364 If an object file @file{O} depends on the proper body of a subunit through
2365 inlining or instantiation, it depends on the parent unit of the subunit.
2366 This means that any modification of the parent unit or one of its subunits
2367 affects the compilation of @file{O}.
2370 The object file for a parent unit depends on all its subunit body files.
2373 The previous two rules meant that for purposes of computing dependencies and
2374 recompilation, a body and all its subunits are treated as an indivisible whole.
2377 These rules are applied transitively: if unit @code{A} @code{with}'s
2378 unit @code{B}, whose elaboration calls an inlined procedure in package
2379 @code{C}, the object file for unit @code{A} will depend on the body of
2380 @code{C}, in file @file{c.adb}.
2382 The set of dependent files described by these rules includes all the
2383 files on which the unit is semantically dependent, as dictated by the
2384 Ada language standard. However, it is a superset of what the
2385 standard describes, because it includes generic, inline, and subunit
2388 An object file must be recreated by recompiling the corresponding source
2389 file if any of the source files on which it depends are modified. For
2390 example, if the @code{make} utility is used to control compilation,
2391 the rule for an Ada object file must mention all the source files on
2392 which the object file depends, according to the above definition.
2393 The determination of the necessary
2394 recompilations is done automatically when one uses @command{gnatmake}.
2397 @node The Ada Library Information Files
2398 @section The Ada Library Information Files
2399 @cindex Ada Library Information files
2400 @cindex @file{ALI} files
2403 Each compilation actually generates two output files. The first of these
2404 is the normal object file that has a @file{.o} extension. The second is a
2405 text file containing full dependency information. It has the same
2406 name as the source file, but an @file{.ali} extension.
2407 This file is known as the Ada Library Information (@file{ALI}) file.
2408 The following information is contained in the @file{ALI} file.
2412 Version information (indicates which version of GNAT was used to compile
2413 the unit(s) in question)
2416 Main program information (including priority and time slice settings,
2417 as well as the wide character encoding used during compilation).
2420 List of arguments used in the @command{gcc} command for the compilation
2423 Attributes of the unit, including configuration pragmas used, an indication
2424 of whether the compilation was successful, exception model used etc.
2427 A list of relevant restrictions applying to the unit (used for consistency)
2431 Categorization information (e.g.@: use of pragma @code{Pure}).
2434 Information on all @code{with}'ed units, including presence of
2435 @code{Elaborate} or @code{Elaborate_All} pragmas.
2438 Information from any @code{Linker_Options} pragmas used in the unit
2441 Information on the use of @code{Body_Version} or @code{Version}
2442 attributes in the unit.
2445 Dependency information. This is a list of files, together with
2446 time stamp and checksum information. These are files on which
2447 the unit depends in the sense that recompilation is required
2448 if any of these units are modified.
2451 Cross-reference data. Contains information on all entities referenced
2452 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2453 provide cross-reference information.
2458 For a full detailed description of the format of the @file{ALI} file,
2459 see the source of the body of unit @code{Lib.Writ}, contained in file
2460 @file{lib-writ.adb} in the GNAT compiler sources.
2462 @node Binding an Ada Program
2463 @section Binding an Ada Program
2466 When using languages such as C and C++, once the source files have been
2467 compiled the only remaining step in building an executable program
2468 is linking the object modules together. This means that it is possible to
2469 link an inconsistent version of a program, in which two units have
2470 included different versions of the same header.
2472 The rules of Ada do not permit such an inconsistent program to be built.
2473 For example, if two clients have different versions of the same package,
2474 it is illegal to build a program containing these two clients.
2475 These rules are enforced by the GNAT binder, which also determines an
2476 elaboration order consistent with the Ada rules.
2478 The GNAT binder is run after all the object files for a program have
2479 been created. It is given the name of the main program unit, and from
2480 this it determines the set of units required by the program, by reading the
2481 corresponding ALI files. It generates error messages if the program is
2482 inconsistent or if no valid order of elaboration exists.
2484 If no errors are detected, the binder produces a main program, in Ada by
2485 default, that contains calls to the elaboration procedures of those
2486 compilation unit that require them, followed by
2487 a call to the main program. This Ada program is compiled to generate the
2488 object file for the main program. The name of
2489 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2490 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2493 Finally, the linker is used to build the resulting executable program,
2494 using the object from the main program from the bind step as well as the
2495 object files for the Ada units of the program.
2497 @node Mixed Language Programming
2498 @section Mixed Language Programming
2499 @cindex Mixed Language Programming
2502 This section describes how to develop a mixed-language program,
2503 specifically one that comprises units in both Ada and C.
2506 * Interfacing to C::
2507 * Calling Conventions::
2510 @node Interfacing to C
2511 @subsection Interfacing to C
2513 Interfacing Ada with a foreign language such as C involves using
2514 compiler directives to import and/or export entity definitions in each
2515 language---using @code{extern} statements in C, for instance, and the
2516 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2517 A full treatment of these topics is provided in Appendix B, section 1
2518 of the Ada Reference Manual.
2520 There are two ways to build a program using GNAT that contains some Ada
2521 sources and some foreign language sources, depending on whether or not
2522 the main subprogram is written in Ada. Here is a source example with
2523 the main subprogram in Ada:
2529 void print_num (int num)
2531 printf ("num is %d.\n", num);
2537 /* num_from_Ada is declared in my_main.adb */
2538 extern int num_from_Ada;
2542 return num_from_Ada;
2546 @smallexample @c ada
2548 procedure My_Main is
2550 -- Declare then export an Integer entity called num_from_Ada
2551 My_Num : Integer := 10;
2552 pragma Export (C, My_Num, "num_from_Ada");
2554 -- Declare an Ada function spec for Get_Num, then use
2555 -- C function get_num for the implementation.
2556 function Get_Num return Integer;
2557 pragma Import (C, Get_Num, "get_num");
2559 -- Declare an Ada procedure spec for Print_Num, then use
2560 -- C function print_num for the implementation.
2561 procedure Print_Num (Num : Integer);
2562 pragma Import (C, Print_Num, "print_num");
2565 Print_Num (Get_Num);
2571 To build this example, first compile the foreign language files to
2572 generate object files:
2574 ^gcc -c file1.c^gcc -c FILE1.C^
2575 ^gcc -c file2.c^gcc -c FILE2.C^
2579 Then, compile the Ada units to produce a set of object files and ALI
2582 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2586 Run the Ada binder on the Ada main program:
2588 gnatbind my_main.ali
2592 Link the Ada main program, the Ada objects and the other language
2595 gnatlink my_main.ali file1.o file2.o
2599 The last three steps can be grouped in a single command:
2601 gnatmake my_main.adb -largs file1.o file2.o
2604 @cindex Binder output file
2606 If the main program is in a language other than Ada, then you may have
2607 more than one entry point into the Ada subsystem. You must use a special
2608 binder option to generate callable routines that initialize and
2609 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2610 Calls to the initialization and finalization routines must be inserted
2611 in the main program, or some other appropriate point in the code. The
2612 call to initialize the Ada units must occur before the first Ada
2613 subprogram is called, and the call to finalize the Ada units must occur
2614 after the last Ada subprogram returns. The binder will place the
2615 initialization and finalization subprograms into the
2616 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2617 sources. To illustrate, we have the following example:
2621 extern void adainit (void);
2622 extern void adafinal (void);
2623 extern int add (int, int);
2624 extern int sub (int, int);
2626 int main (int argc, char *argv[])
2632 /* Should print "21 + 7 = 28" */
2633 printf ("%d + %d = %d\n", a, b, add (a, b));
2634 /* Should print "21 - 7 = 14" */
2635 printf ("%d - %d = %d\n", a, b, sub (a, b));
2641 @smallexample @c ada
2644 function Add (A, B : Integer) return Integer;
2645 pragma Export (C, Add, "add");
2649 package body Unit1 is
2650 function Add (A, B : Integer) return Integer is
2658 function Sub (A, B : Integer) return Integer;
2659 pragma Export (C, Sub, "sub");
2663 package body Unit2 is
2664 function Sub (A, B : Integer) return Integer is
2673 The build procedure for this application is similar to the last
2674 example's. First, compile the foreign language files to generate object
2677 ^gcc -c main.c^gcc -c main.c^
2681 Next, compile the Ada units to produce a set of object files and ALI
2684 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2685 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2689 Run the Ada binder on every generated ALI file. Make sure to use the
2690 @option{-n} option to specify a foreign main program:
2692 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2696 Link the Ada main program, the Ada objects and the foreign language
2697 objects. You need only list the last ALI file here:
2699 gnatlink unit2.ali main.o -o exec_file
2702 This procedure yields a binary executable called @file{exec_file}.
2706 Depending on the circumstances (for example when your non-Ada main object
2707 does not provide symbol @code{main}), you may also need to instruct the
2708 GNAT linker not to include the standard startup objects by passing the
2709 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2711 @node Calling Conventions
2712 @subsection Calling Conventions
2713 @cindex Foreign Languages
2714 @cindex Calling Conventions
2715 GNAT follows standard calling sequence conventions and will thus interface
2716 to any other language that also follows these conventions. The following
2717 Convention identifiers are recognized by GNAT:
2720 @cindex Interfacing to Ada
2721 @cindex Other Ada compilers
2722 @cindex Convention Ada
2724 This indicates that the standard Ada calling sequence will be
2725 used and all Ada data items may be passed without any limitations in the
2726 case where GNAT is used to generate both the caller and callee. It is also
2727 possible to mix GNAT generated code and code generated by another Ada
2728 compiler. In this case, the data types should be restricted to simple
2729 cases, including primitive types. Whether complex data types can be passed
2730 depends on the situation. Probably it is safe to pass simple arrays, such
2731 as arrays of integers or floats. Records may or may not work, depending
2732 on whether both compilers lay them out identically. Complex structures
2733 involving variant records, access parameters, tasks, or protected types,
2734 are unlikely to be able to be passed.
2736 Note that in the case of GNAT running
2737 on a platform that supports HP Ada 83, a higher degree of compatibility
2738 can be guaranteed, and in particular records are layed out in an identical
2739 manner in the two compilers. Note also that if output from two different
2740 compilers is mixed, the program is responsible for dealing with elaboration
2741 issues. Probably the safest approach is to write the main program in the
2742 version of Ada other than GNAT, so that it takes care of its own elaboration
2743 requirements, and then call the GNAT-generated adainit procedure to ensure
2744 elaboration of the GNAT components. Consult the documentation of the other
2745 Ada compiler for further details on elaboration.
2747 However, it is not possible to mix the tasking run time of GNAT and
2748 HP Ada 83, All the tasking operations must either be entirely within
2749 GNAT compiled sections of the program, or entirely within HP Ada 83
2750 compiled sections of the program.
2752 @cindex Interfacing to Assembly
2753 @cindex Convention Assembler
2755 Specifies assembler as the convention. In practice this has the
2756 same effect as convention Ada (but is not equivalent in the sense of being
2757 considered the same convention).
2759 @cindex Convention Asm
2762 Equivalent to Assembler.
2764 @cindex Interfacing to COBOL
2765 @cindex Convention COBOL
2768 Data will be passed according to the conventions described
2769 in section B.4 of the Ada Reference Manual.
2772 @cindex Interfacing to C
2773 @cindex Convention C
2775 Data will be passed according to the conventions described
2776 in section B.3 of the Ada Reference Manual.
2778 A note on interfacing to a C ``varargs'' function:
2779 @findex C varargs function
2780 @cindex Interfacing to C varargs function
2781 @cindex varargs function interfaces
2785 In C, @code{varargs} allows a function to take a variable number of
2786 arguments. There is no direct equivalent in this to Ada. One
2787 approach that can be used is to create a C wrapper for each
2788 different profile and then interface to this C wrapper. For
2789 example, to print an @code{int} value using @code{printf},
2790 create a C function @code{printfi} that takes two arguments, a
2791 pointer to a string and an int, and calls @code{printf}.
2792 Then in the Ada program, use pragma @code{Import} to
2793 interface to @code{printfi}.
2796 It may work on some platforms to directly interface to
2797 a @code{varargs} function by providing a specific Ada profile
2798 for a particular call. However, this does not work on
2799 all platforms, since there is no guarantee that the
2800 calling sequence for a two argument normal C function
2801 is the same as for calling a @code{varargs} C function with
2802 the same two arguments.
2805 @cindex Convention Default
2810 @cindex Convention External
2817 @cindex Interfacing to C++
2818 @cindex Convention C++
2819 @item C_Plus_Plus (or CPP)
2820 This stands for C++. For most purposes this is identical to C.
2821 See the separate description of the specialized GNAT pragmas relating to
2822 C++ interfacing for further details.
2826 @cindex Interfacing to Fortran
2827 @cindex Convention Fortran
2829 Data will be passed according to the conventions described
2830 in section B.5 of the Ada Reference Manual.
2833 This applies to an intrinsic operation, as defined in the Ada
2834 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2835 this means that the body of the subprogram is provided by the compiler itself,
2836 usually by means of an efficient code sequence, and that the user does not
2837 supply an explicit body for it. In an application program, the pragma may
2838 be applied to the following sets of names:
2842 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2843 Shift_Right_Arithmetic. The corresponding subprogram declaration must have
2844 two formal parameters. The
2845 first one must be a signed integer type or a modular type with a binary
2846 modulus, and the second parameter must be of type Natural.
2847 The return type must be the same as the type of the first argument. The size
2848 of this type can only be 8, 16, 32, or 64.
2851 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2852 The corresponding operator declaration must have parameters and result type
2853 that have the same root numeric type (for example, all three are long_float
2854 types). This simplifies the definition of operations that use type checking
2855 to perform dimensional checks:
2857 @smallexample @c ada
2858 type Distance is new Long_Float;
2859 type Time is new Long_Float;
2860 type Velocity is new Long_Float;
2861 function "/" (D : Distance; T : Time)
2863 pragma Import (Intrinsic, "/");
2867 This common idiom is often programmed with a generic definition and an
2868 explicit body. The pragma makes it simpler to introduce such declarations.
2869 It incurs no overhead in compilation time or code size, because it is
2870 implemented as a single machine instruction.
2873 General subprogram entities, to bind an Ada subprogram declaration to
2874 a compiler builtin by name with back-ends where such interfaces are
2875 available. A typical example is the set of ``__builtin'' functions
2876 exposed by the GCC back-end, as in the following example:
2878 @smallexample @c ada
2879 function builtin_sqrt (F : Float) return Float;
2880 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2883 Most of the GCC builtins are accessible this way, and as for other
2884 import conventions (e.g. C), it is the user's responsibility to ensure
2885 that the Ada subprogram profile matches the underlying builtin
2893 @cindex Convention Stdcall
2895 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2896 and specifies that the @code{Stdcall} calling sequence will be used,
2897 as defined by the NT API. Nevertheless, to ease building
2898 cross-platform bindings this convention will be handled as a @code{C} calling
2899 convention on non-Windows platforms.
2902 @cindex Convention DLL
2904 This is equivalent to @code{Stdcall}.
2907 @cindex Convention Win32
2909 This is equivalent to @code{Stdcall}.
2913 @cindex Convention Stubbed
2915 This is a special convention that indicates that the compiler
2916 should provide a stub body that raises @code{Program_Error}.
2920 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2921 that can be used to parametrize conventions and allow additional synonyms
2922 to be specified. For example if you have legacy code in which the convention
2923 identifier Fortran77 was used for Fortran, you can use the configuration
2926 @smallexample @c ada
2927 pragma Convention_Identifier (Fortran77, Fortran);
2931 And from now on the identifier Fortran77 may be used as a convention
2932 identifier (for example in an @code{Import} pragma) with the same
2936 @node Building Mixed Ada & C++ Programs
2937 @section Building Mixed Ada and C++ Programs
2940 A programmer inexperienced with mixed-language development may find that
2941 building an application containing both Ada and C++ code can be a
2942 challenge. This section gives a few
2943 hints that should make this task easier. The first section addresses
2944 the differences between interfacing with C and interfacing with C++.
2946 looks into the delicate problem of linking the complete application from
2947 its Ada and C++ parts. The last section gives some hints on how the GNAT
2948 run-time library can be adapted in order to allow inter-language dispatching
2949 with a new C++ compiler.
2952 * Interfacing to C++::
2953 * Linking a Mixed C++ & Ada Program::
2954 * A Simple Example::
2955 * Interfacing with C++ constructors::
2956 * Interfacing with C++ at the Class Level::
2959 @node Interfacing to C++
2960 @subsection Interfacing to C++
2963 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2964 generating code that is compatible with the G++ Application Binary
2965 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2968 Interfacing can be done at 3 levels: simple data, subprograms, and
2969 classes. In the first two cases, GNAT offers a specific @code{Convention
2970 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2971 Usually, C++ mangles the names of subprograms. To generate proper mangled
2972 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2973 This problem can also be addressed manually in two ways:
2977 by modifying the C++ code in order to force a C convention using
2978 the @code{extern "C"} syntax.
2981 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
2982 Link_Name argument of the pragma import.
2986 Interfacing at the class level can be achieved by using the GNAT specific
2987 pragmas such as @code{CPP_Constructor}. @xref{Interfacing to C++,,,
2988 gnat_rm, GNAT Reference Manual}, for additional information.
2990 @node Linking a Mixed C++ & Ada Program
2991 @subsection Linking a Mixed C++ & Ada Program
2994 Usually the linker of the C++ development system must be used to link
2995 mixed applications because most C++ systems will resolve elaboration
2996 issues (such as calling constructors on global class instances)
2997 transparently during the link phase. GNAT has been adapted to ease the
2998 use of a foreign linker for the last phase. Three cases can be
3003 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3004 The C++ linker can simply be called by using the C++ specific driver
3007 Note that if the C++ code uses inline functions, you will need to
3008 compile your C++ code with the @code{-fkeep-inline-functions} switch in
3009 order to provide an existing function implementation that the Ada code can
3013 $ g++ -c -fkeep-inline-functions file1.C
3014 $ g++ -c -fkeep-inline-functions file2.C
3015 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3019 Using GNAT and G++ from two different GCC installations: If both
3020 compilers are on the @env{PATH}, the previous method may be used. It is
3021 important to note that environment variables such as
3022 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3023 @env{GCC_ROOT} will affect both compilers
3024 at the same time and may make one of the two compilers operate
3025 improperly if set during invocation of the wrong compiler. It is also
3026 very important that the linker uses the proper @file{libgcc.a} GCC
3027 library -- that is, the one from the C++ compiler installation. The
3028 implicit link command as suggested in the @command{gnatmake} command
3029 from the former example can be replaced by an explicit link command with
3030 the full-verbosity option in order to verify which library is used:
3033 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3035 If there is a problem due to interfering environment variables, it can
3036 be worked around by using an intermediate script. The following example
3037 shows the proper script to use when GNAT has not been installed at its
3038 default location and g++ has been installed at its default location:
3046 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3050 Using a non-GNU C++ compiler: The commands previously described can be
3051 used to insure that the C++ linker is used. Nonetheless, you need to add
3052 a few more parameters to the link command line, depending on the exception
3055 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3056 to the libgcc libraries are required:
3061 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3062 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3065 Where CC is the name of the non-GNU C++ compiler.
3067 If the @code{zero cost} exception mechanism is used, and the platform
3068 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3069 paths to more objects are required:
3074 CC `gcc -print-file-name=crtbegin.o` $* \
3075 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3076 `gcc -print-file-name=crtend.o`
3077 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3080 If the @code{zero cost} exception mechanism is used, and the platform
3081 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3082 Tru64 or AIX), the simple approach described above will not work and
3083 a pre-linking phase using GNAT will be necessary.
3087 Another alternative is to use the @command{gprbuild} multi-language builder
3088 which has a large knowledge base and knows how to link Ada and C++ code
3089 together automatically in most cases.
3091 @node A Simple Example
3092 @subsection A Simple Example
3094 The following example, provided as part of the GNAT examples, shows how
3095 to achieve procedural interfacing between Ada and C++ in both
3096 directions. The C++ class A has two methods. The first method is exported
3097 to Ada by the means of an extern C wrapper function. The second method
3098 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3099 a limited record with a layout comparable to the C++ class. The Ada
3100 subprogram, in turn, calls the C++ method. So, starting from the C++
3101 main program, the process passes back and forth between the two
3105 Here are the compilation commands:
3107 $ gnatmake -c simple_cpp_interface
3110 $ gnatbind -n simple_cpp_interface
3111 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3112 -lstdc++ ex7.o cpp_main.o
3116 Here are the corresponding sources:
3124 void adainit (void);
3125 void adafinal (void);
3126 void method1 (A *t);
3148 class A : public Origin @{
3150 void method1 (void);
3151 void method2 (int v);
3161 extern "C" @{ void ada_method2 (A *t, int v);@}
3163 void A::method1 (void)
3166 printf ("in A::method1, a_value = %d \n",a_value);
3170 void A::method2 (int v)
3172 ada_method2 (this, v);
3173 printf ("in A::method2, a_value = %d \n",a_value);
3180 printf ("in A::A, a_value = %d \n",a_value);
3184 @smallexample @c ada
3186 package body Simple_Cpp_Interface is
3188 procedure Ada_Method2 (This : in out A; V : Integer) is
3194 end Simple_Cpp_Interface;
3197 package Simple_Cpp_Interface is
3200 Vptr : System.Address;
3204 pragma Convention (C, A);
3206 procedure Method1 (This : in out A);
3207 pragma Import (C, Method1);
3209 procedure Ada_Method2 (This : in out A; V : Integer);
3210 pragma Export (C, Ada_Method2);
3212 end Simple_Cpp_Interface;
3215 @node Interfacing with C++ constructors
3216 @subsection Interfacing with C++ constructors
3219 In order to interface with C++ constructors GNAT provides the
3220 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3221 gnat_rm, GNAT Reference Manual}, for additional information).
3222 In this section we present some common uses of C++ constructors
3223 in mixed-languages programs in GNAT.
3225 Let us assume that we need to interface with the following
3233 @b{virtual} int Get_Value ();
3234 Root(); // Default constructor
3235 Root(int v); // 1st non-default constructor
3236 Root(int v, int w); // 2nd non-default constructor
3240 For this purpose we can write the following package spec (further
3241 information on how to build this spec is available in
3242 @ref{Interfacing with C++ at the Class Level} and
3243 @ref{Generating Ada Bindings for C and C++ headers}).
3245 @smallexample @c ada
3246 with Interfaces.C; use Interfaces.C;
3248 type Root is tagged limited record
3252 pragma Import (CPP, Root);
3254 function Get_Value (Obj : Root) return int;
3255 pragma Import (CPP, Get_Value);
3257 function Constructor return Root;
3258 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3260 function Constructor (v : Integer) return Root;
3261 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3263 function Constructor (v, w : Integer) return Root;
3264 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3268 On the Ada side the constructor is represented by a function (whose
3269 name is arbitrary) that returns the classwide type corresponding to
3270 the imported C++ class. Although the constructor is described as a
3271 function, it is typically a procedure with an extra implicit argument
3272 (the object being initialized) at the implementation level. GNAT
3273 issues the appropriate call, whatever it is, to get the object
3274 properly initialized.
3276 Constructors can only appear in the following contexts:
3280 On the right side of an initialization of an object of type @var{T}.
3282 On the right side of an initialization of a record component of type @var{T}.
3284 In an Ada 2005 limited aggregate.
3286 In an Ada 2005 nested limited aggregate.
3288 In an Ada 2005 limited aggregate that initializes an object built in
3289 place by an extended return statement.
3293 In a declaration of an object whose type is a class imported from C++,
3294 either the default C++ constructor is implicitly called by GNAT, or
3295 else the required C++ constructor must be explicitly called in the
3296 expression that initializes the object. For example:
3298 @smallexample @c ada
3300 Obj2 : Root := Constructor;
3301 Obj3 : Root := Constructor (v => 10);
3302 Obj4 : Root := Constructor (30, 40);
3305 The first two declarations are equivalent: in both cases the default C++
3306 constructor is invoked (in the former case the call to the constructor is
3307 implicit, and in the latter case the call is explicit in the object
3308 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3309 that takes an integer argument, and @code{Obj4} is initialized by the
3310 non-default C++ constructor that takes two integers.
3312 Let us derive the imported C++ class in the Ada side. For example:
3314 @smallexample @c ada
3315 type DT is new Root with record
3316 C_Value : Natural := 2009;
3320 In this case the components DT inherited from the C++ side must be
3321 initialized by a C++ constructor, and the additional Ada components
3322 of type DT are initialized by GNAT. The initialization of such an
3323 object is done either by default, or by means of a function returning
3324 an aggregate of type DT, or by means of an extension aggregate.
3326 @smallexample @c ada
3328 Obj6 : DT := Function_Returning_DT (50);
3329 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
3332 The declaration of @code{Obj5} invokes the default constructors: the
3333 C++ default constructor of the parent type takes care of the initialization
3334 of the components inherited from Root, and GNAT takes care of the default
3335 initialization of the additional Ada components of type DT (that is,
3336 @code{C_Value} is initialized to value 2009). The order of invocation of
3337 the constructors is consistent with the order of elaboration required by
3338 Ada and C++. That is, the constructor of the parent type is always called
3339 before the constructor of the derived type.
3341 Let us now consider a record that has components whose type is imported
3342 from C++. For example:
3344 @smallexample @c ada
3345 type Rec1 is limited record
3346 Data1 : Root := Constructor (10);
3347 Value : Natural := 1000;
3350 type Rec2 (D : Integer := 20) is limited record
3352 Data2 : Root := Constructor (D, 30);
3356 The initialization of an object of type @code{Rec2} will call the
3357 non-default C++ constructors specified for the imported components.
3360 @smallexample @c ada
3364 Using Ada 2005 we can use limited aggregates to initialize an object
3365 invoking C++ constructors that differ from those specified in the type
3366 declarations. For example:
3368 @smallexample @c ada
3369 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3374 The above declaration uses an Ada 2005 limited aggregate to
3375 initialize @code{Obj9}, and the C++ constructor that has two integer
3376 arguments is invoked to initialize the @code{Data1} component instead
3377 of the constructor specified in the declaration of type @code{Rec1}. In
3378 Ada 2005 the box in the aggregate indicates that unspecified components
3379 are initialized using the expression (if any) available in the component
3380 declaration. That is, in this case discriminant @code{D} is initialized
3381 to value @code{20}, @code{Value} is initialized to value 1000, and the
3382 non-default C++ constructor that handles two integers takes care of
3383 initializing component @code{Data2} with values @code{20,30}.
3385 In Ada 2005 we can use the extended return statement to build the Ada
3386 equivalent to C++ non-default constructors. For example:
3388 @smallexample @c ada
3389 function Constructor (V : Integer) return Rec2 is
3391 return Obj : Rec2 := (Rec => (Data1 => Constructor (V, 20),
3394 -- Further actions required for construction of
3395 -- objects of type Rec2
3401 In this example the extended return statement construct is used to
3402 build in place the returned object whose components are initialized
3403 by means of a limited aggregate. Any further action associated with
3404 the constructor can be placed inside the construct.
3406 @node Interfacing with C++ at the Class Level
3407 @subsection Interfacing with C++ at the Class Level
3409 In this section we demonstrate the GNAT features for interfacing with
3410 C++ by means of an example making use of Ada 2005 abstract interface
3411 types. This example consists of a classification of animals; classes
3412 have been used to model our main classification of animals, and
3413 interfaces provide support for the management of secondary
3414 classifications. We first demonstrate a case in which the types and
3415 constructors are defined on the C++ side and imported from the Ada
3416 side, and latter the reverse case.
3418 The root of our derivation will be the @code{Animal} class, with a
3419 single private attribute (the @code{Age} of the animal) and two public
3420 primitives to set and get the value of this attribute.
3425 @b{virtual} void Set_Age (int New_Age);
3426 @b{virtual} int Age ();
3432 Abstract interface types are defined in C++ by means of classes with pure
3433 virtual functions and no data members. In our example we will use two
3434 interfaces that provide support for the common management of @code{Carnivore}
3435 and @code{Domestic} animals:
3438 @b{class} Carnivore @{
3440 @b{virtual} int Number_Of_Teeth () = 0;
3443 @b{class} Domestic @{
3445 @b{virtual void} Set_Owner (char* Name) = 0;
3449 Using these declarations, we can now say that a @code{Dog} is an animal that is
3450 both Carnivore and Domestic, that is:
3453 @b{class} Dog : Animal, Carnivore, Domestic @{
3455 @b{virtual} int Number_Of_Teeth ();
3456 @b{virtual} void Set_Owner (char* Name);
3458 Dog(); // Constructor
3465 In the following examples we will assume that the previous declarations are
3466 located in a file named @code{animals.h}. The following package demonstrates
3467 how to import these C++ declarations from the Ada side:
3469 @smallexample @c ada
3470 with Interfaces.C.Strings; use Interfaces.C.Strings;
3472 type Carnivore is interface;
3473 pragma Convention (C_Plus_Plus, Carnivore);
3474 function Number_Of_Teeth (X : Carnivore)
3475 return Natural is abstract;
3477 type Domestic is interface;
3478 pragma Convention (C_Plus_Plus, Set_Owner);
3480 (X : in out Domestic;
3481 Name : Chars_Ptr) is abstract;
3483 type Animal is tagged record
3486 pragma Import (C_Plus_Plus, Animal);
3488 procedure Set_Age (X : in out Animal; Age : Integer);
3489 pragma Import (C_Plus_Plus, Set_Age);
3491 function Age (X : Animal) return Integer;
3492 pragma Import (C_Plus_Plus, Age);
3494 type Dog is new Animal and Carnivore and Domestic with record
3495 Tooth_Count : Natural;
3496 Owner : String (1 .. 30);
3498 pragma Import (C_Plus_Plus, Dog);
3500 function Number_Of_Teeth (A : Dog) return Integer;
3501 pragma Import (C_Plus_Plus, Number_Of_Teeth);
3503 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3504 pragma Import (C_Plus_Plus, Set_Owner);
3506 function New_Dog return Dog;
3507 pragma CPP_Constructor (New_Dog);
3508 pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3512 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3513 interfacing with these C++ classes is easy. The only requirement is that all
3514 the primitives and components must be declared exactly in the same order in
3517 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3518 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3519 the arguments to the called primitives will be the same as for C++. For the
3520 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3521 to indicate that they have been defined on the C++ side; this is required
3522 because the dispatch table associated with these tagged types will be built
3523 in the C++ side and therefore will not contain the predefined Ada primitives
3524 which Ada would otherwise expect.
3526 As the reader can see there is no need to indicate the C++ mangled names
3527 associated with each subprogram because it is assumed that all the calls to
3528 these primitives will be dispatching calls. The only exception is the
3529 constructor, which must be registered with the compiler by means of
3530 @code{pragma CPP_Constructor} and needs to provide its associated C++
3531 mangled name because the Ada compiler generates direct calls to it.
3533 With the above packages we can now declare objects of type Dog on the Ada side
3534 and dispatch calls to the corresponding subprograms on the C++ side. We can
3535 also extend the tagged type Dog with further fields and primitives, and
3536 override some of its C++ primitives on the Ada side. For example, here we have
3537 a type derivation defined on the Ada side that inherits all the dispatching
3538 primitives of the ancestor from the C++ side.
3541 @b{with} Animals; @b{use} Animals;
3542 @b{package} Vaccinated_Animals @b{is}
3543 @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3544 @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3545 @b{end} Vaccinated_Animals;
3548 It is important to note that, because of the ABI compatibility, the programmer
3549 does not need to add any further information to indicate either the object
3550 layout or the dispatch table entry associated with each dispatching operation.
3552 Now let us define all the types and constructors on the Ada side and export
3553 them to C++, using the same hierarchy of our previous example:
3555 @smallexample @c ada
3556 with Interfaces.C.Strings;
3557 use Interfaces.C.Strings;
3559 type Carnivore is interface;
3560 pragma Convention (C_Plus_Plus, Carnivore);
3561 function Number_Of_Teeth (X : Carnivore)
3562 return Natural is abstract;
3564 type Domestic is interface;
3565 pragma Convention (C_Plus_Plus, Set_Owner);
3567 (X : in out Domestic;
3568 Name : Chars_Ptr) is abstract;
3570 type Animal is tagged record
3573 pragma Convention (C_Plus_Plus, Animal);
3575 procedure Set_Age (X : in out Animal; Age : Integer);
3576 pragma Export (C_Plus_Plus, Set_Age);
3578 function Age (X : Animal) return Integer;
3579 pragma Export (C_Plus_Plus, Age);
3581 type Dog is new Animal and Carnivore and Domestic with record
3582 Tooth_Count : Natural;
3583 Owner : String (1 .. 30);
3585 pragma Convention (C_Plus_Plus, Dog);
3587 function Number_Of_Teeth (A : Dog) return Integer;
3588 pragma Export (C_Plus_Plus, Number_Of_Teeth);
3590 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3591 pragma Export (C_Plus_Plus, Set_Owner);
3593 function New_Dog return Dog'Class;
3594 pragma Export (C_Plus_Plus, New_Dog);
3598 Compared with our previous example the only difference is the use of
3599 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3600 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3601 nothing else to be done; as explained above, the only requirement is that all
3602 the primitives and components are declared in exactly the same order.
3604 For completeness, let us see a brief C++ main program that uses the
3605 declarations available in @code{animals.h} (presented in our first example) to
3606 import and use the declarations from the Ada side, properly initializing and
3607 finalizing the Ada run-time system along the way:
3610 @b{#include} "animals.h"
3611 @b{#include} <iostream>
3612 @b{using namespace} std;
3614 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3615 void Check_Domestic (Domestic *obj) @{@dots{}@}
3616 void Check_Animal (Animal *obj) @{@dots{}@}
3617 void Check_Dog (Dog *obj) @{@dots{}@}
3620 void adainit (void);
3621 void adafinal (void);
3627 Dog *obj = new_dog(); // Ada constructor
3628 Check_Carnivore (obj); // Check secondary DT
3629 Check_Domestic (obj); // Check secondary DT
3630 Check_Animal (obj); // Check primary DT
3631 Check_Dog (obj); // Check primary DT
3636 adainit (); test(); adafinal ();
3641 @node Comparison between GNAT and C/C++ Compilation Models
3642 @section Comparison between GNAT and C/C++ Compilation Models
3645 The GNAT model of compilation is close to the C and C++ models. You can
3646 think of Ada specs as corresponding to header files in C. As in C, you
3647 don't need to compile specs; they are compiled when they are used. The
3648 Ada @code{with} is similar in effect to the @code{#include} of a C
3651 One notable difference is that, in Ada, you may compile specs separately
3652 to check them for semantic and syntactic accuracy. This is not always
3653 possible with C headers because they are fragments of programs that have
3654 less specific syntactic or semantic rules.
3656 The other major difference is the requirement for running the binder,
3657 which performs two important functions. First, it checks for
3658 consistency. In C or C++, the only defense against assembling
3659 inconsistent programs lies outside the compiler, in a makefile, for
3660 example. The binder satisfies the Ada requirement that it be impossible
3661 to construct an inconsistent program when the compiler is used in normal
3664 @cindex Elaboration order control
3665 The other important function of the binder is to deal with elaboration
3666 issues. There are also elaboration issues in C++ that are handled
3667 automatically. This automatic handling has the advantage of being
3668 simpler to use, but the C++ programmer has no control over elaboration.
3669 Where @code{gnatbind} might complain there was no valid order of
3670 elaboration, a C++ compiler would simply construct a program that
3671 malfunctioned at run time.
3674 @node Comparison between GNAT and Conventional Ada Library Models
3675 @section Comparison between GNAT and Conventional Ada Library Models
3678 This section is intended for Ada programmers who have
3679 used an Ada compiler implementing the traditional Ada library
3680 model, as described in the Ada Reference Manual.
3682 @cindex GNAT library
3683 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3684 source files themselves acts as the library. Compiling Ada programs does
3685 not generate any centralized information, but rather an object file and
3686 a ALI file, which are of interest only to the binder and linker.
3687 In a traditional system, the compiler reads information not only from
3688 the source file being compiled, but also from the centralized library.
3689 This means that the effect of a compilation depends on what has been
3690 previously compiled. In particular:
3694 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3695 to the version of the unit most recently compiled into the library.
3698 Inlining is effective only if the necessary body has already been
3699 compiled into the library.
3702 Compiling a unit may obsolete other units in the library.
3706 In GNAT, compiling one unit never affects the compilation of any other
3707 units because the compiler reads only source files. Only changes to source
3708 files can affect the results of a compilation. In particular:
3712 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3713 to the source version of the unit that is currently accessible to the
3718 Inlining requires the appropriate source files for the package or
3719 subprogram bodies to be available to the compiler. Inlining is always
3720 effective, independent of the order in which units are complied.
3723 Compiling a unit never affects any other compilations. The editing of
3724 sources may cause previous compilations to be out of date if they
3725 depended on the source file being modified.
3729 The most important result of these differences is that order of compilation
3730 is never significant in GNAT. There is no situation in which one is
3731 required to do one compilation before another. What shows up as order of
3732 compilation requirements in the traditional Ada library becomes, in
3733 GNAT, simple source dependencies; in other words, there is only a set
3734 of rules saying what source files must be present when a file is
3738 @node Placement of temporary files
3739 @section Placement of temporary files
3740 @cindex Temporary files (user control over placement)
3743 GNAT creates temporary files in the directory designated by the environment
3744 variable @env{TMPDIR}.
3745 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3746 for detailed information on how environment variables are resolved.
3747 For most users the easiest way to make use of this feature is to simply
3748 define @env{TMPDIR} as a job level logical name).
3749 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3750 for compiler temporary files, then you can include something like the
3751 following command in your @file{LOGIN.COM} file:
3754 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3758 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3759 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3760 designated by @env{TEMP}.
3761 If none of these environment variables are defined then GNAT uses the
3762 directory designated by the logical name @code{SYS$SCRATCH:}
3763 (by default the user's home directory). If all else fails
3764 GNAT uses the current directory for temporary files.
3767 @c *************************
3768 @node Compiling Using gcc
3769 @chapter Compiling Using @command{gcc}
3772 This chapter discusses how to compile Ada programs using the @command{gcc}
3773 command. It also describes the set of switches
3774 that can be used to control the behavior of the compiler.
3776 * Compiling Programs::
3777 * Switches for gcc::
3778 * Search Paths and the Run-Time Library (RTL)::
3779 * Order of Compilation Issues::
3783 @node Compiling Programs
3784 @section Compiling Programs
3787 The first step in creating an executable program is to compile the units
3788 of the program using the @command{gcc} command. You must compile the
3793 the body file (@file{.adb}) for a library level subprogram or generic
3797 the spec file (@file{.ads}) for a library level package or generic
3798 package that has no body
3801 the body file (@file{.adb}) for a library level package
3802 or generic package that has a body
3807 You need @emph{not} compile the following files
3812 the spec of a library unit which has a body
3819 because they are compiled as part of compiling related units. GNAT
3821 when the corresponding body is compiled, and subunits when the parent is
3824 @cindex cannot generate code
3825 If you attempt to compile any of these files, you will get one of the
3826 following error messages (where @var{fff} is the name of the file you
3830 cannot generate code for file @var{fff} (package spec)
3831 to check package spec, use -gnatc
3833 cannot generate code for file @var{fff} (missing subunits)
3834 to check parent unit, use -gnatc
3836 cannot generate code for file @var{fff} (subprogram spec)
3837 to check subprogram spec, use -gnatc
3839 cannot generate code for file @var{fff} (subunit)
3840 to check subunit, use -gnatc
3844 As indicated by the above error messages, if you want to submit
3845 one of these files to the compiler to check for correct semantics
3846 without generating code, then use the @option{-gnatc} switch.
3848 The basic command for compiling a file containing an Ada unit is
3851 @c $ gcc -c @ovar{switches} @file{file name}
3852 @c Expanding @ovar macro inline (explanation in macro def comments)
3853 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3857 where @var{file name} is the name of the Ada file (usually
3859 @file{.ads} for a spec or @file{.adb} for a body).
3862 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3864 The result of a successful compilation is an object file, which has the
3865 same name as the source file but an extension of @file{.o} and an Ada
3866 Library Information (ALI) file, which also has the same name as the
3867 source file, but with @file{.ali} as the extension. GNAT creates these
3868 two output files in the current directory, but you may specify a source
3869 file in any directory using an absolute or relative path specification
3870 containing the directory information.
3873 @command{gcc} is actually a driver program that looks at the extensions of
3874 the file arguments and loads the appropriate compiler. For example, the
3875 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3876 These programs are in directories known to the driver program (in some
3877 configurations via environment variables you set), but need not be in
3878 your path. The @command{gcc} driver also calls the assembler and any other
3879 utilities needed to complete the generation of the required object
3882 It is possible to supply several file names on the same @command{gcc}
3883 command. This causes @command{gcc} to call the appropriate compiler for
3884 each file. For example, the following command lists three separate
3885 files to be compiled:
3888 $ gcc -c x.adb y.adb z.c
3892 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3893 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3894 The compiler generates three object files @file{x.o}, @file{y.o} and
3895 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3896 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3899 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3902 @node Switches for gcc
3903 @section Switches for @command{gcc}
3906 The @command{gcc} command accepts switches that control the
3907 compilation process. These switches are fully described in this section.
3908 First we briefly list all the switches, in alphabetical order, then we
3909 describe the switches in more detail in functionally grouped sections.
3911 More switches exist for GCC than those documented here, especially
3912 for specific targets. However, their use is not recommended as
3913 they may change code generation in ways that are incompatible with
3914 the Ada run-time library, or can cause inconsistencies between
3918 * Output and Error Message Control::
3919 * Warning Message Control::
3920 * Debugging and Assertion Control::
3921 * Validity Checking::
3924 * Using gcc for Syntax Checking::
3925 * Using gcc for Semantic Checking::
3926 * Compiling Different Versions of Ada::
3927 * Character Set Control::
3928 * File Naming Control::
3929 * Subprogram Inlining Control::
3930 * Auxiliary Output Control::
3931 * Debugging Control::
3932 * Exception Handling Control::
3933 * Units to Sources Mapping Files::
3934 * Integrated Preprocessing::
3935 * Code Generation Control::
3944 @cindex @option{-b} (@command{gcc})
3945 @item -b @var{target}
3946 Compile your program to run on @var{target}, which is the name of a
3947 system configuration. You must have a GNAT cross-compiler built if
3948 @var{target} is not the same as your host system.
3951 @cindex @option{-B} (@command{gcc})
3952 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3953 from @var{dir} instead of the default location. Only use this switch
3954 when multiple versions of the GNAT compiler are available.
3955 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3956 GNU Compiler Collection (GCC)}, for further details. You would normally
3957 use the @option{-b} or @option{-V} switch instead.
3960 @cindex @option{-c} (@command{gcc})
3961 Compile. Always use this switch when compiling Ada programs.
3963 Note: for some other languages when using @command{gcc}, notably in
3964 the case of C and C++, it is possible to use
3965 use @command{gcc} without a @option{-c} switch to
3966 compile and link in one step. In the case of GNAT, you
3967 cannot use this approach, because the binder must be run
3968 and @command{gcc} cannot be used to run the GNAT binder.
3972 @cindex @option{-fno-inline} (@command{gcc})
3973 Suppresses all back-end inlining, even if other optimization or inlining
3975 This includes suppression of inlining that results
3976 from the use of the pragma @code{Inline_Always}.
3977 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3978 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3979 effect if this switch is present.
3981 @item -fno-inline-functions
3982 @cindex @option{-fno-inline-functions} (@command{gcc})
3983 Suppresses automatic inlining of subprograms, which is enabled
3984 if @option{-O3} is used.
3986 @item -fno-inline-small-functions
3987 @cindex @option{-fno-inline-small-functions} (@command{gcc})
3988 Suppresses automatic inlining of small subprograms, which is enabled
3989 if @option{-O2} is used.
3991 @item -fno-inline-functions-called-once
3992 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
3993 Suppresses inlining of subprograms local to the unit and called once
3994 from within it, which is enabled if @option{-O1} is used.
3997 @cindex @option{-fno-ivopts} (@command{gcc})
3998 Suppresses high-level loop induction variable optimizations, which are
3999 enabled if @option{-O1} is used. These optimizations are generally
4000 profitable but, for some specific cases of loops with numerous uses
4001 of the iteration variable that follow a common pattern, they may end
4002 up destroying the regularity that could be exploited at a lower level
4003 and thus producing inferior code.
4005 @item -fno-strict-aliasing
4006 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4007 Causes the compiler to avoid assumptions regarding non-aliasing
4008 of objects of different types. See
4009 @ref{Optimization and Strict Aliasing} for details.
4012 @cindex @option{-fstack-check} (@command{gcc})
4013 Activates stack checking.
4014 See @ref{Stack Overflow Checking} for details.
4017 @cindex @option{-fstack-usage} (@command{gcc})
4018 Makes the compiler output stack usage information for the program, on a
4019 per-function basis. See @ref{Static Stack Usage Analysis} for details.
4021 @item -fcallgraph-info@r{[}=su@r{]}
4022 @cindex @option{-fcallgraph-info} (@command{gcc})
4023 Makes the compiler output callgraph information for the program, on a
4024 per-file basis. The information is generated in the VCG format. It can
4025 be decorated with stack-usage per-node information.
4028 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4029 Generate debugging information. This information is stored in the object
4030 file and copied from there to the final executable file by the linker,
4031 where it can be read by the debugger. You must use the
4032 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4035 @cindex @option{-gnat83} (@command{gcc})
4036 Enforce Ada 83 restrictions.
4039 @cindex @option{-gnat95} (@command{gcc})
4040 Enforce Ada 95 restrictions.
4043 @cindex @option{-gnat05} (@command{gcc})
4044 Allow full Ada 2005 features.
4047 @cindex @option{-gnat2005} (@command{gcc})
4048 Allow full Ada 2005 features (same as @option{-gnat05}
4051 @cindex @option{-gnat12} (@command{gcc})
4054 @cindex @option{-gnat2012} (@command{gcc})
4055 Allow full Ada 2012 features (same as @option{-gnat12}
4058 @cindex @option{-gnata} (@command{gcc})
4059 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4060 activated. Note that these pragmas can also be controlled using the
4061 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4062 It also activates pragmas @code{Check}, @code{Precondition}, and
4063 @code{Postcondition}. Note that these pragmas can also be controlled
4064 using the configuration pragma @code{Check_Policy}.
4067 @cindex @option{-gnatA} (@command{gcc})
4068 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4072 @cindex @option{-gnatb} (@command{gcc})
4073 Generate brief messages to @file{stderr} even if verbose mode set.
4076 @cindex @option{-gnatB} (@command{gcc})
4077 Assume no invalid (bad) values except for 'Valid attribute use
4078 (@pxref{Validity Checking}).
4081 @cindex @option{-gnatc} (@command{gcc})
4082 Check syntax and semantics only (no code generation attempted).
4085 @cindex @option{-gnatC} (@command{gcc})
4086 Generate CodePeer information (no code generation attempted).
4087 This switch will generate an intermediate representation suitable for
4088 use by CodePeer (@file{.scil} files). This switch is not compatible with
4089 code generation (it will, among other things, disable some switches such
4090 as -gnatn, and enable others such as -gnata).
4093 @cindex @option{-gnatd} (@command{gcc})
4094 Specify debug options for the compiler. The string of characters after
4095 the @option{-gnatd} specify the specific debug options. The possible
4096 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4097 compiler source file @file{debug.adb} for details of the implemented
4098 debug options. Certain debug options are relevant to applications
4099 programmers, and these are documented at appropriate points in this
4104 @cindex @option{-gnatD[nn]} (@command{gcc})
4107 @item /XDEBUG /LXDEBUG=nnn
4109 Create expanded source files for source level debugging. This switch
4110 also suppress generation of cross-reference information
4111 (see @option{-gnatx}).
4113 @item -gnatec=@var{path}
4114 @cindex @option{-gnatec} (@command{gcc})
4115 Specify a configuration pragma file
4117 (the equal sign is optional)
4119 (@pxref{The Configuration Pragmas Files}).
4121 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4122 @cindex @option{-gnateD} (@command{gcc})
4123 Defines a symbol, associated with @var{value}, for preprocessing.
4124 (@pxref{Integrated Preprocessing}).
4127 @cindex @option{-gnatef} (@command{gcc})
4128 Display full source path name in brief error messages.
4131 @cindex @option{-gnateG} (@command{gcc})
4132 Save result of preprocessing in a text file.
4134 @item -gnatem=@var{path}
4135 @cindex @option{-gnatem} (@command{gcc})
4136 Specify a mapping file
4138 (the equal sign is optional)
4140 (@pxref{Units to Sources Mapping Files}).
4142 @item -gnatep=@var{file}
4143 @cindex @option{-gnatep} (@command{gcc})
4144 Specify a preprocessing data file
4146 (the equal sign is optional)
4148 (@pxref{Integrated Preprocessing}).
4151 @cindex @option{-gnateS} (@command{gcc})
4152 Generate SCO (Source Coverage Obligation) information in the ALI
4153 file. This information is used by advanced coverage tools. See
4154 unit @file{SCOs} in the compiler sources for details in files
4155 @file{scos.ads} and @file{scos.adb}.
4158 @cindex @option{-gnatE} (@command{gcc})
4159 Full dynamic elaboration checks.
4162 @cindex @option{-gnatf} (@command{gcc})
4163 Full errors. Multiple errors per line, all undefined references, do not
4164 attempt to suppress cascaded errors.
4167 @cindex @option{-gnatF} (@command{gcc})
4168 Externals names are folded to all uppercase.
4170 @item ^-gnatg^/GNAT_INTERNAL^
4171 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4172 Internal GNAT implementation mode. This should not be used for
4173 applications programs, it is intended only for use by the compiler
4174 and its run-time library. For documentation, see the GNAT sources.
4175 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4176 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4177 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4178 so that all standard warnings and all standard style options are turned on.
4179 All warnings and style messages are treated as errors.
4183 @cindex @option{-gnatG[nn]} (@command{gcc})
4186 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4188 List generated expanded code in source form.
4190 @item ^-gnath^/HELP^
4191 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4192 Output usage information. The output is written to @file{stdout}.
4194 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4195 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4196 Identifier character set
4198 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4200 For details of the possible selections for @var{c},
4201 see @ref{Character Set Control}.
4203 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4204 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4205 Ignore representation clauses. When this switch is used,
4206 representation clauses are treated as comments. This is useful
4207 when initially porting code where you want to ignore rep clause
4208 problems, and also for compiling foreign code (particularly
4209 for use with ASIS). The representation clauses that are ignored
4210 are: enumeration_representation_clause, record_representation_clause,
4211 and attribute_definition_clause for the following attributes:
4212 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4213 Object_Size, Size, Small, Stream_Size, and Value_Size.
4214 Note that this option should be used only for compiling -- the
4215 code is likely to malfunction at run time.
4218 @cindex @option{-gnatjnn} (@command{gcc})
4219 Reformat error messages to fit on nn character lines
4221 @item -gnatk=@var{n}
4222 @cindex @option{-gnatk} (@command{gcc})
4223 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4226 @cindex @option{-gnatl} (@command{gcc})
4227 Output full source listing with embedded error messages.
4230 @cindex @option{-gnatL} (@command{gcc})
4231 Used in conjunction with -gnatG or -gnatD to intersperse original
4232 source lines (as comment lines with line numbers) in the expanded
4235 @item -gnatm=@var{n}
4236 @cindex @option{-gnatm} (@command{gcc})
4237 Limit number of detected error or warning messages to @var{n}
4238 where @var{n} is in the range 1..999999. The default setting if
4239 no switch is given is 9999. If the number of warnings reaches this
4240 limit, then a message is output and further warnings are suppressed,
4241 but the compilation is continued. If the number of error messages
4242 reaches this limit, then a message is output and the compilation
4243 is abandoned. The equal sign here is optional. A value of zero
4244 means that no limit applies.
4247 @cindex @option{-gnatn} (@command{gcc})
4248 Activate inlining for subprograms for which
4249 pragma @code{inline} is specified. This inlining is performed
4250 by the GCC back-end.
4253 @cindex @option{-gnatN} (@command{gcc})
4254 Activate front end inlining for subprograms for which
4255 pragma @code{Inline} is specified. This inlining is performed
4256 by the front end and will be visible in the
4257 @option{-gnatG} output.
4259 When using a gcc-based back end (in practice this means using any version
4260 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4261 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4262 Historically front end inlining was more extensive than the gcc back end
4263 inlining, but that is no longer the case.
4266 @cindex @option{-gnato} (@command{gcc})
4267 Enable numeric overflow checking (which is not normally enabled by
4268 default). Note that division by zero is a separate check that is not
4269 controlled by this switch (division by zero checking is on by default).
4272 @cindex @option{-gnatp} (@command{gcc})
4273 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4274 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4277 @cindex @option{-gnat-p} (@command{gcc})
4278 Cancel effect of previous @option{-gnatp} switch.
4281 @cindex @option{-gnatP} (@command{gcc})
4282 Enable polling. This is required on some systems (notably Windows NT) to
4283 obtain asynchronous abort and asynchronous transfer of control capability.
4284 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4288 @cindex @option{-gnatq} (@command{gcc})
4289 Don't quit. Try semantics, even if parse errors.
4292 @cindex @option{-gnatQ} (@command{gcc})
4293 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4296 @cindex @option{-gnatr} (@command{gcc})
4297 Treat pragma Restrictions as Restriction_Warnings.
4299 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4300 @cindex @option{-gnatR} (@command{gcc})
4301 Output representation information for declared types and objects.
4304 @cindex @option{-gnats} (@command{gcc})
4308 @cindex @option{-gnatS} (@command{gcc})
4309 Print package Standard.
4312 @cindex @option{-gnatt} (@command{gcc})
4313 Generate tree output file.
4315 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4316 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4317 All compiler tables start at @var{nnn} times usual starting size.
4320 @cindex @option{-gnatu} (@command{gcc})
4321 List units for this compilation.
4324 @cindex @option{-gnatU} (@command{gcc})
4325 Tag all error messages with the unique string ``error:''
4328 @cindex @option{-gnatv} (@command{gcc})
4329 Verbose mode. Full error output with source lines to @file{stdout}.
4332 @cindex @option{-gnatV} (@command{gcc})
4333 Control level of validity checking (@pxref{Validity Checking}).
4335 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4336 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4338 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4339 the exact warnings that
4340 are enabled or disabled (@pxref{Warning Message Control}).
4342 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4343 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4344 Wide character encoding method
4346 (@var{e}=n/h/u/s/e/8).
4349 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4353 @cindex @option{-gnatx} (@command{gcc})
4354 Suppress generation of cross-reference information.
4357 @cindex @option{-gnatX} (@command{gcc})
4358 Enable GNAT implementation extensions and latest Ada version.
4360 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4361 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4362 Enable built-in style checks (@pxref{Style Checking}).
4364 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4365 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4366 Distribution stub generation and compilation
4368 (@var{m}=r/c for receiver/caller stubs).
4371 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4372 to be generated and compiled).
4375 @item ^-I^/SEARCH=^@var{dir}
4376 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4378 Direct GNAT to search the @var{dir} directory for source files needed by
4379 the current compilation
4380 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4382 @item ^-I-^/NOCURRENT_DIRECTORY^
4383 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4385 Except for the source file named in the command line, do not look for source
4386 files in the directory containing the source file named in the command line
4387 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4391 @cindex @option{-mbig-switch} (@command{gcc})
4392 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4393 This standard gcc switch causes the compiler to use larger offsets in its
4394 jump table representation for @code{case} statements.
4395 This may result in less efficient code, but is sometimes necessary
4396 (for example on HP-UX targets)
4397 @cindex HP-UX and @option{-mbig-switch} option
4398 in order to compile large and/or nested @code{case} statements.
4401 @cindex @option{-o} (@command{gcc})
4402 This switch is used in @command{gcc} to redirect the generated object file
4403 and its associated ALI file. Beware of this switch with GNAT, because it may
4404 cause the object file and ALI file to have different names which in turn
4405 may confuse the binder and the linker.
4409 @cindex @option{-nostdinc} (@command{gcc})
4410 Inhibit the search of the default location for the GNAT Run Time
4411 Library (RTL) source files.
4414 @cindex @option{-nostdlib} (@command{gcc})
4415 Inhibit the search of the default location for the GNAT Run Time
4416 Library (RTL) ALI files.
4420 @c Expanding @ovar macro inline (explanation in macro def comments)
4421 @item -O@r{[}@var{n}@r{]}
4422 @cindex @option{-O} (@command{gcc})
4423 @var{n} controls the optimization level.
4427 No optimization, the default setting if no @option{-O} appears
4430 Normal optimization, the default if you specify @option{-O} without
4431 an operand. A good compromise between code quality and compilation
4435 Extensive optimization, may improve execution time, possibly at the cost of
4436 substantially increased compilation time.
4439 Same as @option{-O2}, and also includes inline expansion for small subprograms
4443 Optimize space usage
4447 See also @ref{Optimization Levels}.
4452 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4453 Equivalent to @option{/OPTIMIZE=NONE}.
4454 This is the default behavior in the absence of an @option{/OPTIMIZE}
4457 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4458 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4459 Selects the level of optimization for your program. The supported
4460 keywords are as follows:
4463 Perform most optimizations, including those that
4465 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4466 without keyword options.
4469 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4472 Perform some optimizations, but omit ones that are costly.
4475 Same as @code{SOME}.
4478 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4479 automatic inlining of small subprograms within a unit
4482 Try to unroll loops. This keyword may be specified together with
4483 any keyword above other than @code{NONE}. Loop unrolling
4484 usually, but not always, improves the performance of programs.
4487 Optimize space usage
4491 See also @ref{Optimization Levels}.
4495 @item -pass-exit-codes
4496 @cindex @option{-pass-exit-codes} (@command{gcc})
4497 Catch exit codes from the compiler and use the most meaningful as
4501 @item --RTS=@var{rts-path}
4502 @cindex @option{--RTS} (@command{gcc})
4503 Specifies the default location of the runtime library. Same meaning as the
4504 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4507 @cindex @option{^-S^/ASM^} (@command{gcc})
4508 ^Used in place of @option{-c} to^Used to^
4509 cause the assembler source file to be
4510 generated, using @file{^.s^.S^} as the extension,
4511 instead of the object file.
4512 This may be useful if you need to examine the generated assembly code.
4514 @item ^-fverbose-asm^/VERBOSE_ASM^
4515 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4516 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4517 to cause the generated assembly code file to be annotated with variable
4518 names, making it significantly easier to follow.
4521 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4522 Show commands generated by the @command{gcc} driver. Normally used only for
4523 debugging purposes or if you need to be sure what version of the
4524 compiler you are executing.
4528 @cindex @option{-V} (@command{gcc})
4529 Execute @var{ver} version of the compiler. This is the @command{gcc}
4530 version, not the GNAT version.
4533 @item ^-w^/NO_BACK_END_WARNINGS^
4534 @cindex @option{-w} (@command{gcc})
4535 Turn off warnings generated by the back end of the compiler. Use of
4536 this switch also causes the default for front end warnings to be set
4537 to suppress (as though @option{-gnatws} had appeared at the start of
4543 @c Combining qualifiers does not work on VMS
4544 You may combine a sequence of GNAT switches into a single switch. For
4545 example, the combined switch
4547 @cindex Combining GNAT switches
4553 is equivalent to specifying the following sequence of switches:
4556 -gnato -gnatf -gnati3
4561 The following restrictions apply to the combination of switches
4566 The switch @option{-gnatc} if combined with other switches must come
4567 first in the string.
4570 The switch @option{-gnats} if combined with other switches must come
4571 first in the string.
4575 ^^@option{/DISTRIBUTION_STUBS=},^
4576 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4577 switches, and only one of them may appear in the command line.
4580 The switch @option{-gnat-p} may not be combined with any other switch.
4584 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4585 switch), then all further characters in the switch are interpreted
4586 as style modifiers (see description of @option{-gnaty}).
4589 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4590 switch), then all further characters in the switch are interpreted
4591 as debug flags (see description of @option{-gnatd}).
4594 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4595 switch), then all further characters in the switch are interpreted
4596 as warning mode modifiers (see description of @option{-gnatw}).
4599 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4600 switch), then all further characters in the switch are interpreted
4601 as validity checking options (@pxref{Validity Checking}).
4604 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4605 a combined list of options.
4609 @node Output and Error Message Control
4610 @subsection Output and Error Message Control
4614 The standard default format for error messages is called ``brief format''.
4615 Brief format messages are written to @file{stderr} (the standard error
4616 file) and have the following form:
4619 e.adb:3:04: Incorrect spelling of keyword "function"
4620 e.adb:4:20: ";" should be "is"
4624 The first integer after the file name is the line number in the file,
4625 and the second integer is the column number within the line.
4627 @code{GPS} can parse the error messages
4628 and point to the referenced character.
4630 The following switches provide control over the error message
4636 @cindex @option{-gnatv} (@command{gcc})
4639 The v stands for verbose.
4641 The effect of this setting is to write long-format error
4642 messages to @file{stdout} (the standard output file.
4643 The same program compiled with the
4644 @option{-gnatv} switch would generate:
4648 3. funcion X (Q : Integer)
4650 >>> Incorrect spelling of keyword "function"
4653 >>> ";" should be "is"
4658 The vertical bar indicates the location of the error, and the @samp{>>>}
4659 prefix can be used to search for error messages. When this switch is
4660 used the only source lines output are those with errors.
4663 @cindex @option{-gnatl} (@command{gcc})
4665 The @code{l} stands for list.
4667 This switch causes a full listing of
4668 the file to be generated. In the case where a body is
4669 compiled, the corresponding spec is also listed, along
4670 with any subunits. Typical output from compiling a package
4671 body @file{p.adb} might look like:
4673 @smallexample @c ada
4677 1. package body p is
4679 3. procedure a is separate;
4690 2. pragma Elaborate_Body
4714 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4715 standard output is redirected, a brief summary is written to
4716 @file{stderr} (standard error) giving the number of error messages and
4717 warning messages generated.
4719 @item -^gnatl^OUTPUT_FILE^=file
4720 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4721 This has the same effect as @option{-gnatl} except that the output is
4722 written to a file instead of to standard output. If the given name
4723 @file{fname} does not start with a period, then it is the full name
4724 of the file to be written. If @file{fname} is an extension, it is
4725 appended to the name of the file being compiled. For example, if
4726 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4727 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4730 @cindex @option{-gnatU} (@command{gcc})
4731 This switch forces all error messages to be preceded by the unique
4732 string ``error:''. This means that error messages take a few more
4733 characters in space, but allows easy searching for and identification
4737 @cindex @option{-gnatb} (@command{gcc})
4739 The @code{b} stands for brief.
4741 This switch causes GNAT to generate the
4742 brief format error messages to @file{stderr} (the standard error
4743 file) as well as the verbose
4744 format message or full listing (which as usual is written to
4745 @file{stdout} (the standard output file).
4747 @item -gnatm=@var{n}
4748 @cindex @option{-gnatm} (@command{gcc})
4750 The @code{m} stands for maximum.
4752 @var{n} is a decimal integer in the
4753 range of 1 to 999999 and limits the number of error or warning
4754 messages to be generated. For example, using
4755 @option{-gnatm2} might yield
4758 e.adb:3:04: Incorrect spelling of keyword "function"
4759 e.adb:5:35: missing ".."
4760 fatal error: maximum number of errors detected
4761 compilation abandoned
4765 The default setting if
4766 no switch is given is 9999. If the number of warnings reaches this
4767 limit, then a message is output and further warnings are suppressed,
4768 but the compilation is continued. If the number of error messages
4769 reaches this limit, then a message is output and the compilation
4770 is abandoned. A value of zero means that no limit applies.
4773 Note that the equal sign is optional, so the switches
4774 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4777 @cindex @option{-gnatf} (@command{gcc})
4778 @cindex Error messages, suppressing
4780 The @code{f} stands for full.
4782 Normally, the compiler suppresses error messages that are likely to be
4783 redundant. This switch causes all error
4784 messages to be generated. In particular, in the case of
4785 references to undefined variables. If a given variable is referenced
4786 several times, the normal format of messages is
4788 e.adb:7:07: "V" is undefined (more references follow)
4792 where the parenthetical comment warns that there are additional
4793 references to the variable @code{V}. Compiling the same program with the
4794 @option{-gnatf} switch yields
4797 e.adb:7:07: "V" is undefined
4798 e.adb:8:07: "V" is undefined
4799 e.adb:8:12: "V" is undefined
4800 e.adb:8:16: "V" is undefined
4801 e.adb:9:07: "V" is undefined
4802 e.adb:9:12: "V" is undefined
4806 The @option{-gnatf} switch also generates additional information for
4807 some error messages. Some examples are:
4811 Details on possibly non-portable unchecked conversion
4813 List possible interpretations for ambiguous calls
4815 Additional details on incorrect parameters
4819 @cindex @option{-gnatjnn} (@command{gcc})
4820 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4821 with continuation lines are treated as though the continuation lines were
4822 separate messages (and so a warning with two continuation lines counts as
4823 three warnings, and is listed as three separate messages).
4825 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4826 messages are output in a different manner. A message and all its continuation
4827 lines are treated as a unit, and count as only one warning or message in the
4828 statistics totals. Furthermore, the message is reformatted so that no line
4829 is longer than nn characters.
4832 @cindex @option{-gnatq} (@command{gcc})
4834 The @code{q} stands for quit (really ``don't quit'').
4836 In normal operation mode, the compiler first parses the program and
4837 determines if there are any syntax errors. If there are, appropriate
4838 error messages are generated and compilation is immediately terminated.
4840 GNAT to continue with semantic analysis even if syntax errors have been
4841 found. This may enable the detection of more errors in a single run. On
4842 the other hand, the semantic analyzer is more likely to encounter some
4843 internal fatal error when given a syntactically invalid tree.
4846 @cindex @option{-gnatQ} (@command{gcc})
4847 In normal operation mode, the @file{ALI} file is not generated if any
4848 illegalities are detected in the program. The use of @option{-gnatQ} forces
4849 generation of the @file{ALI} file. This file is marked as being in
4850 error, so it cannot be used for binding purposes, but it does contain
4851 reasonably complete cross-reference information, and thus may be useful
4852 for use by tools (e.g., semantic browsing tools or integrated development
4853 environments) that are driven from the @file{ALI} file. This switch
4854 implies @option{-gnatq}, since the semantic phase must be run to get a
4855 meaningful ALI file.
4857 In addition, if @option{-gnatt} is also specified, then the tree file is
4858 generated even if there are illegalities. It may be useful in this case
4859 to also specify @option{-gnatq} to ensure that full semantic processing
4860 occurs. The resulting tree file can be processed by ASIS, for the purpose
4861 of providing partial information about illegal units, but if the error
4862 causes the tree to be badly malformed, then ASIS may crash during the
4865 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4866 being in error, @command{gnatmake} will attempt to recompile the source when it
4867 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4869 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4870 since ALI files are never generated if @option{-gnats} is set.
4874 @node Warning Message Control
4875 @subsection Warning Message Control
4876 @cindex Warning messages
4878 In addition to error messages, which correspond to illegalities as defined
4879 in the Ada Reference Manual, the compiler detects two kinds of warning
4882 First, the compiler considers some constructs suspicious and generates a
4883 warning message to alert you to a possible error. Second, if the
4884 compiler detects a situation that is sure to raise an exception at
4885 run time, it generates a warning message. The following shows an example
4886 of warning messages:
4888 e.adb:4:24: warning: creation of object may raise Storage_Error
4889 e.adb:10:17: warning: static value out of range
4890 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4894 GNAT considers a large number of situations as appropriate
4895 for the generation of warning messages. As always, warnings are not
4896 definite indications of errors. For example, if you do an out-of-range
4897 assignment with the deliberate intention of raising a
4898 @code{Constraint_Error} exception, then the warning that may be
4899 issued does not indicate an error. Some of the situations for which GNAT
4900 issues warnings (at least some of the time) are given in the following
4901 list. This list is not complete, and new warnings are often added to
4902 subsequent versions of GNAT. The list is intended to give a general idea
4903 of the kinds of warnings that are generated.
4907 Possible infinitely recursive calls
4910 Out-of-range values being assigned
4913 Possible order of elaboration problems
4916 Assertions (pragma Assert) that are sure to fail
4922 Address clauses with possibly unaligned values, or where an attempt is
4923 made to overlay a smaller variable with a larger one.
4926 Fixed-point type declarations with a null range
4929 Direct_IO or Sequential_IO instantiated with a type that has access values
4932 Variables that are never assigned a value
4935 Variables that are referenced before being initialized
4938 Task entries with no corresponding @code{accept} statement
4941 Duplicate accepts for the same task entry in a @code{select}
4944 Objects that take too much storage
4947 Unchecked conversion between types of differing sizes
4950 Missing @code{return} statement along some execution path in a function
4953 Incorrect (unrecognized) pragmas
4956 Incorrect external names
4959 Allocation from empty storage pool
4962 Potentially blocking operation in protected type
4965 Suspicious parenthesization of expressions
4968 Mismatching bounds in an aggregate
4971 Attempt to return local value by reference
4974 Premature instantiation of a generic body
4977 Attempt to pack aliased components
4980 Out of bounds array subscripts
4983 Wrong length on string assignment
4986 Violations of style rules if style checking is enabled
4989 Unused @code{with} clauses
4992 @code{Bit_Order} usage that does not have any effect
4995 @code{Standard.Duration} used to resolve universal fixed expression
4998 Dereference of possibly null value
5001 Declaration that is likely to cause storage error
5004 Internal GNAT unit @code{with}'ed by application unit
5007 Values known to be out of range at compile time
5010 Unreferenced labels and variables
5013 Address overlays that could clobber memory
5016 Unexpected initialization when address clause present
5019 Bad alignment for address clause
5022 Useless type conversions
5025 Redundant assignment statements and other redundant constructs
5028 Useless exception handlers
5031 Accidental hiding of name by child unit
5034 Access before elaboration detected at compile time
5037 A range in a @code{for} loop that is known to be null or might be null
5042 The following section lists compiler switches that are available
5043 to control the handling of warning messages. It is also possible
5044 to exercise much finer control over what warnings are issued and
5045 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5046 gnat_rm, GNAT Reference manual}.
5051 @emph{Activate all optional errors.}
5052 @cindex @option{-gnatwa} (@command{gcc})
5053 This switch activates most optional warning messages, see remaining list
5054 in this section for details on optional warning messages that can be
5055 individually controlled. The warnings that are not turned on by this
5057 @option{-gnatwd} (implicit dereferencing),
5058 @option{-gnatwh} (hiding),
5059 @option{-gnatwl} (elaboration warnings),
5060 @option{-gnatw.o} (warn on values set by out parameters ignored)
5061 and @option{-gnatwt} (tracking of deleted conditional code).
5062 All other optional warnings are turned on.
5065 @emph{Suppress all optional errors.}
5066 @cindex @option{-gnatwA} (@command{gcc})
5067 This switch suppresses all optional warning messages, see remaining list
5068 in this section for details on optional warning messages that can be
5069 individually controlled.
5072 @emph{Activate warnings on failing assertions.}
5073 @cindex @option{-gnatw.a} (@command{gcc})
5074 @cindex Assert failures
5075 This switch activates warnings for assertions where the compiler can tell at
5076 compile time that the assertion will fail. Note that this warning is given
5077 even if assertions are disabled. The default is that such warnings are
5081 @emph{Suppress warnings on failing assertions.}
5082 @cindex @option{-gnatw.A} (@command{gcc})
5083 @cindex Assert failures
5084 This switch suppresses warnings for assertions where the compiler can tell at
5085 compile time that the assertion will fail.
5088 @emph{Activate warnings on bad fixed values.}
5089 @cindex @option{-gnatwb} (@command{gcc})
5090 @cindex Bad fixed values
5091 @cindex Fixed-point Small value
5093 This switch activates warnings for static fixed-point expressions whose
5094 value is not an exact multiple of Small. Such values are implementation
5095 dependent, since an implementation is free to choose either of the multiples
5096 that surround the value. GNAT always chooses the closer one, but this is not
5097 required behavior, and it is better to specify a value that is an exact
5098 multiple, ensuring predictable execution. The default is that such warnings
5102 @emph{Suppress warnings on bad fixed values.}
5103 @cindex @option{-gnatwB} (@command{gcc})
5104 This switch suppresses warnings for static fixed-point expressions whose
5105 value is not an exact multiple of Small.
5108 @emph{Activate warnings on biased representation.}
5109 @cindex @option{-gnatw.b} (@command{gcc})
5110 @cindex Biased representation
5111 This switch activates warnings when a size clause, value size clause, component
5112 clause, or component size clause forces the use of biased representation for an
5113 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5114 to represent 10/11). The default is that such warnings are generated.
5117 @emph{Suppress warnings on biased representation.}
5118 @cindex @option{-gnatwB} (@command{gcc})
5119 This switch suppresses warnings for representation clauses that force the use
5120 of biased representation.
5123 @emph{Activate warnings on conditionals.}
5124 @cindex @option{-gnatwc} (@command{gcc})
5125 @cindex Conditionals, constant
5126 This switch activates warnings for conditional expressions used in
5127 tests that are known to be True or False at compile time. The default
5128 is that such warnings are not generated.
5129 Note that this warning does
5130 not get issued for the use of boolean variables or constants whose
5131 values are known at compile time, since this is a standard technique
5132 for conditional compilation in Ada, and this would generate too many
5133 false positive warnings.
5135 This warning option also activates a special test for comparisons using
5136 the operators ``>='' and`` <=''.
5137 If the compiler can tell that only the equality condition is possible,
5138 then it will warn that the ``>'' or ``<'' part of the test
5139 is useless and that the operator could be replaced by ``=''.
5140 An example would be comparing a @code{Natural} variable <= 0.
5142 This warning option also generates warnings if
5143 one or both tests is optimized away in a membership test for integer
5144 values if the result can be determined at compile time. Range tests on
5145 enumeration types are not included, since it is common for such tests
5146 to include an end point.
5148 This warning can also be turned on using @option{-gnatwa}.
5151 @emph{Suppress warnings on conditionals.}
5152 @cindex @option{-gnatwC} (@command{gcc})
5153 This switch suppresses warnings for conditional expressions used in
5154 tests that are known to be True or False at compile time.
5157 @emph{Activate warnings on missing component clauses.}
5158 @cindex @option{-gnatw.c} (@command{gcc})
5159 @cindex Component clause, missing
5160 This switch activates warnings for record components where a record
5161 representation clause is present and has component clauses for the
5162 majority, but not all, of the components. A warning is given for each
5163 component for which no component clause is present.
5165 This warning can also be turned on using @option{-gnatwa}.
5168 @emph{Suppress warnings on missing component clauses.}
5169 @cindex @option{-gnatwC} (@command{gcc})
5170 This switch suppresses warnings for record components that are
5171 missing a component clause in the situation described above.
5174 @emph{Activate warnings on implicit dereferencing.}
5175 @cindex @option{-gnatwd} (@command{gcc})
5176 If this switch is set, then the use of a prefix of an access type
5177 in an indexed component, slice, or selected component without an
5178 explicit @code{.all} will generate a warning. With this warning
5179 enabled, access checks occur only at points where an explicit
5180 @code{.all} appears in the source code (assuming no warnings are
5181 generated as a result of this switch). The default is that such
5182 warnings are not generated.
5183 Note that @option{-gnatwa} does not affect the setting of
5184 this warning option.
5187 @emph{Suppress warnings on implicit dereferencing.}
5188 @cindex @option{-gnatwD} (@command{gcc})
5189 @cindex Implicit dereferencing
5190 @cindex Dereferencing, implicit
5191 This switch suppresses warnings for implicit dereferences in
5192 indexed components, slices, and selected components.
5195 @emph{Treat warnings and style checks as errors.}
5196 @cindex @option{-gnatwe} (@command{gcc})
5197 @cindex Warnings, treat as error
5198 This switch causes warning messages and style check messages to be
5200 The warning string still appears, but the warning messages are counted
5201 as errors, and prevent the generation of an object file. Note that this
5202 is the only -gnatw switch that affects the handling of style check messages.
5205 @emph{Activate every optional warning}
5206 @cindex @option{-gnatw.e} (@command{gcc})
5207 @cindex Warnings, activate every optional warning
5208 This switch activates all optional warnings, including those which
5209 are not activated by @code{-gnatwa}.
5212 @emph{Activate warnings on unreferenced formals.}
5213 @cindex @option{-gnatwf} (@command{gcc})
5214 @cindex Formals, unreferenced
5215 This switch causes a warning to be generated if a formal parameter
5216 is not referenced in the body of the subprogram. This warning can
5217 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5218 default is that these warnings are not generated.
5221 @emph{Suppress warnings on unreferenced formals.}
5222 @cindex @option{-gnatwF} (@command{gcc})
5223 This switch suppresses warnings for unreferenced formal
5224 parameters. Note that the
5225 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5226 effect of warning on unreferenced entities other than subprogram
5230 @emph{Activate warnings on unrecognized pragmas.}
5231 @cindex @option{-gnatwg} (@command{gcc})
5232 @cindex Pragmas, unrecognized
5233 This switch causes a warning to be generated if an unrecognized
5234 pragma is encountered. Apart from issuing this warning, the
5235 pragma is ignored and has no effect. This warning can
5236 also be turned on using @option{-gnatwa}. The default
5237 is that such warnings are issued (satisfying the Ada Reference
5238 Manual requirement that such warnings appear).
5241 @emph{Suppress warnings on unrecognized pragmas.}
5242 @cindex @option{-gnatwG} (@command{gcc})
5243 This switch suppresses warnings for unrecognized pragmas.
5246 @emph{Activate warnings on hiding.}
5247 @cindex @option{-gnatwh} (@command{gcc})
5248 @cindex Hiding of Declarations
5249 This switch activates warnings on hiding declarations.
5250 A declaration is considered hiding
5251 if it is for a non-overloadable entity, and it declares an entity with the
5252 same name as some other entity that is directly or use-visible. The default
5253 is that such warnings are not generated.
5254 Note that @option{-gnatwa} does not affect the setting of this warning option.
5257 @emph{Suppress warnings on hiding.}
5258 @cindex @option{-gnatwH} (@command{gcc})
5259 This switch suppresses warnings on hiding declarations.
5262 @emph{Activate warnings on implementation units.}
5263 @cindex @option{-gnatwi} (@command{gcc})
5264 This switch activates warnings for a @code{with} of an internal GNAT
5265 implementation unit, defined as any unit from the @code{Ada},
5266 @code{Interfaces}, @code{GNAT},
5267 ^^@code{DEC},^ or @code{System}
5268 hierarchies that is not
5269 documented in either the Ada Reference Manual or the GNAT
5270 Programmer's Reference Manual. Such units are intended only
5271 for internal implementation purposes and should not be @code{with}'ed
5272 by user programs. The default is that such warnings are generated
5273 This warning can also be turned on using @option{-gnatwa}.
5276 @emph{Disable warnings on implementation units.}
5277 @cindex @option{-gnatwI} (@command{gcc})
5278 This switch disables warnings for a @code{with} of an internal GNAT
5279 implementation unit.
5282 @emph{Activate warnings on overlapping actuals.}
5283 @cindex @option{-gnatw.i} (@command{gcc})
5284 This switch enables a warning on statically detectable overlapping actuals in
5285 a subprogram call, when one of the actuals is an in-out parameter, and the
5286 types of the actuals are not by-copy types. The warning is off by default,
5287 and is not included under -gnatwa.
5290 @emph{Disable warnings on overlapping actuals.}
5291 @cindex @option{-gnatw.I} (@command{gcc})
5292 This switch disables warnings on overlapping actuals in a call..
5295 @emph{Activate warnings on obsolescent features (Annex J).}
5296 @cindex @option{-gnatwj} (@command{gcc})
5297 @cindex Features, obsolescent
5298 @cindex Obsolescent features
5299 If this warning option is activated, then warnings are generated for
5300 calls to subprograms marked with @code{pragma Obsolescent} and
5301 for use of features in Annex J of the Ada Reference Manual. In the
5302 case of Annex J, not all features are flagged. In particular use
5303 of the renamed packages (like @code{Text_IO}) and use of package
5304 @code{ASCII} are not flagged, since these are very common and
5305 would generate many annoying positive warnings. The default is that
5306 such warnings are not generated. This warning is also turned on by
5307 the use of @option{-gnatwa}.
5309 In addition to the above cases, warnings are also generated for
5310 GNAT features that have been provided in past versions but which
5311 have been superseded (typically by features in the new Ada standard).
5312 For example, @code{pragma Ravenscar} will be flagged since its
5313 function is replaced by @code{pragma Profile(Ravenscar)}.
5315 Note that this warning option functions differently from the
5316 restriction @code{No_Obsolescent_Features} in two respects.
5317 First, the restriction applies only to annex J features.
5318 Second, the restriction does flag uses of package @code{ASCII}.
5321 @emph{Suppress warnings on obsolescent features (Annex J).}
5322 @cindex @option{-gnatwJ} (@command{gcc})
5323 This switch disables warnings on use of obsolescent features.
5326 @emph{Activate warnings on variables that could be constants.}
5327 @cindex @option{-gnatwk} (@command{gcc})
5328 This switch activates warnings for variables that are initialized but
5329 never modified, and then could be declared constants. The default is that
5330 such warnings are not given.
5331 This warning can also be turned on using @option{-gnatwa}.
5334 @emph{Suppress warnings on variables that could be constants.}
5335 @cindex @option{-gnatwK} (@command{gcc})
5336 This switch disables warnings on variables that could be declared constants.
5339 @emph{Activate warnings for elaboration pragmas.}
5340 @cindex @option{-gnatwl} (@command{gcc})
5341 @cindex Elaboration, warnings
5342 This switch activates warnings on missing
5343 @code{Elaborate_All} and @code{Elaborate} pragmas.
5344 See the section in this guide on elaboration checking for details on
5345 when such pragmas should be used. In dynamic elaboration mode, this switch
5346 generations warnings about the need to add elaboration pragmas. Note however,
5347 that if you blindly follow these warnings, and add @code{Elaborate_All}
5348 warnings wherever they are recommended, you basically end up with the
5349 equivalent of the static elaboration model, which may not be what you want for
5350 legacy code for which the static model does not work.
5352 For the static model, the messages generated are labeled "info:" (for
5353 information messages). They are not warnings to add elaboration pragmas,
5354 merely informational messages showing what implicit elaboration pragmas
5355 have been added, for use in analyzing elaboration circularity problems.
5357 Warnings are also generated if you
5358 are using the static mode of elaboration, and a @code{pragma Elaborate}
5359 is encountered. The default is that such warnings
5361 This warning is not automatically turned on by the use of @option{-gnatwa}.
5364 @emph{Suppress warnings for elaboration pragmas.}
5365 @cindex @option{-gnatwL} (@command{gcc})
5366 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5367 See the section in this guide on elaboration checking for details on
5368 when such pragmas should be used.
5371 @emph{Activate warnings on modified but unreferenced variables.}
5372 @cindex @option{-gnatwm} (@command{gcc})
5373 This switch activates warnings for variables that are assigned (using
5374 an initialization value or with one or more assignment statements) but
5375 whose value is never read. The warning is suppressed for volatile
5376 variables and also for variables that are renamings of other variables
5377 or for which an address clause is given.
5378 This warning can also be turned on using @option{-gnatwa}.
5379 The default is that these warnings are not given.
5382 @emph{Disable warnings on modified but unreferenced variables.}
5383 @cindex @option{-gnatwM} (@command{gcc})
5384 This switch disables warnings for variables that are assigned or
5385 initialized, but never read.
5388 @emph{Activate warnings on suspicious modulus values.}
5389 @cindex @option{-gnatw.m} (@command{gcc})
5390 This switch activates warnings for modulus values that seem suspicious.
5391 The cases caught are where the size is the same as the modulus (e.g.
5392 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5393 with no size clause. The guess in both cases is that 2**x was intended
5394 rather than x. The default is that these warnings are given.
5397 @emph{Disable warnings on suspicious modulus values.}
5398 @cindex @option{-gnatw.M} (@command{gcc})
5399 This switch disables warnings for suspicious modulus values.
5402 @emph{Set normal warnings mode.}
5403 @cindex @option{-gnatwn} (@command{gcc})
5404 This switch sets normal warning mode, in which enabled warnings are
5405 issued and treated as warnings rather than errors. This is the default
5406 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5407 an explicit @option{-gnatws} or
5408 @option{-gnatwe}. It also cancels the effect of the
5409 implicit @option{-gnatwe} that is activated by the
5410 use of @option{-gnatg}.
5413 @emph{Activate warnings on address clause overlays.}
5414 @cindex @option{-gnatwo} (@command{gcc})
5415 @cindex Address Clauses, warnings
5416 This switch activates warnings for possibly unintended initialization
5417 effects of defining address clauses that cause one variable to overlap
5418 another. The default is that such warnings are generated.
5419 This warning can also be turned on using @option{-gnatwa}.
5422 @emph{Suppress warnings on address clause overlays.}
5423 @cindex @option{-gnatwO} (@command{gcc})
5424 This switch suppresses warnings on possibly unintended initialization
5425 effects of defining address clauses that cause one variable to overlap
5429 @emph{Activate warnings on modified but unreferenced out parameters.}
5430 @cindex @option{-gnatw.o} (@command{gcc})
5431 This switch activates warnings for variables that are modified by using
5432 them as actuals for a call to a procedure with an out mode formal, where
5433 the resulting assigned value is never read. It is applicable in the case
5434 where there is more than one out mode formal. If there is only one out
5435 mode formal, the warning is issued by default (controlled by -gnatwu).
5436 The warning is suppressed for volatile
5437 variables and also for variables that are renamings of other variables
5438 or for which an address clause is given.
5439 The default is that these warnings are not given. Note that this warning
5440 is not included in -gnatwa, it must be activated explicitly.
5443 @emph{Disable warnings on modified but unreferenced out parameters.}
5444 @cindex @option{-gnatw.O} (@command{gcc})
5445 This switch suppresses warnings for variables that are modified by using
5446 them as actuals for a call to a procedure with an out mode formal, where
5447 the resulting assigned value is never read.
5450 @emph{Activate warnings on ineffective pragma Inlines.}
5451 @cindex @option{-gnatwp} (@command{gcc})
5452 @cindex Inlining, warnings
5453 This switch activates warnings for failure of front end inlining
5454 (activated by @option{-gnatN}) to inline a particular call. There are
5455 many reasons for not being able to inline a call, including most
5456 commonly that the call is too complex to inline. The default is
5457 that such warnings are not given.
5458 This warning can also be turned on using @option{-gnatwa}.
5459 Warnings on ineffective inlining by the gcc back-end can be activated
5460 separately, using the gcc switch -Winline.
5463 @emph{Suppress warnings on ineffective pragma Inlines.}
5464 @cindex @option{-gnatwP} (@command{gcc})
5465 This switch suppresses warnings on ineffective pragma Inlines. If the
5466 inlining mechanism cannot inline a call, it will simply ignore the
5470 @emph{Activate warnings on parameter ordering.}
5471 @cindex @option{-gnatw.p} (@command{gcc})
5472 @cindex Parameter order, warnings
5473 This switch activates warnings for cases of suspicious parameter
5474 ordering when the list of arguments are all simple identifiers that
5475 match the names of the formals, but are in a different order. The
5476 warning is suppressed if any use of named parameter notation is used,
5477 so this is the appropriate way to suppress a false positive (and
5478 serves to emphasize that the "misordering" is deliberate). The
5480 that such warnings are not given.
5481 This warning can also be turned on using @option{-gnatwa}.
5484 @emph{Suppress warnings on parameter ordering.}
5485 @cindex @option{-gnatw.P} (@command{gcc})
5486 This switch suppresses warnings on cases of suspicious parameter
5490 @emph{Activate warnings on questionable missing parentheses.}
5491 @cindex @option{-gnatwq} (@command{gcc})
5492 @cindex Parentheses, warnings
5493 This switch activates warnings for cases where parentheses are not used and
5494 the result is potential ambiguity from a readers point of view. For example
5495 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5496 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5497 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5498 follow the rule of always parenthesizing to make the association clear, and
5499 this warning switch warns if such parentheses are not present. The default
5500 is that these warnings are given.
5501 This warning can also be turned on using @option{-gnatwa}.
5504 @emph{Suppress warnings on questionable missing parentheses.}
5505 @cindex @option{-gnatwQ} (@command{gcc})
5506 This switch suppresses warnings for cases where the association is not
5507 clear and the use of parentheses is preferred.
5510 @emph{Activate warnings on redundant constructs.}
5511 @cindex @option{-gnatwr} (@command{gcc})
5512 This switch activates warnings for redundant constructs. The following
5513 is the current list of constructs regarded as redundant:
5517 Assignment of an item to itself.
5519 Type conversion that converts an expression to its own type.
5521 Use of the attribute @code{Base} where @code{typ'Base} is the same
5524 Use of pragma @code{Pack} when all components are placed by a record
5525 representation clause.
5527 Exception handler containing only a reraise statement (raise with no
5528 operand) which has no effect.
5530 Use of the operator abs on an operand that is known at compile time
5533 Comparison of boolean expressions to an explicit True value.
5536 This warning can also be turned on using @option{-gnatwa}.
5537 The default is that warnings for redundant constructs are not given.
5540 @emph{Suppress warnings on redundant constructs.}
5541 @cindex @option{-gnatwR} (@command{gcc})
5542 This switch suppresses warnings for redundant constructs.
5545 @emph{Activate warnings for object renaming function.}
5546 @cindex @option{-gnatw.r} (@command{gcc})
5547 This switch activates warnings for an object renaming that renames a
5548 function call, which is equivalent to a constant declaration (as
5549 opposed to renaming the function itself). The default is that these
5550 warnings are given. This warning can also be turned on using
5554 @emph{Suppress warnings for object renaming function.}
5555 @cindex @option{-gnatwT} (@command{gcc})
5556 This switch suppresses warnings for object renaming function.
5559 @emph{Suppress all warnings.}
5560 @cindex @option{-gnatws} (@command{gcc})
5561 This switch completely suppresses the
5562 output of all warning messages from the GNAT front end.
5563 Note that it does not suppress warnings from the @command{gcc} back end.
5564 To suppress these back end warnings as well, use the switch @option{-w}
5565 in addition to @option{-gnatws}. Also this switch has no effect on the
5566 handling of style check messages.
5569 @emph{Activate warnings for tracking of deleted conditional code.}
5570 @cindex @option{-gnatwt} (@command{gcc})
5571 @cindex Deactivated code, warnings
5572 @cindex Deleted code, warnings
5573 This switch activates warnings for tracking of code in conditionals (IF and
5574 CASE statements) that is detected to be dead code which cannot be executed, and
5575 which is removed by the front end. This warning is off by default, and is not
5576 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5577 useful for detecting deactivated code in certified applications.
5580 @emph{Suppress warnings for tracking of deleted conditional code.}
5581 @cindex @option{-gnatwT} (@command{gcc})
5582 This switch suppresses warnings for tracking of deleted conditional code.
5585 @emph{Activate warnings on unused entities.}
5586 @cindex @option{-gnatwu} (@command{gcc})
5587 This switch activates warnings to be generated for entities that
5588 are declared but not referenced, and for units that are @code{with}'ed
5590 referenced. In the case of packages, a warning is also generated if
5591 no entities in the package are referenced. This means that if the package
5592 is referenced but the only references are in @code{use}
5593 clauses or @code{renames}
5594 declarations, a warning is still generated. A warning is also generated
5595 for a generic package that is @code{with}'ed but never instantiated.
5596 In the case where a package or subprogram body is compiled, and there
5597 is a @code{with} on the corresponding spec
5598 that is only referenced in the body,
5599 a warning is also generated, noting that the
5600 @code{with} can be moved to the body. The default is that
5601 such warnings are not generated.
5602 This switch also activates warnings on unreferenced formals
5603 (it includes the effect of @option{-gnatwf}).
5604 This warning can also be turned on using @option{-gnatwa}.
5607 @emph{Suppress warnings on unused entities.}
5608 @cindex @option{-gnatwU} (@command{gcc})
5609 This switch suppresses warnings for unused entities and packages.
5610 It also turns off warnings on unreferenced formals (and thus includes
5611 the effect of @option{-gnatwF}).
5614 @emph{Activate warnings on unordered enumeration types.}
5615 @cindex @option{-gnatw.u} (@command{gcc})
5616 This switch causes enumeration types to be considered as conceptually
5617 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5618 The effect is to generate warnings in clients that use explicit comparisons
5619 or subranges, since these constructs both treat objects of the type as
5620 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5621 which the type is declared, or its body or subunits.) Please refer to
5622 the description of pragma @code{Ordered} in the
5623 @cite{@value{EDITION} Reference Manual} for further details.
5626 @emph{Deactivate warnings on unordered enumeration types.}
5627 @cindex @option{-gnatw.U} (@command{gcc})
5628 This switch causes all enumeration types to be considered as ordered, so
5629 that no warnings are given for comparisons or subranges for any type.
5632 @emph{Activate warnings on unassigned variables.}
5633 @cindex @option{-gnatwv} (@command{gcc})
5634 @cindex Unassigned variable warnings
5635 This switch activates warnings for access to variables which
5636 may not be properly initialized. The default is that
5637 such warnings are generated.
5638 This warning can also be turned on using @option{-gnatwa}.
5641 @emph{Suppress warnings on unassigned variables.}
5642 @cindex @option{-gnatwV} (@command{gcc})
5643 This switch suppresses warnings for access to variables which
5644 may not be properly initialized.
5645 For variables of a composite type, the warning can also be suppressed in
5646 Ada 2005 by using a default initialization with a box. For example, if
5647 Table is an array of records whose components are only partially uninitialized,
5648 then the following code:
5650 @smallexample @c ada
5651 Tab : Table := (others => <>);
5654 will suppress warnings on subsequent statements that access components
5658 @emph{Activate warnings on wrong low bound assumption.}
5659 @cindex @option{-gnatww} (@command{gcc})
5660 @cindex String indexing warnings
5661 This switch activates warnings for indexing an unconstrained string parameter
5662 with a literal or S'Length. This is a case where the code is assuming that the
5663 low bound is one, which is in general not true (for example when a slice is
5664 passed). The default is that such warnings are generated.
5665 This warning can also be turned on using @option{-gnatwa}.
5668 @emph{Suppress warnings on wrong low bound assumption.}
5669 @cindex @option{-gnatwW} (@command{gcc})
5670 This switch suppresses warnings for indexing an unconstrained string parameter
5671 with a literal or S'Length. Note that this warning can also be suppressed
5672 in a particular case by adding an
5673 assertion that the lower bound is 1,
5674 as shown in the following example.
5676 @smallexample @c ada
5677 procedure K (S : String) is
5678 pragma Assert (S'First = 1);
5683 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5684 @cindex @option{-gnatw.w} (@command{gcc})
5685 @cindex Warnings Off control
5686 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5687 where either the pragma is entirely useless (because it suppresses no
5688 warnings), or it could be replaced by @code{pragma Unreferenced} or
5689 @code{pragma Unmodified}.The default is that these warnings are not given.
5690 Note that this warning is not included in -gnatwa, it must be
5691 activated explicitly.
5694 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5695 @cindex @option{-gnatw.W} (@command{gcc})
5696 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5699 @emph{Activate warnings on Export/Import pragmas.}
5700 @cindex @option{-gnatwx} (@command{gcc})
5701 @cindex Export/Import pragma warnings
5702 This switch activates warnings on Export/Import pragmas when
5703 the compiler detects a possible conflict between the Ada and
5704 foreign language calling sequences. For example, the use of
5705 default parameters in a convention C procedure is dubious
5706 because the C compiler cannot supply the proper default, so
5707 a warning is issued. The default is that such warnings are
5709 This warning can also be turned on using @option{-gnatwa}.
5712 @emph{Suppress warnings on Export/Import pragmas.}
5713 @cindex @option{-gnatwX} (@command{gcc})
5714 This switch suppresses warnings on Export/Import pragmas.
5715 The sense of this is that you are telling the compiler that
5716 you know what you are doing in writing the pragma, and it
5717 should not complain at you.
5720 @emph{Activate warnings for No_Exception_Propagation mode.}
5721 @cindex @option{-gnatwm} (@command{gcc})
5722 This switch activates warnings for exception usage when pragma Restrictions
5723 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5724 explicit exception raises which are not covered by a local handler, and for
5725 exception handlers which do not cover a local raise. The default is that these
5726 warnings are not given.
5729 @emph{Disable warnings for No_Exception_Propagation mode.}
5730 This switch disables warnings for exception usage when pragma Restrictions
5731 (No_Exception_Propagation) is in effect.
5734 @emph{Activate warnings for Ada 2005 compatibility issues.}
5735 @cindex @option{-gnatwy} (@command{gcc})
5736 @cindex Ada 2005 compatibility issues warnings
5737 For the most part Ada 2005 is upwards compatible with Ada 95,
5738 but there are some exceptions (for example the fact that
5739 @code{interface} is now a reserved word in Ada 2005). This
5740 switch activates several warnings to help in identifying
5741 and correcting such incompatibilities. The default is that
5742 these warnings are generated. Note that at one point Ada 2005
5743 was called Ada 0Y, hence the choice of character.
5744 This warning can also be turned on using @option{-gnatwa}.
5747 @emph{Disable warnings for Ada 2005 compatibility issues.}
5748 @cindex @option{-gnatwY} (@command{gcc})
5749 @cindex Ada 2005 compatibility issues warnings
5750 This switch suppresses several warnings intended to help in identifying
5751 incompatibilities between Ada 95 and Ada 2005.
5754 @emph{Activate warnings on unchecked conversions.}
5755 @cindex @option{-gnatwz} (@command{gcc})
5756 @cindex Unchecked_Conversion warnings
5757 This switch activates warnings for unchecked conversions
5758 where the types are known at compile time to have different
5760 is that such warnings are generated. Warnings are also
5761 generated for subprogram pointers with different conventions,
5762 and, on VMS only, for data pointers with different conventions.
5763 This warning can also be turned on using @option{-gnatwa}.
5766 @emph{Suppress warnings on unchecked conversions.}
5767 @cindex @option{-gnatwZ} (@command{gcc})
5768 This switch suppresses warnings for unchecked conversions
5769 where the types are known at compile time to have different
5770 sizes or conventions.
5772 @item ^-Wunused^WARNINGS=UNUSED^
5773 @cindex @option{-Wunused}
5774 The warnings controlled by the @option{-gnatw} switch are generated by
5775 the front end of the compiler. The @option{GCC} back end can provide
5776 additional warnings and they are controlled by the @option{-W} switch.
5777 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5778 warnings for entities that are declared but not referenced.
5780 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5781 @cindex @option{-Wuninitialized}
5782 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5783 the back end warning for uninitialized variables. This switch must be
5784 used in conjunction with an optimization level greater than zero.
5786 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5787 @cindex @option{-Wall}
5788 This switch enables all the above warnings from the @option{GCC} back end.
5789 The code generator detects a number of warning situations that are missed
5790 by the @option{GNAT} front end, and this switch can be used to activate them.
5791 The use of this switch also sets the default front end warning mode to
5792 @option{-gnatwa}, that is, most front end warnings activated as well.
5794 @item ^-w^/NO_BACK_END_WARNINGS^
5796 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5797 The use of this switch also sets the default front end warning mode to
5798 @option{-gnatws}, that is, front end warnings suppressed as well.
5804 A string of warning parameters can be used in the same parameter. For example:
5811 will turn on all optional warnings except for elaboration pragma warnings,
5812 and also specify that warnings should be treated as errors.
5814 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5839 @node Debugging and Assertion Control
5840 @subsection Debugging and Assertion Control
5844 @cindex @option{-gnata} (@command{gcc})
5850 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5851 are ignored. This switch, where @samp{a} stands for assert, causes
5852 @code{Assert} and @code{Debug} pragmas to be activated.
5854 The pragmas have the form:
5858 @b{pragma} Assert (@var{Boolean-expression} @r{[},
5859 @var{static-string-expression}@r{]})
5860 @b{pragma} Debug (@var{procedure call})
5865 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5866 If the result is @code{True}, the pragma has no effect (other than
5867 possible side effects from evaluating the expression). If the result is
5868 @code{False}, the exception @code{Assert_Failure} declared in the package
5869 @code{System.Assertions} is
5870 raised (passing @var{static-string-expression}, if present, as the
5871 message associated with the exception). If no string expression is
5872 given the default is a string giving the file name and line number
5875 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5876 @code{pragma Debug} may appear within a declaration sequence, allowing
5877 debugging procedures to be called between declarations.
5880 @item /DEBUG@r{[}=debug-level@r{]}
5882 Specifies how much debugging information is to be included in
5883 the resulting object file where 'debug-level' is one of the following:
5886 Include both debugger symbol records and traceback
5888 This is the default setting.
5890 Include both debugger symbol records and traceback in
5893 Excludes both debugger symbol records and traceback
5894 the object file. Same as /NODEBUG.
5896 Includes only debugger symbol records in the object
5897 file. Note that this doesn't include traceback information.
5902 @node Validity Checking
5903 @subsection Validity Checking
5904 @findex Validity Checking
5907 The Ada Reference Manual defines the concept of invalid values (see
5908 RM 13.9.1). The primary source of invalid values is uninitialized
5909 variables. A scalar variable that is left uninitialized may contain
5910 an invalid value; the concept of invalid does not apply to access or
5913 It is an error to read an invalid value, but the RM does not require
5914 run-time checks to detect such errors, except for some minimal
5915 checking to prevent erroneous execution (i.e. unpredictable
5916 behavior). This corresponds to the @option{-gnatVd} switch below,
5917 which is the default. For example, by default, if the expression of a
5918 case statement is invalid, it will raise Constraint_Error rather than
5919 causing a wild jump, and if an array index on the left-hand side of an
5920 assignment is invalid, it will raise Constraint_Error rather than
5921 overwriting an arbitrary memory location.
5923 The @option{-gnatVa} may be used to enable additional validity checks,
5924 which are not required by the RM. These checks are often very
5925 expensive (which is why the RM does not require them). These checks
5926 are useful in tracking down uninitialized variables, but they are
5927 not usually recommended for production builds.
5929 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
5930 control; you can enable whichever validity checks you desire. However,
5931 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5932 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5933 sufficient for non-debugging use.
5935 The @option{-gnatB} switch tells the compiler to assume that all
5936 values are valid (that is, within their declared subtype range)
5937 except in the context of a use of the Valid attribute. This means
5938 the compiler can generate more efficient code, since the range
5939 of values is better known at compile time. However, an uninitialized
5940 variable can cause wild jumps and memory corruption in this mode.
5942 The @option{-gnatV^@var{x}^^} switch allows control over the validity
5943 checking mode as described below.
5945 The @code{x} argument is a string of letters that
5946 indicate validity checks that are performed or not performed in addition
5947 to the default checks required by Ada as described above.
5950 The options allowed for this qualifier
5951 indicate validity checks that are performed or not performed in addition
5952 to the default checks required by Ada as described above.
5958 @emph{All validity checks.}
5959 @cindex @option{-gnatVa} (@command{gcc})
5960 All validity checks are turned on.
5962 That is, @option{-gnatVa} is
5963 equivalent to @option{gnatVcdfimorst}.
5967 @emph{Validity checks for copies.}
5968 @cindex @option{-gnatVc} (@command{gcc})
5969 The right hand side of assignments, and the initializing values of
5970 object declarations are validity checked.
5973 @emph{Default (RM) validity checks.}
5974 @cindex @option{-gnatVd} (@command{gcc})
5975 Some validity checks are done by default following normal Ada semantics
5977 A check is done in case statements that the expression is within the range
5978 of the subtype. If it is not, Constraint_Error is raised.
5979 For assignments to array components, a check is done that the expression used
5980 as index is within the range. If it is not, Constraint_Error is raised.
5981 Both these validity checks may be turned off using switch @option{-gnatVD}.
5982 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5983 switch @option{-gnatVd} will leave the checks turned on.
5984 Switch @option{-gnatVD} should be used only if you are sure that all such
5985 expressions have valid values. If you use this switch and invalid values
5986 are present, then the program is erroneous, and wild jumps or memory
5987 overwriting may occur.
5990 @emph{Validity checks for elementary components.}
5991 @cindex @option{-gnatVe} (@command{gcc})
5992 In the absence of this switch, assignments to record or array components are
5993 not validity checked, even if validity checks for assignments generally
5994 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5995 require valid data, but assignment of individual components does. So for
5996 example, there is a difference between copying the elements of an array with a
5997 slice assignment, compared to assigning element by element in a loop. This
5998 switch allows you to turn off validity checking for components, even when they
5999 are assigned component by component.
6002 @emph{Validity checks for floating-point values.}
6003 @cindex @option{-gnatVf} (@command{gcc})
6004 In the absence of this switch, validity checking occurs only for discrete
6005 values. If @option{-gnatVf} is specified, then validity checking also applies
6006 for floating-point values, and NaNs and infinities are considered invalid,
6007 as well as out of range values for constrained types. Note that this means
6008 that standard IEEE infinity mode is not allowed. The exact contexts
6009 in which floating-point values are checked depends on the setting of other
6010 options. For example,
6011 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6012 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6013 (the order does not matter) specifies that floating-point parameters of mode
6014 @code{in} should be validity checked.
6017 @emph{Validity checks for @code{in} mode parameters}
6018 @cindex @option{-gnatVi} (@command{gcc})
6019 Arguments for parameters of mode @code{in} are validity checked in function
6020 and procedure calls at the point of call.
6023 @emph{Validity checks for @code{in out} mode parameters.}
6024 @cindex @option{-gnatVm} (@command{gcc})
6025 Arguments for parameters of mode @code{in out} are validity checked in
6026 procedure calls at the point of call. The @code{'m'} here stands for
6027 modify, since this concerns parameters that can be modified by the call.
6028 Note that there is no specific option to test @code{out} parameters,
6029 but any reference within the subprogram will be tested in the usual
6030 manner, and if an invalid value is copied back, any reference to it
6031 will be subject to validity checking.
6034 @emph{No validity checks.}
6035 @cindex @option{-gnatVn} (@command{gcc})
6036 This switch turns off all validity checking, including the default checking
6037 for case statements and left hand side subscripts. Note that the use of
6038 the switch @option{-gnatp} suppresses all run-time checks, including
6039 validity checks, and thus implies @option{-gnatVn}. When this switch
6040 is used, it cancels any other @option{-gnatV} previously issued.
6043 @emph{Validity checks for operator and attribute operands.}
6044 @cindex @option{-gnatVo} (@command{gcc})
6045 Arguments for predefined operators and attributes are validity checked.
6046 This includes all operators in package @code{Standard},
6047 the shift operators defined as intrinsic in package @code{Interfaces}
6048 and operands for attributes such as @code{Pos}. Checks are also made
6049 on individual component values for composite comparisons, and on the
6050 expressions in type conversions and qualified expressions. Checks are
6051 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6054 @emph{Validity checks for parameters.}
6055 @cindex @option{-gnatVp} (@command{gcc})
6056 This controls the treatment of parameters within a subprogram (as opposed
6057 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6058 of parameters on a call. If either of these call options is used, then
6059 normally an assumption is made within a subprogram that the input arguments
6060 have been validity checking at the point of call, and do not need checking
6061 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6062 is not made, and parameters are not assumed to be valid, so their validity
6063 will be checked (or rechecked) within the subprogram.
6066 @emph{Validity checks for function returns.}
6067 @cindex @option{-gnatVr} (@command{gcc})
6068 The expression in @code{return} statements in functions is validity
6072 @emph{Validity checks for subscripts.}
6073 @cindex @option{-gnatVs} (@command{gcc})
6074 All subscripts expressions are checked for validity, whether they appear
6075 on the right side or left side (in default mode only left side subscripts
6076 are validity checked).
6079 @emph{Validity checks for tests.}
6080 @cindex @option{-gnatVt} (@command{gcc})
6081 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6082 statements are checked, as well as guard expressions in entry calls.
6087 The @option{-gnatV} switch may be followed by
6088 ^a string of letters^a list of options^
6089 to turn on a series of validity checking options.
6091 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6092 specifies that in addition to the default validity checking, copies and
6093 function return expressions are to be validity checked.
6094 In order to make it easier
6095 to specify the desired combination of effects,
6097 the upper case letters @code{CDFIMORST} may
6098 be used to turn off the corresponding lower case option.
6101 the prefix @code{NO} on an option turns off the corresponding validity
6104 @item @code{NOCOPIES}
6105 @item @code{NODEFAULT}
6106 @item @code{NOFLOATS}
6107 @item @code{NOIN_PARAMS}
6108 @item @code{NOMOD_PARAMS}
6109 @item @code{NOOPERANDS}
6110 @item @code{NORETURNS}
6111 @item @code{NOSUBSCRIPTS}
6112 @item @code{NOTESTS}
6116 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6117 turns on all validity checking options except for
6118 checking of @code{@b{in out}} procedure arguments.
6120 The specification of additional validity checking generates extra code (and
6121 in the case of @option{-gnatVa} the code expansion can be substantial).
6122 However, these additional checks can be very useful in detecting
6123 uninitialized variables, incorrect use of unchecked conversion, and other
6124 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6125 is useful in conjunction with the extra validity checking, since this
6126 ensures that wherever possible uninitialized variables have invalid values.
6128 See also the pragma @code{Validity_Checks} which allows modification of
6129 the validity checking mode at the program source level, and also allows for
6130 temporary disabling of validity checks.
6132 @node Style Checking
6133 @subsection Style Checking
6134 @findex Style checking
6137 The @option{-gnaty^x^(option,option,@dots{})^} switch
6138 @cindex @option{-gnaty} (@command{gcc})
6139 causes the compiler to
6140 enforce specified style rules. A limited set of style rules has been used
6141 in writing the GNAT sources themselves. This switch allows user programs
6142 to activate all or some of these checks. If the source program fails a
6143 specified style check, an appropriate message is given, preceded by
6144 the character sequence ``(style)''. This message does not prevent
6145 successful compilation (unless the @option{-gnatwe} switch is used).
6147 Note that this is by no means intended to be a general facility for
6148 checking arbitrary coding standards. It is simply an embedding of the
6149 style rules we have chosen for the GNAT sources. If you are starting
6150 a project which does not have established style standards, you may
6151 find it useful to adopt the entire set of GNAT coding standards, or
6152 some subset of them. If you already have an established set of coding
6153 standards, then it may be that selected style checking options do
6154 indeed correspond to choices you have made, but for general checking
6155 of an existing set of coding rules, you should look to the gnatcheck
6156 tool, which is designed for that purpose.
6159 @code{(option,option,@dots{})} is a sequence of keywords
6162 The string @var{x} is a sequence of letters or digits
6164 indicating the particular style
6165 checks to be performed. The following checks are defined:
6170 @emph{Specify indentation level.}
6171 If a digit from 1-9 appears
6172 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6173 then proper indentation is checked, with the digit indicating the
6174 indentation level required. A value of zero turns off this style check.
6175 The general style of required indentation is as specified by
6176 the examples in the Ada Reference Manual. Full line comments must be
6177 aligned with the @code{--} starting on a column that is a multiple of
6178 the alignment level, or they may be aligned the same way as the following
6179 non-blank line (this is useful when full line comments appear in the middle
6183 @emph{Check attribute casing.}
6184 Attribute names, including the case of keywords such as @code{digits}
6185 used as attributes names, must be written in mixed case, that is, the
6186 initial letter and any letter following an underscore must be uppercase.
6187 All other letters must be lowercase.
6189 @item ^A^ARRAY_INDEXES^
6190 @emph{Use of array index numbers in array attributes.}
6191 When using the array attributes First, Last, Range,
6192 or Length, the index number must be omitted for one-dimensional arrays
6193 and is required for multi-dimensional arrays.
6196 @emph{Blanks not allowed at statement end.}
6197 Trailing blanks are not allowed at the end of statements. The purpose of this
6198 rule, together with h (no horizontal tabs), is to enforce a canonical format
6199 for the use of blanks to separate source tokens.
6201 @item ^B^BOOLEAN_OPERATORS^
6202 @emph{Check Boolean operators.}
6203 The use of AND/OR operators is not permitted except in the cases of modular
6204 operands, array operands, and simple stand-alone boolean variables or
6205 boolean constants. In all other cases AND THEN/OR ELSE are required.
6208 @emph{Check comments.}
6209 Comments must meet the following set of rules:
6214 The ``@code{--}'' that starts the column must either start in column one,
6215 or else at least one blank must precede this sequence.
6218 Comments that follow other tokens on a line must have at least one blank
6219 following the ``@code{--}'' at the start of the comment.
6222 Full line comments must have at least two blanks following the
6223 ``@code{--}'' that starts the comment, with the following exceptions.
6226 A line consisting only of the ``@code{--}'' characters, possibly preceded
6227 by blanks is permitted.
6230 A comment starting with ``@code{--x}'' where @code{x} is a special character
6232 This allows proper processing of the output generated by specialized tools
6233 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6235 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6236 special character is defined as being in one of the ASCII ranges
6237 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6238 Note that this usage is not permitted
6239 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6242 A line consisting entirely of minus signs, possibly preceded by blanks, is
6243 permitted. This allows the construction of box comments where lines of minus
6244 signs are used to form the top and bottom of the box.
6247 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6248 least one blank follows the initial ``@code{--}''. Together with the preceding
6249 rule, this allows the construction of box comments, as shown in the following
6252 ---------------------------
6253 -- This is a box comment --
6254 -- with two text lines. --
6255 ---------------------------
6259 @item ^d^DOS_LINE_ENDINGS^
6260 @emph{Check no DOS line terminators present.}
6261 All lines must be terminated by a single ASCII.LF
6262 character (in particular the DOS line terminator sequence CR/LF is not
6266 @emph{Check end/exit labels.}
6267 Optional labels on @code{end} statements ending subprograms and on
6268 @code{exit} statements exiting named loops, are required to be present.
6271 @emph{No form feeds or vertical tabs.}
6272 Neither form feeds nor vertical tab characters are permitted
6276 @emph{GNAT style mode}
6277 The set of style check switches is set to match that used by the GNAT sources.
6278 This may be useful when developing code that is eventually intended to be
6279 incorporated into GNAT. For further details, see GNAT sources.
6282 @emph{No horizontal tabs.}
6283 Horizontal tab characters are not permitted in the source text.
6284 Together with the b (no blanks at end of line) check, this
6285 enforces a canonical form for the use of blanks to separate
6289 @emph{Check if-then layout.}
6290 The keyword @code{then} must appear either on the same
6291 line as corresponding @code{if}, or on a line on its own, lined
6292 up under the @code{if} with at least one non-blank line in between
6293 containing all or part of the condition to be tested.
6296 @emph{check mode IN keywords}
6297 Mode @code{in} (the default mode) is not
6298 allowed to be given explicitly. @code{in out} is fine,
6299 but not @code{in} on its own.
6302 @emph{Check keyword casing.}
6303 All keywords must be in lower case (with the exception of keywords
6304 such as @code{digits} used as attribute names to which this check
6308 @emph{Check layout.}
6309 Layout of statement and declaration constructs must follow the
6310 recommendations in the Ada Reference Manual, as indicated by the
6311 form of the syntax rules. For example an @code{else} keyword must
6312 be lined up with the corresponding @code{if} keyword.
6314 There are two respects in which the style rule enforced by this check
6315 option are more liberal than those in the Ada Reference Manual. First
6316 in the case of record declarations, it is permissible to put the
6317 @code{record} keyword on the same line as the @code{type} keyword, and
6318 then the @code{end} in @code{end record} must line up under @code{type}.
6319 This is also permitted when the type declaration is split on two lines.
6320 For example, any of the following three layouts is acceptable:
6322 @smallexample @c ada
6345 Second, in the case of a block statement, a permitted alternative
6346 is to put the block label on the same line as the @code{declare} or
6347 @code{begin} keyword, and then line the @code{end} keyword up under
6348 the block label. For example both the following are permitted:
6350 @smallexample @c ada
6368 The same alternative format is allowed for loops. For example, both of
6369 the following are permitted:
6371 @smallexample @c ada
6373 Clear : while J < 10 loop
6384 @item ^Lnnn^MAX_NESTING=nnn^
6385 @emph{Set maximum nesting level}
6386 The maximum level of nesting of constructs (including subprograms, loops,
6387 blocks, packages, and conditionals) may not exceed the given value
6388 @option{nnn}. A value of zero disconnects this style check.
6390 @item ^m^LINE_LENGTH^
6391 @emph{Check maximum line length.}
6392 The length of source lines must not exceed 79 characters, including
6393 any trailing blanks. The value of 79 allows convenient display on an
6394 80 character wide device or window, allowing for possible special
6395 treatment of 80 character lines. Note that this count is of
6396 characters in the source text. This means that a tab character counts
6397 as one character in this count but a wide character sequence counts as
6398 a single character (however many bytes are needed in the encoding).
6400 @item ^Mnnn^MAX_LENGTH=nnn^
6401 @emph{Set maximum line length.}
6402 The length of lines must not exceed the
6403 given value @option{nnn}. The maximum value that can be specified is 32767.
6405 @item ^n^STANDARD_CASING^
6406 @emph{Check casing of entities in Standard.}
6407 Any identifier from Standard must be cased
6408 to match the presentation in the Ada Reference Manual (for example,
6409 @code{Integer} and @code{ASCII.NUL}).
6412 @emph{Turn off all style checks}
6413 All style check options are turned off.
6415 @item ^o^ORDERED_SUBPROGRAMS^
6416 @emph{Check order of subprogram bodies.}
6417 All subprogram bodies in a given scope
6418 (e.g.@: a package body) must be in alphabetical order. The ordering
6419 rule uses normal Ada rules for comparing strings, ignoring casing
6420 of letters, except that if there is a trailing numeric suffix, then
6421 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6424 @item ^O^OVERRIDING_INDICATORS^
6425 @emph{Check that overriding subprograms are explicitly marked as such.}
6426 The declaration of a primitive operation of a type extension that overrides
6427 an inherited operation must carry an overriding indicator.
6430 @emph{Check pragma casing.}
6431 Pragma names must be written in mixed case, that is, the
6432 initial letter and any letter following an underscore must be uppercase.
6433 All other letters must be lowercase.
6435 @item ^r^REFERENCES^
6436 @emph{Check references.}
6437 All identifier references must be cased in the same way as the
6438 corresponding declaration. No specific casing style is imposed on
6439 identifiers. The only requirement is for consistency of references
6442 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6443 @emph{Check no statements after THEN/ELSE.}
6444 No statements are allowed
6445 on the same line as a THEN or ELSE keyword following the
6446 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6447 and a special exception allows a pragma to appear after ELSE.
6450 @emph{Check separate specs.}
6451 Separate declarations (``specs'') are required for subprograms (a
6452 body is not allowed to serve as its own declaration). The only
6453 exception is that parameterless library level procedures are
6454 not required to have a separate declaration. This exception covers
6455 the most frequent form of main program procedures.
6458 @emph{Check token spacing.}
6459 The following token spacing rules are enforced:
6464 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6467 The token @code{=>} must be surrounded by spaces.
6470 The token @code{<>} must be preceded by a space or a left parenthesis.
6473 Binary operators other than @code{**} must be surrounded by spaces.
6474 There is no restriction on the layout of the @code{**} binary operator.
6477 Colon must be surrounded by spaces.
6480 Colon-equal (assignment, initialization) must be surrounded by spaces.
6483 Comma must be the first non-blank character on the line, or be
6484 immediately preceded by a non-blank character, and must be followed
6488 If the token preceding a left parenthesis ends with a letter or digit, then
6489 a space must separate the two tokens.
6492 if the token following a right parenthesis starts with a letter or digit, then
6493 a space must separate the two tokens.
6496 A right parenthesis must either be the first non-blank character on
6497 a line, or it must be preceded by a non-blank character.
6500 A semicolon must not be preceded by a space, and must not be followed by
6501 a non-blank character.
6504 A unary plus or minus may not be followed by a space.
6507 A vertical bar must be surrounded by spaces.
6510 @item ^u^UNNECESSARY_BLANK_LINES^
6511 @emph{Check unnecessary blank lines.}
6512 Unnecessary blank lines are not allowed. A blank line is considered
6513 unnecessary if it appears at the end of the file, or if more than
6514 one blank line occurs in sequence.
6516 @item ^x^XTRA_PARENS^
6517 @emph{Check extra parentheses.}
6518 Unnecessary extra level of parentheses (C-style) are not allowed
6519 around conditions in @code{if} statements, @code{while} statements and
6520 @code{exit} statements.
6522 @item ^y^ALL_BUILTIN^
6523 @emph{Set all standard style check options}
6524 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6525 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6526 @option{-gnatyS}, @option{-gnatyLnnn},
6527 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6531 @emph{Remove style check options}
6532 This causes any subsequent options in the string to act as canceling the
6533 corresponding style check option. To cancel maximum nesting level control,
6534 use @option{L} parameter witout any integer value after that, because any
6535 digit following @option{-} in the parameter string of the @option{-gnaty}
6536 option will be threated as canceling indentation check. The same is true
6537 for @option{M} parameter. @option{y} and @option{N} parameters are not
6538 allowed after @option{-}.
6541 This causes any subsequent options in the string to enable the corresponding
6542 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6548 @emph{Removing style check options}
6549 If the name of a style check is preceded by @option{NO} then the corresponding
6550 style check is turned off. For example @option{NOCOMMENTS} turns off style
6551 checking for comments.
6556 In the above rules, appearing in column one is always permitted, that is,
6557 counts as meeting either a requirement for a required preceding space,
6558 or as meeting a requirement for no preceding space.
6560 Appearing at the end of a line is also always permitted, that is, counts
6561 as meeting either a requirement for a following space, or as meeting
6562 a requirement for no following space.
6565 If any of these style rules is violated, a message is generated giving
6566 details on the violation. The initial characters of such messages are
6567 always ``@code{(style)}''. Note that these messages are treated as warning
6568 messages, so they normally do not prevent the generation of an object
6569 file. The @option{-gnatwe} switch can be used to treat warning messages,
6570 including style messages, as fatal errors.
6574 @option{-gnaty} on its own (that is not
6575 followed by any letters or digits), then the effect is equivalent
6576 to the use of @option{-gnatyy}, as described above, that is all
6577 built-in standard style check options are enabled.
6581 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6582 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6583 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6593 clears any previously set style checks.
6595 @node Run-Time Checks
6596 @subsection Run-Time Checks
6597 @cindex Division by zero
6598 @cindex Access before elaboration
6599 @cindex Checks, division by zero
6600 @cindex Checks, access before elaboration
6601 @cindex Checks, stack overflow checking
6604 By default, the following checks are suppressed: integer overflow
6605 checks, stack overflow checks, and checks for access before
6606 elaboration on subprogram calls. All other checks, including range
6607 checks and array bounds checks, are turned on by default. The
6608 following @command{gcc} switches refine this default behavior.
6613 @cindex @option{-gnatp} (@command{gcc})
6614 @cindex Suppressing checks
6615 @cindex Checks, suppressing
6617 This switch causes the unit to be compiled
6618 as though @code{pragma Suppress (All_checks)}
6619 had been present in the source. Validity checks are also eliminated (in
6620 other words @option{-gnatp} also implies @option{-gnatVn}.
6621 Use this switch to improve the performance
6622 of the code at the expense of safety in the presence of invalid data or
6625 Note that when checks are suppressed, the compiler is allowed, but not
6626 required, to omit the checking code. If the run-time cost of the
6627 checking code is zero or near-zero, the compiler will generate it even
6628 if checks are suppressed. In particular, if the compiler can prove
6629 that a certain check will necessarily fail, it will generate code to
6630 do an unconditional ``raise'', even if checks are suppressed. The
6631 compiler warns in this case. Another case in which checks may not be
6632 eliminated is when they are embedded in certain run time routines such
6633 as math library routines.
6635 Of course, run-time checks are omitted whenever the compiler can prove
6636 that they will not fail, whether or not checks are suppressed.
6638 Note that if you suppress a check that would have failed, program
6639 execution is erroneous, which means the behavior is totally
6640 unpredictable. The program might crash, or print wrong answers, or
6641 do anything else. It might even do exactly what you wanted it to do
6642 (and then it might start failing mysteriously next week or next
6643 year). The compiler will generate code based on the assumption that
6644 the condition being checked is true, which can result in disaster if
6645 that assumption is wrong.
6647 The @option{-gnatp} switch has no effect if a subsequent
6648 @option{-gnat-p} switch appears.
6651 @cindex @option{-gnat-p} (@command{gcc})
6652 @cindex Suppressing checks
6653 @cindex Checks, suppressing
6655 This switch cancels the effect of a previous @option{gnatp} switch.
6658 @cindex @option{-gnato} (@command{gcc})
6659 @cindex Overflow checks
6660 @cindex Check, overflow
6661 Enables overflow checking for integer operations.
6662 This causes GNAT to generate slower and larger executable
6663 programs by adding code to check for overflow (resulting in raising
6664 @code{Constraint_Error} as required by standard Ada
6665 semantics). These overflow checks correspond to situations in which
6666 the true value of the result of an operation may be outside the base
6667 range of the result type. The following example shows the distinction:
6669 @smallexample @c ada
6670 X1 : Integer := "Integer'Last";
6671 X2 : Integer range 1 .. 5 := "5";
6672 X3 : Integer := "Integer'Last";
6673 X4 : Integer range 1 .. 5 := "5";
6674 F : Float := "2.0E+20";
6683 Note that if explicit values are assigned at compile time, the
6684 compiler may be able to detect overflow at compile time, in which case
6685 no actual run-time checking code is required, and Constraint_Error
6686 will be raised unconditionally, with or without
6687 @option{-gnato}. That's why the assigned values in the above fragment
6688 are in quotes, the meaning is "assign a value not known to the
6689 compiler that happens to be equal to ...". The remaining discussion
6690 assumes that the compiler cannot detect the values at compile time.
6692 Here the first addition results in a value that is outside the base range
6693 of Integer, and hence requires an overflow check for detection of the
6694 constraint error. Thus the first assignment to @code{X1} raises a
6695 @code{Constraint_Error} exception only if @option{-gnato} is set.
6697 The second increment operation results in a violation of the explicit
6698 range constraint; such range checks are performed by default, and are
6699 unaffected by @option{-gnato}.
6701 The two conversions of @code{F} both result in values that are outside
6702 the base range of type @code{Integer} and thus will raise
6703 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6704 The fact that the result of the second conversion is assigned to
6705 variable @code{X4} with a restricted range is irrelevant, since the problem
6706 is in the conversion, not the assignment.
6708 Basically the rule is that in the default mode (@option{-gnato} not
6709 used), the generated code assures that all integer variables stay
6710 within their declared ranges, or within the base range if there is
6711 no declared range. This prevents any serious problems like indexes
6712 out of range for array operations.
6714 What is not checked in default mode is an overflow that results in
6715 an in-range, but incorrect value. In the above example, the assignments
6716 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6717 range of the target variable, but the result is wrong in the sense that
6718 it is too large to be represented correctly. Typically the assignment
6719 to @code{X1} will result in wrap around to the largest negative number.
6720 The conversions of @code{F} will result in some @code{Integer} value
6721 and if that integer value is out of the @code{X4} range then the
6722 subsequent assignment would generate an exception.
6724 @findex Machine_Overflows
6725 Note that the @option{-gnato} switch does not affect the code generated
6726 for any floating-point operations; it applies only to integer
6728 For floating-point, GNAT has the @code{Machine_Overflows}
6729 attribute set to @code{False} and the normal mode of operation is to
6730 generate IEEE NaN and infinite values on overflow or invalid operations
6731 (such as dividing 0.0 by 0.0).
6733 The reason that we distinguish overflow checking from other kinds of
6734 range constraint checking is that a failure of an overflow check, unlike
6735 for example the failure of a range check, can result in an incorrect
6736 value, but cannot cause random memory destruction (like an out of range
6737 subscript), or a wild jump (from an out of range case value). Overflow
6738 checking is also quite expensive in time and space, since in general it
6739 requires the use of double length arithmetic.
6741 Note again that @option{-gnato} is off by default, so overflow checking is
6742 not performed in default mode. This means that out of the box, with the
6743 default settings, GNAT does not do all the checks expected from the
6744 language description in the Ada Reference Manual. If you want all constraint
6745 checks to be performed, as described in this Manual, then you must
6746 explicitly use the -gnato switch either on the @command{gnatmake} or
6747 @command{gcc} command.
6750 @cindex @option{-gnatE} (@command{gcc})
6751 @cindex Elaboration checks
6752 @cindex Check, elaboration
6753 Enables dynamic checks for access-before-elaboration
6754 on subprogram calls and generic instantiations.
6755 Note that @option{-gnatE} is not necessary for safety, because in the
6756 default mode, GNAT ensures statically that the checks would not fail.
6757 For full details of the effect and use of this switch,
6758 @xref{Compiling Using gcc}.
6761 @cindex @option{-fstack-check} (@command{gcc})
6762 @cindex Stack Overflow Checking
6763 @cindex Checks, stack overflow checking
6764 Activates stack overflow checking. For full details of the effect and use of
6765 this switch see @ref{Stack Overflow Checking}.
6770 The setting of these switches only controls the default setting of the
6771 checks. You may modify them using either @code{Suppress} (to remove
6772 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6775 @node Using gcc for Syntax Checking
6776 @subsection Using @command{gcc} for Syntax Checking
6779 @cindex @option{-gnats} (@command{gcc})
6783 The @code{s} stands for ``syntax''.
6786 Run GNAT in syntax checking only mode. For
6787 example, the command
6790 $ gcc -c -gnats x.adb
6794 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6795 series of files in a single command
6797 , and can use wild cards to specify such a group of files.
6798 Note that you must specify the @option{-c} (compile
6799 only) flag in addition to the @option{-gnats} flag.
6802 You may use other switches in conjunction with @option{-gnats}. In
6803 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6804 format of any generated error messages.
6806 When the source file is empty or contains only empty lines and/or comments,
6807 the output is a warning:
6810 $ gcc -c -gnats -x ada toto.txt
6811 toto.txt:1:01: warning: empty file, contains no compilation units
6815 Otherwise, the output is simply the error messages, if any. No object file or
6816 ALI file is generated by a syntax-only compilation. Also, no units other
6817 than the one specified are accessed. For example, if a unit @code{X}
6818 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6819 check only mode does not access the source file containing unit
6822 @cindex Multiple units, syntax checking
6823 Normally, GNAT allows only a single unit in a source file. However, this
6824 restriction does not apply in syntax-check-only mode, and it is possible
6825 to check a file containing multiple compilation units concatenated
6826 together. This is primarily used by the @code{gnatchop} utility
6827 (@pxref{Renaming Files Using gnatchop}).
6830 @node Using gcc for Semantic Checking
6831 @subsection Using @command{gcc} for Semantic Checking
6834 @cindex @option{-gnatc} (@command{gcc})
6838 The @code{c} stands for ``check''.
6840 Causes the compiler to operate in semantic check mode,
6841 with full checking for all illegalities specified in the
6842 Ada Reference Manual, but without generation of any object code
6843 (no object file is generated).
6845 Because dependent files must be accessed, you must follow the GNAT
6846 semantic restrictions on file structuring to operate in this mode:
6850 The needed source files must be accessible
6851 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6854 Each file must contain only one compilation unit.
6857 The file name and unit name must match (@pxref{File Naming Rules}).
6860 The output consists of error messages as appropriate. No object file is
6861 generated. An @file{ALI} file is generated for use in the context of
6862 cross-reference tools, but this file is marked as not being suitable
6863 for binding (since no object file is generated).
6864 The checking corresponds exactly to the notion of
6865 legality in the Ada Reference Manual.
6867 Any unit can be compiled in semantics-checking-only mode, including
6868 units that would not normally be compiled (subunits,
6869 and specifications where a separate body is present).
6872 @node Compiling Different Versions of Ada
6873 @subsection Compiling Different Versions of Ada
6876 The switches described in this section allow you to explicitly specify
6877 the version of the Ada language that your programs are written in.
6878 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6879 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6880 indicate Ada 83 compatibility mode.
6883 @cindex Compatibility with Ada 83
6885 @item -gnat83 (Ada 83 Compatibility Mode)
6886 @cindex @option{-gnat83} (@command{gcc})
6887 @cindex ACVC, Ada 83 tests
6891 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6892 specifies that the program is to be compiled in Ada 83 mode. With
6893 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6894 semantics where this can be done easily.
6895 It is not possible to guarantee this switch does a perfect
6896 job; some subtle tests, such as are
6897 found in earlier ACVC tests (and that have been removed from the ACATS suite
6898 for Ada 95), might not compile correctly.
6899 Nevertheless, this switch may be useful in some circumstances, for example
6900 where, due to contractual reasons, existing code needs to be maintained
6901 using only Ada 83 features.
6903 With few exceptions (most notably the need to use @code{<>} on
6904 @cindex Generic formal parameters
6905 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6906 reserved words, and the use of packages
6907 with optional bodies), it is not necessary to specify the
6908 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6909 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6910 a correct Ada 83 program is usually also a correct program
6911 in these later versions of the language standard.
6912 For further information, please refer to @ref{Compatibility and Porting Guide}.
6914 @item -gnat95 (Ada 95 mode)
6915 @cindex @option{-gnat95} (@command{gcc})
6919 This switch directs the compiler to implement the Ada 95 version of the
6921 Since Ada 95 is almost completely upwards
6922 compatible with Ada 83, Ada 83 programs may generally be compiled using
6923 this switch (see the description of the @option{-gnat83} switch for further
6924 information about Ada 83 mode).
6925 If an Ada 2005 program is compiled in Ada 95 mode,
6926 uses of the new Ada 2005 features will cause error
6927 messages or warnings.
6929 This switch also can be used to cancel the effect of a previous
6930 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
6931 switch earlier in the command line.
6933 @item -gnat05 or -gnat2005 (Ada 2005 mode)
6934 @cindex @option{-gnat05} (@command{gcc})
6935 @cindex @option{-gnat2005} (@command{gcc})
6936 @cindex Ada 2005 mode
6939 This switch directs the compiler to implement the Ada 2005 version of the
6940 language, as documented in the official Ada standards document.
6941 Since Ada 2005 is almost completely upwards
6942 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6943 may generally be compiled using this switch (see the description of the
6944 @option{-gnat83} and @option{-gnat95} switches for further
6947 Note that even though Ada 2005 is the current official version of the
6948 language, GNAT still compiles in Ada 95 mode by default, so if you are
6949 using Ada 2005 features in your program, you must use this switch (or
6950 the equivalent Ada_05 or Ada_2005 configuration pragmas).
6952 @item -gnat12 or -gnat2012 (Ada 2012 mode)
6953 @cindex @option{-gnat12} (@command{gcc})
6954 @cindex @option{-gnat2012} (@command{gcc})
6955 @cindex Ada 2012 mode
6958 This switch directs the compiler to implement the Ada 2012 version of the
6960 Since Ada 2012 is almost completely upwards
6961 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
6962 Ada 83 and Ada 95 programs
6963 may generally be compiled using this switch (see the description of the
6964 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
6965 for further information).
6967 For information about the approved ``Ada Issues'' that have been incorporated
6968 into Ada 2012, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6969 Included with GNAT releases is a file @file{features-ada12} that describes
6970 the set of implemented Ada 2012 features.
6972 @item -gnatX (Enable GNAT Extensions)
6973 @cindex @option{-gnatX} (@command{gcc})
6974 @cindex Ada language extensions
6975 @cindex GNAT extensions
6978 This switch directs the compiler to implement the latest version of the
6979 language (currently Ada 2012) and also to enable certain GNAT implementation
6980 extensions that are not part of any Ada standard. For a full list of these
6981 extensions, see the GNAT reference manual.
6985 @node Character Set Control
6986 @subsection Character Set Control
6988 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6989 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6992 Normally GNAT recognizes the Latin-1 character set in source program
6993 identifiers, as described in the Ada Reference Manual.
6995 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6996 single character ^^or word^ indicating the character set, as follows:
7000 ISO 8859-1 (Latin-1) identifiers
7003 ISO 8859-2 (Latin-2) letters allowed in identifiers
7006 ISO 8859-3 (Latin-3) letters allowed in identifiers
7009 ISO 8859-4 (Latin-4) letters allowed in identifiers
7012 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7015 ISO 8859-15 (Latin-9) letters allowed in identifiers
7018 IBM PC letters (code page 437) allowed in identifiers
7021 IBM PC letters (code page 850) allowed in identifiers
7023 @item ^f^FULL_UPPER^
7024 Full upper-half codes allowed in identifiers
7027 No upper-half codes allowed in identifiers
7030 Wide-character codes (that is, codes greater than 255)
7031 allowed in identifiers
7034 @xref{Foreign Language Representation}, for full details on the
7035 implementation of these character sets.
7037 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7038 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7039 Specify the method of encoding for wide characters.
7040 @var{e} is one of the following:
7045 Hex encoding (brackets coding also recognized)
7048 Upper half encoding (brackets encoding also recognized)
7051 Shift/JIS encoding (brackets encoding also recognized)
7054 EUC encoding (brackets encoding also recognized)
7057 UTF-8 encoding (brackets encoding also recognized)
7060 Brackets encoding only (default value)
7062 For full details on these encoding
7063 methods see @ref{Wide Character Encodings}.
7064 Note that brackets coding is always accepted, even if one of the other
7065 options is specified, so for example @option{-gnatW8} specifies that both
7066 brackets and UTF-8 encodings will be recognized. The units that are
7067 with'ed directly or indirectly will be scanned using the specified
7068 representation scheme, and so if one of the non-brackets scheme is
7069 used, it must be used consistently throughout the program. However,
7070 since brackets encoding is always recognized, it may be conveniently
7071 used in standard libraries, allowing these libraries to be used with
7072 any of the available coding schemes.
7075 If no @option{-gnatW?} parameter is present, then the default
7076 representation is normally Brackets encoding only. However, if the
7077 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7078 byte order mark or BOM for UTF-8), then these three characters are
7079 skipped and the default representation for the file is set to UTF-8.
7081 Note that the wide character representation that is specified (explicitly
7082 or by default) for the main program also acts as the default encoding used
7083 for Wide_Text_IO files if not specifically overridden by a WCEM form
7087 @node File Naming Control
7088 @subsection File Naming Control
7091 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7092 @cindex @option{-gnatk} (@command{gcc})
7093 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7094 1-999, indicates the maximum allowable length of a file name (not
7095 including the @file{.ads} or @file{.adb} extension). The default is not
7096 to enable file name krunching.
7098 For the source file naming rules, @xref{File Naming Rules}.
7101 @node Subprogram Inlining Control
7102 @subsection Subprogram Inlining Control
7107 @cindex @option{-gnatn} (@command{gcc})
7109 The @code{n} here is intended to suggest the first syllable of the
7112 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7113 inlining to actually occur, optimization must be enabled. To enable
7114 inlining of subprograms specified by pragma @code{Inline},
7115 you must also specify this switch.
7116 In the absence of this switch, GNAT does not attempt
7117 inlining and does not need to access the bodies of
7118 subprograms for which @code{pragma Inline} is specified if they are not
7119 in the current unit.
7121 If you specify this switch the compiler will access these bodies,
7122 creating an extra source dependency for the resulting object file, and
7123 where possible, the call will be inlined.
7124 For further details on when inlining is possible
7125 see @ref{Inlining of Subprograms}.
7128 @cindex @option{-gnatN} (@command{gcc})
7129 This switch activates front-end inlining which also
7130 generates additional dependencies.
7132 When using a gcc-based back end (in practice this means using any version
7133 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7134 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7135 Historically front end inlining was more extensive than the gcc back end
7136 inlining, but that is no longer the case.
7139 @node Auxiliary Output Control
7140 @subsection Auxiliary Output Control
7144 @cindex @option{-gnatt} (@command{gcc})
7145 @cindex Writing internal trees
7146 @cindex Internal trees, writing to file
7147 Causes GNAT to write the internal tree for a unit to a file (with the
7148 extension @file{.adt}.
7149 This not normally required, but is used by separate analysis tools.
7151 these tools do the necessary compilations automatically, so you should
7152 not have to specify this switch in normal operation.
7153 Note that the combination of switches @option{-gnatct}
7154 generates a tree in the form required by ASIS applications.
7157 @cindex @option{-gnatu} (@command{gcc})
7158 Print a list of units required by this compilation on @file{stdout}.
7159 The listing includes all units on which the unit being compiled depends
7160 either directly or indirectly.
7163 @item -pass-exit-codes
7164 @cindex @option{-pass-exit-codes} (@command{gcc})
7165 If this switch is not used, the exit code returned by @command{gcc} when
7166 compiling multiple files indicates whether all source files have
7167 been successfully used to generate object files or not.
7169 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7170 exit status and allows an integrated development environment to better
7171 react to a compilation failure. Those exit status are:
7175 There was an error in at least one source file.
7177 At least one source file did not generate an object file.
7179 The compiler died unexpectedly (internal error for example).
7181 An object file has been generated for every source file.
7186 @node Debugging Control
7187 @subsection Debugging Control
7191 @cindex Debugging options
7194 @cindex @option{-gnatd} (@command{gcc})
7195 Activate internal debugging switches. @var{x} is a letter or digit, or
7196 string of letters or digits, which specifies the type of debugging
7197 outputs desired. Normally these are used only for internal development
7198 or system debugging purposes. You can find full documentation for these
7199 switches in the body of the @code{Debug} unit in the compiler source
7200 file @file{debug.adb}.
7204 @cindex @option{-gnatG} (@command{gcc})
7205 This switch causes the compiler to generate auxiliary output containing
7206 a pseudo-source listing of the generated expanded code. Like most Ada
7207 compilers, GNAT works by first transforming the high level Ada code into
7208 lower level constructs. For example, tasking operations are transformed
7209 into calls to the tasking run-time routines. A unique capability of GNAT
7210 is to list this expanded code in a form very close to normal Ada source.
7211 This is very useful in understanding the implications of various Ada
7212 usage on the efficiency of the generated code. There are many cases in
7213 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7214 generate a lot of run-time code. By using @option{-gnatG} you can identify
7215 these cases, and consider whether it may be desirable to modify the coding
7216 approach to improve efficiency.
7218 The optional parameter @code{nn} if present after -gnatG specifies an
7219 alternative maximum line length that overrides the normal default of 72.
7220 This value is in the range 40-999999, values less than 40 being silently
7221 reset to 40. The equal sign is optional.
7223 The format of the output is very similar to standard Ada source, and is
7224 easily understood by an Ada programmer. The following special syntactic
7225 additions correspond to low level features used in the generated code that
7226 do not have any exact analogies in pure Ada source form. The following
7227 is a partial list of these special constructions. See the spec
7228 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7230 If the switch @option{-gnatL} is used in conjunction with
7231 @cindex @option{-gnatL} (@command{gcc})
7232 @option{-gnatG}, then the original source lines are interspersed
7233 in the expanded source (as comment lines with the original line number).
7236 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7237 Shows the storage pool being used for an allocator.
7239 @item at end @var{procedure-name};
7240 Shows the finalization (cleanup) procedure for a scope.
7242 @item (if @var{expr} then @var{expr} else @var{expr})
7243 Conditional expression equivalent to the @code{x?y:z} construction in C.
7245 @item @var{target}^^^(@var{source})
7246 A conversion with floating-point truncation instead of rounding.
7248 @item @var{target}?(@var{source})
7249 A conversion that bypasses normal Ada semantic checking. In particular
7250 enumeration types and fixed-point types are treated simply as integers.
7252 @item @var{target}?^^^(@var{source})
7253 Combines the above two cases.
7255 @item @var{x} #/ @var{y}
7256 @itemx @var{x} #mod @var{y}
7257 @itemx @var{x} #* @var{y}
7258 @itemx @var{x} #rem @var{y}
7259 A division or multiplication of fixed-point values which are treated as
7260 integers without any kind of scaling.
7262 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7263 Shows the storage pool associated with a @code{free} statement.
7265 @item [subtype or type declaration]
7266 Used to list an equivalent declaration for an internally generated
7267 type that is referenced elsewhere in the listing.
7269 @c @item freeze @var{type-name} @ovar{actions}
7270 @c Expanding @ovar macro inline (explanation in macro def comments)
7271 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7272 Shows the point at which @var{type-name} is frozen, with possible
7273 associated actions to be performed at the freeze point.
7275 @item reference @var{itype}
7276 Reference (and hence definition) to internal type @var{itype}.
7278 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7279 Intrinsic function call.
7281 @item @var{label-name} : label
7282 Declaration of label @var{labelname}.
7284 @item #$ @var{subprogram-name}
7285 An implicit call to a run-time support routine
7286 (to meet the requirement of H.3.1(9) in a
7289 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7290 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7291 @var{expr}, but handled more efficiently).
7293 @item [constraint_error]
7294 Raise the @code{Constraint_Error} exception.
7296 @item @var{expression}'reference
7297 A pointer to the result of evaluating @var{expression}.
7299 @item @var{target-type}!(@var{source-expression})
7300 An unchecked conversion of @var{source-expression} to @var{target-type}.
7302 @item [@var{numerator}/@var{denominator}]
7303 Used to represent internal real literals (that) have no exact
7304 representation in base 2-16 (for example, the result of compile time
7305 evaluation of the expression 1.0/27.0).
7309 @cindex @option{-gnatD} (@command{gcc})
7310 When used in conjunction with @option{-gnatG}, this switch causes
7311 the expanded source, as described above for
7312 @option{-gnatG} to be written to files with names
7313 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7314 instead of to the standard output file. For
7315 example, if the source file name is @file{hello.adb}, then a file
7316 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written. The debugging
7317 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7318 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7319 you to do source level debugging using the generated code which is
7320 sometimes useful for complex code, for example to find out exactly
7321 which part of a complex construction raised an exception. This switch
7322 also suppress generation of cross-reference information (see
7323 @option{-gnatx}) since otherwise the cross-reference information
7324 would refer to the @file{^.dg^.DG^} file, which would cause
7325 confusion since this is not the original source file.
7327 Note that @option{-gnatD} actually implies @option{-gnatG}
7328 automatically, so it is not necessary to give both options.
7329 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7331 If the switch @option{-gnatL} is used in conjunction with
7332 @cindex @option{-gnatL} (@command{gcc})
7333 @option{-gnatDG}, then the original source lines are interspersed
7334 in the expanded source (as comment lines with the original line number).
7336 The optional parameter @code{nn} if present after -gnatD specifies an
7337 alternative maximum line length that overrides the normal default of 72.
7338 This value is in the range 40-999999, values less than 40 being silently
7339 reset to 40. The equal sign is optional.
7342 @cindex @option{-gnatr} (@command{gcc})
7343 @cindex pragma Restrictions
7344 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7345 so that violation of restrictions causes warnings rather than illegalities.
7346 This is useful during the development process when new restrictions are added
7347 or investigated. The switch also causes pragma Profile to be treated as
7348 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7349 restriction warnings rather than restrictions.
7352 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7353 @cindex @option{-gnatR} (@command{gcc})
7354 This switch controls output from the compiler of a listing showing
7355 representation information for declared types and objects. For
7356 @option{-gnatR0}, no information is output (equivalent to omitting
7357 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7358 so @option{-gnatR} with no parameter has the same effect), size and alignment
7359 information is listed for declared array and record types. For
7360 @option{-gnatR2}, size and alignment information is listed for all
7361 declared types and objects. Finally @option{-gnatR3} includes symbolic
7362 expressions for values that are computed at run time for
7363 variant records. These symbolic expressions have a mostly obvious
7364 format with #n being used to represent the value of the n'th
7365 discriminant. See source files @file{repinfo.ads/adb} in the
7366 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7367 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7368 the output is to a file with the name @file{^file.rep^file_REP^} where
7369 file is the name of the corresponding source file.
7372 @item /REPRESENTATION_INFO
7373 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7374 This qualifier controls output from the compiler of a listing showing
7375 representation information for declared types and objects. For
7376 @option{/REPRESENTATION_INFO=NONE}, no information is output
7377 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7378 @option{/REPRESENTATION_INFO} without option is equivalent to
7379 @option{/REPRESENTATION_INFO=ARRAYS}.
7380 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7381 information is listed for declared array and record types. For
7382 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7383 is listed for all expression information for values that are computed
7384 at run time for variant records. These symbolic expressions have a mostly
7385 obvious format with #n being used to represent the value of the n'th
7386 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7387 @code{GNAT} sources for full details on the format of
7388 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7389 If _FILE is added at the end of an option
7390 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7391 then the output is to a file with the name @file{file_REP} where
7392 file is the name of the corresponding source file.
7394 Note that it is possible for record components to have zero size. In
7395 this case, the component clause uses an obvious extension of permitted
7396 Ada syntax, for example @code{at 0 range 0 .. -1}.
7398 Representation information requires that code be generated (since it is the
7399 code generator that lays out complex data structures). If an attempt is made
7400 to output representation information when no code is generated, for example
7401 when a subunit is compiled on its own, then no information can be generated
7402 and the compiler outputs a message to this effect.
7405 @cindex @option{-gnatS} (@command{gcc})
7406 The use of the switch @option{-gnatS} for an
7407 Ada compilation will cause the compiler to output a
7408 representation of package Standard in a form very
7409 close to standard Ada. It is not quite possible to
7410 do this entirely in standard Ada (since new
7411 numeric base types cannot be created in standard
7412 Ada), but the output is easily
7413 readable to any Ada programmer, and is useful to
7414 determine the characteristics of target dependent
7415 types in package Standard.
7418 @cindex @option{-gnatx} (@command{gcc})
7419 Normally the compiler generates full cross-referencing information in
7420 the @file{ALI} file. This information is used by a number of tools,
7421 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7422 suppresses this information. This saves some space and may slightly
7423 speed up compilation, but means that these tools cannot be used.
7426 @node Exception Handling Control
7427 @subsection Exception Handling Control
7430 GNAT uses two methods for handling exceptions at run-time. The
7431 @code{setjmp/longjmp} method saves the context when entering
7432 a frame with an exception handler. Then when an exception is
7433 raised, the context can be restored immediately, without the
7434 need for tracing stack frames. This method provides very fast
7435 exception propagation, but introduces significant overhead for
7436 the use of exception handlers, even if no exception is raised.
7438 The other approach is called ``zero cost'' exception handling.
7439 With this method, the compiler builds static tables to describe
7440 the exception ranges. No dynamic code is required when entering
7441 a frame containing an exception handler. When an exception is
7442 raised, the tables are used to control a back trace of the
7443 subprogram invocation stack to locate the required exception
7444 handler. This method has considerably poorer performance for
7445 the propagation of exceptions, but there is no overhead for
7446 exception handlers if no exception is raised. Note that in this
7447 mode and in the context of mixed Ada and C/C++ programming,
7448 to propagate an exception through a C/C++ code, the C/C++ code
7449 must be compiled with the @option{-funwind-tables} GCC's
7452 The following switches may be used to control which of the
7453 two exception handling methods is used.
7459 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7460 This switch causes the setjmp/longjmp run-time (when available) to be used
7461 for exception handling. If the default
7462 mechanism for the target is zero cost exceptions, then
7463 this switch can be used to modify this default, and must be
7464 used for all units in the partition.
7465 This option is rarely used. One case in which it may be
7466 advantageous is if you have an application where exception
7467 raising is common and the overall performance of the
7468 application is improved by favoring exception propagation.
7471 @cindex @option{--RTS=zcx} (@command{gnatmake})
7472 @cindex Zero Cost Exceptions
7473 This switch causes the zero cost approach to be used
7474 for exception handling. If this is the default mechanism for the
7475 target (see below), then this switch is unneeded. If the default
7476 mechanism for the target is setjmp/longjmp exceptions, then
7477 this switch can be used to modify this default, and must be
7478 used for all units in the partition.
7479 This option can only be used if the zero cost approach
7480 is available for the target in use, otherwise it will generate an error.
7484 The same option @option{--RTS} must be used both for @command{gcc}
7485 and @command{gnatbind}. Passing this option to @command{gnatmake}
7486 (@pxref{Switches for gnatmake}) will ensure the required consistency
7487 through the compilation and binding steps.
7489 @node Units to Sources Mapping Files
7490 @subsection Units to Sources Mapping Files
7494 @item -gnatem=@var{path}
7495 @cindex @option{-gnatem} (@command{gcc})
7496 A mapping file is a way to communicate to the compiler two mappings:
7497 from unit names to file names (without any directory information) and from
7498 file names to path names (with full directory information). These mappings
7499 are used by the compiler to short-circuit the path search.
7501 The use of mapping files is not required for correct operation of the
7502 compiler, but mapping files can improve efficiency, particularly when
7503 sources are read over a slow network connection. In normal operation,
7504 you need not be concerned with the format or use of mapping files,
7505 and the @option{-gnatem} switch is not a switch that you would use
7506 explicitly. It is intended primarily for use by automatic tools such as
7507 @command{gnatmake} running under the project file facility. The
7508 description here of the format of mapping files is provided
7509 for completeness and for possible use by other tools.
7511 A mapping file is a sequence of sets of three lines. In each set, the
7512 first line is the unit name, in lower case, with @code{%s} appended
7513 for specs and @code{%b} appended for bodies; the second line is the
7514 file name; and the third line is the path name.
7520 /gnat/project1/sources/main.2.ada
7523 When the switch @option{-gnatem} is specified, the compiler will
7524 create in memory the two mappings from the specified file. If there is
7525 any problem (nonexistent file, truncated file or duplicate entries),
7526 no mapping will be created.
7528 Several @option{-gnatem} switches may be specified; however, only the
7529 last one on the command line will be taken into account.
7531 When using a project file, @command{gnatmake} creates a temporary
7532 mapping file and communicates it to the compiler using this switch.
7536 @node Integrated Preprocessing
7537 @subsection Integrated Preprocessing
7540 GNAT sources may be preprocessed immediately before compilation.
7541 In this case, the actual
7542 text of the source is not the text of the source file, but is derived from it
7543 through a process called preprocessing. Integrated preprocessing is specified
7544 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7545 indicates, through a text file, the preprocessing data to be used.
7546 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7549 Note that when integrated preprocessing is used, the output from the
7550 preprocessor is not written to any external file. Instead it is passed
7551 internally to the compiler. If you need to preserve the result of
7552 preprocessing in a file, then you should use @command{gnatprep}
7553 to perform the desired preprocessing in stand-alone mode.
7556 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7557 used when Integrated Preprocessing is used. The reason is that preprocessing
7558 with another Preprocessing Data file without changing the sources will
7559 not trigger recompilation without this switch.
7562 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7563 always trigger recompilation for sources that are preprocessed,
7564 because @command{gnatmake} cannot compute the checksum of the source after
7568 The actual preprocessing function is described in details in section
7569 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7570 preprocessing is triggered and parameterized.
7574 @item -gnatep=@var{file}
7575 @cindex @option{-gnatep} (@command{gcc})
7576 This switch indicates to the compiler the file name (without directory
7577 information) of the preprocessor data file to use. The preprocessor data file
7578 should be found in the source directories.
7581 A preprocessing data file is a text file with significant lines indicating
7582 how should be preprocessed either a specific source or all sources not
7583 mentioned in other lines. A significant line is a nonempty, non-comment line.
7584 Comments are similar to Ada comments.
7587 Each significant line starts with either a literal string or the character '*'.
7588 A literal string is the file name (without directory information) of the source
7589 to preprocess. A character '*' indicates the preprocessing for all the sources
7590 that are not specified explicitly on other lines (order of the lines is not
7591 significant). It is an error to have two lines with the same file name or two
7592 lines starting with the character '*'.
7595 After the file name or the character '*', another optional literal string
7596 indicating the file name of the definition file to be used for preprocessing
7597 (@pxref{Form of Definitions File}). The definition files are found by the
7598 compiler in one of the source directories. In some cases, when compiling
7599 a source in a directory other than the current directory, if the definition
7600 file is in the current directory, it may be necessary to add the current
7601 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7602 the compiler would not find the definition file.
7605 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7606 be found. Those ^switches^switches^ are:
7611 Causes both preprocessor lines and the lines deleted by
7612 preprocessing to be replaced by blank lines, preserving the line number.
7613 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7614 it cancels the effect of @option{-c}.
7617 Causes both preprocessor lines and the lines deleted
7618 by preprocessing to be retained as comments marked
7619 with the special string ``@code{--! }''.
7621 @item -Dsymbol=value
7622 Define or redefine a symbol, associated with value. A symbol is an Ada
7623 identifier, or an Ada reserved word, with the exception of @code{if},
7624 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7625 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7626 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7627 same name defined in a definition file.
7630 Causes a sorted list of symbol names and values to be
7631 listed on the standard output file.
7634 Causes undefined symbols to be treated as having the value @code{FALSE}
7636 of a preprocessor test. In the absence of this option, an undefined symbol in
7637 a @code{#if} or @code{#elsif} test will be treated as an error.
7642 Examples of valid lines in a preprocessor data file:
7645 "toto.adb" "prep.def" -u
7646 -- preprocess "toto.adb", using definition file "prep.def",
7647 -- undefined symbol are False.
7650 -- preprocess all other sources without a definition file;
7651 -- suppressed lined are commented; symbol VERSION has the value V101.
7653 "titi.adb" "prep2.def" -s
7654 -- preprocess "titi.adb", using definition file "prep2.def";
7655 -- list all symbols with their values.
7658 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7659 @cindex @option{-gnateD} (@command{gcc})
7660 Define or redefine a preprocessing symbol, associated with value. If no value
7661 is given on the command line, then the value of the symbol is @code{True}.
7662 A symbol is an identifier, following normal Ada (case-insensitive)
7663 rules for its syntax, and value is any sequence (including an empty sequence)
7664 of characters from the set (letters, digits, period, underline).
7665 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7666 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7669 A symbol declared with this ^switch^switch^ on the command line replaces a
7670 symbol with the same name either in a definition file or specified with a
7671 ^switch^switch^ -D in the preprocessor data file.
7674 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7677 When integrated preprocessing is performed and the preprocessor modifies
7678 the source text, write the result of this preprocessing into a file
7679 <source>^.prep^_prep^.
7683 @node Code Generation Control
7684 @subsection Code Generation Control
7688 The GCC technology provides a wide range of target dependent
7689 @option{-m} switches for controlling
7690 details of code generation with respect to different versions of
7691 architectures. This includes variations in instruction sets (e.g.@:
7692 different members of the power pc family), and different requirements
7693 for optimal arrangement of instructions (e.g.@: different members of
7694 the x86 family). The list of available @option{-m} switches may be
7695 found in the GCC documentation.
7697 Use of these @option{-m} switches may in some cases result in improved
7700 The GNAT Pro technology is tested and qualified without any
7701 @option{-m} switches,
7702 so generally the most reliable approach is to avoid the use of these
7703 switches. However, we generally expect most of these switches to work
7704 successfully with GNAT Pro, and many customers have reported successful
7705 use of these options.
7707 Our general advice is to avoid the use of @option{-m} switches unless
7708 special needs lead to requirements in this area. In particular,
7709 there is no point in using @option{-m} switches to improve performance
7710 unless you actually see a performance improvement.
7714 @subsection Return Codes
7715 @cindex Return Codes
7716 @cindex @option{/RETURN_CODES=VMS}
7719 On VMS, GNAT compiled programs return POSIX-style codes by default,
7720 e.g.@: @option{/RETURN_CODES=POSIX}.
7722 To enable VMS style return codes, use GNAT BIND and LINK with the option
7723 @option{/RETURN_CODES=VMS}. For example:
7726 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7727 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7731 Programs built with /RETURN_CODES=VMS are suitable to be called in
7732 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7733 are suitable for spawning with appropriate GNAT RTL routines.
7737 @node Search Paths and the Run-Time Library (RTL)
7738 @section Search Paths and the Run-Time Library (RTL)
7741 With the GNAT source-based library system, the compiler must be able to
7742 find source files for units that are needed by the unit being compiled.
7743 Search paths are used to guide this process.
7745 The compiler compiles one source file whose name must be given
7746 explicitly on the command line. In other words, no searching is done
7747 for this file. To find all other source files that are needed (the most
7748 common being the specs of units), the compiler examines the following
7749 directories, in the following order:
7753 The directory containing the source file of the main unit being compiled
7754 (the file name on the command line).
7757 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7758 @command{gcc} command line, in the order given.
7761 @findex ADA_PRJ_INCLUDE_FILE
7762 Each of the directories listed in the text file whose name is given
7763 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7766 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7767 driver when project files are used. It should not normally be set
7771 @findex ADA_INCLUDE_PATH
7772 Each of the directories listed in the value of the
7773 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7775 Construct this value
7776 exactly as the @env{PATH} environment variable: a list of directory
7777 names separated by colons (semicolons when working with the NT version).
7780 Normally, define this value as a logical name containing a comma separated
7781 list of directory names.
7783 This variable can also be defined by means of an environment string
7784 (an argument to the HP C exec* set of functions).
7788 DEFINE ANOTHER_PATH FOO:[BAG]
7789 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7792 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7793 first, followed by the standard Ada
7794 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7795 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7796 (Text_IO, Sequential_IO, etc)
7797 instead of the standard Ada packages. Thus, in order to get the standard Ada
7798 packages by default, ADA_INCLUDE_PATH must be redefined.
7802 The content of the @file{ada_source_path} file which is part of the GNAT
7803 installation tree and is used to store standard libraries such as the
7804 GNAT Run Time Library (RTL) source files.
7806 @ref{Installing a library}
7811 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7812 inhibits the use of the directory
7813 containing the source file named in the command line. You can still
7814 have this directory on your search path, but in this case it must be
7815 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7817 Specifying the switch @option{-nostdinc}
7818 inhibits the search of the default location for the GNAT Run Time
7819 Library (RTL) source files.
7821 The compiler outputs its object files and ALI files in the current
7824 Caution: The object file can be redirected with the @option{-o} switch;
7825 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7826 so the @file{ALI} file will not go to the right place. Therefore, you should
7827 avoid using the @option{-o} switch.
7831 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7832 children make up the GNAT RTL, together with the simple @code{System.IO}
7833 package used in the @code{"Hello World"} example. The sources for these units
7834 are needed by the compiler and are kept together in one directory. Not
7835 all of the bodies are needed, but all of the sources are kept together
7836 anyway. In a normal installation, you need not specify these directory
7837 names when compiling or binding. Either the environment variables or
7838 the built-in defaults cause these files to be found.
7840 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7841 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7842 consisting of child units of @code{GNAT}. This is a collection of generally
7843 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7844 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7846 Besides simplifying access to the RTL, a major use of search paths is
7847 in compiling sources from multiple directories. This can make
7848 development environments much more flexible.
7850 @node Order of Compilation Issues
7851 @section Order of Compilation Issues
7854 If, in our earlier example, there was a spec for the @code{hello}
7855 procedure, it would be contained in the file @file{hello.ads}; yet this
7856 file would not have to be explicitly compiled. This is the result of the
7857 model we chose to implement library management. Some of the consequences
7858 of this model are as follows:
7862 There is no point in compiling specs (except for package
7863 specs with no bodies) because these are compiled as needed by clients. If
7864 you attempt a useless compilation, you will receive an error message.
7865 It is also useless to compile subunits because they are compiled as needed
7869 There are no order of compilation requirements: performing a
7870 compilation never obsoletes anything. The only way you can obsolete
7871 something and require recompilations is to modify one of the
7872 source files on which it depends.
7875 There is no library as such, apart from the ALI files
7876 (@pxref{The Ada Library Information Files}, for information on the format
7877 of these files). For now we find it convenient to create separate ALI files,
7878 but eventually the information therein may be incorporated into the object
7882 When you compile a unit, the source files for the specs of all units
7883 that it @code{with}'s, all its subunits, and the bodies of any generics it
7884 instantiates must be available (reachable by the search-paths mechanism
7885 described above), or you will receive a fatal error message.
7892 The following are some typical Ada compilation command line examples:
7895 @item $ gcc -c xyz.adb
7896 Compile body in file @file{xyz.adb} with all default options.
7899 @item $ gcc -c -O2 -gnata xyz-def.adb
7902 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7905 Compile the child unit package in file @file{xyz-def.adb} with extensive
7906 optimizations, and pragma @code{Assert}/@code{Debug} statements
7909 @item $ gcc -c -gnatc abc-def.adb
7910 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7914 @node Binding Using gnatbind
7915 @chapter Binding Using @code{gnatbind}
7919 * Running gnatbind::
7920 * Switches for gnatbind::
7921 * Command-Line Access::
7922 * Search Paths for gnatbind::
7923 * Examples of gnatbind Usage::
7927 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7928 to bind compiled GNAT objects.
7930 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7931 driver (see @ref{The GNAT Driver and Project Files}).
7933 The @code{gnatbind} program performs four separate functions:
7937 Checks that a program is consistent, in accordance with the rules in
7938 Chapter 10 of the Ada Reference Manual. In particular, error
7939 messages are generated if a program uses inconsistent versions of a
7943 Checks that an acceptable order of elaboration exists for the program
7944 and issues an error message if it cannot find an order of elaboration
7945 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7948 Generates a main program incorporating the given elaboration order.
7949 This program is a small Ada package (body and spec) that
7950 must be subsequently compiled
7951 using the GNAT compiler. The necessary compilation step is usually
7952 performed automatically by @command{gnatlink}. The two most important
7953 functions of this program
7954 are to call the elaboration routines of units in an appropriate order
7955 and to call the main program.
7958 Determines the set of object files required by the given main program.
7959 This information is output in the forms of comments in the generated program,
7960 to be read by the @command{gnatlink} utility used to link the Ada application.
7963 @node Running gnatbind
7964 @section Running @code{gnatbind}
7967 The form of the @code{gnatbind} command is
7970 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7971 @c Expanding @ovar macro inline (explanation in macro def comments)
7972 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
7976 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7977 unit body. @code{gnatbind} constructs an Ada
7978 package in two files whose names are
7979 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7980 For example, if given the
7981 parameter @file{hello.ali}, for a main program contained in file
7982 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7983 and @file{b~hello.adb}.
7985 When doing consistency checking, the binder takes into consideration
7986 any source files it can locate. For example, if the binder determines
7987 that the given main program requires the package @code{Pack}, whose
7989 file is @file{pack.ali} and whose corresponding source spec file is
7990 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7991 (using the same search path conventions as previously described for the
7992 @command{gcc} command). If it can locate this source file, it checks that
7994 or source checksums of the source and its references to in @file{ALI} files
7995 match. In other words, any @file{ALI} files that mentions this spec must have
7996 resulted from compiling this version of the source file (or in the case
7997 where the source checksums match, a version close enough that the
7998 difference does not matter).
8000 @cindex Source files, use by binder
8001 The effect of this consistency checking, which includes source files, is
8002 that the binder ensures that the program is consistent with the latest
8003 version of the source files that can be located at bind time. Editing a
8004 source file without compiling files that depend on the source file cause
8005 error messages to be generated by the binder.
8007 For example, suppose you have a main program @file{hello.adb} and a
8008 package @code{P}, from file @file{p.ads} and you perform the following
8013 Enter @code{gcc -c hello.adb} to compile the main program.
8016 Enter @code{gcc -c p.ads} to compile package @code{P}.
8019 Edit file @file{p.ads}.
8022 Enter @code{gnatbind hello}.
8026 At this point, the file @file{p.ali} contains an out-of-date time stamp
8027 because the file @file{p.ads} has been edited. The attempt at binding
8028 fails, and the binder generates the following error messages:
8031 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8032 error: "p.ads" has been modified and must be recompiled
8036 Now both files must be recompiled as indicated, and then the bind can
8037 succeed, generating a main program. You need not normally be concerned
8038 with the contents of this file, but for reference purposes a sample
8039 binder output file is given in @ref{Example of Binder Output File}.
8041 In most normal usage, the default mode of @command{gnatbind} which is to
8042 generate the main package in Ada, as described in the previous section.
8043 In particular, this means that any Ada programmer can read and understand
8044 the generated main program. It can also be debugged just like any other
8045 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8046 @command{gnatbind} and @command{gnatlink}.
8048 @node Switches for gnatbind
8049 @section Switches for @command{gnatbind}
8052 The following switches are available with @code{gnatbind}; details will
8053 be presented in subsequent sections.
8056 * Consistency-Checking Modes::
8057 * Binder Error Message Control::
8058 * Elaboration Control::
8060 * Dynamic Allocation Control::
8061 * Binding with Non-Ada Main Programs::
8062 * Binding Programs with No Main Subprogram::
8069 @cindex @option{--version} @command{gnatbind}
8070 Display Copyright and version, then exit disregarding all other options.
8073 @cindex @option{--help} @command{gnatbind}
8074 If @option{--version} was not used, display usage, then exit disregarding
8078 @cindex @option{-a} @command{gnatbind}
8079 Indicates that, if supported by the platform, the adainit procedure should
8080 be treated as an initialisation routine by the linker (a constructor). This
8081 is intended to be used by the Project Manager to automatically initialize
8082 shared Stand-Alone Libraries.
8084 @item ^-aO^/OBJECT_SEARCH^
8085 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8086 Specify directory to be searched for ALI files.
8088 @item ^-aI^/SOURCE_SEARCH^
8089 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8090 Specify directory to be searched for source file.
8092 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8093 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8094 Output ALI list (to standard output or to the named file).
8096 @item ^-b^/REPORT_ERRORS=BRIEF^
8097 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8098 Generate brief messages to @file{stderr} even if verbose mode set.
8100 @item ^-c^/NOOUTPUT^
8101 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8102 Check only, no generation of binder output file.
8104 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8105 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8106 This switch can be used to change the default task stack size value
8107 to a specified size @var{nn}, which is expressed in bytes by default, or
8108 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8110 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8111 in effect, to completing all task specs with
8112 @smallexample @c ada
8113 pragma Storage_Size (nn);
8115 When they do not already have such a pragma.
8117 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8118 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8119 This switch can be used to change the default secondary stack size value
8120 to a specified size @var{nn}, which is expressed in bytes by default, or
8121 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8124 The secondary stack is used to deal with functions that return a variable
8125 sized result, for example a function returning an unconstrained
8126 String. There are two ways in which this secondary stack is allocated.
8128 For most targets, the secondary stack is growing on demand and is allocated
8129 as a chain of blocks in the heap. The -D option is not very
8130 relevant. It only give some control over the size of the allocated
8131 blocks (whose size is the minimum of the default secondary stack size value,
8132 and the actual size needed for the current allocation request).
8134 For certain targets, notably VxWorks 653,
8135 the secondary stack is allocated by carving off a fixed ratio chunk of the
8136 primary task stack. The -D option is used to define the
8137 size of the environment task's secondary stack.
8139 @item ^-e^/ELABORATION_DEPENDENCIES^
8140 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8141 Output complete list of elaboration-order dependencies.
8143 @item ^-E^/STORE_TRACEBACKS^
8144 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8145 Store tracebacks in exception occurrences when the target supports it.
8147 @c The following may get moved to an appendix
8148 This option is currently supported on the following targets:
8149 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8151 See also the packages @code{GNAT.Traceback} and
8152 @code{GNAT.Traceback.Symbolic} for more information.
8154 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8155 @command{gcc} option.
8158 @item ^-F^/FORCE_ELABS_FLAGS^
8159 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8160 Force the checks of elaboration flags. @command{gnatbind} does not normally
8161 generate checks of elaboration flags for the main executable, except when
8162 a Stand-Alone Library is used. However, there are cases when this cannot be
8163 detected by gnatbind. An example is importing an interface of a Stand-Alone
8164 Library through a pragma Import and only specifying through a linker switch
8165 this Stand-Alone Library. This switch is used to guarantee that elaboration
8166 flag checks are generated.
8169 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8170 Output usage (help) information
8172 @item ^-H32^/32_MALLOC^
8173 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8174 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8175 For further details see @ref{Dynamic Allocation Control}.
8177 @item ^-H64^/64_MALLOC^
8178 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8179 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8180 @cindex @code{__gnat_malloc}
8181 For further details see @ref{Dynamic Allocation Control}.
8184 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8185 Specify directory to be searched for source and ALI files.
8187 @item ^-I-^/NOCURRENT_DIRECTORY^
8188 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8189 Do not look for sources in the current directory where @code{gnatbind} was
8190 invoked, and do not look for ALI files in the directory containing the
8191 ALI file named in the @code{gnatbind} command line.
8193 @item ^-l^/ORDER_OF_ELABORATION^
8194 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8195 Output chosen elaboration order.
8197 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8198 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8199 Bind the units for library building. In this case the adainit and
8200 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8201 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8202 ^@var{xxx}final^@var{XXX}FINAL^.
8203 Implies ^-n^/NOCOMPILE^.
8205 (@xref{GNAT and Libraries}, for more details.)
8208 On OpenVMS, these init and final procedures are exported in uppercase
8209 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8210 the init procedure will be "TOTOINIT" and the exported name of the final
8211 procedure will be "TOTOFINAL".
8214 @item ^-Mxyz^/RENAME_MAIN=xyz^
8215 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8216 Rename generated main program from main to xyz. This option is
8217 supported on cross environments only.
8219 @item ^-m^/ERROR_LIMIT=^@var{n}
8220 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8221 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8222 in the range 1..999999. The default value if no switch is
8223 given is 9999. If the number of warnings reaches this limit, then a
8224 message is output and further warnings are suppressed, the bind
8225 continues in this case. If the number of errors reaches this
8226 limit, then a message is output and the bind is abandoned.
8227 A value of zero means that no limit is enforced. The equal
8231 Furthermore, under Windows, the sources pointed to by the libraries path
8232 set in the registry are not searched for.
8236 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8240 @cindex @option{-nostdinc} (@command{gnatbind})
8241 Do not look for sources in the system default directory.
8244 @cindex @option{-nostdlib} (@command{gnatbind})
8245 Do not look for library files in the system default directory.
8247 @item --RTS=@var{rts-path}
8248 @cindex @option{--RTS} (@code{gnatbind})
8249 Specifies the default location of the runtime library. Same meaning as the
8250 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8252 @item ^-o ^/OUTPUT=^@var{file}
8253 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8254 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8255 Note that if this option is used, then linking must be done manually,
8256 gnatlink cannot be used.
8258 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8259 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8260 Output object list (to standard output or to the named file).
8262 @item ^-p^/PESSIMISTIC_ELABORATION^
8263 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8264 Pessimistic (worst-case) elaboration order
8267 @cindex @option{^-R^-R^} (@command{gnatbind})
8268 Output closure source list.
8270 @item ^-s^/READ_SOURCES=ALL^
8271 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8272 Require all source files to be present.
8274 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8275 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8276 Specifies the value to be used when detecting uninitialized scalar
8277 objects with pragma Initialize_Scalars.
8278 The @var{xxx} ^string specified with the switch^option^ may be either
8280 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8281 @item ``@option{^lo^LOW^}'' for the lowest possible value
8282 @item ``@option{^hi^HIGH^}'' for the highest possible value
8283 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8284 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8287 In addition, you can specify @option{-Sev} to indicate that the value is
8288 to be set at run time. In this case, the program will look for an environment
8289 @cindex GNAT_INIT_SCALARS
8290 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8291 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8292 If no environment variable is found, or if it does not have a valid value,
8293 then the default is @option{in} (invalid values).
8297 @cindex @option{-static} (@code{gnatbind})
8298 Link against a static GNAT run time.
8301 @cindex @option{-shared} (@code{gnatbind})
8302 Link against a shared GNAT run time when available.
8305 @item ^-t^/NOTIME_STAMP_CHECK^
8306 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8307 Tolerate time stamp and other consistency errors
8309 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8310 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8311 Set the time slice value to @var{n} milliseconds. If the system supports
8312 the specification of a specific time slice value, then the indicated value
8313 is used. If the system does not support specific time slice values, but
8314 does support some general notion of round-robin scheduling, then any
8315 nonzero value will activate round-robin scheduling.
8317 A value of zero is treated specially. It turns off time
8318 slicing, and in addition, indicates to the tasking run time that the
8319 semantics should match as closely as possible the Annex D
8320 requirements of the Ada RM, and in particular sets the default
8321 scheduling policy to @code{FIFO_Within_Priorities}.
8323 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8324 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8325 Enable dynamic stack usage, with @var{n} results stored and displayed
8326 at program termination. A result is generated when a task
8327 terminates. Results that can't be stored are displayed on the fly, at
8328 task termination. This option is currently not supported on Itanium
8329 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8331 @item ^-v^/REPORT_ERRORS=VERBOSE^
8332 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8333 Verbose mode. Write error messages, header, summary output to
8338 @cindex @option{-w} (@code{gnatbind})
8339 Warning mode (@var{x}=s/e for suppress/treat as error)
8343 @item /WARNINGS=NORMAL
8344 @cindex @option{/WARNINGS} (@code{gnatbind})
8345 Normal warnings mode. Warnings are issued but ignored
8347 @item /WARNINGS=SUPPRESS
8348 @cindex @option{/WARNINGS} (@code{gnatbind})
8349 All warning messages are suppressed
8351 @item /WARNINGS=ERROR
8352 @cindex @option{/WARNINGS} (@code{gnatbind})
8353 Warning messages are treated as fatal errors
8356 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8357 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8358 Override default wide character encoding for standard Text_IO files.
8360 @item ^-x^/READ_SOURCES=NONE^
8361 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8362 Exclude source files (check object consistency only).
8365 @item /READ_SOURCES=AVAILABLE
8366 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8367 Default mode, in which sources are checked for consistency only if
8371 @item ^-y^/ENABLE_LEAP_SECONDS^
8372 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8373 Enable leap seconds support in @code{Ada.Calendar} and its children.
8375 @item ^-z^/ZERO_MAIN^
8376 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8382 You may obtain this listing of switches by running @code{gnatbind} with
8386 @node Consistency-Checking Modes
8387 @subsection Consistency-Checking Modes
8390 As described earlier, by default @code{gnatbind} checks
8391 that object files are consistent with one another and are consistent
8392 with any source files it can locate. The following switches control binder
8397 @item ^-s^/READ_SOURCES=ALL^
8398 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8399 Require source files to be present. In this mode, the binder must be
8400 able to locate all source files that are referenced, in order to check
8401 their consistency. In normal mode, if a source file cannot be located it
8402 is simply ignored. If you specify this switch, a missing source
8405 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8406 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8407 Override default wide character encoding for standard Text_IO files.
8408 Normally the default wide character encoding method used for standard
8409 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8410 the main source input (see description of switch
8411 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8412 use of this switch for the binder (which has the same set of
8413 possible arguments) overrides this default as specified.
8415 @item ^-x^/READ_SOURCES=NONE^
8416 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8417 Exclude source files. In this mode, the binder only checks that ALI
8418 files are consistent with one another. Source files are not accessed.
8419 The binder runs faster in this mode, and there is still a guarantee that
8420 the resulting program is self-consistent.
8421 If a source file has been edited since it was last compiled, and you
8422 specify this switch, the binder will not detect that the object
8423 file is out of date with respect to the source file. Note that this is the
8424 mode that is automatically used by @command{gnatmake} because in this
8425 case the checking against sources has already been performed by
8426 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8429 @item /READ_SOURCES=AVAILABLE
8430 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8431 This is the default mode in which source files are checked if they are
8432 available, and ignored if they are not available.
8436 @node Binder Error Message Control
8437 @subsection Binder Error Message Control
8440 The following switches provide control over the generation of error
8441 messages from the binder:
8445 @item ^-v^/REPORT_ERRORS=VERBOSE^
8446 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8447 Verbose mode. In the normal mode, brief error messages are generated to
8448 @file{stderr}. If this switch is present, a header is written
8449 to @file{stdout} and any error messages are directed to @file{stdout}.
8450 All that is written to @file{stderr} is a brief summary message.
8452 @item ^-b^/REPORT_ERRORS=BRIEF^
8453 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8454 Generate brief error messages to @file{stderr} even if verbose mode is
8455 specified. This is relevant only when used with the
8456 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8460 @cindex @option{-m} (@code{gnatbind})
8461 Limits the number of error messages to @var{n}, a decimal integer in the
8462 range 1-999. The binder terminates immediately if this limit is reached.
8465 @cindex @option{-M} (@code{gnatbind})
8466 Renames the generated main program from @code{main} to @code{xxx}.
8467 This is useful in the case of some cross-building environments, where
8468 the actual main program is separate from the one generated
8472 @item ^-ws^/WARNINGS=SUPPRESS^
8473 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8475 Suppress all warning messages.
8477 @item ^-we^/WARNINGS=ERROR^
8478 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8479 Treat any warning messages as fatal errors.
8482 @item /WARNINGS=NORMAL
8483 Standard mode with warnings generated, but warnings do not get treated
8487 @item ^-t^/NOTIME_STAMP_CHECK^
8488 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8489 @cindex Time stamp checks, in binder
8490 @cindex Binder consistency checks
8491 @cindex Consistency checks, in binder
8492 The binder performs a number of consistency checks including:
8496 Check that time stamps of a given source unit are consistent
8498 Check that checksums of a given source unit are consistent
8500 Check that consistent versions of @code{GNAT} were used for compilation
8502 Check consistency of configuration pragmas as required
8506 Normally failure of such checks, in accordance with the consistency
8507 requirements of the Ada Reference Manual, causes error messages to be
8508 generated which abort the binder and prevent the output of a binder
8509 file and subsequent link to obtain an executable.
8511 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8512 into warnings, so that
8513 binding and linking can continue to completion even in the presence of such
8514 errors. The result may be a failed link (due to missing symbols), or a
8515 non-functional executable which has undefined semantics.
8516 @emph{This means that
8517 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8521 @node Elaboration Control
8522 @subsection Elaboration Control
8525 The following switches provide additional control over the elaboration
8526 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8529 @item ^-p^/PESSIMISTIC_ELABORATION^
8530 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8531 Normally the binder attempts to choose an elaboration order that is
8532 likely to minimize the likelihood of an elaboration order error resulting
8533 in raising a @code{Program_Error} exception. This switch reverses the
8534 action of the binder, and requests that it deliberately choose an order
8535 that is likely to maximize the likelihood of an elaboration error.
8536 This is useful in ensuring portability and avoiding dependence on
8537 accidental fortuitous elaboration ordering.
8539 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8541 elaboration checking is used (@option{-gnatE} switch used for compilation).
8542 This is because in the default static elaboration mode, all necessary
8543 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8544 These implicit pragmas are still respected by the binder in
8545 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8546 safe elaboration order is assured.
8549 @node Output Control
8550 @subsection Output Control
8553 The following switches allow additional control over the output
8554 generated by the binder.
8559 @item ^-c^/NOOUTPUT^
8560 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8561 Check only. Do not generate the binder output file. In this mode the
8562 binder performs all error checks but does not generate an output file.
8564 @item ^-e^/ELABORATION_DEPENDENCIES^
8565 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8566 Output complete list of elaboration-order dependencies, showing the
8567 reason for each dependency. This output can be rather extensive but may
8568 be useful in diagnosing problems with elaboration order. The output is
8569 written to @file{stdout}.
8572 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8573 Output usage information. The output is written to @file{stdout}.
8575 @item ^-K^/LINKER_OPTION_LIST^
8576 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8577 Output linker options to @file{stdout}. Includes library search paths,
8578 contents of pragmas Ident and Linker_Options, and libraries added
8581 @item ^-l^/ORDER_OF_ELABORATION^
8582 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8583 Output chosen elaboration order. The output is written to @file{stdout}.
8585 @item ^-O^/OBJECT_LIST^
8586 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8587 Output full names of all the object files that must be linked to provide
8588 the Ada component of the program. The output is written to @file{stdout}.
8589 This list includes the files explicitly supplied and referenced by the user
8590 as well as implicitly referenced run-time unit files. The latter are
8591 omitted if the corresponding units reside in shared libraries. The
8592 directory names for the run-time units depend on the system configuration.
8594 @item ^-o ^/OUTPUT=^@var{file}
8595 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8596 Set name of output file to @var{file} instead of the normal
8597 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8598 binder generated body filename.
8599 Note that if this option is used, then linking must be done manually.
8600 It is not possible to use gnatlink in this case, since it cannot locate
8603 @item ^-r^/RESTRICTION_LIST^
8604 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8605 Generate list of @code{pragma Restrictions} that could be applied to
8606 the current unit. This is useful for code audit purposes, and also may
8607 be used to improve code generation in some cases.
8611 @node Dynamic Allocation Control
8612 @subsection Dynamic Allocation Control
8615 The heap control switches -- @option{-H32} and @option{-H64} --
8616 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8617 They only affect compiler-generated allocations via @code{__gnat_malloc};
8618 explicit calls to @code{malloc} and related functions from the C
8619 run-time library are unaffected.
8623 Allocate memory on 32-bit heap
8626 Allocate memory on 64-bit heap. This is the default
8627 unless explicitly overridden by a @code{'Size} clause on the access type.
8632 See also @ref{Access types and 32/64-bit allocation}.
8636 These switches are only effective on VMS platforms.
8640 @node Binding with Non-Ada Main Programs
8641 @subsection Binding with Non-Ada Main Programs
8644 In our description so far we have assumed that the main
8645 program is in Ada, and that the task of the binder is to generate a
8646 corresponding function @code{main} that invokes this Ada main
8647 program. GNAT also supports the building of executable programs where
8648 the main program is not in Ada, but some of the called routines are
8649 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8650 The following switch is used in this situation:
8654 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8655 No main program. The main program is not in Ada.
8659 In this case, most of the functions of the binder are still required,
8660 but instead of generating a main program, the binder generates a file
8661 containing the following callable routines:
8666 You must call this routine to initialize the Ada part of the program by
8667 calling the necessary elaboration routines. A call to @code{adainit} is
8668 required before the first call to an Ada subprogram.
8670 Note that it is assumed that the basic execution environment must be setup
8671 to be appropriate for Ada execution at the point where the first Ada
8672 subprogram is called. In particular, if the Ada code will do any
8673 floating-point operations, then the FPU must be setup in an appropriate
8674 manner. For the case of the x86, for example, full precision mode is
8675 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8676 that the FPU is in the right state.
8680 You must call this routine to perform any library-level finalization
8681 required by the Ada subprograms. A call to @code{adafinal} is required
8682 after the last call to an Ada subprogram, and before the program
8687 If the @option{^-n^/NOMAIN^} switch
8688 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8689 @cindex Binder, multiple input files
8690 is given, more than one ALI file may appear on
8691 the command line for @code{gnatbind}. The normal @dfn{closure}
8692 calculation is performed for each of the specified units. Calculating
8693 the closure means finding out the set of units involved by tracing
8694 @code{with} references. The reason it is necessary to be able to
8695 specify more than one ALI file is that a given program may invoke two or
8696 more quite separate groups of Ada units.
8698 The binder takes the name of its output file from the last specified ALI
8699 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8700 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8701 The output is an Ada unit in source form that can be compiled with GNAT.
8702 This compilation occurs automatically as part of the @command{gnatlink}
8705 Currently the GNAT run time requires a FPU using 80 bits mode
8706 precision. Under targets where this is not the default it is required to
8707 call GNAT.Float_Control.Reset before using floating point numbers (this
8708 include float computation, float input and output) in the Ada code. A
8709 side effect is that this could be the wrong mode for the foreign code
8710 where floating point computation could be broken after this call.
8712 @node Binding Programs with No Main Subprogram
8713 @subsection Binding Programs with No Main Subprogram
8716 It is possible to have an Ada program which does not have a main
8717 subprogram. This program will call the elaboration routines of all the
8718 packages, then the finalization routines.
8720 The following switch is used to bind programs organized in this manner:
8723 @item ^-z^/ZERO_MAIN^
8724 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8725 Normally the binder checks that the unit name given on the command line
8726 corresponds to a suitable main subprogram. When this switch is used,
8727 a list of ALI files can be given, and the execution of the program
8728 consists of elaboration of these units in an appropriate order. Note
8729 that the default wide character encoding method for standard Text_IO
8730 files is always set to Brackets if this switch is set (you can use
8732 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8735 @node Command-Line Access
8736 @section Command-Line Access
8739 The package @code{Ada.Command_Line} provides access to the command-line
8740 arguments and program name. In order for this interface to operate
8741 correctly, the two variables
8753 are declared in one of the GNAT library routines. These variables must
8754 be set from the actual @code{argc} and @code{argv} values passed to the
8755 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8756 generates the C main program to automatically set these variables.
8757 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8758 set these variables. If they are not set, the procedures in
8759 @code{Ada.Command_Line} will not be available, and any attempt to use
8760 them will raise @code{Constraint_Error}. If command line access is
8761 required, your main program must set @code{gnat_argc} and
8762 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8765 @node Search Paths for gnatbind
8766 @section Search Paths for @code{gnatbind}
8769 The binder takes the name of an ALI file as its argument and needs to
8770 locate source files as well as other ALI files to verify object consistency.
8772 For source files, it follows exactly the same search rules as @command{gcc}
8773 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8774 directories searched are:
8778 The directory containing the ALI file named in the command line, unless
8779 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8782 All directories specified by @option{^-I^/SEARCH^}
8783 switches on the @code{gnatbind}
8784 command line, in the order given.
8787 @findex ADA_PRJ_OBJECTS_FILE
8788 Each of the directories listed in the text file whose name is given
8789 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8792 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8793 driver when project files are used. It should not normally be set
8797 @findex ADA_OBJECTS_PATH
8798 Each of the directories listed in the value of the
8799 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8801 Construct this value
8802 exactly as the @env{PATH} environment variable: a list of directory
8803 names separated by colons (semicolons when working with the NT version
8807 Normally, define this value as a logical name containing a comma separated
8808 list of directory names.
8810 This variable can also be defined by means of an environment string
8811 (an argument to the HP C exec* set of functions).
8815 DEFINE ANOTHER_PATH FOO:[BAG]
8816 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8819 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8820 first, followed by the standard Ada
8821 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8822 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8823 (Text_IO, Sequential_IO, etc)
8824 instead of the standard Ada packages. Thus, in order to get the standard Ada
8825 packages by default, ADA_OBJECTS_PATH must be redefined.
8829 The content of the @file{ada_object_path} file which is part of the GNAT
8830 installation tree and is used to store standard libraries such as the
8831 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8834 @ref{Installing a library}
8839 In the binder the switch @option{^-I^/SEARCH^}
8840 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8841 is used to specify both source and
8842 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8843 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8844 instead if you want to specify
8845 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8846 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8847 if you want to specify library paths
8848 only. This means that for the binder
8849 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8850 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8851 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8852 The binder generates the bind file (a C language source file) in the
8853 current working directory.
8859 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8860 children make up the GNAT Run-Time Library, together with the package
8861 GNAT and its children, which contain a set of useful additional
8862 library functions provided by GNAT. The sources for these units are
8863 needed by the compiler and are kept together in one directory. The ALI
8864 files and object files generated by compiling the RTL are needed by the
8865 binder and the linker and are kept together in one directory, typically
8866 different from the directory containing the sources. In a normal
8867 installation, you need not specify these directory names when compiling
8868 or binding. Either the environment variables or the built-in defaults
8869 cause these files to be found.
8871 Besides simplifying access to the RTL, a major use of search paths is
8872 in compiling sources from multiple directories. This can make
8873 development environments much more flexible.
8875 @node Examples of gnatbind Usage
8876 @section Examples of @code{gnatbind} Usage
8879 This section contains a number of examples of using the GNAT binding
8880 utility @code{gnatbind}.
8883 @item gnatbind hello
8884 The main program @code{Hello} (source program in @file{hello.adb}) is
8885 bound using the standard switch settings. The generated main program is
8886 @file{b~hello.adb}. This is the normal, default use of the binder.
8889 @item gnatbind hello -o mainprog.adb
8892 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8894 The main program @code{Hello} (source program in @file{hello.adb}) is
8895 bound using the standard switch settings. The generated main program is
8896 @file{mainprog.adb} with the associated spec in
8897 @file{mainprog.ads}. Note that you must specify the body here not the
8898 spec. Note that if this option is used, then linking must be done manually,
8899 since gnatlink will not be able to find the generated file.
8902 @c ------------------------------------
8903 @node Linking Using gnatlink
8904 @chapter Linking Using @command{gnatlink}
8905 @c ------------------------------------
8909 This chapter discusses @command{gnatlink}, a tool that links
8910 an Ada program and builds an executable file. This utility
8911 invokes the system linker ^(via the @command{gcc} command)^^
8912 with a correct list of object files and library references.
8913 @command{gnatlink} automatically determines the list of files and
8914 references for the Ada part of a program. It uses the binder file
8915 generated by the @command{gnatbind} to determine this list.
8917 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8918 driver (see @ref{The GNAT Driver and Project Files}).
8921 * Running gnatlink::
8922 * Switches for gnatlink::
8925 @node Running gnatlink
8926 @section Running @command{gnatlink}
8929 The form of the @command{gnatlink} command is
8932 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8933 @c @ovar{non-Ada objects} @ovar{linker options}
8934 @c Expanding @ovar macro inline (explanation in macro def comments)
8935 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
8936 @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
8941 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8943 or linker options) may be in any order, provided that no non-Ada object may
8944 be mistaken for a main @file{ALI} file.
8945 Any file name @file{F} without the @file{.ali}
8946 extension will be taken as the main @file{ALI} file if a file exists
8947 whose name is the concatenation of @file{F} and @file{.ali}.
8950 @file{@var{mainprog}.ali} references the ALI file of the main program.
8951 The @file{.ali} extension of this file can be omitted. From this
8952 reference, @command{gnatlink} locates the corresponding binder file
8953 @file{b~@var{mainprog}.adb} and, using the information in this file along
8954 with the list of non-Ada objects and linker options, constructs a
8955 linker command file to create the executable.
8957 The arguments other than the @command{gnatlink} switches and the main
8958 @file{ALI} file are passed to the linker uninterpreted.
8959 They typically include the names of
8960 object files for units written in other languages than Ada and any library
8961 references required to resolve references in any of these foreign language
8962 units, or in @code{Import} pragmas in any Ada units.
8964 @var{linker options} is an optional list of linker specific
8966 The default linker called by gnatlink is @command{gcc} which in
8967 turn calls the appropriate system linker.
8968 Standard options for the linker such as @option{-lmy_lib} or
8969 @option{-Ldir} can be added as is.
8970 For options that are not recognized by
8971 @command{gcc} as linker options, use the @command{gcc} switches
8972 @option{-Xlinker} or @option{-Wl,}.
8973 Refer to the GCC documentation for
8974 details. Here is an example showing how to generate a linker map:
8977 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8980 Using @var{linker options} it is possible to set the program stack and
8983 See @ref{Setting Stack Size from gnatlink} and
8984 @ref{Setting Heap Size from gnatlink}.
8987 @command{gnatlink} determines the list of objects required by the Ada
8988 program and prepends them to the list of objects passed to the linker.
8989 @command{gnatlink} also gathers any arguments set by the use of
8990 @code{pragma Linker_Options} and adds them to the list of arguments
8991 presented to the linker.
8994 @command{gnatlink} accepts the following types of extra files on the command
8995 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8996 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8997 handled according to their extension.
9000 @node Switches for gnatlink
9001 @section Switches for @command{gnatlink}
9004 The following switches are available with the @command{gnatlink} utility:
9010 @cindex @option{--version} @command{gnatlink}
9011 Display Copyright and version, then exit disregarding all other options.
9014 @cindex @option{--help} @command{gnatlink}
9015 If @option{--version} was not used, display usage, then exit disregarding
9018 @item ^-f^/FORCE_OBJECT_FILE_LIST^
9019 @cindex Command line length
9020 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
9021 On some targets, the command line length is limited, and @command{gnatlink}
9022 will generate a separate file for the linker if the list of object files
9024 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
9025 to be generated even if
9026 the limit is not exceeded. This is useful in some cases to deal with
9027 special situations where the command line length is exceeded.
9030 @cindex Debugging information, including
9031 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
9032 The option to include debugging information causes the Ada bind file (in
9033 other words, @file{b~@var{mainprog}.adb}) to be compiled with
9034 @option{^-g^/DEBUG^}.
9035 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
9036 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
9037 Without @option{^-g^/DEBUG^}, the binder removes these files by
9038 default. The same procedure apply if a C bind file was generated using
9039 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
9040 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
9042 @item ^-n^/NOCOMPILE^
9043 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
9044 Do not compile the file generated by the binder. This may be used when
9045 a link is rerun with different options, but there is no need to recompile
9049 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
9050 Causes additional information to be output, including a full list of the
9051 included object files. This switch option is most useful when you want
9052 to see what set of object files are being used in the link step.
9054 @item ^-v -v^/VERBOSE/VERBOSE^
9055 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9056 Very verbose mode. Requests that the compiler operate in verbose mode when
9057 it compiles the binder file, and that the system linker run in verbose mode.
9059 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9060 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9061 @var{exec-name} specifies an alternate name for the generated
9062 executable program. If this switch is omitted, the executable has the same
9063 name as the main unit. For example, @code{gnatlink try.ali} creates
9064 an executable called @file{^try^TRY.EXE^}.
9067 @item -b @var{target}
9068 @cindex @option{-b} (@command{gnatlink})
9069 Compile your program to run on @var{target}, which is the name of a
9070 system configuration. You must have a GNAT cross-compiler built if
9071 @var{target} is not the same as your host system.
9074 @cindex @option{-B} (@command{gnatlink})
9075 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9076 from @var{dir} instead of the default location. Only use this switch
9077 when multiple versions of the GNAT compiler are available.
9078 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9079 for further details. You would normally use the @option{-b} or
9080 @option{-V} switch instead.
9082 @item --GCC=@var{compiler_name}
9083 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9084 Program used for compiling the binder file. The default is
9085 @command{gcc}. You need to use quotes around @var{compiler_name} if
9086 @code{compiler_name} contains spaces or other separator characters.
9087 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9088 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9089 inserted after your command name. Thus in the above example the compiler
9090 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9091 A limitation of this syntax is that the name and path name of the executable
9092 itself must not include any embedded spaces. If the compiler executable is
9093 different from the default one (gcc or <prefix>-gcc), then the back-end
9094 switches in the ALI file are not used to compile the binder generated source.
9095 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9096 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9097 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9098 is taken into account. However, all the additional switches are also taken
9100 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9101 @option{--GCC="bar -x -y -z -t"}.
9103 @item --LINK=@var{name}
9104 @cindex @option{--LINK=} (@command{gnatlink})
9105 @var{name} is the name of the linker to be invoked. This is especially
9106 useful in mixed language programs since languages such as C++ require
9107 their own linker to be used. When this switch is omitted, the default
9108 name for the linker is @command{gcc}. When this switch is used, the
9109 specified linker is called instead of @command{gcc} with exactly the same
9110 parameters that would have been passed to @command{gcc} so if the desired
9111 linker requires different parameters it is necessary to use a wrapper
9112 script that massages the parameters before invoking the real linker. It
9113 may be useful to control the exact invocation by using the verbose
9119 @item /DEBUG=TRACEBACK
9120 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9121 This qualifier causes sufficient information to be included in the
9122 executable file to allow a traceback, but does not include the full
9123 symbol information needed by the debugger.
9125 @item /IDENTIFICATION="<string>"
9126 @code{"<string>"} specifies the string to be stored in the image file
9127 identification field in the image header.
9128 It overrides any pragma @code{Ident} specified string.
9130 @item /NOINHIBIT-EXEC
9131 Generate the executable file even if there are linker warnings.
9133 @item /NOSTART_FILES
9134 Don't link in the object file containing the ``main'' transfer address.
9135 Used when linking with a foreign language main program compiled with an
9139 Prefer linking with object libraries over sharable images, even without
9145 @node The GNAT Make Program gnatmake
9146 @chapter The GNAT Make Program @command{gnatmake}
9150 * Running gnatmake::
9151 * Switches for gnatmake::
9152 * Mode Switches for gnatmake::
9153 * Notes on the Command Line::
9154 * How gnatmake Works::
9155 * Examples of gnatmake Usage::
9158 A typical development cycle when working on an Ada program consists of
9159 the following steps:
9163 Edit some sources to fix bugs.
9169 Compile all sources affected.
9179 The third step can be tricky, because not only do the modified files
9180 @cindex Dependency rules
9181 have to be compiled, but any files depending on these files must also be
9182 recompiled. The dependency rules in Ada can be quite complex, especially
9183 in the presence of overloading, @code{use} clauses, generics and inlined
9186 @command{gnatmake} automatically takes care of the third and fourth steps
9187 of this process. It determines which sources need to be compiled,
9188 compiles them, and binds and links the resulting object files.
9190 Unlike some other Ada make programs, the dependencies are always
9191 accurately recomputed from the new sources. The source based approach of
9192 the GNAT compilation model makes this possible. This means that if
9193 changes to the source program cause corresponding changes in
9194 dependencies, they will always be tracked exactly correctly by
9197 @node Running gnatmake
9198 @section Running @command{gnatmake}
9201 The usual form of the @command{gnatmake} command is
9204 @c $ gnatmake @ovar{switches} @var{file_name}
9205 @c @ovar{file_names} @ovar{mode_switches}
9206 @c Expanding @ovar macro inline (explanation in macro def comments)
9207 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9208 @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9212 The only required argument is one @var{file_name}, which specifies
9213 a compilation unit that is a main program. Several @var{file_names} can be
9214 specified: this will result in several executables being built.
9215 If @code{switches} are present, they can be placed before the first
9216 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9217 If @var{mode_switches} are present, they must always be placed after
9218 the last @var{file_name} and all @code{switches}.
9220 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9221 extension may be omitted from the @var{file_name} arguments. However, if
9222 you are using non-standard extensions, then it is required that the
9223 extension be given. A relative or absolute directory path can be
9224 specified in a @var{file_name}, in which case, the input source file will
9225 be searched for in the specified directory only. Otherwise, the input
9226 source file will first be searched in the directory where
9227 @command{gnatmake} was invoked and if it is not found, it will be search on
9228 the source path of the compiler as described in
9229 @ref{Search Paths and the Run-Time Library (RTL)}.
9231 All @command{gnatmake} output (except when you specify
9232 @option{^-M^/DEPENDENCIES_LIST^}) is to
9233 @file{stderr}. The output produced by the
9234 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9237 @node Switches for gnatmake
9238 @section Switches for @command{gnatmake}
9241 You may specify any of the following switches to @command{gnatmake}:
9247 @cindex @option{--version} @command{gnatmake}
9248 Display Copyright and version, then exit disregarding all other options.
9251 @cindex @option{--help} @command{gnatmake}
9252 If @option{--version} was not used, display usage, then exit disregarding
9256 @item --GCC=@var{compiler_name}
9257 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9258 Program used for compiling. The default is `@command{gcc}'. You need to use
9259 quotes around @var{compiler_name} if @code{compiler_name} contains
9260 spaces or other separator characters. As an example @option{--GCC="foo -x
9261 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9262 compiler. A limitation of this syntax is that the name and path name of
9263 the executable itself must not include any embedded spaces. Note that
9264 switch @option{-c} is always inserted after your command name. Thus in the
9265 above example the compiler command that will be used by @command{gnatmake}
9266 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9267 used, only the last @var{compiler_name} is taken into account. However,
9268 all the additional switches are also taken into account. Thus,
9269 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9270 @option{--GCC="bar -x -y -z -t"}.
9272 @item --GNATBIND=@var{binder_name}
9273 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9274 Program used for binding. The default is `@code{gnatbind}'. You need to
9275 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9276 or other separator characters. As an example @option{--GNATBIND="bar -x
9277 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9278 binder. Binder switches that are normally appended by @command{gnatmake}
9279 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9280 A limitation of this syntax is that the name and path name of the executable
9281 itself must not include any embedded spaces.
9283 @item --GNATLINK=@var{linker_name}
9284 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9285 Program used for linking. The default is `@command{gnatlink}'. You need to
9286 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9287 or other separator characters. As an example @option{--GNATLINK="lan -x
9288 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9289 linker. Linker switches that are normally appended by @command{gnatmake} to
9290 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9291 A limitation of this syntax is that the name and path name of the executable
9292 itself must not include any embedded spaces.
9296 @item ^--subdirs^/SUBDIRS^=subdir
9297 Actual object directory of each project file is the subdirectory subdir of the
9298 object directory specified or defaulted in the project file.
9300 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9301 Disallow simultaneous compilations in the same object directory when
9302 project files are used.
9304 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9305 By default, shared library projects are not allowed to import static library
9306 projects. When this switch is used on the command line, this restriction is
9310 @item --create-map-file
9311 When linking an executable, create a map file. The name of the map file
9312 has the same name as the executable with extension ".map".
9314 @item --create-map-file=mapfile
9315 When linking an executable, create a map file. The name of the map file is
9320 @item ^-a^/ALL_FILES^
9321 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9322 Consider all files in the make process, even the GNAT internal system
9323 files (for example, the predefined Ada library files), as well as any
9324 locked files. Locked files are files whose ALI file is write-protected.
9326 @command{gnatmake} does not check these files,
9327 because the assumption is that the GNAT internal files are properly up
9328 to date, and also that any write protected ALI files have been properly
9329 installed. Note that if there is an installation problem, such that one
9330 of these files is not up to date, it will be properly caught by the
9332 You may have to specify this switch if you are working on GNAT
9333 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9334 in conjunction with @option{^-f^/FORCE_COMPILE^}
9335 if you need to recompile an entire application,
9336 including run-time files, using special configuration pragmas,
9337 such as a @code{Normalize_Scalars} pragma.
9340 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9343 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9346 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9349 @item ^-b^/ACTIONS=BIND^
9350 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9351 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9352 compilation and binding, but no link.
9353 Can be combined with @option{^-l^/ACTIONS=LINK^}
9354 to do binding and linking. When not combined with
9355 @option{^-c^/ACTIONS=COMPILE^}
9356 all the units in the closure of the main program must have been previously
9357 compiled and must be up to date. The root unit specified by @var{file_name}
9358 may be given without extension, with the source extension or, if no GNAT
9359 Project File is specified, with the ALI file extension.
9361 @item ^-c^/ACTIONS=COMPILE^
9362 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9363 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9364 is also specified. Do not perform linking, except if both
9365 @option{^-b^/ACTIONS=BIND^} and
9366 @option{^-l^/ACTIONS=LINK^} are also specified.
9367 If the root unit specified by @var{file_name} is not a main unit, this is the
9368 default. Otherwise @command{gnatmake} will attempt binding and linking
9369 unless all objects are up to date and the executable is more recent than
9373 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9374 Use a temporary mapping file. A mapping file is a way to communicate
9375 to the compiler two mappings: from unit names to file names (without
9376 any directory information) and from file names to path names (with
9377 full directory information). A mapping file can make the compiler's
9378 file searches faster, especially if there are many source directories,
9379 or the sources are read over a slow network connection. If
9380 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9381 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9382 is initially populated based on the project file. If
9383 @option{^-C^/MAPPING^} is used without
9384 @option{^-P^/PROJECT_FILE^},
9385 the mapping file is initially empty. Each invocation of the compiler
9386 will add any newly accessed sources to the mapping file.
9388 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9389 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9390 Use a specific mapping file. The file, specified as a path name (absolute or
9391 relative) by this switch, should already exist, otherwise the switch is
9392 ineffective. The specified mapping file will be communicated to the compiler.
9393 This switch is not compatible with a project file
9394 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9395 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9397 @item ^-d^/DISPLAY_PROGRESS^
9398 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9399 Display progress for each source, up to date or not, as a single line
9402 completed x out of y (zz%)
9405 If the file needs to be compiled this is displayed after the invocation of
9406 the compiler. These lines are displayed even in quiet output mode.
9408 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9409 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9410 Put all object files and ALI file in directory @var{dir}.
9411 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9412 and ALI files go in the current working directory.
9414 This switch cannot be used when using a project file.
9418 @cindex @option{-eL} (@command{gnatmake})
9419 @cindex symbolic links
9420 Follow all symbolic links when processing project files.
9421 This should be used if your project uses symbolic links for files or
9422 directories, but is not needed in other cases.
9424 @cindex naming scheme
9425 This also assumes that no directory matches the naming scheme for files (for
9426 instance that you do not have a directory called "sources.ads" when using the
9427 default GNAT naming scheme).
9429 When you do not have to use this switch (ie by default), gnatmake is able to
9430 save a lot of system calls (several per source file and object file), which
9431 can result in a significant speed up to load and manipulate a project file,
9432 especially when using source files from a remote system.
9436 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9437 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9438 Output the commands for the compiler, the binder and the linker
9439 on ^standard output^SYS$OUTPUT^,
9440 instead of ^standard error^SYS$ERROR^.
9442 @item ^-f^/FORCE_COMPILE^
9443 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9444 Force recompilations. Recompile all sources, even though some object
9445 files may be up to date, but don't recompile predefined or GNAT internal
9446 files or locked files (files with a write-protected ALI file),
9447 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9449 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9450 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9451 When using project files, if some errors or warnings are detected during
9452 parsing and verbose mode is not in effect (no use of switch
9453 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9454 file, rather than its simple file name.
9457 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9458 Enable debugging. This switch is simply passed to the compiler and to the
9461 @item ^-i^/IN_PLACE^
9462 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9463 In normal mode, @command{gnatmake} compiles all object files and ALI files
9464 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9465 then instead object files and ALI files that already exist are overwritten
9466 in place. This means that once a large project is organized into separate
9467 directories in the desired manner, then @command{gnatmake} will automatically
9468 maintain and update this organization. If no ALI files are found on the
9469 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9470 the new object and ALI files are created in the
9471 directory containing the source being compiled. If another organization
9472 is desired, where objects and sources are kept in different directories,
9473 a useful technique is to create dummy ALI files in the desired directories.
9474 When detecting such a dummy file, @command{gnatmake} will be forced to
9475 recompile the corresponding source file, and it will be put the resulting
9476 object and ALI files in the directory where it found the dummy file.
9478 @item ^-j^/PROCESSES=^@var{n}
9479 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9480 @cindex Parallel make
9481 Use @var{n} processes to carry out the (re)compilations. On a
9482 multiprocessor machine compilations will occur in parallel. In the
9483 event of compilation errors, messages from various compilations might
9484 get interspersed (but @command{gnatmake} will give you the full ordered
9485 list of failing compiles at the end). If this is problematic, rerun
9486 the make process with n set to 1 to get a clean list of messages.
9488 @item ^-k^/CONTINUE_ON_ERROR^
9489 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9490 Keep going. Continue as much as possible after a compilation error. To
9491 ease the programmer's task in case of compilation errors, the list of
9492 sources for which the compile fails is given when @command{gnatmake}
9495 If @command{gnatmake} is invoked with several @file{file_names} and with this
9496 switch, if there are compilation errors when building an executable,
9497 @command{gnatmake} will not attempt to build the following executables.
9499 @item ^-l^/ACTIONS=LINK^
9500 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9501 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9502 and linking. Linking will not be performed if combined with
9503 @option{^-c^/ACTIONS=COMPILE^}
9504 but not with @option{^-b^/ACTIONS=BIND^}.
9505 When not combined with @option{^-b^/ACTIONS=BIND^}
9506 all the units in the closure of the main program must have been previously
9507 compiled and must be up to date, and the main program needs to have been bound.
9508 The root unit specified by @var{file_name}
9509 may be given without extension, with the source extension or, if no GNAT
9510 Project File is specified, with the ALI file extension.
9512 @item ^-m^/MINIMAL_RECOMPILATION^
9513 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9514 Specify that the minimum necessary amount of recompilations
9515 be performed. In this mode @command{gnatmake} ignores time
9516 stamp differences when the only
9517 modifications to a source file consist in adding/removing comments,
9518 empty lines, spaces or tabs. This means that if you have changed the
9519 comments in a source file or have simply reformatted it, using this
9520 switch will tell @command{gnatmake} not to recompile files that depend on it
9521 (provided other sources on which these files depend have undergone no
9522 semantic modifications). Note that the debugging information may be
9523 out of date with respect to the sources if the @option{-m} switch causes
9524 a compilation to be switched, so the use of this switch represents a
9525 trade-off between compilation time and accurate debugging information.
9527 @item ^-M^/DEPENDENCIES_LIST^
9528 @cindex Dependencies, producing list
9529 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9530 Check if all objects are up to date. If they are, output the object
9531 dependences to @file{stdout} in a form that can be directly exploited in
9532 a @file{Makefile}. By default, each source file is prefixed with its
9533 (relative or absolute) directory name. This name is whatever you
9534 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9535 and @option{^-I^/SEARCH^} switches. If you use
9536 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9537 @option{^-q^/QUIET^}
9538 (see below), only the source file names,
9539 without relative paths, are output. If you just specify the
9540 @option{^-M^/DEPENDENCIES_LIST^}
9541 switch, dependencies of the GNAT internal system files are omitted. This
9542 is typically what you want. If you also specify
9543 the @option{^-a^/ALL_FILES^} switch,
9544 dependencies of the GNAT internal files are also listed. Note that
9545 dependencies of the objects in external Ada libraries (see switch
9546 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9549 @item ^-n^/DO_OBJECT_CHECK^
9550 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9551 Don't compile, bind, or link. Checks if all objects are up to date.
9552 If they are not, the full name of the first file that needs to be
9553 recompiled is printed.
9554 Repeated use of this option, followed by compiling the indicated source
9555 file, will eventually result in recompiling all required units.
9557 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9558 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9559 Output executable name. The name of the final executable program will be
9560 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9561 name for the executable will be the name of the input file in appropriate form
9562 for an executable file on the host system.
9564 This switch cannot be used when invoking @command{gnatmake} with several
9567 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9568 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9569 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9570 automatically missing object directories, library directories and exec
9573 @item ^-P^/PROJECT_FILE=^@var{project}
9574 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9575 Use project file @var{project}. Only one such switch can be used.
9576 @xref{gnatmake and Project Files}.
9579 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9580 Quiet. When this flag is not set, the commands carried out by
9581 @command{gnatmake} are displayed.
9583 @item ^-s^/SWITCH_CHECK/^
9584 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9585 Recompile if compiler switches have changed since last compilation.
9586 All compiler switches but -I and -o are taken into account in the
9588 orders between different ``first letter'' switches are ignored, but
9589 orders between same switches are taken into account. For example,
9590 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9591 is equivalent to @option{-O -g}.
9593 This switch is recommended when Integrated Preprocessing is used.
9596 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9597 Unique. Recompile at most the main files. It implies -c. Combined with
9598 -f, it is equivalent to calling the compiler directly. Note that using
9599 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9600 (@pxref{Project Files and Main Subprograms}).
9602 @item ^-U^/ALL_PROJECTS^
9603 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9604 When used without a project file or with one or several mains on the command
9605 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9606 on the command line, all sources of all project files are checked and compiled
9607 if not up to date, and libraries are rebuilt, if necessary.
9610 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9611 Verbose. Display the reason for all recompilations @command{gnatmake}
9612 decides are necessary, with the highest verbosity level.
9614 @item ^-vl^/LOW_VERBOSITY^
9615 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9616 Verbosity level Low. Display fewer lines than in verbosity Medium.
9618 @item ^-vm^/MEDIUM_VERBOSITY^
9619 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9620 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9622 @item ^-vh^/HIGH_VERBOSITY^
9623 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9624 Verbosity level High. Equivalent to ^-v^/REASONS^.
9626 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9627 Indicate the verbosity of the parsing of GNAT project files.
9628 @xref{Switches Related to Project Files}.
9630 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9631 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9632 Indicate that sources that are not part of any Project File may be compiled.
9633 Normally, when using Project Files, only sources that are part of a Project
9634 File may be compile. When this switch is used, a source outside of all Project
9635 Files may be compiled. The ALI file and the object file will be put in the
9636 object directory of the main Project. The compilation switches used will only
9637 be those specified on the command line. Even when
9638 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9639 command line need to be sources of a project file.
9641 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9642 Indicate that external variable @var{name} has the value @var{value}.
9643 The Project Manager will use this value for occurrences of
9644 @code{external(name)} when parsing the project file.
9645 @xref{Switches Related to Project Files}.
9648 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9649 No main subprogram. Bind and link the program even if the unit name
9650 given on the command line is a package name. The resulting executable
9651 will execute the elaboration routines of the package and its closure,
9652 then the finalization routines.
9657 @item @command{gcc} @asis{switches}
9659 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9660 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9663 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9664 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9665 automatically treated as a compiler switch, and passed on to all
9666 compilations that are carried out.
9671 Source and library search path switches:
9675 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9676 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9677 When looking for source files also look in directory @var{dir}.
9678 The order in which source files search is undertaken is
9679 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9681 @item ^-aL^/SKIP_MISSING=^@var{dir}
9682 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9683 Consider @var{dir} as being an externally provided Ada library.
9684 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9685 files have been located in directory @var{dir}. This allows you to have
9686 missing bodies for the units in @var{dir} and to ignore out of date bodies
9687 for the same units. You still need to specify
9688 the location of the specs for these units by using the switches
9689 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9690 or @option{^-I^/SEARCH=^@var{dir}}.
9691 Note: this switch is provided for compatibility with previous versions
9692 of @command{gnatmake}. The easier method of causing standard libraries
9693 to be excluded from consideration is to write-protect the corresponding
9696 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9697 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9698 When searching for library and object files, look in directory
9699 @var{dir}. The order in which library files are searched is described in
9700 @ref{Search Paths for gnatbind}.
9702 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9703 @cindex Search paths, for @command{gnatmake}
9704 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9705 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9706 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9708 @item ^-I^/SEARCH=^@var{dir}
9709 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9710 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9711 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9713 @item ^-I-^/NOCURRENT_DIRECTORY^
9714 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9715 @cindex Source files, suppressing search
9716 Do not look for source files in the directory containing the source
9717 file named in the command line.
9718 Do not look for ALI or object files in the directory
9719 where @command{gnatmake} was invoked.
9721 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9722 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9723 @cindex Linker libraries
9724 Add directory @var{dir} to the list of directories in which the linker
9725 will search for libraries. This is equivalent to
9726 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9728 Furthermore, under Windows, the sources pointed to by the libraries path
9729 set in the registry are not searched for.
9733 @cindex @option{-nostdinc} (@command{gnatmake})
9734 Do not look for source files in the system default directory.
9737 @cindex @option{-nostdlib} (@command{gnatmake})
9738 Do not look for library files in the system default directory.
9740 @item --RTS=@var{rts-path}
9741 @cindex @option{--RTS} (@command{gnatmake})
9742 Specifies the default location of the runtime library. GNAT looks for the
9744 in the following directories, and stops as soon as a valid runtime is found
9745 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9746 @file{ada_object_path} present):
9749 @item <current directory>/$rts_path
9751 @item <default-search-dir>/$rts_path
9753 @item <default-search-dir>/rts-$rts_path
9757 The selected path is handled like a normal RTS path.
9761 @node Mode Switches for gnatmake
9762 @section Mode Switches for @command{gnatmake}
9765 The mode switches (referred to as @code{mode_switches}) allow the
9766 inclusion of switches that are to be passed to the compiler itself, the
9767 binder or the linker. The effect of a mode switch is to cause all
9768 subsequent switches up to the end of the switch list, or up to the next
9769 mode switch, to be interpreted as switches to be passed on to the
9770 designated component of GNAT.
9774 @item -cargs @var{switches}
9775 @cindex @option{-cargs} (@command{gnatmake})
9776 Compiler switches. Here @var{switches} is a list of switches
9777 that are valid switches for @command{gcc}. They will be passed on to
9778 all compile steps performed by @command{gnatmake}.
9780 @item -bargs @var{switches}
9781 @cindex @option{-bargs} (@command{gnatmake})
9782 Binder switches. Here @var{switches} is a list of switches
9783 that are valid switches for @code{gnatbind}. They will be passed on to
9784 all bind steps performed by @command{gnatmake}.
9786 @item -largs @var{switches}
9787 @cindex @option{-largs} (@command{gnatmake})
9788 Linker switches. Here @var{switches} is a list of switches
9789 that are valid switches for @command{gnatlink}. They will be passed on to
9790 all link steps performed by @command{gnatmake}.
9792 @item -margs @var{switches}
9793 @cindex @option{-margs} (@command{gnatmake})
9794 Make switches. The switches are directly interpreted by @command{gnatmake},
9795 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9799 @node Notes on the Command Line
9800 @section Notes on the Command Line
9803 This section contains some additional useful notes on the operation
9804 of the @command{gnatmake} command.
9808 @cindex Recompilation, by @command{gnatmake}
9809 If @command{gnatmake} finds no ALI files, it recompiles the main program
9810 and all other units required by the main program.
9811 This means that @command{gnatmake}
9812 can be used for the initial compile, as well as during subsequent steps of
9813 the development cycle.
9816 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9817 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9818 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9822 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9823 is used to specify both source and
9824 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9825 instead if you just want to specify
9826 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9827 if you want to specify library paths
9831 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9832 This may conveniently be used to exclude standard libraries from
9833 consideration and in particular it means that the use of the
9834 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9835 unless @option{^-a^/ALL_FILES^} is also specified.
9838 @command{gnatmake} has been designed to make the use of Ada libraries
9839 particularly convenient. Assume you have an Ada library organized
9840 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9841 of your Ada compilation units,
9842 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9843 specs of these units, but no bodies. Then to compile a unit
9844 stored in @code{main.adb}, which uses this Ada library you would just type
9848 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
9851 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9852 /SKIP_MISSING=@i{[OBJ_DIR]} main
9857 Using @command{gnatmake} along with the
9858 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9859 switch provides a mechanism for avoiding unnecessary recompilations. Using
9861 you can update the comments/format of your
9862 source files without having to recompile everything. Note, however, that
9863 adding or deleting lines in a source files may render its debugging
9864 info obsolete. If the file in question is a spec, the impact is rather
9865 limited, as that debugging info will only be useful during the
9866 elaboration phase of your program. For bodies the impact can be more
9867 significant. In all events, your debugger will warn you if a source file
9868 is more recent than the corresponding object, and alert you to the fact
9869 that the debugging information may be out of date.
9872 @node How gnatmake Works
9873 @section How @command{gnatmake} Works
9876 Generally @command{gnatmake} automatically performs all necessary
9877 recompilations and you don't need to worry about how it works. However,
9878 it may be useful to have some basic understanding of the @command{gnatmake}
9879 approach and in particular to understand how it uses the results of
9880 previous compilations without incorrectly depending on them.
9882 First a definition: an object file is considered @dfn{up to date} if the
9883 corresponding ALI file exists and if all the source files listed in the
9884 dependency section of this ALI file have time stamps matching those in
9885 the ALI file. This means that neither the source file itself nor any
9886 files that it depends on have been modified, and hence there is no need
9887 to recompile this file.
9889 @command{gnatmake} works by first checking if the specified main unit is up
9890 to date. If so, no compilations are required for the main unit. If not,
9891 @command{gnatmake} compiles the main program to build a new ALI file that
9892 reflects the latest sources. Then the ALI file of the main unit is
9893 examined to find all the source files on which the main program depends,
9894 and @command{gnatmake} recursively applies the above procedure on all these
9897 This process ensures that @command{gnatmake} only trusts the dependencies
9898 in an existing ALI file if they are known to be correct. Otherwise it
9899 always recompiles to determine a new, guaranteed accurate set of
9900 dependencies. As a result the program is compiled ``upside down'' from what may
9901 be more familiar as the required order of compilation in some other Ada
9902 systems. In particular, clients are compiled before the units on which
9903 they depend. The ability of GNAT to compile in any order is critical in
9904 allowing an order of compilation to be chosen that guarantees that
9905 @command{gnatmake} will recompute a correct set of new dependencies if
9908 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9909 imported by several of the executables, it will be recompiled at most once.
9911 Note: when using non-standard naming conventions
9912 (@pxref{Using Other File Names}), changing through a configuration pragmas
9913 file the version of a source and invoking @command{gnatmake} to recompile may
9914 have no effect, if the previous version of the source is still accessible
9915 by @command{gnatmake}. It may be necessary to use the switch
9916 ^-f^/FORCE_COMPILE^.
9918 @node Examples of gnatmake Usage
9919 @section Examples of @command{gnatmake} Usage
9922 @item gnatmake hello.adb
9923 Compile all files necessary to bind and link the main program
9924 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9925 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9927 @item gnatmake main1 main2 main3
9928 Compile all files necessary to bind and link the main programs
9929 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9930 (containing unit @code{Main2}) and @file{main3.adb}
9931 (containing unit @code{Main3}) and bind and link the resulting object files
9932 to generate three executable files @file{^main1^MAIN1.EXE^},
9933 @file{^main2^MAIN2.EXE^}
9934 and @file{^main3^MAIN3.EXE^}.
9937 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9941 @item gnatmake Main_Unit /QUIET
9942 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9943 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9945 Compile all files necessary to bind and link the main program unit
9946 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9947 be done with optimization level 2 and the order of elaboration will be
9948 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9949 displaying commands it is executing.
9952 @c *************************
9953 @node Improving Performance
9954 @chapter Improving Performance
9955 @cindex Improving performance
9958 This chapter presents several topics related to program performance.
9959 It first describes some of the tradeoffs that need to be considered
9960 and some of the techniques for making your program run faster.
9961 It then documents the @command{gnatelim} tool and unused subprogram/data
9962 elimination feature, which can reduce the size of program executables.
9964 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9965 driver (see @ref{The GNAT Driver and Project Files}).
9969 * Performance Considerations::
9970 * Text_IO Suggestions::
9971 * Reducing Size of Ada Executables with gnatelim::
9972 * Reducing Size of Executables with unused subprogram/data elimination::
9976 @c *****************************
9977 @node Performance Considerations
9978 @section Performance Considerations
9981 The GNAT system provides a number of options that allow a trade-off
9986 performance of the generated code
9989 speed of compilation
9992 minimization of dependences and recompilation
9995 the degree of run-time checking.
9999 The defaults (if no options are selected) aim at improving the speed
10000 of compilation and minimizing dependences, at the expense of performance
10001 of the generated code:
10008 no inlining of subprogram calls
10011 all run-time checks enabled except overflow and elaboration checks
10015 These options are suitable for most program development purposes. This
10016 chapter describes how you can modify these choices, and also provides
10017 some guidelines on debugging optimized code.
10020 * Controlling Run-Time Checks::
10021 * Use of Restrictions::
10022 * Optimization Levels::
10023 * Debugging Optimized Code::
10024 * Inlining of Subprograms::
10025 * Other Optimization Switches::
10026 * Optimization and Strict Aliasing::
10029 * Coverage Analysis::
10033 @node Controlling Run-Time Checks
10034 @subsection Controlling Run-Time Checks
10037 By default, GNAT generates all run-time checks, except integer overflow
10038 checks, stack overflow checks, and checks for access before elaboration on
10039 subprogram calls. The latter are not required in default mode, because all
10040 necessary checking is done at compile time.
10041 @cindex @option{-gnatp} (@command{gcc})
10042 @cindex @option{-gnato} (@command{gcc})
10043 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
10044 be modified. @xref{Run-Time Checks}.
10046 Our experience is that the default is suitable for most development
10049 We treat integer overflow specially because these
10050 are quite expensive and in our experience are not as important as other
10051 run-time checks in the development process. Note that division by zero
10052 is not considered an overflow check, and divide by zero checks are
10053 generated where required by default.
10055 Elaboration checks are off by default, and also not needed by default, since
10056 GNAT uses a static elaboration analysis approach that avoids the need for
10057 run-time checking. This manual contains a full chapter discussing the issue
10058 of elaboration checks, and if the default is not satisfactory for your use,
10059 you should read this chapter.
10061 For validity checks, the minimal checks required by the Ada Reference
10062 Manual (for case statements and assignments to array elements) are on
10063 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10064 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10065 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10066 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10067 are also suppressed entirely if @option{-gnatp} is used.
10069 @cindex Overflow checks
10070 @cindex Checks, overflow
10073 @cindex pragma Suppress
10074 @cindex pragma Unsuppress
10075 Note that the setting of the switches controls the default setting of
10076 the checks. They may be modified using either @code{pragma Suppress} (to
10077 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10078 checks) in the program source.
10080 @node Use of Restrictions
10081 @subsection Use of Restrictions
10084 The use of pragma Restrictions allows you to control which features are
10085 permitted in your program. Apart from the obvious point that if you avoid
10086 relatively expensive features like finalization (enforceable by the use
10087 of pragma Restrictions (No_Finalization), the use of this pragma does not
10088 affect the generated code in most cases.
10090 One notable exception to this rule is that the possibility of task abort
10091 results in some distributed overhead, particularly if finalization or
10092 exception handlers are used. The reason is that certain sections of code
10093 have to be marked as non-abortable.
10095 If you use neither the @code{abort} statement, nor asynchronous transfer
10096 of control (@code{select @dots{} then abort}), then this distributed overhead
10097 is removed, which may have a general positive effect in improving
10098 overall performance. Especially code involving frequent use of tasking
10099 constructs and controlled types will show much improved performance.
10100 The relevant restrictions pragmas are
10102 @smallexample @c ada
10103 pragma Restrictions (No_Abort_Statements);
10104 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10108 It is recommended that these restriction pragmas be used if possible. Note
10109 that this also means that you can write code without worrying about the
10110 possibility of an immediate abort at any point.
10112 @node Optimization Levels
10113 @subsection Optimization Levels
10114 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10117 Without any optimization ^option,^qualifier,^
10118 the compiler's goal is to reduce the cost of
10119 compilation and to make debugging produce the expected results.
10120 Statements are independent: if you stop the program with a breakpoint between
10121 statements, you can then assign a new value to any variable or change
10122 the program counter to any other statement in the subprogram and get exactly
10123 the results you would expect from the source code.
10125 Turning on optimization makes the compiler attempt to improve the
10126 performance and/or code size at the expense of compilation time and
10127 possibly the ability to debug the program.
10129 If you use multiple
10130 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10131 the last such option is the one that is effective.
10134 The default is optimization off. This results in the fastest compile
10135 times, but GNAT makes absolutely no attempt to optimize, and the
10136 generated programs are considerably larger and slower than when
10137 optimization is enabled. You can use the
10139 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10140 @option{-O2}, @option{-O3}, and @option{-Os})
10143 @code{OPTIMIZE} qualifier
10145 to @command{gcc} to control the optimization level:
10148 @item ^-O0^/OPTIMIZE=NONE^
10149 No optimization (the default);
10150 generates unoptimized code but has
10151 the fastest compilation time.
10153 Note that many other compilers do fairly extensive optimization
10154 even if ``no optimization'' is specified. With gcc, it is
10155 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10156 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10157 really does mean no optimization at all. This difference between
10158 gcc and other compilers should be kept in mind when doing
10159 performance comparisons.
10161 @item ^-O1^/OPTIMIZE=SOME^
10162 Moderate optimization;
10163 optimizes reasonably well but does not
10164 degrade compilation time significantly.
10166 @item ^-O2^/OPTIMIZE=ALL^
10168 @itemx /OPTIMIZE=DEVELOPMENT
10171 generates highly optimized code and has
10172 the slowest compilation time.
10174 @item ^-O3^/OPTIMIZE=INLINING^
10175 Full optimization as in @option{-O2};
10176 also uses more aggressive automatic inlining of subprograms within a unit
10177 (@pxref{Inlining of Subprograms}) and attemps to vectorize loops.
10179 @item ^-Os^/OPTIMIZE=SPACE^
10180 Optimize space usage (code and data) of resulting program.
10184 Higher optimization levels perform more global transformations on the
10185 program and apply more expensive analysis algorithms in order to generate
10186 faster and more compact code. The price in compilation time, and the
10187 resulting improvement in execution time,
10188 both depend on the particular application and the hardware environment.
10189 You should experiment to find the best level for your application.
10191 Since the precise set of optimizations done at each level will vary from
10192 release to release (and sometime from target to target), it is best to think
10193 of the optimization settings in general terms.
10194 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10195 the GNU Compiler Collection (GCC)}, for details about
10196 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10197 individually enable or disable specific optimizations.
10199 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10200 been tested extensively at all optimization levels. There are some bugs
10201 which appear only with optimization turned on, but there have also been
10202 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10203 level of optimization does not improve the reliability of the code
10204 generator, which in practice is highly reliable at all optimization
10207 Note regarding the use of @option{-O3}: The use of this optimization level
10208 is generally discouraged with GNAT, since it often results in larger
10209 executables which may run more slowly. See further discussion of this point
10210 in @ref{Inlining of Subprograms}.
10212 @node Debugging Optimized Code
10213 @subsection Debugging Optimized Code
10214 @cindex Debugging optimized code
10215 @cindex Optimization and debugging
10218 Although it is possible to do a reasonable amount of debugging at
10220 nonzero optimization levels,
10221 the higher the level the more likely that
10224 @option{/OPTIMIZE} settings other than @code{NONE},
10225 such settings will make it more likely that
10227 source-level constructs will have been eliminated by optimization.
10228 For example, if a loop is strength-reduced, the loop
10229 control variable may be completely eliminated and thus cannot be
10230 displayed in the debugger.
10231 This can only happen at @option{-O2} or @option{-O3}.
10232 Explicit temporary variables that you code might be eliminated at
10233 ^level^setting^ @option{-O1} or higher.
10235 The use of the @option{^-g^/DEBUG^} switch,
10236 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10237 which is needed for source-level debugging,
10238 affects the size of the program executable on disk,
10239 and indeed the debugging information can be quite large.
10240 However, it has no effect on the generated code (and thus does not
10241 degrade performance)
10243 Since the compiler generates debugging tables for a compilation unit before
10244 it performs optimizations, the optimizing transformations may invalidate some
10245 of the debugging data. You therefore need to anticipate certain
10246 anomalous situations that may arise while debugging optimized code.
10247 These are the most common cases:
10251 @i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next}
10253 the PC bouncing back and forth in the code. This may result from any of
10254 the following optimizations:
10258 @i{Common subexpression elimination:} using a single instance of code for a
10259 quantity that the source computes several times. As a result you
10260 may not be able to stop on what looks like a statement.
10263 @i{Invariant code motion:} moving an expression that does not change within a
10264 loop, to the beginning of the loop.
10267 @i{Instruction scheduling:} moving instructions so as to
10268 overlap loads and stores (typically) with other code, or in
10269 general to move computations of values closer to their uses. Often
10270 this causes you to pass an assignment statement without the assignment
10271 happening and then later bounce back to the statement when the
10272 value is actually needed. Placing a breakpoint on a line of code
10273 and then stepping over it may, therefore, not always cause all the
10274 expected side-effects.
10278 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10279 two identical pieces of code are merged and the program counter suddenly
10280 jumps to a statement that is not supposed to be executed, simply because
10281 it (and the code following) translates to the same thing as the code
10282 that @emph{was} supposed to be executed. This effect is typically seen in
10283 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10284 a @code{break} in a C @code{^switch^switch^} statement.
10287 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10288 There are various reasons for this effect:
10292 In a subprogram prologue, a parameter may not yet have been moved to its
10296 A variable may be dead, and its register re-used. This is
10297 probably the most common cause.
10300 As mentioned above, the assignment of a value to a variable may
10304 A variable may be eliminated entirely by value propagation or
10305 other means. In this case, GCC may incorrectly generate debugging
10306 information for the variable
10310 In general, when an unexpected value appears for a local variable or parameter
10311 you should first ascertain if that value was actually computed by
10312 your program, as opposed to being incorrectly reported by the debugger.
10314 array elements in an object designated by an access value
10315 are generally less of a problem, once you have ascertained that the access
10317 Typically, this means checking variables in the preceding code and in the
10318 calling subprogram to verify that the value observed is explainable from other
10319 values (one must apply the procedure recursively to those
10320 other values); or re-running the code and stopping a little earlier
10321 (perhaps before the call) and stepping to better see how the variable obtained
10322 the value in question; or continuing to step @emph{from} the point of the
10323 strange value to see if code motion had simply moved the variable's
10328 In light of such anomalies, a recommended technique is to use @option{-O0}
10329 early in the software development cycle, when extensive debugging capabilities
10330 are most needed, and then move to @option{-O1} and later @option{-O2} as
10331 the debugger becomes less critical.
10332 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10333 a release management issue.
10335 Note that if you use @option{-g} you can then use the @command{strip} program
10336 on the resulting executable,
10337 which removes both debugging information and global symbols.
10340 @node Inlining of Subprograms
10341 @subsection Inlining of Subprograms
10344 A call to a subprogram in the current unit is inlined if all the
10345 following conditions are met:
10349 The optimization level is at least @option{-O1}.
10352 The called subprogram is suitable for inlining: It must be small enough
10353 and not contain something that @command{gcc} cannot support in inlined
10357 @cindex pragma Inline
10359 Either @code{pragma Inline} applies to the subprogram, or it is local to
10360 the unit and called once from within it, or it is small and optimization
10361 level @option{-O2} is specified, or automatic inlining (optimization level
10362 @option{-O3}) is specified.
10366 Calls to subprograms in @code{with}'ed units are normally not inlined.
10367 To achieve actual inlining (that is, replacement of the call by the code
10368 in the body of the subprogram), the following conditions must all be true.
10372 The optimization level is at least @option{-O1}.
10375 The called subprogram is suitable for inlining: It must be small enough
10376 and not contain something that @command{gcc} cannot support in inlined
10380 The call appears in a body (not in a package spec).
10383 There is a @code{pragma Inline} for the subprogram.
10386 @cindex @option{-gnatn} (@command{gcc})
10387 The @option{^-gnatn^/INLINE^} switch
10388 is used in the @command{gcc} command line
10391 Even if all these conditions are met, it may not be possible for
10392 the compiler to inline the call, due to the length of the body,
10393 or features in the body that make it impossible for the compiler
10394 to do the inlining.
10396 Note that specifying the @option{-gnatn} switch causes additional
10397 compilation dependencies. Consider the following:
10399 @smallexample @c ada
10419 With the default behavior (no @option{-gnatn} switch specified), the
10420 compilation of the @code{Main} procedure depends only on its own source,
10421 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10422 means that editing the body of @code{R} does not require recompiling
10425 On the other hand, the call @code{R.Q} is not inlined under these
10426 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10427 is compiled, the call will be inlined if the body of @code{Q} is small
10428 enough, but now @code{Main} depends on the body of @code{R} in
10429 @file{r.adb} as well as on the spec. This means that if this body is edited,
10430 the main program must be recompiled. Note that this extra dependency
10431 occurs whether or not the call is in fact inlined by @command{gcc}.
10433 The use of front end inlining with @option{-gnatN} generates similar
10434 additional dependencies.
10436 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10437 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10438 can be used to prevent
10439 all inlining. This switch overrides all other conditions and ensures
10440 that no inlining occurs. The extra dependences resulting from
10441 @option{-gnatn} will still be active, even if
10442 this switch is used to suppress the resulting inlining actions.
10444 @cindex @option{-fno-inline-functions} (@command{gcc})
10445 Note: The @option{-fno-inline-functions} switch can be used to prevent
10446 automatic inlining of subprograms if @option{-O3} is used.
10448 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10449 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10450 automatic inlining of small subprograms if @option{-O2} is used.
10452 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10453 Note: The @option{-fno-inline-functions-called-once} switch
10454 can be used to prevent inlining of subprograms local to the unit
10455 and called once from within it if @option{-O1} is used.
10457 Note regarding the use of @option{-O3}: There is no difference in inlining
10458 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10459 pragma @code{Inline} assuming the use of @option{-gnatn}
10460 or @option{-gnatN} (the switches that activate inlining). If you have used
10461 pragma @code{Inline} in appropriate cases, then it is usually much better
10462 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10463 in this case only has the effect of inlining subprograms you did not
10464 think should be inlined. We often find that the use of @option{-O3} slows
10465 down code by performing excessive inlining, leading to increased instruction
10466 cache pressure from the increased code size. So the bottom line here is
10467 that you should not automatically assume that @option{-O3} is better than
10468 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10469 it actually improves performance.
10471 @node Other Optimization Switches
10472 @subsection Other Optimization Switches
10473 @cindex Optimization Switches
10475 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10476 @command{gcc} optimization switches are potentially usable. These switches
10477 have not been extensively tested with GNAT but can generally be expected
10478 to work. Examples of switches in this category are
10479 @option{-funroll-loops} and
10480 the various target-specific @option{-m} options (in particular, it has been
10481 observed that @option{-march=pentium4} can significantly improve performance
10482 on appropriate machines). For full details of these switches, see
10483 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10484 the GNU Compiler Collection (GCC)}.
10486 @node Optimization and Strict Aliasing
10487 @subsection Optimization and Strict Aliasing
10489 @cindex Strict Aliasing
10490 @cindex No_Strict_Aliasing
10493 The strong typing capabilities of Ada allow an optimizer to generate
10494 efficient code in situations where other languages would be forced to
10495 make worst case assumptions preventing such optimizations. Consider
10496 the following example:
10498 @smallexample @c ada
10501 type Int1 is new Integer;
10502 type Int2 is new Integer;
10503 type Int1A is access Int1;
10504 type Int2A is access Int2;
10511 for J in Data'Range loop
10512 if Data (J) = Int1V.all then
10513 Int2V.all := Int2V.all + 1;
10522 In this example, since the variable @code{Int1V} can only access objects
10523 of type @code{Int1}, and @code{Int2V} can only access objects of type
10524 @code{Int2}, there is no possibility that the assignment to
10525 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10526 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10527 for all iterations of the loop and avoid the extra memory reference
10528 required to dereference it each time through the loop.
10530 This kind of optimization, called strict aliasing analysis, is
10531 triggered by specifying an optimization level of @option{-O2} or
10532 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10533 when access values are involved.
10535 However, although this optimization is always correct in terms of
10536 the formal semantics of the Ada Reference Manual, difficulties can
10537 arise if features like @code{Unchecked_Conversion} are used to break
10538 the typing system. Consider the following complete program example:
10540 @smallexample @c ada
10543 type int1 is new integer;
10544 type int2 is new integer;
10545 type a1 is access int1;
10546 type a2 is access int2;
10551 function to_a2 (Input : a1) return a2;
10554 with Unchecked_Conversion;
10556 function to_a2 (Input : a1) return a2 is
10558 new Unchecked_Conversion (a1, a2);
10560 return to_a2u (Input);
10566 with Text_IO; use Text_IO;
10568 v1 : a1 := new int1;
10569 v2 : a2 := to_a2 (v1);
10573 put_line (int1'image (v1.all));
10579 This program prints out 0 in @option{-O0} or @option{-O1}
10580 mode, but it prints out 1 in @option{-O2} mode. That's
10581 because in strict aliasing mode, the compiler can and
10582 does assume that the assignment to @code{v2.all} could not
10583 affect the value of @code{v1.all}, since different types
10586 This behavior is not a case of non-conformance with the standard, since
10587 the Ada RM specifies that an unchecked conversion where the resulting
10588 bit pattern is not a correct value of the target type can result in an
10589 abnormal value and attempting to reference an abnormal value makes the
10590 execution of a program erroneous. That's the case here since the result
10591 does not point to an object of type @code{int2}. This means that the
10592 effect is entirely unpredictable.
10594 However, although that explanation may satisfy a language
10595 lawyer, in practice an applications programmer expects an
10596 unchecked conversion involving pointers to create true
10597 aliases and the behavior of printing 1 seems plain wrong.
10598 In this case, the strict aliasing optimization is unwelcome.
10600 Indeed the compiler recognizes this possibility, and the
10601 unchecked conversion generates a warning:
10604 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10605 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10606 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
10610 Unfortunately the problem is recognized when compiling the body of
10611 package @code{p2}, but the actual "bad" code is generated while
10612 compiling the body of @code{m} and this latter compilation does not see
10613 the suspicious @code{Unchecked_Conversion}.
10615 As implied by the warning message, there are approaches you can use to
10616 avoid the unwanted strict aliasing optimization in a case like this.
10618 One possibility is to simply avoid the use of @option{-O2}, but
10619 that is a bit drastic, since it throws away a number of useful
10620 optimizations that do not involve strict aliasing assumptions.
10622 A less drastic approach is to compile the program using the
10623 option @option{-fno-strict-aliasing}. Actually it is only the
10624 unit containing the dereferencing of the suspicious pointer
10625 that needs to be compiled. So in this case, if we compile
10626 unit @code{m} with this switch, then we get the expected
10627 value of zero printed. Analyzing which units might need
10628 the switch can be painful, so a more reasonable approach
10629 is to compile the entire program with options @option{-O2}
10630 and @option{-fno-strict-aliasing}. If the performance is
10631 satisfactory with this combination of options, then the
10632 advantage is that the entire issue of possible "wrong"
10633 optimization due to strict aliasing is avoided.
10635 To avoid the use of compiler switches, the configuration
10636 pragma @code{No_Strict_Aliasing} with no parameters may be
10637 used to specify that for all access types, the strict
10638 aliasing optimization should be suppressed.
10640 However, these approaches are still overkill, in that they causes
10641 all manipulations of all access values to be deoptimized. A more
10642 refined approach is to concentrate attention on the specific
10643 access type identified as problematic.
10645 First, if a careful analysis of uses of the pointer shows
10646 that there are no possible problematic references, then
10647 the warning can be suppressed by bracketing the
10648 instantiation of @code{Unchecked_Conversion} to turn
10651 @smallexample @c ada
10652 pragma Warnings (Off);
10654 new Unchecked_Conversion (a1, a2);
10655 pragma Warnings (On);
10659 Of course that approach is not appropriate for this particular
10660 example, since indeed there is a problematic reference. In this
10661 case we can take one of two other approaches.
10663 The first possibility is to move the instantiation of unchecked
10664 conversion to the unit in which the type is declared. In
10665 this example, we would move the instantiation of
10666 @code{Unchecked_Conversion} from the body of package
10667 @code{p2} to the spec of package @code{p1}. Now the
10668 warning disappears. That's because any use of the
10669 access type knows there is a suspicious unchecked
10670 conversion, and the strict aliasing optimization
10671 is automatically suppressed for the type.
10673 If it is not practical to move the unchecked conversion to the same unit
10674 in which the destination access type is declared (perhaps because the
10675 source type is not visible in that unit), you may use pragma
10676 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10677 same declarative sequence as the declaration of the access type:
10679 @smallexample @c ada
10680 type a2 is access int2;
10681 pragma No_Strict_Aliasing (a2);
10685 Here again, the compiler now knows that the strict aliasing optimization
10686 should be suppressed for any reference to type @code{a2} and the
10687 expected behavior is obtained.
10689 Finally, note that although the compiler can generate warnings for
10690 simple cases of unchecked conversions, there are tricker and more
10691 indirect ways of creating type incorrect aliases which the compiler
10692 cannot detect. Examples are the use of address overlays and unchecked
10693 conversions involving composite types containing access types as
10694 components. In such cases, no warnings are generated, but there can
10695 still be aliasing problems. One safe coding practice is to forbid the
10696 use of address clauses for type overlaying, and to allow unchecked
10697 conversion only for primitive types. This is not really a significant
10698 restriction since any possible desired effect can be achieved by
10699 unchecked conversion of access values.
10701 The aliasing analysis done in strict aliasing mode can certainly
10702 have significant benefits. We have seen cases of large scale
10703 application code where the time is increased by up to 5% by turning
10704 this optimization off. If you have code that includes significant
10705 usage of unchecked conversion, you might want to just stick with
10706 @option{-O1} and avoid the entire issue. If you get adequate
10707 performance at this level of optimization level, that's probably
10708 the safest approach. If tests show that you really need higher
10709 levels of optimization, then you can experiment with @option{-O2}
10710 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10711 has on size and speed of the code. If you really need to use
10712 @option{-O2} with strict aliasing in effect, then you should
10713 review any uses of unchecked conversion of access types,
10714 particularly if you are getting the warnings described above.
10717 @node Coverage Analysis
10718 @subsection Coverage Analysis
10721 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10722 the user to determine the distribution of execution time across a program,
10723 @pxref{Profiling} for details of usage.
10727 @node Text_IO Suggestions
10728 @section @code{Text_IO} Suggestions
10729 @cindex @code{Text_IO} and performance
10732 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10733 the requirement of maintaining page and line counts. If performance
10734 is critical, a recommendation is to use @code{Stream_IO} instead of
10735 @code{Text_IO} for volume output, since this package has less overhead.
10737 If @code{Text_IO} must be used, note that by default output to the standard
10738 output and standard error files is unbuffered (this provides better
10739 behavior when output statements are used for debugging, or if the
10740 progress of a program is observed by tracking the output, e.g. by
10741 using the Unix @command{tail -f} command to watch redirected output.
10743 If you are generating large volumes of output with @code{Text_IO} and
10744 performance is an important factor, use a designated file instead
10745 of the standard output file, or change the standard output file to
10746 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10750 @node Reducing Size of Ada Executables with gnatelim
10751 @section Reducing Size of Ada Executables with @code{gnatelim}
10755 This section describes @command{gnatelim}, a tool which detects unused
10756 subprograms and helps the compiler to create a smaller executable for your
10761 * Running gnatelim::
10762 * Processing Precompiled Libraries::
10763 * Correcting the List of Eliminate Pragmas::
10764 * Making Your Executables Smaller::
10765 * Summary of the gnatelim Usage Cycle::
10768 @node About gnatelim
10769 @subsection About @code{gnatelim}
10772 When a program shares a set of Ada
10773 packages with other programs, it may happen that this program uses
10774 only a fraction of the subprograms defined in these packages. The code
10775 created for these unused subprograms increases the size of the executable.
10777 @code{gnatelim} tracks unused subprograms in an Ada program and
10778 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10779 subprograms that are declared but never called. By placing the list of
10780 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10781 recompiling your program, you may decrease the size of its executable,
10782 because the compiler will not generate the code for 'eliminated' subprograms.
10783 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10784 information about this pragma.
10786 @code{gnatelim} needs as its input data the name of the main subprogram.
10788 If a set of source files is specified as @code{gnatelim} arguments, it
10789 treats these files as a complete set of sources making up a program to
10790 analyse, and analyses only these sources.
10792 After a full successful build of the main subprogram @code{gnatelim} can be
10793 called without specifying sources to analyse, in this case it computes
10794 the source closure of the main unit from the @file{ALI} files.
10796 The following command will create the set of @file{ALI} files needed for
10800 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10803 Note that @code{gnatelim} does not need object files.
10805 @node Running gnatelim
10806 @subsection Running @code{gnatelim}
10809 @code{gnatelim} has the following command-line interface:
10812 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
10816 @var{main_unit_name} should be a name of a source file that contains the main
10817 subprogram of a program (partition).
10819 Each @var{filename} is the name (including the extension) of a source
10820 file to process. ``Wildcards'' are allowed, and
10821 the file name may contain path information.
10823 @samp{@var{gcc_switches}} is a list of switches for
10824 @command{gcc}. They will be passed on to all compiler invocations made by
10825 @command{gnatelim} to generate the ASIS trees. Here you can provide
10826 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
10827 use the @option{-gnatec} switch to set the configuration file,
10828 use the @option{-gnat05} switch if sources should be compiled in
10831 @code{gnatelim} has the following switches:
10835 @item ^-files^/FILES^=@var{filename}
10836 @cindex @option{^-files^/FILES^} (@code{gnatelim})
10837 Take the argument source files from the specified file. This file should be an
10838 ordinary text file containing file names separated by spaces or
10839 line breaks. You can use this switch more than once in the same call to
10840 @command{gnatelim}. You also can combine this switch with
10841 an explicit list of files.
10844 @cindex @option{^-log^/LOG^} (@command{gnatelim})
10845 Duplicate all the output sent to @file{stderr} into a log file. The log file
10846 is named @file{gnatelim.log} and is located in the current directory.
10848 @item ^-log^/LOGFILE^=@var{filename}
10849 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
10850 Duplicate all the output sent to @file{stderr} into a specified log file.
10852 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
10853 @item ^--no-elim-dispatch^/NO_DISPATCH^
10854 Do not generate pragmas for dispatching operations.
10856 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
10857 @item ^-o^/OUTPUT^=@var{report_file}
10858 Put @command{gnatelim} output into a specified file. If this file already exists,
10859 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
10863 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10864 Quiet mode: by default @code{gnatelim} outputs to the standard error
10865 stream the number of program units left to be processed. This option turns
10868 @cindex @option{^-t^/TIME^} (@command{gnatelim})
10870 Print out execution time.
10872 @item ^-v^/VERBOSE^
10873 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10874 Verbose mode: @code{gnatelim} version information is printed as Ada
10875 comments to the standard output stream. Also, in addition to the number of
10876 program units left @code{gnatelim} will output the name of the current unit
10879 @item ^-wq^/WARNINGS=QUIET^
10880 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
10881 Quet warning mode - some warnings are suppressed. In particular warnings that
10882 indicate that the analysed set of sources is incomplete to make up a
10883 partition and that some subprogram bodies are missing are not generated.
10886 @node Processing Precompiled Libraries
10887 @subsection Processing Precompiled Libraries
10890 If some program uses a precompiled Ada library, it can be processed by
10891 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
10892 Eliminate pragma for a subprogram if the body of this subprogram has not
10893 been analysed, this is a typical case for subprograms from precompiled
10894 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
10895 warnings about missing source files and non-analyzed subprogram bodies
10896 that can be generated when processing precompiled Ada libraries.
10898 @node Correcting the List of Eliminate Pragmas
10899 @subsection Correcting the List of Eliminate Pragmas
10902 In some rare cases @code{gnatelim} may try to eliminate
10903 subprograms that are actually called in the program. In this case, the
10904 compiler will generate an error message of the form:
10907 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
10911 You will need to manually remove the wrong @code{Eliminate} pragmas from
10912 the configuration file indicated in the error message. You should recompile
10913 your program from scratch after that, because you need a consistent
10914 configuration file(s) during the entire compilation.
10916 @node Making Your Executables Smaller
10917 @subsection Making Your Executables Smaller
10920 In order to get a smaller executable for your program you now have to
10921 recompile the program completely with the configuration file containing
10922 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
10923 @file{gnat.adc} file located in your current directory, just do:
10926 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10930 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10931 recompile everything
10932 with the set of pragmas @code{Eliminate} that you have obtained with
10933 @command{gnatelim}).
10935 Be aware that the set of @code{Eliminate} pragmas is specific to each
10936 program. It is not recommended to merge sets of @code{Eliminate}
10937 pragmas created for different programs in one configuration file.
10939 @node Summary of the gnatelim Usage Cycle
10940 @subsection Summary of the @code{gnatelim} Usage Cycle
10943 Here is a quick summary of the steps to be taken in order to reduce
10944 the size of your executables with @code{gnatelim}. You may use
10945 other GNAT options to control the optimization level,
10946 to produce the debugging information, to set search path, etc.
10950 Create a complete set of @file{ALI} files (if the program has not been
10954 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10958 Generate a list of @code{Eliminate} pragmas in default configuration file
10959 @file{gnat.adc} in the current directory
10962 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10965 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
10970 Recompile the application
10973 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10978 @node Reducing Size of Executables with unused subprogram/data elimination
10979 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10980 @findex unused subprogram/data elimination
10983 This section describes how you can eliminate unused subprograms and data from
10984 your executable just by setting options at compilation time.
10987 * About unused subprogram/data elimination::
10988 * Compilation options::
10989 * Example of unused subprogram/data elimination::
10992 @node About unused subprogram/data elimination
10993 @subsection About unused subprogram/data elimination
10996 By default, an executable contains all code and data of its composing objects
10997 (directly linked or coming from statically linked libraries), even data or code
10998 never used by this executable.
11000 This feature will allow you to eliminate such unused code from your
11001 executable, making it smaller (in disk and in memory).
11003 This functionality is available on all Linux platforms except for the IA-64
11004 architecture and on all cross platforms using the ELF binary file format.
11005 In both cases GNU binutils version 2.16 or later are required to enable it.
11007 @node Compilation options
11008 @subsection Compilation options
11011 The operation of eliminating the unused code and data from the final executable
11012 is directly performed by the linker.
11014 In order to do this, it has to work with objects compiled with the
11016 @option{-ffunction-sections} @option{-fdata-sections}.
11017 @cindex @option{-ffunction-sections} (@command{gcc})
11018 @cindex @option{-fdata-sections} (@command{gcc})
11019 These options are usable with C and Ada files.
11020 They will place respectively each
11021 function or data in a separate section in the resulting object file.
11023 Once the objects and static libraries are created with these options, the
11024 linker can perform the dead code elimination. You can do this by setting
11025 the @option{-Wl,--gc-sections} option to gcc command or in the
11026 @option{-largs} section of @command{gnatmake}. This will perform a
11027 garbage collection of code and data never referenced.
11029 If the linker performs a partial link (@option{-r} ld linker option), then you
11030 will need to provide one or several entry point using the
11031 @option{-e} / @option{--entry} ld option.
11033 Note that objects compiled without the @option{-ffunction-sections} and
11034 @option{-fdata-sections} options can still be linked with the executable.
11035 However, no dead code elimination will be performed on those objects (they will
11038 The GNAT static library is now compiled with -ffunction-sections and
11039 -fdata-sections on some platforms. This allows you to eliminate the unused code
11040 and data of the GNAT library from your executable.
11042 @node Example of unused subprogram/data elimination
11043 @subsection Example of unused subprogram/data elimination
11046 Here is a simple example:
11048 @smallexample @c ada
11057 Used_Data : Integer;
11058 Unused_Data : Integer;
11060 procedure Used (Data : Integer);
11061 procedure Unused (Data : Integer);
11064 package body Aux is
11065 procedure Used (Data : Integer) is
11070 procedure Unused (Data : Integer) is
11072 Unused_Data := Data;
11078 @code{Unused} and @code{Unused_Data} are never referenced in this code
11079 excerpt, and hence they may be safely removed from the final executable.
11084 $ nm test | grep used
11085 020015f0 T aux__unused
11086 02005d88 B aux__unused_data
11087 020015cc T aux__used
11088 02005d84 B aux__used_data
11090 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11091 -largs -Wl,--gc-sections
11093 $ nm test | grep used
11094 02005350 T aux__used
11095 0201ffe0 B aux__used_data
11099 It can be observed that the procedure @code{Unused} and the object
11100 @code{Unused_Data} are removed by the linker when using the
11101 appropriate options.
11103 @c ********************************
11104 @node Renaming Files Using gnatchop
11105 @chapter Renaming Files Using @code{gnatchop}
11109 This chapter discusses how to handle files with multiple units by using
11110 the @code{gnatchop} utility. This utility is also useful in renaming
11111 files to meet the standard GNAT default file naming conventions.
11114 * Handling Files with Multiple Units::
11115 * Operating gnatchop in Compilation Mode::
11116 * Command Line for gnatchop::
11117 * Switches for gnatchop::
11118 * Examples of gnatchop Usage::
11121 @node Handling Files with Multiple Units
11122 @section Handling Files with Multiple Units
11125 The basic compilation model of GNAT requires that a file submitted to the
11126 compiler have only one unit and there be a strict correspondence
11127 between the file name and the unit name.
11129 The @code{gnatchop} utility allows both of these rules to be relaxed,
11130 allowing GNAT to process files which contain multiple compilation units
11131 and files with arbitrary file names. @code{gnatchop}
11132 reads the specified file and generates one or more output files,
11133 containing one unit per file. The unit and the file name correspond,
11134 as required by GNAT.
11136 If you want to permanently restructure a set of ``foreign'' files so that
11137 they match the GNAT rules, and do the remaining development using the
11138 GNAT structure, you can simply use @command{gnatchop} once, generate the
11139 new set of files and work with them from that point on.
11141 Alternatively, if you want to keep your files in the ``foreign'' format,
11142 perhaps to maintain compatibility with some other Ada compilation
11143 system, you can set up a procedure where you use @command{gnatchop} each
11144 time you compile, regarding the source files that it writes as temporary
11145 files that you throw away.
11147 Note that if your file containing multiple units starts with a byte order
11148 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11149 will each start with a copy of this BOM, meaning that they can be compiled
11150 automatically in UTF-8 mode without needing to specify an explicit encoding.
11152 @node Operating gnatchop in Compilation Mode
11153 @section Operating gnatchop in Compilation Mode
11156 The basic function of @code{gnatchop} is to take a file with multiple units
11157 and split it into separate files. The boundary between files is reasonably
11158 clear, except for the issue of comments and pragmas. In default mode, the
11159 rule is that any pragmas between units belong to the previous unit, except
11160 that configuration pragmas always belong to the following unit. Any comments
11161 belong to the following unit. These rules
11162 almost always result in the right choice of
11163 the split point without needing to mark it explicitly and most users will
11164 find this default to be what they want. In this default mode it is incorrect to
11165 submit a file containing only configuration pragmas, or one that ends in
11166 configuration pragmas, to @code{gnatchop}.
11168 However, using a special option to activate ``compilation mode'',
11170 can perform another function, which is to provide exactly the semantics
11171 required by the RM for handling of configuration pragmas in a compilation.
11172 In the absence of configuration pragmas (at the main file level), this
11173 option has no effect, but it causes such configuration pragmas to be handled
11174 in a quite different manner.
11176 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11177 only configuration pragmas, then this file is appended to the
11178 @file{gnat.adc} file in the current directory. This behavior provides
11179 the required behavior described in the RM for the actions to be taken
11180 on submitting such a file to the compiler, namely that these pragmas
11181 should apply to all subsequent compilations in the same compilation
11182 environment. Using GNAT, the current directory, possibly containing a
11183 @file{gnat.adc} file is the representation
11184 of a compilation environment. For more information on the
11185 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11187 Second, in compilation mode, if @code{gnatchop}
11188 is given a file that starts with
11189 configuration pragmas, and contains one or more units, then these
11190 configuration pragmas are prepended to each of the chopped files. This
11191 behavior provides the required behavior described in the RM for the
11192 actions to be taken on compiling such a file, namely that the pragmas
11193 apply to all units in the compilation, but not to subsequently compiled
11196 Finally, if configuration pragmas appear between units, they are appended
11197 to the previous unit. This results in the previous unit being illegal,
11198 since the compiler does not accept configuration pragmas that follow
11199 a unit. This provides the required RM behavior that forbids configuration
11200 pragmas other than those preceding the first compilation unit of a
11203 For most purposes, @code{gnatchop} will be used in default mode. The
11204 compilation mode described above is used only if you need exactly
11205 accurate behavior with respect to compilations, and you have files
11206 that contain multiple units and configuration pragmas. In this
11207 circumstance the use of @code{gnatchop} with the compilation mode
11208 switch provides the required behavior, and is for example the mode
11209 in which GNAT processes the ACVC tests.
11211 @node Command Line for gnatchop
11212 @section Command Line for @code{gnatchop}
11215 The @code{gnatchop} command has the form:
11218 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11219 @c @ovar{directory}
11220 @c Expanding @ovar macro inline (explanation in macro def comments)
11221 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11222 @r{[}@var{directory}@r{]}
11226 The only required argument is the file name of the file to be chopped.
11227 There are no restrictions on the form of this file name. The file itself
11228 contains one or more Ada units, in normal GNAT format, concatenated
11229 together. As shown, more than one file may be presented to be chopped.
11231 When run in default mode, @code{gnatchop} generates one output file in
11232 the current directory for each unit in each of the files.
11234 @var{directory}, if specified, gives the name of the directory to which
11235 the output files will be written. If it is not specified, all files are
11236 written to the current directory.
11238 For example, given a
11239 file called @file{hellofiles} containing
11241 @smallexample @c ada
11246 with Text_IO; use Text_IO;
11249 Put_Line ("Hello");
11259 $ gnatchop ^hellofiles^HELLOFILES.^
11263 generates two files in the current directory, one called
11264 @file{hello.ads} containing the single line that is the procedure spec,
11265 and the other called @file{hello.adb} containing the remaining text. The
11266 original file is not affected. The generated files can be compiled in
11270 When gnatchop is invoked on a file that is empty or that contains only empty
11271 lines and/or comments, gnatchop will not fail, but will not produce any
11274 For example, given a
11275 file called @file{toto.txt} containing
11277 @smallexample @c ada
11289 $ gnatchop ^toto.txt^TOT.TXT^
11293 will not produce any new file and will result in the following warnings:
11296 toto.txt:1:01: warning: empty file, contains no compilation units
11297 no compilation units found
11298 no source files written
11301 @node Switches for gnatchop
11302 @section Switches for @code{gnatchop}
11305 @command{gnatchop} recognizes the following switches:
11311 @cindex @option{--version} @command{gnatchop}
11312 Display Copyright and version, then exit disregarding all other options.
11315 @cindex @option{--help} @command{gnatchop}
11316 If @option{--version} was not used, display usage, then exit disregarding
11319 @item ^-c^/COMPILATION^
11320 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11321 Causes @code{gnatchop} to operate in compilation mode, in which
11322 configuration pragmas are handled according to strict RM rules. See
11323 previous section for a full description of this mode.
11326 @item -gnat@var{xxx}
11327 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11328 used to parse the given file. Not all @var{xxx} options make sense,
11329 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11330 process a source file that uses Latin-2 coding for identifiers.
11334 Causes @code{gnatchop} to generate a brief help summary to the standard
11335 output file showing usage information.
11337 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11338 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11339 Limit generated file names to the specified number @code{mm}
11341 This is useful if the
11342 resulting set of files is required to be interoperable with systems
11343 which limit the length of file names.
11345 If no value is given, or
11346 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11347 a default of 39, suitable for OpenVMS Alpha
11348 Systems, is assumed
11351 No space is allowed between the @option{-k} and the numeric value. The numeric
11352 value may be omitted in which case a default of @option{-k8},
11354 with DOS-like file systems, is used. If no @option{-k} switch
11356 there is no limit on the length of file names.
11359 @item ^-p^/PRESERVE^
11360 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11361 Causes the file ^modification^creation^ time stamp of the input file to be
11362 preserved and used for the time stamp of the output file(s). This may be
11363 useful for preserving coherency of time stamps in an environment where
11364 @code{gnatchop} is used as part of a standard build process.
11367 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11368 Causes output of informational messages indicating the set of generated
11369 files to be suppressed. Warnings and error messages are unaffected.
11371 @item ^-r^/REFERENCE^
11372 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11373 @findex Source_Reference
11374 Generate @code{Source_Reference} pragmas. Use this switch if the output
11375 files are regarded as temporary and development is to be done in terms
11376 of the original unchopped file. This switch causes
11377 @code{Source_Reference} pragmas to be inserted into each of the
11378 generated files to refers back to the original file name and line number.
11379 The result is that all error messages refer back to the original
11381 In addition, the debugging information placed into the object file (when
11382 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11384 also refers back to this original file so that tools like profilers and
11385 debuggers will give information in terms of the original unchopped file.
11387 If the original file to be chopped itself contains
11388 a @code{Source_Reference}
11389 pragma referencing a third file, then gnatchop respects
11390 this pragma, and the generated @code{Source_Reference} pragmas
11391 in the chopped file refer to the original file, with appropriate
11392 line numbers. This is particularly useful when @code{gnatchop}
11393 is used in conjunction with @code{gnatprep} to compile files that
11394 contain preprocessing statements and multiple units.
11396 @item ^-v^/VERBOSE^
11397 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11398 Causes @code{gnatchop} to operate in verbose mode. The version
11399 number and copyright notice are output, as well as exact copies of
11400 the gnat1 commands spawned to obtain the chop control information.
11402 @item ^-w^/OVERWRITE^
11403 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11404 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11405 fatal error if there is already a file with the same name as a
11406 file it would otherwise output, in other words if the files to be
11407 chopped contain duplicated units. This switch bypasses this
11408 check, and causes all but the last instance of such duplicated
11409 units to be skipped.
11412 @item --GCC=@var{xxxx}
11413 @cindex @option{--GCC=} (@code{gnatchop})
11414 Specify the path of the GNAT parser to be used. When this switch is used,
11415 no attempt is made to add the prefix to the GNAT parser executable.
11419 @node Examples of gnatchop Usage
11420 @section Examples of @code{gnatchop} Usage
11424 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11427 @item gnatchop -w hello_s.ada prerelease/files
11430 Chops the source file @file{hello_s.ada}. The output files will be
11431 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11433 files with matching names in that directory (no files in the current
11434 directory are modified).
11436 @item gnatchop ^archive^ARCHIVE.^
11437 Chops the source file @file{^archive^ARCHIVE.^}
11438 into the current directory. One
11439 useful application of @code{gnatchop} is in sending sets of sources
11440 around, for example in email messages. The required sources are simply
11441 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11443 @command{gnatchop} is used at the other end to reconstitute the original
11446 @item gnatchop file1 file2 file3 direc
11447 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11448 the resulting files in the directory @file{direc}. Note that if any units
11449 occur more than once anywhere within this set of files, an error message
11450 is generated, and no files are written. To override this check, use the
11451 @option{^-w^/OVERWRITE^} switch,
11452 in which case the last occurrence in the last file will
11453 be the one that is output, and earlier duplicate occurrences for a given
11454 unit will be skipped.
11457 @node Configuration Pragmas
11458 @chapter Configuration Pragmas
11459 @cindex Configuration pragmas
11460 @cindex Pragmas, configuration
11463 Configuration pragmas include those pragmas described as
11464 such in the Ada Reference Manual, as well as
11465 implementation-dependent pragmas that are configuration pragmas.
11466 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11467 for details on these additional GNAT-specific configuration pragmas.
11468 Most notably, the pragma @code{Source_File_Name}, which allows
11469 specifying non-default names for source files, is a configuration
11470 pragma. The following is a complete list of configuration pragmas
11471 recognized by GNAT:
11481 Assume_No_Invalid_Values
11486 Compile_Time_Warning
11488 Component_Alignment
11489 Convention_Identifier
11497 External_Name_Casing
11500 Float_Representation
11513 Priority_Specific_Dispatching
11516 Propagate_Exceptions
11519 Restricted_Run_Time
11521 Restrictions_Warnings
11523 Short_Circuit_And_Or
11525 Source_File_Name_Project
11528 Suppress_Exception_Locations
11529 Task_Dispatching_Policy
11535 Wide_Character_Encoding
11540 * Handling of Configuration Pragmas::
11541 * The Configuration Pragmas Files::
11544 @node Handling of Configuration Pragmas
11545 @section Handling of Configuration Pragmas
11547 Configuration pragmas may either appear at the start of a compilation
11548 unit, in which case they apply only to that unit, or they may apply to
11549 all compilations performed in a given compilation environment.
11551 GNAT also provides the @code{gnatchop} utility to provide an automatic
11552 way to handle configuration pragmas following the semantics for
11553 compilations (that is, files with multiple units), described in the RM.
11554 See @ref{Operating gnatchop in Compilation Mode} for details.
11555 However, for most purposes, it will be more convenient to edit the
11556 @file{gnat.adc} file that contains configuration pragmas directly,
11557 as described in the following section.
11559 @node The Configuration Pragmas Files
11560 @section The Configuration Pragmas Files
11561 @cindex @file{gnat.adc}
11564 In GNAT a compilation environment is defined by the current
11565 directory at the time that a compile command is given. This current
11566 directory is searched for a file whose name is @file{gnat.adc}. If
11567 this file is present, it is expected to contain one or more
11568 configuration pragmas that will be applied to the current compilation.
11569 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11572 Configuration pragmas may be entered into the @file{gnat.adc} file
11573 either by running @code{gnatchop} on a source file that consists only of
11574 configuration pragmas, or more conveniently by
11575 direct editing of the @file{gnat.adc} file, which is a standard format
11578 In addition to @file{gnat.adc}, additional files containing configuration
11579 pragmas may be applied to the current compilation using the switch
11580 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11581 contains only configuration pragmas. These configuration pragmas are
11582 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11583 is present and switch @option{-gnatA} is not used).
11585 It is allowed to specify several switches @option{-gnatec}, all of which
11586 will be taken into account.
11588 If you are using project file, a separate mechanism is provided using
11589 project attributes, see @ref{Specifying Configuration Pragmas} for more
11593 Of special interest to GNAT OpenVMS Alpha is the following
11594 configuration pragma:
11596 @smallexample @c ada
11598 pragma Extend_System (Aux_DEC);
11603 In the presence of this pragma, GNAT adds to the definition of the
11604 predefined package SYSTEM all the additional types and subprograms that are
11605 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11608 @node Handling Arbitrary File Naming Conventions Using gnatname
11609 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11610 @cindex Arbitrary File Naming Conventions
11613 * Arbitrary File Naming Conventions::
11614 * Running gnatname::
11615 * Switches for gnatname::
11616 * Examples of gnatname Usage::
11619 @node Arbitrary File Naming Conventions
11620 @section Arbitrary File Naming Conventions
11623 The GNAT compiler must be able to know the source file name of a compilation
11624 unit. When using the standard GNAT default file naming conventions
11625 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11626 does not need additional information.
11629 When the source file names do not follow the standard GNAT default file naming
11630 conventions, the GNAT compiler must be given additional information through
11631 a configuration pragmas file (@pxref{Configuration Pragmas})
11633 When the non-standard file naming conventions are well-defined,
11634 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11635 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11636 if the file naming conventions are irregular or arbitrary, a number
11637 of pragma @code{Source_File_Name} for individual compilation units
11639 To help maintain the correspondence between compilation unit names and
11640 source file names within the compiler,
11641 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11644 @node Running gnatname
11645 @section Running @code{gnatname}
11648 The usual form of the @code{gnatname} command is
11651 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11652 @c @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11653 @c Expanding @ovar macro inline (explanation in macro def comments)
11654 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11655 @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11659 All of the arguments are optional. If invoked without any argument,
11660 @code{gnatname} will display its usage.
11663 When used with at least one naming pattern, @code{gnatname} will attempt to
11664 find all the compilation units in files that follow at least one of the
11665 naming patterns. To find these compilation units,
11666 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11670 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11671 Each Naming Pattern is enclosed between double quotes (or single
11672 quotes on Windows).
11673 A Naming Pattern is a regular expression similar to the wildcard patterns
11674 used in file names by the Unix shells or the DOS prompt.
11677 @code{gnatname} may be called with several sections of directories/patterns.
11678 Sections are separated by switch @code{--and}. In each section, there must be
11679 at least one pattern. If no directory is specified in a section, the current
11680 directory (or the project directory is @code{-P} is used) is implied.
11681 The options other that the directory switches and the patterns apply globally
11682 even if they are in different sections.
11685 Examples of Naming Patterns are
11694 For a more complete description of the syntax of Naming Patterns,
11695 see the second kind of regular expressions described in @file{g-regexp.ads}
11696 (the ``Glob'' regular expressions).
11699 When invoked with no switch @code{-P}, @code{gnatname} will create a
11700 configuration pragmas file @file{gnat.adc} in the current working directory,
11701 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11704 @node Switches for gnatname
11705 @section Switches for @code{gnatname}
11708 Switches for @code{gnatname} must precede any specified Naming Pattern.
11711 You may specify any of the following switches to @code{gnatname}:
11717 @cindex @option{--version} @command{gnatname}
11718 Display Copyright and version, then exit disregarding all other options.
11721 @cindex @option{--help} @command{gnatname}
11722 If @option{--version} was not used, display usage, then exit disregarding
11726 Start another section of directories/patterns.
11728 @item ^-c^/CONFIG_FILE=^@file{file}
11729 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11730 Create a configuration pragmas file @file{file} (instead of the default
11733 There may be zero, one or more space between @option{-c} and
11736 @file{file} may include directory information. @file{file} must be
11737 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11738 When a switch @option{^-c^/CONFIG_FILE^} is
11739 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11741 @item ^-d^/SOURCE_DIRS=^@file{dir}
11742 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11743 Look for source files in directory @file{dir}. There may be zero, one or more
11744 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11745 When a switch @option{^-d^/SOURCE_DIRS^}
11746 is specified, the current working directory will not be searched for source
11747 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11748 or @option{^-D^/DIR_FILES^} switch.
11749 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11750 If @file{dir} is a relative path, it is relative to the directory of
11751 the configuration pragmas file specified with switch
11752 @option{^-c^/CONFIG_FILE^},
11753 or to the directory of the project file specified with switch
11754 @option{^-P^/PROJECT_FILE^} or,
11755 if neither switch @option{^-c^/CONFIG_FILE^}
11756 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11757 current working directory. The directory
11758 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11760 @item ^-D^/DIRS_FILE=^@file{file}
11761 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11762 Look for source files in all directories listed in text file @file{file}.
11763 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11765 @file{file} must be an existing, readable text file.
11766 Each nonempty line in @file{file} must be a directory.
11767 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11768 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11771 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11772 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11773 Foreign patterns. Using this switch, it is possible to add sources of languages
11774 other than Ada to the list of sources of a project file.
11775 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11778 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11781 will look for Ada units in all files with the @file{.ada} extension,
11782 and will add to the list of file for project @file{prj.gpr} the C files
11783 with extension @file{.^c^C^}.
11786 @cindex @option{^-h^/HELP^} (@code{gnatname})
11787 Output usage (help) information. The output is written to @file{stdout}.
11789 @item ^-P^/PROJECT_FILE=^@file{proj}
11790 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11791 Create or update project file @file{proj}. There may be zero, one or more space
11792 between @option{-P} and @file{proj}. @file{proj} may include directory
11793 information. @file{proj} must be writable.
11794 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11795 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11796 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11798 @item ^-v^/VERBOSE^
11799 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11800 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11801 This includes name of the file written, the name of the directories to search
11802 and, for each file in those directories whose name matches at least one of
11803 the Naming Patterns, an indication of whether the file contains a unit,
11804 and if so the name of the unit.
11806 @item ^-v -v^/VERBOSE /VERBOSE^
11807 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11808 Very Verbose mode. In addition to the output produced in verbose mode,
11809 for each file in the searched directories whose name matches none of
11810 the Naming Patterns, an indication is given that there is no match.
11812 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11813 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11814 Excluded patterns. Using this switch, it is possible to exclude some files
11815 that would match the name patterns. For example,
11817 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11820 will look for Ada units in all files with the @file{.ada} extension,
11821 except those whose names end with @file{_nt.ada}.
11825 @node Examples of gnatname Usage
11826 @section Examples of @code{gnatname} Usage
11830 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11836 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11841 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11842 and be writable. In addition, the directory
11843 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11844 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11847 Note the optional spaces after @option{-c} and @option{-d}.
11852 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11853 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11856 $ gnatname /PROJECT_FILE=[HOME.ME]PROJ
11857 /EXCLUDED_PATTERN=*_nt_body.ada
11858 /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11859 /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11863 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11864 even in conjunction with one or several switches
11865 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11866 are used in this example.
11868 @c *****************************************
11869 @c * G N A T P r o j e c t M a n a g e r *
11870 @c *****************************************
11872 @c ------ macros for projects.texi
11873 @c These macros are needed when building the gprbuild documentation, but
11874 @c should have no effect in the gnat user's guide
11876 @macro CODESAMPLE{TXT}
11884 @macro PROJECTFILE{TXT}
11888 @c simulates a newline when in a @CODESAMPLE
11899 @macro TIPHTML{TXT}
11903 @macro IMPORTANT{TXT}
11918 @include projects.texi
11920 @c *****************************************
11921 @c * Cross-referencing tools
11922 @c *****************************************
11924 @node The Cross-Referencing Tools gnatxref and gnatfind
11925 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
11930 The compiler generates cross-referencing information (unless
11931 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
11932 This information indicates where in the source each entity is declared and
11933 referenced. Note that entities in package Standard are not included, but
11934 entities in all other predefined units are included in the output.
11936 Before using any of these two tools, you need to compile successfully your
11937 application, so that GNAT gets a chance to generate the cross-referencing
11940 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
11941 information to provide the user with the capability to easily locate the
11942 declaration and references to an entity. These tools are quite similar,
11943 the difference being that @code{gnatfind} is intended for locating
11944 definitions and/or references to a specified entity or entities, whereas
11945 @code{gnatxref} is oriented to generating a full report of all
11948 To use these tools, you must not compile your application using the
11949 @option{-gnatx} switch on the @command{gnatmake} command line
11950 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
11951 information will not be generated.
11953 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
11954 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
11957 * Switches for gnatxref::
11958 * Switches for gnatfind::
11959 * Project Files for gnatxref and gnatfind::
11960 * Regular Expressions in gnatfind and gnatxref::
11961 * Examples of gnatxref Usage::
11962 * Examples of gnatfind Usage::
11965 @node Switches for gnatxref
11966 @section @code{gnatxref} Switches
11969 The command invocation for @code{gnatxref} is:
11971 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
11972 @c Expanding @ovar macro inline (explanation in macro def comments)
11973 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
11982 identifies the source files for which a report is to be generated. The
11983 ``with''ed units will be processed too. You must provide at least one file.
11985 These file names are considered to be regular expressions, so for instance
11986 specifying @file{source*.adb} is the same as giving every file in the current
11987 directory whose name starts with @file{source} and whose extension is
11990 You shouldn't specify any directory name, just base names. @command{gnatxref}
11991 and @command{gnatfind} will be able to locate these files by themselves using
11992 the source path. If you specify directories, no result is produced.
11997 The switches can be:
12001 @cindex @option{--version} @command{gnatxref}
12002 Display Copyright and version, then exit disregarding all other options.
12005 @cindex @option{--help} @command{gnatxref}
12006 If @option{--version} was not used, display usage, then exit disregarding
12009 @item ^-a^/ALL_FILES^
12010 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
12011 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12012 the read-only files found in the library search path. Otherwise, these files
12013 will be ignored. This option can be used to protect Gnat sources or your own
12014 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12015 much faster, and their output much smaller. Read-only here refers to access
12016 or permissions status in the file system for the current user.
12019 @cindex @option{-aIDIR} (@command{gnatxref})
12020 When looking for source files also look in directory DIR. The order in which
12021 source file search is undertaken is the same as for @command{gnatmake}.
12024 @cindex @option{-aODIR} (@command{gnatxref})
12025 When searching for library and object files, look in directory
12026 DIR. The order in which library files are searched is the same as for
12027 @command{gnatmake}.
12030 @cindex @option{-nostdinc} (@command{gnatxref})
12031 Do not look for sources in the system default directory.
12034 @cindex @option{-nostdlib} (@command{gnatxref})
12035 Do not look for library files in the system default directory.
12037 @item --ext=@var{extension}
12038 @cindex @option{--ext} (@command{gnatxref})
12039 Specify an alternate ali file extension. The default is @code{ali} and other
12040 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12041 switch. Note that if this switch overrides the default, which means that only
12042 the new extension will be considered.
12044 @item --RTS=@var{rts-path}
12045 @cindex @option{--RTS} (@command{gnatxref})
12046 Specifies the default location of the runtime library. Same meaning as the
12047 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12049 @item ^-d^/DERIVED_TYPES^
12050 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
12051 If this switch is set @code{gnatxref} will output the parent type
12052 reference for each matching derived types.
12054 @item ^-f^/FULL_PATHNAME^
12055 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
12056 If this switch is set, the output file names will be preceded by their
12057 directory (if the file was found in the search path). If this switch is
12058 not set, the directory will not be printed.
12060 @item ^-g^/IGNORE_LOCALS^
12061 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
12062 If this switch is set, information is output only for library-level
12063 entities, ignoring local entities. The use of this switch may accelerate
12064 @code{gnatfind} and @code{gnatxref}.
12067 @cindex @option{-IDIR} (@command{gnatxref})
12068 Equivalent to @samp{-aODIR -aIDIR}.
12071 @cindex @option{-pFILE} (@command{gnatxref})
12072 Specify a project file to use @xref{GNAT Project Manager}.
12073 If you need to use the @file{.gpr}
12074 project files, you should use gnatxref through the GNAT driver
12075 (@command{gnat xref -Pproject}).
12077 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12078 project file in the current directory.
12080 If a project file is either specified or found by the tools, then the content
12081 of the source directory and object directory lines are added as if they
12082 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
12083 and @samp{^-aO^OBJECT_SEARCH^}.
12085 Output only unused symbols. This may be really useful if you give your
12086 main compilation unit on the command line, as @code{gnatxref} will then
12087 display every unused entity and 'with'ed package.
12091 Instead of producing the default output, @code{gnatxref} will generate a
12092 @file{tags} file that can be used by vi. For examples how to use this
12093 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
12094 to the standard output, thus you will have to redirect it to a file.
12100 All these switches may be in any order on the command line, and may even
12101 appear after the file names. They need not be separated by spaces, thus
12102 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12103 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12105 @node Switches for gnatfind
12106 @section @code{gnatfind} Switches
12109 The command line for @code{gnatfind} is:
12112 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12113 @c @r{[}@var{file1} @var{file2} @dots{}]
12114 @c Expanding @ovar macro inline (explanation in macro def comments)
12115 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12116 @r{[}@var{file1} @var{file2} @dots{}@r{]}
12124 An entity will be output only if it matches the regular expression found
12125 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
12127 Omitting the pattern is equivalent to specifying @samp{*}, which
12128 will match any entity. Note that if you do not provide a pattern, you
12129 have to provide both a sourcefile and a line.
12131 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12132 for matching purposes. At the current time there is no support for
12133 8-bit codes other than Latin-1, or for wide characters in identifiers.
12136 @code{gnatfind} will look for references, bodies or declarations
12137 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
12138 and column @var{column}. See @ref{Examples of gnatfind Usage}
12139 for syntax examples.
12142 is a decimal integer identifying the line number containing
12143 the reference to the entity (or entities) to be located.
12146 is a decimal integer identifying the exact location on the
12147 line of the first character of the identifier for the
12148 entity reference. Columns are numbered from 1.
12150 @item file1 file2 @dots{}
12151 The search will be restricted to these source files. If none are given, then
12152 the search will be done for every library file in the search path.
12153 These file must appear only after the pattern or sourcefile.
12155 These file names are considered to be regular expressions, so for instance
12156 specifying @file{source*.adb} is the same as giving every file in the current
12157 directory whose name starts with @file{source} and whose extension is
12160 The location of the spec of the entity will always be displayed, even if it
12161 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{} The
12162 occurrences of the entity in the separate units of the ones given on the
12163 command line will also be displayed.
12165 Note that if you specify at least one file in this part, @code{gnatfind} may
12166 sometimes not be able to find the body of the subprograms.
12171 At least one of 'sourcefile' or 'pattern' has to be present on
12174 The following switches are available:
12178 @cindex @option{--version} @command{gnatfind}
12179 Display Copyright and version, then exit disregarding all other options.
12182 @cindex @option{--help} @command{gnatfind}
12183 If @option{--version} was not used, display usage, then exit disregarding
12186 @item ^-a^/ALL_FILES^
12187 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
12188 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12189 the read-only files found in the library search path. Otherwise, these files
12190 will be ignored. This option can be used to protect Gnat sources or your own
12191 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12192 much faster, and their output much smaller. Read-only here refers to access
12193 or permission status in the file system for the current user.
12196 @cindex @option{-aIDIR} (@command{gnatfind})
12197 When looking for source files also look in directory DIR. The order in which
12198 source file search is undertaken is the same as for @command{gnatmake}.
12201 @cindex @option{-aODIR} (@command{gnatfind})
12202 When searching for library and object files, look in directory
12203 DIR. The order in which library files are searched is the same as for
12204 @command{gnatmake}.
12207 @cindex @option{-nostdinc} (@command{gnatfind})
12208 Do not look for sources in the system default directory.
12211 @cindex @option{-nostdlib} (@command{gnatfind})
12212 Do not look for library files in the system default directory.
12214 @item --ext=@var{extension}
12215 @cindex @option{--ext} (@command{gnatfind})
12216 Specify an alternate ali file extension. The default is @code{ali} and other
12217 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12218 switch. Note that if this switch overrides the default, which means that only
12219 the new extension will be considered.
12221 @item --RTS=@var{rts-path}
12222 @cindex @option{--RTS} (@command{gnatfind})
12223 Specifies the default location of the runtime library. Same meaning as the
12224 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12226 @item ^-d^/DERIVED_TYPE_INFORMATION^
12227 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
12228 If this switch is set, then @code{gnatfind} will output the parent type
12229 reference for each matching derived types.
12231 @item ^-e^/EXPRESSIONS^
12232 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
12233 By default, @code{gnatfind} accept the simple regular expression set for
12234 @samp{pattern}. If this switch is set, then the pattern will be
12235 considered as full Unix-style regular expression.
12237 @item ^-f^/FULL_PATHNAME^
12238 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
12239 If this switch is set, the output file names will be preceded by their
12240 directory (if the file was found in the search path). If this switch is
12241 not set, the directory will not be printed.
12243 @item ^-g^/IGNORE_LOCALS^
12244 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
12245 If this switch is set, information is output only for library-level
12246 entities, ignoring local entities. The use of this switch may accelerate
12247 @code{gnatfind} and @code{gnatxref}.
12250 @cindex @option{-IDIR} (@command{gnatfind})
12251 Equivalent to @samp{-aODIR -aIDIR}.
12254 @cindex @option{-pFILE} (@command{gnatfind})
12255 Specify a project file (@pxref{GNAT Project Manager}) to use.
12256 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12257 project file in the current directory.
12259 If a project file is either specified or found by the tools, then the content
12260 of the source directory and object directory lines are added as if they
12261 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
12262 @samp{^-aO^/OBJECT_SEARCH^}.
12264 @item ^-r^/REFERENCES^
12265 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
12266 By default, @code{gnatfind} will output only the information about the
12267 declaration, body or type completion of the entities. If this switch is
12268 set, the @code{gnatfind} will locate every reference to the entities in
12269 the files specified on the command line (or in every file in the search
12270 path if no file is given on the command line).
12272 @item ^-s^/PRINT_LINES^
12273 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
12274 If this switch is set, then @code{gnatfind} will output the content
12275 of the Ada source file lines were the entity was found.
12277 @item ^-t^/TYPE_HIERARCHY^
12278 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
12279 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12280 the specified type. It act like -d option but recursively from parent
12281 type to parent type. When this switch is set it is not possible to
12282 specify more than one file.
12287 All these switches may be in any order on the command line, and may even
12288 appear after the file names. They need not be separated by spaces, thus
12289 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12290 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12292 As stated previously, gnatfind will search in every directory in the
12293 search path. You can force it to look only in the current directory if
12294 you specify @code{*} at the end of the command line.
12296 @node Project Files for gnatxref and gnatfind
12297 @section Project Files for @command{gnatxref} and @command{gnatfind}
12300 Project files allow a programmer to specify how to compile its
12301 application, where to find sources, etc. These files are used
12303 primarily by GPS, but they can also be used
12306 @code{gnatxref} and @code{gnatfind}.
12308 A project file name must end with @file{.gpr}. If a single one is
12309 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
12310 extract the information from it. If multiple project files are found, none of
12311 them is read, and you have to use the @samp{-p} switch to specify the one
12314 The following lines can be included, even though most of them have default
12315 values which can be used in most cases.
12316 The lines can be entered in any order in the file.
12317 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
12318 each line. If you have multiple instances, only the last one is taken into
12323 [default: @code{"^./^[]^"}]
12324 specifies a directory where to look for source files. Multiple @code{src_dir}
12325 lines can be specified and they will be searched in the order they
12329 [default: @code{"^./^[]^"}]
12330 specifies a directory where to look for object and library files. Multiple
12331 @code{obj_dir} lines can be specified, and they will be searched in the order
12334 @item comp_opt=SWITCHES
12335 [default: @code{""}]
12336 creates a variable which can be referred to subsequently by using
12337 the @code{$@{comp_opt@}} notation. This is intended to store the default
12338 switches given to @command{gnatmake} and @command{gcc}.
12340 @item bind_opt=SWITCHES
12341 [default: @code{""}]
12342 creates a variable which can be referred to subsequently by using
12343 the @samp{$@{bind_opt@}} notation. This is intended to store the default
12344 switches given to @command{gnatbind}.
12346 @item link_opt=SWITCHES
12347 [default: @code{""}]
12348 creates a variable which can be referred to subsequently by using
12349 the @samp{$@{link_opt@}} notation. This is intended to store the default
12350 switches given to @command{gnatlink}.
12352 @item main=EXECUTABLE
12353 [default: @code{""}]
12354 specifies the name of the executable for the application. This variable can
12355 be referred to in the following lines by using the @samp{$@{main@}} notation.
12358 @item comp_cmd=COMMAND
12359 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
12362 @item comp_cmd=COMMAND
12363 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
12365 specifies the command used to compile a single file in the application.
12368 @item make_cmd=COMMAND
12369 [default: @code{"GNAT MAKE $@{main@}
12370 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
12371 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
12372 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
12375 @item make_cmd=COMMAND
12376 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
12377 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
12378 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
12380 specifies the command used to recompile the whole application.
12382 @item run_cmd=COMMAND
12383 [default: @code{"$@{main@}"}]
12384 specifies the command used to run the application.
12386 @item debug_cmd=COMMAND
12387 [default: @code{"gdb $@{main@}"}]
12388 specifies the command used to debug the application
12393 @command{gnatxref} and @command{gnatfind} only take into account the
12394 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
12396 @node Regular Expressions in gnatfind and gnatxref
12397 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
12400 As specified in the section about @command{gnatfind}, the pattern can be a
12401 regular expression. Actually, there are to set of regular expressions
12402 which are recognized by the program:
12405 @item globbing patterns
12406 These are the most usual regular expression. They are the same that you
12407 generally used in a Unix shell command line, or in a DOS session.
12409 Here is a more formal grammar:
12416 term ::= elmt -- matches elmt
12417 term ::= elmt elmt -- concatenation (elmt then elmt)
12418 term ::= * -- any string of 0 or more characters
12419 term ::= ? -- matches any character
12420 term ::= [char @{char@}] -- matches any character listed
12421 term ::= [char - char] -- matches any character in range
12425 @item full regular expression
12426 The second set of regular expressions is much more powerful. This is the
12427 type of regular expressions recognized by utilities such a @file{grep}.
12429 The following is the form of a regular expression, expressed in Ada
12430 reference manual style BNF is as follows
12437 regexp ::= term @{| term@} -- alternation (term or term @dots{})
12439 term ::= item @{item@} -- concatenation (item then item)
12441 item ::= elmt -- match elmt
12442 item ::= elmt * -- zero or more elmt's
12443 item ::= elmt + -- one or more elmt's
12444 item ::= elmt ? -- matches elmt or nothing
12447 elmt ::= nschar -- matches given character
12448 elmt ::= [nschar @{nschar@}] -- matches any character listed
12449 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
12450 elmt ::= [char - char] -- matches chars in given range
12451 elmt ::= \ char -- matches given character
12452 elmt ::= . -- matches any single character
12453 elmt ::= ( regexp ) -- parens used for grouping
12455 char ::= any character, including special characters
12456 nschar ::= any character except ()[].*+?^^^
12460 Following are a few examples:
12464 will match any of the two strings @samp{abcde} and @samp{fghi},
12467 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
12468 @samp{abcccd}, and so on,
12471 will match any string which has only lowercase characters in it (and at
12472 least one character.
12477 @node Examples of gnatxref Usage
12478 @section Examples of @code{gnatxref} Usage
12480 @subsection General Usage
12483 For the following examples, we will consider the following units:
12485 @smallexample @c ada
12491 3: procedure Foo (B : in Integer);
12498 1: package body Main is
12499 2: procedure Foo (B : in Integer) is
12510 2: procedure Print (B : Integer);
12519 The first thing to do is to recompile your application (for instance, in
12520 that case just by doing a @samp{gnatmake main}, so that GNAT generates
12521 the cross-referencing information.
12522 You can then issue any of the following commands:
12524 @item gnatxref main.adb
12525 @code{gnatxref} generates cross-reference information for main.adb
12526 and every unit 'with'ed by main.adb.
12528 The output would be:
12536 Decl: main.ads 3:20
12537 Body: main.adb 2:20
12538 Ref: main.adb 4:13 5:13 6:19
12541 Ref: main.adb 6:8 7:8
12551 Decl: main.ads 3:15
12552 Body: main.adb 2:15
12555 Body: main.adb 1:14
12558 Ref: main.adb 6:12 7:12
12562 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
12563 its body is in main.adb, line 1, column 14 and is not referenced any where.
12565 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
12566 it referenced in main.adb, line 6 column 12 and line 7 column 12.
12568 @item gnatxref package1.adb package2.ads
12569 @code{gnatxref} will generates cross-reference information for
12570 package1.adb, package2.ads and any other package 'with'ed by any
12576 @subsection Using gnatxref with vi
12578 @code{gnatxref} can generate a tags file output, which can be used
12579 directly from @command{vi}. Note that the standard version of @command{vi}
12580 will not work properly with overloaded symbols. Consider using another
12581 free implementation of @command{vi}, such as @command{vim}.
12584 $ gnatxref -v gnatfind.adb > tags
12588 will generate the tags file for @code{gnatfind} itself (if the sources
12589 are in the search path!).
12591 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
12592 (replacing @var{entity} by whatever you are looking for), and vi will
12593 display a new file with the corresponding declaration of entity.
12596 @node Examples of gnatfind Usage
12597 @section Examples of @code{gnatfind} Usage
12601 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
12602 Find declarations for all entities xyz referenced at least once in
12603 main.adb. The references are search in every library file in the search
12606 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
12609 The output will look like:
12611 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12612 ^directory/^[directory]^main.adb:24:10: xyz <= body
12613 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12617 that is to say, one of the entities xyz found in main.adb is declared at
12618 line 12 of main.ads (and its body is in main.adb), and another one is
12619 declared at line 45 of foo.ads
12621 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
12622 This is the same command as the previous one, instead @code{gnatfind} will
12623 display the content of the Ada source file lines.
12625 The output will look like:
12628 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12630 ^directory/^[directory]^main.adb:24:10: xyz <= body
12632 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12637 This can make it easier to find exactly the location your are looking
12640 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
12641 Find references to all entities containing an x that are
12642 referenced on line 123 of main.ads.
12643 The references will be searched only in main.ads and foo.adb.
12645 @item gnatfind main.ads:123
12646 Find declarations and bodies for all entities that are referenced on
12647 line 123 of main.ads.
12649 This is the same as @code{gnatfind "*":main.adb:123}.
12651 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
12652 Find the declaration for the entity referenced at column 45 in
12653 line 123 of file main.adb in directory mydir. Note that it
12654 is usual to omit the identifier name when the column is given,
12655 since the column position identifies a unique reference.
12657 The column has to be the beginning of the identifier, and should not
12658 point to any character in the middle of the identifier.
12662 @c *********************************
12663 @node The GNAT Pretty-Printer gnatpp
12664 @chapter The GNAT Pretty-Printer @command{gnatpp}
12666 @cindex Pretty-Printer
12669 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
12670 for source reformatting / pretty-printing.
12671 It takes an Ada source file as input and generates a reformatted
12673 You can specify various style directives via switches; e.g.,
12674 identifier case conventions, rules of indentation, and comment layout.
12676 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
12677 tree for the input source and thus requires the input to be syntactically and
12678 semantically legal.
12679 If this condition is not met, @command{gnatpp} will terminate with an
12680 error message; no output file will be generated.
12682 If the source files presented to @command{gnatpp} contain
12683 preprocessing directives, then the output file will
12684 correspond to the generated source after all
12685 preprocessing is carried out. There is no way
12686 using @command{gnatpp} to obtain pretty printed files that
12687 include the preprocessing directives.
12689 If the compilation unit
12690 contained in the input source depends semantically upon units located
12691 outside the current directory, you have to provide the source search path
12692 when invoking @command{gnatpp}, if these units are contained in files with
12693 names that do not follow the GNAT file naming rules, you have to provide
12694 the configuration file describing the corresponding naming scheme;
12695 see the description of the @command{gnatpp}
12696 switches below. Another possibility is to use a project file and to
12697 call @command{gnatpp} through the @command{gnat} driver
12699 The @command{gnatpp} command has the form
12702 @c $ gnatpp @ovar{switches} @var{filename}
12703 @c Expanding @ovar macro inline (explanation in macro def comments)
12704 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
12711 @var{switches} is an optional sequence of switches defining such properties as
12712 the formatting rules, the source search path, and the destination for the
12716 @var{filename} is the name (including the extension) of the source file to
12717 reformat; ``wildcards'' or several file names on the same gnatpp command are
12718 allowed. The file name may contain path information; it does not have to
12719 follow the GNAT file naming rules
12722 @samp{@var{gcc_switches}} is a list of switches for
12723 @command{gcc}. They will be passed on to all compiler invocations made by
12724 @command{gnatelim} to generate the ASIS trees. Here you can provide
12725 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
12726 use the @option{-gnatec} switch to set the configuration file,
12727 use the @option{-gnat05} switch if sources should be compiled in
12732 * Switches for gnatpp::
12733 * Formatting Rules::
12736 @node Switches for gnatpp
12737 @section Switches for @command{gnatpp}
12740 The following subsections describe the various switches accepted by
12741 @command{gnatpp}, organized by category.
12744 You specify a switch by supplying a name and generally also a value.
12745 In many cases the values for a switch with a given name are incompatible with
12747 (for example the switch that controls the casing of a reserved word may have
12748 exactly one value: upper case, lower case, or
12749 mixed case) and thus exactly one such switch can be in effect for an
12750 invocation of @command{gnatpp}.
12751 If more than one is supplied, the last one is used.
12752 However, some values for the same switch are mutually compatible.
12753 You may supply several such switches to @command{gnatpp}, but then
12754 each must be specified in full, with both the name and the value.
12755 Abbreviated forms (the name appearing once, followed by each value) are
12757 For example, to set
12758 the alignment of the assignment delimiter both in declarations and in
12759 assignment statements, you must write @option{-A2A3}
12760 (or @option{-A2 -A3}), but not @option{-A23}.
12764 In many cases the set of options for a given qualifier are incompatible with
12765 each other (for example the qualifier that controls the casing of a reserved
12766 word may have exactly one option, which specifies either upper case, lower
12767 case, or mixed case), and thus exactly one such option can be in effect for
12768 an invocation of @command{gnatpp}.
12769 If more than one is supplied, the last one is used.
12770 However, some qualifiers have options that are mutually compatible,
12771 and then you may then supply several such options when invoking
12775 In most cases, it is obvious whether or not the
12776 ^values for a switch with a given name^options for a given qualifier^
12777 are compatible with each other.
12778 When the semantics might not be evident, the summaries below explicitly
12779 indicate the effect.
12782 * Alignment Control::
12784 * Construct Layout Control::
12785 * General Text Layout Control::
12786 * Other Formatting Options::
12787 * Setting the Source Search Path::
12788 * Output File Control::
12789 * Other gnatpp Switches::
12792 @node Alignment Control
12793 @subsection Alignment Control
12794 @cindex Alignment control in @command{gnatpp}
12797 Programs can be easier to read if certain constructs are vertically aligned.
12798 By default all alignments are set ON.
12799 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
12800 OFF, and then use one or more of the other
12801 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
12802 to activate alignment for specific constructs.
12805 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
12809 Set all alignments to ON
12812 @item ^-A0^/ALIGN=OFF^
12813 Set all alignments to OFF
12815 @item ^-A1^/ALIGN=COLONS^
12816 Align @code{:} in declarations
12818 @item ^-A2^/ALIGN=DECLARATIONS^
12819 Align @code{:=} in initializations in declarations
12821 @item ^-A3^/ALIGN=STATEMENTS^
12822 Align @code{:=} in assignment statements
12824 @item ^-A4^/ALIGN=ARROWS^
12825 Align @code{=>} in associations
12827 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
12828 Align @code{at} keywords in the component clauses in record
12829 representation clauses
12833 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
12836 @node Casing Control
12837 @subsection Casing Control
12838 @cindex Casing control in @command{gnatpp}
12841 @command{gnatpp} allows you to specify the casing for reserved words,
12842 pragma names, attribute designators and identifiers.
12843 For identifiers you may define a
12844 general rule for name casing but also override this rule
12845 via a set of dictionary files.
12847 Three types of casing are supported: lower case, upper case, and mixed case.
12848 Lower and upper case are self-explanatory (but since some letters in
12849 Latin1 and other GNAT-supported character sets
12850 exist only in lower-case form, an upper case conversion will have no
12852 ``Mixed case'' means that the first letter, and also each letter immediately
12853 following an underscore, are converted to their uppercase forms;
12854 all the other letters are converted to their lowercase forms.
12857 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
12858 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
12859 Attribute designators are lower case
12861 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
12862 Attribute designators are upper case
12864 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
12865 Attribute designators are mixed case (this is the default)
12867 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
12868 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
12869 Keywords (technically, these are known in Ada as @emph{reserved words}) are
12870 lower case (this is the default)
12872 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
12873 Keywords are upper case
12875 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
12876 @item ^-nD^/NAME_CASING=AS_DECLARED^
12877 Name casing for defining occurrences are as they appear in the source file
12878 (this is the default)
12880 @item ^-nU^/NAME_CASING=UPPER_CASE^
12881 Names are in upper case
12883 @item ^-nL^/NAME_CASING=LOWER_CASE^
12884 Names are in lower case
12886 @item ^-nM^/NAME_CASING=MIXED_CASE^
12887 Names are in mixed case
12889 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
12890 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
12891 Pragma names are lower case
12893 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
12894 Pragma names are upper case
12896 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
12897 Pragma names are mixed case (this is the default)
12899 @item ^-D@var{file}^/DICTIONARY=@var{file}^
12900 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
12901 Use @var{file} as a @emph{dictionary file} that defines
12902 the casing for a set of specified names,
12903 thereby overriding the effect on these names by
12904 any explicit or implicit
12905 ^-n^/NAME_CASING^ switch.
12906 To supply more than one dictionary file,
12907 use ^several @option{-D} switches^a list of files as options^.
12910 @option{gnatpp} implicitly uses a @emph{default dictionary file}
12911 to define the casing for the Ada predefined names and
12912 the names declared in the GNAT libraries.
12914 @item ^-D-^/SPECIFIC_CASING^
12915 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
12916 Do not use the default dictionary file;
12917 instead, use the casing
12918 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
12923 The structure of a dictionary file, and details on the conventions
12924 used in the default dictionary file, are defined in @ref{Name Casing}.
12926 The @option{^-D-^/SPECIFIC_CASING^} and
12927 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
12930 @node Construct Layout Control
12931 @subsection Construct Layout Control
12932 @cindex Layout control in @command{gnatpp}
12935 This group of @command{gnatpp} switches controls the layout of comments and
12936 complex syntactic constructs. See @ref{Formatting Comments} for details
12940 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
12941 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
12942 All the comments remain unchanged
12944 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
12945 GNAT-style comment line indentation (this is the default).
12947 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
12948 Reference-manual comment line indentation.
12950 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
12951 GNAT-style comment beginning
12953 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
12954 Reformat comment blocks
12956 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
12957 Keep unchanged special form comments
12959 Reformat comment blocks
12961 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
12962 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
12963 GNAT-style layout (this is the default)
12965 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
12968 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
12971 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
12973 All the VT characters are removed from the comment text. All the HT characters
12974 are expanded with the sequences of space characters to get to the next tab
12977 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
12978 @item ^--no-separate-is^/NO_SEPARATE_IS^
12979 Do not place the keyword @code{is} on a separate line in a subprogram body in
12980 case if the spec occupies more then one line.
12982 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
12983 @item ^--separate-label^/SEPARATE_LABEL^
12984 Place statement label(s) on a separate line, with the following statement
12987 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
12988 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
12989 Place the keyword @code{loop} in FOR and WHILE loop statements and the
12990 keyword @code{then} in IF statements on a separate line.
12992 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
12993 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
12994 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
12995 keyword @code{then} in IF statements on a separate line. This option is
12996 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
12998 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
12999 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
13000 Start each USE clause in a context clause from a separate line.
13002 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
13003 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
13004 Use a separate line for a loop or block statement name, but do not use an extra
13005 indentation level for the statement itself.
13011 The @option{-c1} and @option{-c2} switches are incompatible.
13012 The @option{-c3} and @option{-c4} switches are compatible with each other and
13013 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
13014 the other comment formatting switches.
13016 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
13021 For the @option{/COMMENTS_LAYOUT} qualifier:
13024 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
13026 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
13027 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
13031 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
13032 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
13035 @node General Text Layout Control
13036 @subsection General Text Layout Control
13039 These switches allow control over line length and indentation.
13042 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
13043 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
13044 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
13046 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
13047 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
13048 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
13050 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
13051 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
13052 Indentation level for continuation lines (relative to the line being
13053 continued), @var{nnn} from 1@dots{}9.
13055 value is one less then the (normal) indentation level, unless the
13056 indentation is set to 1 (in which case the default value for continuation
13057 line indentation is also 1)
13060 @node Other Formatting Options
13061 @subsection Other Formatting Options
13064 These switches control the inclusion of missing end/exit labels, and
13065 the indentation level in @b{case} statements.
13068 @item ^-e^/NO_MISSED_LABELS^
13069 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
13070 Do not insert missing end/exit labels. An end label is the name of
13071 a construct that may optionally be repeated at the end of the
13072 construct's declaration;
13073 e.g., the names of packages, subprograms, and tasks.
13074 An exit label is the name of a loop that may appear as target
13075 of an exit statement within the loop.
13076 By default, @command{gnatpp} inserts these end/exit labels when
13077 they are absent from the original source. This option suppresses such
13078 insertion, so that the formatted source reflects the original.
13080 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
13081 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
13082 Insert a Form Feed character after a pragma Page.
13084 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
13085 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
13086 Do not use an additional indentation level for @b{case} alternatives
13087 and variants if there are @var{nnn} or more (the default
13089 If @var{nnn} is 0, an additional indentation level is
13090 used for @b{case} alternatives and variants regardless of their number.
13093 @node Setting the Source Search Path
13094 @subsection Setting the Source Search Path
13097 To define the search path for the input source file, @command{gnatpp}
13098 uses the same switches as the GNAT compiler, with the same effects.
13101 @item ^-I^/SEARCH=^@var{dir}
13102 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
13103 The same as the corresponding gcc switch
13105 @item ^-I-^/NOCURRENT_DIRECTORY^
13106 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
13107 The same as the corresponding gcc switch
13109 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
13110 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
13111 The same as the corresponding gcc switch
13113 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
13114 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
13115 The same as the corresponding gcc switch
13119 @node Output File Control
13120 @subsection Output File Control
13123 By default the output is sent to the file whose name is obtained by appending
13124 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
13125 (if the file with this name already exists, it is unconditionally overwritten).
13126 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
13127 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
13129 The output may be redirected by the following switches:
13132 @item ^-pipe^/STANDARD_OUTPUT^
13133 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
13134 Send the output to @code{Standard_Output}
13136 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
13137 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
13138 Write the output into @var{output_file}.
13139 If @var{output_file} already exists, @command{gnatpp} terminates without
13140 reading or processing the input file.
13142 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
13143 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
13144 Write the output into @var{output_file}, overwriting the existing file
13145 (if one is present).
13147 @item ^-r^/REPLACE^
13148 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
13149 Replace the input source file with the reformatted output, and copy the
13150 original input source into the file whose name is obtained by appending the
13151 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
13152 If a file with this name already exists, @command{gnatpp} terminates without
13153 reading or processing the input file.
13155 @item ^-rf^/OVERRIDING_REPLACE^
13156 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
13157 Like @option{^-r^/REPLACE^} except that if the file with the specified name
13158 already exists, it is overwritten.
13160 @item ^-rnb^/REPLACE_NO_BACKUP^
13161 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
13162 Replace the input source file with the reformatted output without
13163 creating any backup copy of the input source.
13165 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
13166 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
13167 Specifies the format of the reformatted output file. The @var{xxx}
13168 ^string specified with the switch^option^ may be either
13170 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
13171 @item ``@option{^crlf^CRLF^}''
13172 the same as @option{^crlf^CRLF^}
13173 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
13174 @item ``@option{^lf^LF^}''
13175 the same as @option{^unix^UNIX^}
13178 @item ^-W^/RESULT_ENCODING=^@var{e}
13179 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
13180 Specify the wide character encoding method used to write the code in the
13182 @var{e} is one of the following:
13190 Upper half encoding
13192 @item ^s^SHIFT_JIS^
13202 Brackets encoding (default value)
13208 Options @option{^-pipe^/STANDARD_OUTPUT^},
13209 @option{^-o^/OUTPUT^} and
13210 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
13211 contains only one file to reformat.
13213 @option{^--eol^/END_OF_LINE^}
13215 @option{^-W^/RESULT_ENCODING^}
13216 cannot be used together
13217 with @option{^-pipe^/STANDARD_OUTPUT^} option.
13219 @node Other gnatpp Switches
13220 @subsection Other @code{gnatpp} Switches
13223 The additional @command{gnatpp} switches are defined in this subsection.
13226 @item ^-files @var{filename}^/FILES=@var{filename}^
13227 @cindex @option{^-files^/FILES^} (@code{gnatpp})
13228 Take the argument source files from the specified file. This file should be an
13229 ordinary text file containing file names separated by spaces or
13230 line breaks. You can use this switch more than once in the same call to
13231 @command{gnatpp}. You also can combine this switch with an explicit list of
13234 @item ^-v^/VERBOSE^
13235 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
13237 @command{gnatpp} generates version information and then
13238 a trace of the actions it takes to produce or obtain the ASIS tree.
13240 @item ^-w^/WARNINGS^
13241 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
13243 @command{gnatpp} generates a warning whenever it cannot provide
13244 a required layout in the result source.
13247 @node Formatting Rules
13248 @section Formatting Rules
13251 The following subsections show how @command{gnatpp} treats ``white space'',
13252 comments, program layout, and name casing.
13253 They provide the detailed descriptions of the switches shown above.
13256 * White Space and Empty Lines::
13257 * Formatting Comments::
13258 * Construct Layout::
13262 @node White Space and Empty Lines
13263 @subsection White Space and Empty Lines
13266 @command{gnatpp} does not have an option to control space characters.
13267 It will add or remove spaces according to the style illustrated by the
13268 examples in the @cite{Ada Reference Manual}.
13270 The only format effectors
13271 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
13272 that will appear in the output file are platform-specific line breaks,
13273 and also format effectors within (but not at the end of) comments.
13274 In particular, each horizontal tab character that is not inside
13275 a comment will be treated as a space and thus will appear in the
13276 output file as zero or more spaces depending on
13277 the reformatting of the line in which it appears.
13278 The only exception is a Form Feed character, which is inserted after a
13279 pragma @code{Page} when @option{-ff} is set.
13281 The output file will contain no lines with trailing ``white space'' (spaces,
13284 Empty lines in the original source are preserved
13285 only if they separate declarations or statements.
13286 In such contexts, a
13287 sequence of two or more empty lines is replaced by exactly one empty line.
13288 Note that a blank line will be removed if it separates two ``comment blocks''
13289 (a comment block is a sequence of whole-line comments).
13290 In order to preserve a visual separation between comment blocks, use an
13291 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
13292 Likewise, if for some reason you wish to have a sequence of empty lines,
13293 use a sequence of empty comments instead.
13295 @node Formatting Comments
13296 @subsection Formatting Comments
13299 Comments in Ada code are of two kinds:
13302 a @emph{whole-line comment}, which appears by itself (possibly preceded by
13303 ``white space'') on a line
13306 an @emph{end-of-line comment}, which follows some other Ada lexical element
13311 The indentation of a whole-line comment is that of either
13312 the preceding or following line in
13313 the formatted source, depending on switch settings as will be described below.
13315 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
13316 between the end of the preceding Ada lexical element and the beginning
13317 of the comment as appear in the original source,
13318 unless either the comment has to be split to
13319 satisfy the line length limitation, or else the next line contains a
13320 whole line comment that is considered a continuation of this end-of-line
13321 comment (because it starts at the same position).
13323 cases, the start of the end-of-line comment is moved right to the nearest
13324 multiple of the indentation level.
13325 This may result in a ``line overflow'' (the right-shifted comment extending
13326 beyond the maximum line length), in which case the comment is split as
13329 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
13330 (GNAT-style comment line indentation)
13331 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
13332 (reference-manual comment line indentation).
13333 With reference-manual style, a whole-line comment is indented as if it
13334 were a declaration or statement at the same place
13335 (i.e., according to the indentation of the preceding line(s)).
13336 With GNAT style, a whole-line comment that is immediately followed by an
13337 @b{if} or @b{case} statement alternative, a record variant, or the reserved
13338 word @b{begin}, is indented based on the construct that follows it.
13341 @smallexample @c ada
13353 Reference-manual indentation produces:
13355 @smallexample @c ada
13367 while GNAT-style indentation produces:
13369 @smallexample @c ada
13381 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
13382 (GNAT style comment beginning) has the following
13387 For each whole-line comment that does not end with two hyphens,
13388 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
13389 to ensure that there are at least two spaces between these hyphens and the
13390 first non-blank character of the comment.
13394 For an end-of-line comment, if in the original source the next line is a
13395 whole-line comment that starts at the same position
13396 as the end-of-line comment,
13397 then the whole-line comment (and all whole-line comments
13398 that follow it and that start at the same position)
13399 will start at this position in the output file.
13402 That is, if in the original source we have:
13404 @smallexample @c ada
13407 A := B + C; -- B must be in the range Low1..High1
13408 -- C must be in the range Low2..High2
13409 --B+C will be in the range Low1+Low2..High1+High2
13415 Then in the formatted source we get
13417 @smallexample @c ada
13420 A := B + C; -- B must be in the range Low1..High1
13421 -- C must be in the range Low2..High2
13422 -- B+C will be in the range Low1+Low2..High1+High2
13428 A comment that exceeds the line length limit will be split.
13430 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
13431 the line belongs to a reformattable block, splitting the line generates a
13432 @command{gnatpp} warning.
13433 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
13434 comments may be reformatted in typical
13435 word processor style (that is, moving words between lines and putting as
13436 many words in a line as possible).
13439 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
13440 that has a special format (that is, a character that is neither a letter nor digit
13441 not white space nor line break immediately following the leading @code{--} of
13442 the comment) should be without any change moved from the argument source
13443 into reformatted source. This switch allows to preserve comments that are used
13444 as a special marks in the code (e.g.@: SPARK annotation).
13446 @node Construct Layout
13447 @subsection Construct Layout
13450 In several cases the suggested layout in the Ada Reference Manual includes
13451 an extra level of indentation that many programmers prefer to avoid. The
13452 affected cases include:
13456 @item Record type declaration (RM 3.8)
13458 @item Record representation clause (RM 13.5.1)
13460 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
13462 @item Block statement in case if a block has a statement identifier (RM 5.6)
13466 In compact mode (when GNAT style layout or compact layout is set),
13467 the pretty printer uses one level of indentation instead
13468 of two. This is achieved in the record definition and record representation
13469 clause cases by putting the @code{record} keyword on the same line as the
13470 start of the declaration or representation clause, and in the block and loop
13471 case by putting the block or loop header on the same line as the statement
13475 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
13476 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
13477 layout on the one hand, and uncompact layout
13478 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
13479 can be illustrated by the following examples:
13483 @multitable @columnfractions .5 .5
13484 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
13487 @smallexample @c ada
13494 @smallexample @c ada
13503 @smallexample @c ada
13505 a at 0 range 0 .. 31;
13506 b at 4 range 0 .. 31;
13510 @smallexample @c ada
13513 a at 0 range 0 .. 31;
13514 b at 4 range 0 .. 31;
13519 @smallexample @c ada
13527 @smallexample @c ada
13537 @smallexample @c ada
13538 Clear : for J in 1 .. 10 loop
13543 @smallexample @c ada
13545 for J in 1 .. 10 loop
13556 GNAT style, compact layout Uncompact layout
13558 type q is record type q is
13559 a : integer; record
13560 b : integer; a : integer;
13561 end record; b : integer;
13564 for q use record for q use
13565 a at 0 range 0 .. 31; record
13566 b at 4 range 0 .. 31; a at 0 range 0 .. 31;
13567 end record; b at 4 range 0 .. 31;
13570 Block : declare Block :
13571 A : Integer := 3; declare
13572 begin A : Integer := 3;
13574 end Block; Proc (A, A);
13577 Clear : for J in 1 .. 10 loop Clear :
13578 A (J) := 0; for J in 1 .. 10 loop
13579 end loop Clear; A (J) := 0;
13586 A further difference between GNAT style layout and compact layout is that
13587 GNAT style layout inserts empty lines as separation for
13588 compound statements, return statements and bodies.
13590 Note that the layout specified by
13591 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
13592 for named block and loop statements overrides the layout defined by these
13593 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
13594 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
13595 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
13598 @subsection Name Casing
13601 @command{gnatpp} always converts the usage occurrence of a (simple) name to
13602 the same casing as the corresponding defining identifier.
13604 You control the casing for defining occurrences via the
13605 @option{^-n^/NAME_CASING^} switch.
13607 With @option{-nD} (``as declared'', which is the default),
13610 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
13612 defining occurrences appear exactly as in the source file
13613 where they are declared.
13614 The other ^values for this switch^options for this qualifier^ ---
13615 @option{^-nU^UPPER_CASE^},
13616 @option{^-nL^LOWER_CASE^},
13617 @option{^-nM^MIXED_CASE^} ---
13619 ^upper, lower, or mixed case, respectively^the corresponding casing^.
13620 If @command{gnatpp} changes the casing of a defining
13621 occurrence, it analogously changes the casing of all the
13622 usage occurrences of this name.
13624 If the defining occurrence of a name is not in the source compilation unit
13625 currently being processed by @command{gnatpp}, the casing of each reference to
13626 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
13627 switch (subject to the dictionary file mechanism described below).
13628 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
13630 casing for the defining occurrence of the name.
13632 Some names may need to be spelled with casing conventions that are not
13633 covered by the upper-, lower-, and mixed-case transformations.
13634 You can arrange correct casing by placing such names in a
13635 @emph{dictionary file},
13636 and then supplying a @option{^-D^/DICTIONARY^} switch.
13637 The casing of names from dictionary files overrides
13638 any @option{^-n^/NAME_CASING^} switch.
13640 To handle the casing of Ada predefined names and the names from GNAT libraries,
13641 @command{gnatpp} assumes a default dictionary file.
13642 The name of each predefined entity is spelled with the same casing as is used
13643 for the entity in the @cite{Ada Reference Manual}.
13644 The name of each entity in the GNAT libraries is spelled with the same casing
13645 as is used in the declaration of that entity.
13647 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
13648 default dictionary file.
13649 Instead, the casing for predefined and GNAT-defined names will be established
13650 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
13651 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
13652 will appear as just shown,
13653 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
13654 To ensure that even such names are rendered in uppercase,
13655 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
13656 (or else, less conveniently, place these names in upper case in a dictionary
13659 A dictionary file is
13660 a plain text file; each line in this file can be either a blank line
13661 (containing only space characters and ASCII.HT characters), an Ada comment
13662 line, or the specification of exactly one @emph{casing schema}.
13664 A casing schema is a string that has the following syntax:
13668 @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
13670 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
13675 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
13676 @var{identifier} lexical element and the @var{letter_or_digit} category.)
13678 The casing schema string can be followed by white space and/or an Ada-style
13679 comment; any amount of white space is allowed before the string.
13681 If a dictionary file is passed as
13683 the value of a @option{-D@var{file}} switch
13686 an option to the @option{/DICTIONARY} qualifier
13689 simple name and every identifier, @command{gnatpp} checks if the dictionary
13690 defines the casing for the name or for some of its parts (the term ``subword''
13691 is used below to denote the part of a name which is delimited by ``_'' or by
13692 the beginning or end of the word and which does not contain any ``_'' inside):
13696 if the whole name is in the dictionary, @command{gnatpp} uses for this name
13697 the casing defined by the dictionary; no subwords are checked for this word
13700 for every subword @command{gnatpp} checks if the dictionary contains the
13701 corresponding string of the form @code{*@var{simple_identifier}*},
13702 and if it does, the casing of this @var{simple_identifier} is used
13706 if the whole name does not contain any ``_'' inside, and if for this name
13707 the dictionary contains two entries - one of the form @var{identifier},
13708 and another - of the form *@var{simple_identifier}*, then the first one
13709 is applied to define the casing of this name
13712 if more than one dictionary file is passed as @command{gnatpp} switches, each
13713 dictionary adds new casing exceptions and overrides all the existing casing
13714 exceptions set by the previous dictionaries
13717 when @command{gnatpp} checks if the word or subword is in the dictionary,
13718 this check is not case sensitive
13722 For example, suppose we have the following source to reformat:
13724 @smallexample @c ada
13727 name1 : integer := 1;
13728 name4_name3_name2 : integer := 2;
13729 name2_name3_name4 : Boolean;
13732 name2_name3_name4 := name4_name3_name2 > name1;
13738 And suppose we have two dictionaries:
13755 If @command{gnatpp} is called with the following switches:
13759 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
13762 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
13767 then we will get the following name casing in the @command{gnatpp} output:
13769 @smallexample @c ada
13772 NAME1 : Integer := 1;
13773 Name4_NAME3_Name2 : Integer := 2;
13774 Name2_NAME3_Name4 : Boolean;
13777 Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
13782 @c *********************************
13783 @node The GNAT Metric Tool gnatmetric
13784 @chapter The GNAT Metric Tool @command{gnatmetric}
13786 @cindex Metric tool
13789 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
13790 for computing various program metrics.
13791 It takes an Ada source file as input and generates a file containing the
13792 metrics data as output. Various switches control which
13793 metrics are computed and output.
13795 @command{gnatmetric} generates and uses the ASIS
13796 tree for the input source and thus requires the input to be syntactically and
13797 semantically legal.
13798 If this condition is not met, @command{gnatmetric} will generate
13799 an error message; no metric information for this file will be
13800 computed and reported.
13802 If the compilation unit contained in the input source depends semantically
13803 upon units in files located outside the current directory, you have to provide
13804 the source search path when invoking @command{gnatmetric}.
13805 If it depends semantically upon units that are contained
13806 in files with names that do not follow the GNAT file naming rules, you have to
13807 provide the configuration file describing the corresponding naming scheme (see
13808 the description of the @command{gnatmetric} switches below.)
13809 Alternatively, you may use a project file and invoke @command{gnatmetric}
13810 through the @command{gnat} driver.
13812 The @command{gnatmetric} command has the form
13815 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
13816 @c Expanding @ovar macro inline (explanation in macro def comments)
13817 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
13824 @var{switches} specify the metrics to compute and define the destination for
13828 Each @var{filename} is the name (including the extension) of a source
13829 file to process. ``Wildcards'' are allowed, and
13830 the file name may contain path information.
13831 If no @var{filename} is supplied, then the @var{switches} list must contain
13833 @option{-files} switch (@pxref{Other gnatmetric Switches}).
13834 Including both a @option{-files} switch and one or more
13835 @var{filename} arguments is permitted.
13838 @samp{@var{gcc_switches}} is a list of switches for
13839 @command{gcc}. They will be passed on to all compiler invocations made by
13840 @command{gnatmetric} to generate the ASIS trees. Here you can provide
13841 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
13842 and use the @option{-gnatec} switch to set the configuration file,
13843 use the @option{-gnat05} switch if sources should be compiled in
13848 * Switches for gnatmetric::
13851 @node Switches for gnatmetric
13852 @section Switches for @command{gnatmetric}
13855 The following subsections describe the various switches accepted by
13856 @command{gnatmetric}, organized by category.
13859 * Output Files Control::
13860 * Disable Metrics For Local Units::
13861 * Specifying a set of metrics to compute::
13862 * Other gnatmetric Switches::
13863 * Generate project-wide metrics::
13866 @node Output Files Control
13867 @subsection Output File Control
13868 @cindex Output file control in @command{gnatmetric}
13871 @command{gnatmetric} has two output formats. It can generate a
13872 textual (human-readable) form, and also XML. By default only textual
13873 output is generated.
13875 When generating the output in textual form, @command{gnatmetric} creates
13876 for each Ada source file a corresponding text file
13877 containing the computed metrics, except for the case when the set of metrics
13878 specified by gnatmetric parameters consists only of metrics that are computed
13879 for the whole set of analyzed sources, but not for each Ada source.
13880 By default, this file is placed in the same directory as where the source
13881 file is located, and its name is obtained
13882 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
13885 All the output information generated in XML format is placed in a single
13886 file. By default this file is placed in the current directory and has the
13887 name ^@file{metrix.xml}^@file{METRIX$XML}^.
13889 Some of the computed metrics are summed over the units passed to
13890 @command{gnatmetric}; for example, the total number of lines of code.
13891 By default this information is sent to @file{stdout}, but a file
13892 can be specified with the @option{-og} switch.
13894 The following switches control the @command{gnatmetric} output:
13897 @cindex @option{^-x^/XML^} (@command{gnatmetric})
13899 Generate the XML output
13901 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
13903 Generate the XML output and the XML schema file that describes the structure
13904 of the XML metric report, this schema is assigned to the XML file. The schema
13905 file has the same name as the XML output file with @file{.xml} suffix replaced
13908 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
13909 @item ^-nt^/NO_TEXT^
13910 Do not generate the output in text form (implies @option{^-x^/XML^})
13912 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
13913 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
13914 Put text files with detailed metrics into @var{output_dir}
13916 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
13917 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
13918 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
13919 in the name of the output file.
13921 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
13922 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
13923 Put global metrics into @var{file_name}
13925 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
13926 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
13927 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
13929 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
13930 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
13931 Use ``short'' source file names in the output. (The @command{gnatmetric}
13932 output includes the name(s) of the Ada source file(s) from which the metrics
13933 are computed. By default each name includes the absolute path. The
13934 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
13935 to exclude all directory information from the file names that are output.)
13939 @node Disable Metrics For Local Units
13940 @subsection Disable Metrics For Local Units
13941 @cindex Disable Metrics For Local Units in @command{gnatmetric}
13944 @command{gnatmetric} relies on the GNAT compilation model @minus{}
13946 unit per one source file. It computes line metrics for the whole source
13947 file, and it also computes syntax
13948 and complexity metrics for the file's outermost unit.
13950 By default, @command{gnatmetric} will also compute all metrics for certain
13951 kinds of locally declared program units:
13955 subprogram (and generic subprogram) bodies;
13958 package (and generic package) specs and bodies;
13961 task object and type specifications and bodies;
13964 protected object and type specifications and bodies.
13968 These kinds of entities will be referred to as
13969 @emph{eligible local program units}, or simply @emph{eligible local units},
13970 @cindex Eligible local unit (for @command{gnatmetric})
13971 in the discussion below.
13973 Note that a subprogram declaration, generic instantiation,
13974 or renaming declaration only receives metrics
13975 computation when it appear as the outermost entity
13978 Suppression of metrics computation for eligible local units can be
13979 obtained via the following switch:
13982 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
13983 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
13984 Do not compute detailed metrics for eligible local program units
13988 @node Specifying a set of metrics to compute
13989 @subsection Specifying a set of metrics to compute
13992 By default all the metrics are computed and reported. The switches
13993 described in this subsection allow you to control, on an individual
13994 basis, whether metrics are computed and
13995 reported. If at least one positive metric
13996 switch is specified (that is, a switch that defines that a given
13997 metric or set of metrics is to be computed), then only
13998 explicitly specified metrics are reported.
14001 * Line Metrics Control::
14002 * Syntax Metrics Control::
14003 * Complexity Metrics Control::
14004 * Object-Oriented Metrics Control::
14007 @node Line Metrics Control
14008 @subsubsection Line Metrics Control
14009 @cindex Line metrics control in @command{gnatmetric}
14012 For any (legal) source file, and for each of its
14013 eligible local program units, @command{gnatmetric} computes the following
14018 the total number of lines;
14021 the total number of code lines (i.e., non-blank lines that are not comments)
14024 the number of comment lines
14027 the number of code lines containing end-of-line comments;
14030 the comment percentage: the ratio between the number of lines that contain
14031 comments and the number of all non-blank lines, expressed as a percentage;
14034 the number of empty lines and lines containing only space characters and/or
14035 format effectors (blank lines)
14038 the average number of code lines in subprogram bodies, task bodies, entry
14039 bodies and statement sequences in package bodies (this metric is only computed
14040 across the whole set of the analyzed units)
14045 @command{gnatmetric} sums the values of the line metrics for all the
14046 files being processed and then generates the cumulative results. The tool
14047 also computes for all the files being processed the average number of code
14050 You can use the following switches to select the specific line metrics
14051 to be computed and reported.
14054 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
14057 @cindex @option{--no-lines@var{x}}
14060 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
14061 Report all the line metrics
14063 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
14064 Do not report any of line metrics
14066 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
14067 Report the number of all lines
14069 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
14070 Do not report the number of all lines
14072 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
14073 Report the number of code lines
14075 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
14076 Do not report the number of code lines
14078 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
14079 Report the number of comment lines
14081 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
14082 Do not report the number of comment lines
14084 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
14085 Report the number of code lines containing
14086 end-of-line comments
14088 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
14089 Do not report the number of code lines containing
14090 end-of-line comments
14092 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
14093 Report the comment percentage in the program text
14095 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
14096 Do not report the comment percentage in the program text
14098 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
14099 Report the number of blank lines
14101 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
14102 Do not report the number of blank lines
14104 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
14105 Report the average number of code lines in subprogram bodies, task bodies,
14106 entry bodies and statement sequences in package bodies. The metric is computed
14107 and reported for the whole set of processed Ada sources only.
14109 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
14110 Do not report the average number of code lines in subprogram bodies,
14111 task bodies, entry bodies and statement sequences in package bodies.
14115 @node Syntax Metrics Control
14116 @subsubsection Syntax Metrics Control
14117 @cindex Syntax metrics control in @command{gnatmetric}
14120 @command{gnatmetric} computes various syntactic metrics for the
14121 outermost unit and for each eligible local unit:
14124 @item LSLOC (``Logical Source Lines Of Code'')
14125 The total number of declarations and the total number of statements
14127 @item Maximal static nesting level of inner program units
14129 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
14130 package, a task unit, a protected unit, a
14131 protected entry, a generic unit, or an explicitly declared subprogram other
14132 than an enumeration literal.''
14134 @item Maximal nesting level of composite syntactic constructs
14135 This corresponds to the notion of the
14136 maximum nesting level in the GNAT built-in style checks
14137 (@pxref{Style Checking})
14141 For the outermost unit in the file, @command{gnatmetric} additionally computes
14142 the following metrics:
14145 @item Public subprograms
14146 This metric is computed for package specs. It is the
14147 number of subprograms and generic subprograms declared in the visible
14148 part (including the visible part of nested packages, protected objects, and
14151 @item All subprograms
14152 This metric is computed for bodies and subunits. The
14153 metric is equal to a total number of subprogram bodies in the compilation
14155 Neither generic instantiations nor renamings-as-a-body nor body stubs
14156 are counted. Any subprogram body is counted, independently of its nesting
14157 level and enclosing constructs. Generic bodies and bodies of protected
14158 subprograms are counted in the same way as ``usual'' subprogram bodies.
14161 This metric is computed for package specs and
14162 generic package declarations. It is the total number of types
14163 that can be referenced from outside this compilation unit, plus the
14164 number of types from all the visible parts of all the visible generic
14165 packages. Generic formal types are not counted. Only types, not subtypes,
14169 Along with the total number of public types, the following
14170 types are counted and reported separately:
14177 Root tagged types (abstract, non-abstract, private, non-private). Type
14178 extensions are @emph{not} counted
14181 Private types (including private extensions)
14192 This metric is computed for any compilation unit. It is equal to the total
14193 number of the declarations of different types given in the compilation unit.
14194 The private and the corresponding full type declaration are counted as one
14195 type declaration. Incomplete type declarations and generic formal types
14197 No distinction is made among different kinds of types (abstract,
14198 private etc.); the total number of types is computed and reported.
14203 By default, all the syntax metrics are computed and reported. You can use the
14204 following switches to select specific syntax metrics.
14208 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
14211 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
14214 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
14215 Report all the syntax metrics
14217 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
14218 Do not report any of syntax metrics
14220 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
14221 Report the total number of declarations
14223 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
14224 Do not report the total number of declarations
14226 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
14227 Report the total number of statements
14229 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
14230 Do not report the total number of statements
14232 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
14233 Report the number of public subprograms in a compilation unit
14235 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
14236 Do not report the number of public subprograms in a compilation unit
14238 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
14239 Report the number of all the subprograms in a compilation unit
14241 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
14242 Do not report the number of all the subprograms in a compilation unit
14244 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
14245 Report the number of public types in a compilation unit
14247 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
14248 Do not report the number of public types in a compilation unit
14250 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
14251 Report the number of all the types in a compilation unit
14253 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
14254 Do not report the number of all the types in a compilation unit
14256 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
14257 Report the maximal program unit nesting level
14259 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
14260 Do not report the maximal program unit nesting level
14262 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
14263 Report the maximal construct nesting level
14265 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
14266 Do not report the maximal construct nesting level
14270 @node Complexity Metrics Control
14271 @subsubsection Complexity Metrics Control
14272 @cindex Complexity metrics control in @command{gnatmetric}
14275 For a program unit that is an executable body (a subprogram body (including
14276 generic bodies), task body, entry body or a package body containing
14277 its own statement sequence) @command{gnatmetric} computes the following
14278 complexity metrics:
14282 McCabe cyclomatic complexity;
14285 McCabe essential complexity;
14288 maximal loop nesting level
14293 The McCabe complexity metrics are defined
14294 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
14296 According to McCabe, both control statements and short-circuit control forms
14297 should be taken into account when computing cyclomatic complexity. For each
14298 body, we compute three metric values:
14302 the complexity introduced by control
14303 statements only, without taking into account short-circuit forms,
14306 the complexity introduced by short-circuit control forms only, and
14310 cyclomatic complexity, which is the sum of these two values.
14314 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
14315 the code in the exception handlers and in all the nested program units.
14317 By default, all the complexity metrics are computed and reported.
14318 For more fine-grained control you can use
14319 the following switches:
14322 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
14325 @cindex @option{--no-complexity@var{x}}
14328 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
14329 Report all the complexity metrics
14331 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
14332 Do not report any of complexity metrics
14334 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
14335 Report the McCabe Cyclomatic Complexity
14337 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
14338 Do not report the McCabe Cyclomatic Complexity
14340 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
14341 Report the Essential Complexity
14343 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
14344 Do not report the Essential Complexity
14346 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
14347 Report maximal loop nesting level
14349 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
14350 Do not report maximal loop nesting level
14352 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
14353 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
14354 task bodies, entry bodies and statement sequences in package bodies.
14355 The metric is computed and reported for whole set of processed Ada sources
14358 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
14359 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
14360 bodies, task bodies, entry bodies and statement sequences in package bodies
14362 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
14363 @item ^-ne^/NO_EXITS_AS_GOTOS^
14364 Do not consider @code{exit} statements as @code{goto}s when
14365 computing Essential Complexity
14367 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
14368 Report the extra exit points for subprogram bodies. As an exit point, this
14369 metric counts @code{return} statements and raise statements in case when the
14370 raised exception is not handled in the same body. In case of a function this
14371 metric subtracts 1 from the number of exit points, because a function body
14372 must contain at least one @code{return} statement.
14374 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
14375 Do not report the extra exit points for subprogram bodies
14379 @node Object-Oriented Metrics Control
14380 @subsubsection Object-Oriented Metrics Control
14381 @cindex Object-Oriented metrics control in @command{gnatmetric}
14384 @cindex Coupling metrics (in in @command{gnatmetric})
14385 Coupling metrics are object-oriented metrics that measure the
14386 dependencies between a given class (or a group of classes) and the
14387 ``external world'' (that is, the other classes in the program). In this
14388 subsection the term ``class'' is used in its
14389 traditional object-oriented programming sense
14390 (an instantiable module that contains data and/or method members).
14391 A @emph{category} (of classes)
14392 is a group of closely related classes that are reused and/or
14395 A class @code{K}'s @emph{efferent coupling} is the number of classes
14396 that @code{K} depends upon.
14397 A category's efferent coupling is the number of classes outside the
14398 category that the classes inside the category depend upon.
14400 A class @code{K}'s @emph{afferent coupling} is the number of classes
14401 that depend upon @code{K}.
14402 A category's afferent coupling is the number of classes outside the
14403 category that depend on classes belonging to the category.
14405 Ada's implementation of the object-oriented paradigm does not use the
14406 traditional class notion, so the definition of the coupling
14407 metrics for Ada maps the class and class category notions
14408 onto Ada constructs.
14410 For the coupling metrics, several kinds of modules -- a library package,
14411 a library generic package, and a library generic package instantiation --
14412 that define a tagged type or an interface type are
14413 considered to be a class. A category consists of a library package (or
14414 a library generic package) that defines a tagged or an interface type,
14415 together with all its descendant (generic) packages that define tagged
14416 or interface types. For any package counted as a class,
14417 its body and subunits (if any) are considered
14418 together with its spec when counting the dependencies, and coupling
14419 metrics are reported for spec units only. For dependencies
14420 between classes, the Ada semantic dependencies are considered.
14421 For coupling metrics, only dependencies on units that are considered as
14422 classes, are considered.
14424 When computing coupling metrics, @command{gnatmetric} counts only
14425 dependencies between units that are arguments of the gnatmetric call.
14426 Coupling metrics are program-wide (or project-wide) metrics, so to
14427 get a valid result, you should call @command{gnatmetric} for
14428 the whole set of sources that make up your program. It can be done
14429 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
14430 option (see See @ref{The GNAT Driver and Project Files} for details.
14432 By default, all the coupling metrics are disabled. You can use the following
14433 switches to specify the coupling metrics to be computed and reported:
14438 @cindex @option{--package@var{x}} (@command{gnatmetric})
14439 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
14440 @cindex @option{--category@var{x}} (@command{gnatmetric})
14441 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
14445 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
14448 @item ^--coupling-all^/COUPLING_METRICS=ALL^
14449 Report all the coupling metrics
14451 @item ^--no-coupling-all^/COUPLING_METRICS=NONE^
14452 Do not report any of metrics
14454 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT^
14455 Report package efferent coupling
14457 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=NOPACKAGE_EFFERENT^
14458 Do not report package efferent coupling
14460 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT^
14461 Report package afferent coupling
14463 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=NOPACKAGE_AFFERENT^
14464 Do not report package afferent coupling
14466 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT^
14467 Report category efferent coupling
14469 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=NOCATEGORY_EFFERENT^
14470 Do not report category efferent coupling
14472 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT^
14473 Report category afferent coupling
14475 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=NOCATEGORY_AFFERENT^
14476 Do not report category afferent coupling
14480 @node Other gnatmetric Switches
14481 @subsection Other @code{gnatmetric} Switches
14484 Additional @command{gnatmetric} switches are as follows:
14487 @item ^-files @var{filename}^/FILES=@var{filename}^
14488 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
14489 Take the argument source files from the specified file. This file should be an
14490 ordinary text file containing file names separated by spaces or
14491 line breaks. You can use this switch more than once in the same call to
14492 @command{gnatmetric}. You also can combine this switch with
14493 an explicit list of files.
14495 @item ^-v^/VERBOSE^
14496 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
14498 @command{gnatmetric} generates version information and then
14499 a trace of sources being processed.
14501 @item ^-dv^/DEBUG_OUTPUT^
14502 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
14504 @command{gnatmetric} generates various messages useful to understand what
14505 happens during the metrics computation
14508 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
14512 @node Generate project-wide metrics
14513 @subsection Generate project-wide metrics
14515 In order to compute metrics on all units of a given project, you can use
14516 the @command{gnat} driver along with the @option{-P} option:
14522 If the project @code{proj} depends upon other projects, you can compute
14523 the metrics on the project closure using the @option{-U} option:
14525 gnat metric -Pproj -U
14529 Finally, if not all the units are relevant to a particular main
14530 program in the project closure, you can generate metrics for the set
14531 of units needed to create a given main program (unit closure) using
14532 the @option{-U} option followed by the name of the main unit:
14534 gnat metric -Pproj -U main
14538 @c ***********************************
14539 @node File Name Krunching Using gnatkr
14540 @chapter File Name Krunching Using @code{gnatkr}
14544 This chapter discusses the method used by the compiler to shorten
14545 the default file names chosen for Ada units so that they do not
14546 exceed the maximum length permitted. It also describes the
14547 @code{gnatkr} utility that can be used to determine the result of
14548 applying this shortening.
14552 * Krunching Method::
14553 * Examples of gnatkr Usage::
14557 @section About @code{gnatkr}
14560 The default file naming rule in GNAT
14561 is that the file name must be derived from
14562 the unit name. The exact default rule is as follows:
14565 Take the unit name and replace all dots by hyphens.
14567 If such a replacement occurs in the
14568 second character position of a name, and the first character is
14569 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
14570 then replace the dot by the character
14571 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
14572 instead of a minus.
14574 The reason for this exception is to avoid clashes
14575 with the standard names for children of System, Ada, Interfaces,
14576 and GNAT, which use the prefixes
14577 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
14580 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
14581 switch of the compiler activates a ``krunching''
14582 circuit that limits file names to nn characters (where nn is a decimal
14583 integer). For example, using OpenVMS,
14584 where the maximum file name length is
14585 39, the value of nn is usually set to 39, but if you want to generate
14586 a set of files that would be usable if ported to a system with some
14587 different maximum file length, then a different value can be specified.
14588 The default value of 39 for OpenVMS need not be specified.
14590 The @code{gnatkr} utility can be used to determine the krunched name for
14591 a given file, when krunched to a specified maximum length.
14594 @section Using @code{gnatkr}
14597 The @code{gnatkr} command has the form
14601 @c $ gnatkr @var{name} @ovar{length}
14602 @c Expanding @ovar macro inline (explanation in macro def comments)
14603 $ gnatkr @var{name} @r{[}@var{length}@r{]}
14609 $ gnatkr @var{name} /COUNT=nn
14614 @var{name} is the uncrunched file name, derived from the name of the unit
14615 in the standard manner described in the previous section (i.e., in particular
14616 all dots are replaced by hyphens). The file name may or may not have an
14617 extension (defined as a suffix of the form period followed by arbitrary
14618 characters other than period). If an extension is present then it will
14619 be preserved in the output. For example, when krunching @file{hellofile.ads}
14620 to eight characters, the result will be hellofil.ads.
14622 Note: for compatibility with previous versions of @code{gnatkr} dots may
14623 appear in the name instead of hyphens, but the last dot will always be
14624 taken as the start of an extension. So if @code{gnatkr} is given an argument
14625 such as @file{Hello.World.adb} it will be treated exactly as if the first
14626 period had been a hyphen, and for example krunching to eight characters
14627 gives the result @file{hellworl.adb}.
14629 Note that the result is always all lower case (except on OpenVMS where it is
14630 all upper case). Characters of the other case are folded as required.
14632 @var{length} represents the length of the krunched name. The default
14633 when no argument is given is ^8^39^ characters. A length of zero stands for
14634 unlimited, in other words do not chop except for system files where the
14635 implied crunching length is always eight characters.
14638 The output is the krunched name. The output has an extension only if the
14639 original argument was a file name with an extension.
14641 @node Krunching Method
14642 @section Krunching Method
14645 The initial file name is determined by the name of the unit that the file
14646 contains. The name is formed by taking the full expanded name of the
14647 unit and replacing the separating dots with hyphens and
14648 using ^lowercase^uppercase^
14649 for all letters, except that a hyphen in the second character position is
14650 replaced by a ^tilde^dollar sign^ if the first character is
14651 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
14652 The extension is @code{.ads} for a
14653 spec and @code{.adb} for a body.
14654 Krunching does not affect the extension, but the file name is shortened to
14655 the specified length by following these rules:
14659 The name is divided into segments separated by hyphens, tildes or
14660 underscores and all hyphens, tildes, and underscores are
14661 eliminated. If this leaves the name short enough, we are done.
14664 If the name is too long, the longest segment is located (left-most
14665 if there are two of equal length), and shortened by dropping
14666 its last character. This is repeated until the name is short enough.
14668 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
14669 to fit the name into 8 characters as required by some operating systems.
14672 our-strings-wide_fixed 22
14673 our strings wide fixed 19
14674 our string wide fixed 18
14675 our strin wide fixed 17
14676 our stri wide fixed 16
14677 our stri wide fixe 15
14678 our str wide fixe 14
14679 our str wid fixe 13
14685 Final file name: oustwifi.adb
14689 The file names for all predefined units are always krunched to eight
14690 characters. The krunching of these predefined units uses the following
14691 special prefix replacements:
14695 replaced by @file{^a^A^-}
14698 replaced by @file{^g^G^-}
14701 replaced by @file{^i^I^-}
14704 replaced by @file{^s^S^-}
14707 These system files have a hyphen in the second character position. That
14708 is why normal user files replace such a character with a
14709 ^tilde^dollar sign^, to
14710 avoid confusion with system file names.
14712 As an example of this special rule, consider
14713 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
14716 ada-strings-wide_fixed 22
14717 a- strings wide fixed 18
14718 a- string wide fixed 17
14719 a- strin wide fixed 16
14720 a- stri wide fixed 15
14721 a- stri wide fixe 14
14722 a- str wide fixe 13
14728 Final file name: a-stwifi.adb
14732 Of course no file shortening algorithm can guarantee uniqueness over all
14733 possible unit names, and if file name krunching is used then it is your
14734 responsibility to ensure that no name clashes occur. The utility
14735 program @code{gnatkr} is supplied for conveniently determining the
14736 krunched name of a file.
14738 @node Examples of gnatkr Usage
14739 @section Examples of @code{gnatkr} Usage
14746 $ gnatkr very_long_unit_name.ads --> velounna.ads
14747 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
14748 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
14749 $ gnatkr grandparent-parent-child --> grparchi
14751 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
14752 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
14755 @node Preprocessing Using gnatprep
14756 @chapter Preprocessing Using @code{gnatprep}
14760 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
14762 Although designed for use with GNAT, @code{gnatprep} does not depend on any
14763 special GNAT features.
14764 For further discussion of conditional compilation in general, see
14765 @ref{Conditional Compilation}.
14768 * Preprocessing Symbols::
14770 * Switches for gnatprep::
14771 * Form of Definitions File::
14772 * Form of Input Text for gnatprep::
14775 @node Preprocessing Symbols
14776 @section Preprocessing Symbols
14779 Preprocessing symbols are defined in definition files and referred to in
14780 sources to be preprocessed. A Preprocessing symbol is an identifier, following
14781 normal Ada (case-insensitive) rules for its syntax, with the restriction that
14782 all characters need to be in the ASCII set (no accented letters).
14784 @node Using gnatprep
14785 @section Using @code{gnatprep}
14788 To call @code{gnatprep} use
14791 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
14792 @c Expanding @ovar macro inline (explanation in macro def comments)
14793 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
14800 is an optional sequence of switches as described in the next section.
14803 is the full name of the input file, which is an Ada source
14804 file containing preprocessor directives.
14807 is the full name of the output file, which is an Ada source
14808 in standard Ada form. When used with GNAT, this file name will
14809 normally have an ads or adb suffix.
14812 is the full name of a text file containing definitions of
14813 preprocessing symbols to be referenced by the preprocessor. This argument is
14814 optional, and can be replaced by the use of the @option{-D} switch.
14818 @node Switches for gnatprep
14819 @section Switches for @code{gnatprep}
14824 @item ^-b^/BLANK_LINES^
14825 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
14826 Causes both preprocessor lines and the lines deleted by
14827 preprocessing to be replaced by blank lines in the output source file,
14828 preserving line numbers in the output file.
14830 @item ^-c^/COMMENTS^
14831 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
14832 Causes both preprocessor lines and the lines deleted
14833 by preprocessing to be retained in the output source as comments marked
14834 with the special string @code{"--! "}. This option will result in line numbers
14835 being preserved in the output file.
14837 @item ^-C^/REPLACE_IN_COMMENTS^
14838 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
14839 Causes comments to be scanned. Normally comments are ignored by gnatprep.
14840 If this option is specified, then comments are scanned and any $symbol
14841 substitutions performed as in program text. This is particularly useful
14842 when structured comments are used (e.g., when writing programs in the
14843 SPARK dialect of Ada). Note that this switch is not available when
14844 doing integrated preprocessing (it would be useless in this context
14845 since comments are ignored by the compiler in any case).
14847 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
14848 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
14849 Defines a new preprocessing symbol, associated with value. If no value is given
14850 on the command line, then symbol is considered to be @code{True}. This switch
14851 can be used in place of a definition file.
14855 @cindex @option{/REMOVE} (@command{gnatprep})
14856 This is the default setting which causes lines deleted by preprocessing
14857 to be entirely removed from the output file.
14860 @item ^-r^/REFERENCE^
14861 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
14862 Causes a @code{Source_Reference} pragma to be generated that
14863 references the original input file, so that error messages will use
14864 the file name of this original file. The use of this switch implies
14865 that preprocessor lines are not to be removed from the file, so its
14866 use will force @option{^-b^/BLANK_LINES^} mode if
14867 @option{^-c^/COMMENTS^}
14868 has not been specified explicitly.
14870 Note that if the file to be preprocessed contains multiple units, then
14871 it will be necessary to @code{gnatchop} the output file from
14872 @code{gnatprep}. If a @code{Source_Reference} pragma is present
14873 in the preprocessed file, it will be respected by
14874 @code{gnatchop ^-r^/REFERENCE^}
14875 so that the final chopped files will correctly refer to the original
14876 input source file for @code{gnatprep}.
14878 @item ^-s^/SYMBOLS^
14879 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
14880 Causes a sorted list of symbol names and values to be
14881 listed on the standard output file.
14883 @item ^-u^/UNDEFINED^
14884 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
14885 Causes undefined symbols to be treated as having the value FALSE in the context
14886 of a preprocessor test. In the absence of this option, an undefined symbol in
14887 a @code{#if} or @code{#elsif} test will be treated as an error.
14893 Note: if neither @option{-b} nor @option{-c} is present,
14894 then preprocessor lines and
14895 deleted lines are completely removed from the output, unless -r is
14896 specified, in which case -b is assumed.
14899 @node Form of Definitions File
14900 @section Form of Definitions File
14903 The definitions file contains lines of the form
14910 where symbol is a preprocessing symbol, and value is one of the following:
14914 Empty, corresponding to a null substitution
14916 A string literal using normal Ada syntax
14918 Any sequence of characters from the set
14919 (letters, digits, period, underline).
14923 Comment lines may also appear in the definitions file, starting with
14924 the usual @code{--},
14925 and comments may be added to the definitions lines.
14927 @node Form of Input Text for gnatprep
14928 @section Form of Input Text for @code{gnatprep}
14931 The input text may contain preprocessor conditional inclusion lines,
14932 as well as general symbol substitution sequences.
14934 The preprocessor conditional inclusion commands have the form
14939 #if @i{expression} @r{[}then@r{]}
14941 #elsif @i{expression} @r{[}then@r{]}
14943 #elsif @i{expression} @r{[}then@r{]}
14954 In this example, @i{expression} is defined by the following grammar:
14956 @i{expression} ::= <symbol>
14957 @i{expression} ::= <symbol> = "<value>"
14958 @i{expression} ::= <symbol> = <symbol>
14959 @i{expression} ::= <symbol> 'Defined
14960 @i{expression} ::= not @i{expression}
14961 @i{expression} ::= @i{expression} and @i{expression}
14962 @i{expression} ::= @i{expression} or @i{expression}
14963 @i{expression} ::= @i{expression} and then @i{expression}
14964 @i{expression} ::= @i{expression} or else @i{expression}
14965 @i{expression} ::= ( @i{expression} )
14968 The following restriction exists: it is not allowed to have "and" or "or"
14969 following "not" in the same expression without parentheses. For example, this
14976 This should be one of the following:
14984 For the first test (@i{expression} ::= <symbol>) the symbol must have
14985 either the value true or false, that is to say the right-hand of the
14986 symbol definition must be one of the (case-insensitive) literals
14987 @code{True} or @code{False}. If the value is true, then the
14988 corresponding lines are included, and if the value is false, they are
14991 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
14992 the symbol has been defined in the definition file or by a @option{-D}
14993 switch on the command line. Otherwise, the test is false.
14995 The equality tests are case insensitive, as are all the preprocessor lines.
14997 If the symbol referenced is not defined in the symbol definitions file,
14998 then the effect depends on whether or not switch @option{-u}
14999 is specified. If so, then the symbol is treated as if it had the value
15000 false and the test fails. If this switch is not specified, then
15001 it is an error to reference an undefined symbol. It is also an error to
15002 reference a symbol that is defined with a value other than @code{True}
15005 The use of the @code{not} operator inverts the sense of this logical test.
15006 The @code{not} operator cannot be combined with the @code{or} or @code{and}
15007 operators, without parentheses. For example, "if not X or Y then" is not
15008 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
15010 The @code{then} keyword is optional as shown
15012 The @code{#} must be the first non-blank character on a line, but
15013 otherwise the format is free form. Spaces or tabs may appear between
15014 the @code{#} and the keyword. The keywords and the symbols are case
15015 insensitive as in normal Ada code. Comments may be used on a
15016 preprocessor line, but other than that, no other tokens may appear on a
15017 preprocessor line. Any number of @code{elsif} clauses can be present,
15018 including none at all. The @code{else} is optional, as in Ada.
15020 The @code{#} marking the start of a preprocessor line must be the first
15021 non-blank character on the line, i.e., it must be preceded only by
15022 spaces or horizontal tabs.
15024 Symbol substitution outside of preprocessor lines is obtained by using
15032 anywhere within a source line, except in a comment or within a
15033 string literal. The identifier
15034 following the @code{$} must match one of the symbols defined in the symbol
15035 definition file, and the result is to substitute the value of the
15036 symbol in place of @code{$symbol} in the output file.
15038 Note that although the substitution of strings within a string literal
15039 is not possible, it is possible to have a symbol whose defined value is
15040 a string literal. So instead of setting XYZ to @code{hello} and writing:
15043 Header : String := "$XYZ";
15047 you should set XYZ to @code{"hello"} and write:
15050 Header : String := $XYZ;
15054 and then the substitution will occur as desired.
15056 @node The GNAT Library Browser gnatls
15057 @chapter The GNAT Library Browser @code{gnatls}
15059 @cindex Library browser
15062 @code{gnatls} is a tool that outputs information about compiled
15063 units. It gives the relationship between objects, unit names and source
15064 files. It can also be used to check the source dependencies of a unit
15065 as well as various characteristics.
15067 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
15068 driver (see @ref{The GNAT Driver and Project Files}).
15072 * Switches for gnatls::
15073 * Examples of gnatls Usage::
15076 @node Running gnatls
15077 @section Running @code{gnatls}
15080 The @code{gnatls} command has the form
15083 $ gnatls switches @var{object_or_ali_file}
15087 The main argument is the list of object or @file{ali} files
15088 (@pxref{The Ada Library Information Files})
15089 for which information is requested.
15091 In normal mode, without additional option, @code{gnatls} produces a
15092 four-column listing. Each line represents information for a specific
15093 object. The first column gives the full path of the object, the second
15094 column gives the name of the principal unit in this object, the third
15095 column gives the status of the source and the fourth column gives the
15096 full path of the source representing this unit.
15097 Here is a simple example of use:
15101 ^./^[]^demo1.o demo1 DIF demo1.adb
15102 ^./^[]^demo2.o demo2 OK demo2.adb
15103 ^./^[]^hello.o h1 OK hello.adb
15104 ^./^[]^instr-child.o instr.child MOK instr-child.adb
15105 ^./^[]^instr.o instr OK instr.adb
15106 ^./^[]^tef.o tef DIF tef.adb
15107 ^./^[]^text_io_example.o text_io_example OK text_io_example.adb
15108 ^./^[]^tgef.o tgef DIF tgef.adb
15112 The first line can be interpreted as follows: the main unit which is
15114 object file @file{demo1.o} is demo1, whose main source is in
15115 @file{demo1.adb}. Furthermore, the version of the source used for the
15116 compilation of demo1 has been modified (DIF). Each source file has a status
15117 qualifier which can be:
15120 @item OK (unchanged)
15121 The version of the source file used for the compilation of the
15122 specified unit corresponds exactly to the actual source file.
15124 @item MOK (slightly modified)
15125 The version of the source file used for the compilation of the
15126 specified unit differs from the actual source file but not enough to
15127 require recompilation. If you use gnatmake with the qualifier
15128 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
15129 MOK will not be recompiled.
15131 @item DIF (modified)
15132 No version of the source found on the path corresponds to the source
15133 used to build this object.
15135 @item ??? (file not found)
15136 No source file was found for this unit.
15138 @item HID (hidden, unchanged version not first on PATH)
15139 The version of the source that corresponds exactly to the source used
15140 for compilation has been found on the path but it is hidden by another
15141 version of the same source that has been modified.
15145 @node Switches for gnatls
15146 @section Switches for @code{gnatls}
15149 @code{gnatls} recognizes the following switches:
15153 @cindex @option{--version} @command{gnatls}
15154 Display Copyright and version, then exit disregarding all other options.
15157 @cindex @option{--help} @command{gnatls}
15158 If @option{--version} was not used, display usage, then exit disregarding
15161 @item ^-a^/ALL_UNITS^
15162 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
15163 Consider all units, including those of the predefined Ada library.
15164 Especially useful with @option{^-d^/DEPENDENCIES^}.
15166 @item ^-d^/DEPENDENCIES^
15167 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
15168 List sources from which specified units depend on.
15170 @item ^-h^/OUTPUT=OPTIONS^
15171 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
15172 Output the list of options.
15174 @item ^-o^/OUTPUT=OBJECTS^
15175 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
15176 Only output information about object files.
15178 @item ^-s^/OUTPUT=SOURCES^
15179 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
15180 Only output information about source files.
15182 @item ^-u^/OUTPUT=UNITS^
15183 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
15184 Only output information about compilation units.
15186 @item ^-files^/FILES^=@var{file}
15187 @cindex @option{^-files^/FILES^} (@code{gnatls})
15188 Take as arguments the files listed in text file @var{file}.
15189 Text file @var{file} may contain empty lines that are ignored.
15190 Each nonempty line should contain the name of an existing file.
15191 Several such switches may be specified simultaneously.
15193 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15194 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
15195 @itemx ^-I^/SEARCH=^@var{dir}
15196 @itemx ^-I-^/NOCURRENT_DIRECTORY^
15198 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
15199 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
15200 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
15201 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
15202 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
15203 flags (@pxref{Switches for gnatmake}).
15205 @item --RTS=@var{rts-path}
15206 @cindex @option{--RTS} (@code{gnatls})
15207 Specifies the default location of the runtime library. Same meaning as the
15208 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15210 @item ^-v^/OUTPUT=VERBOSE^
15211 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
15212 Verbose mode. Output the complete source, object and project paths. Do not use
15213 the default column layout but instead use long format giving as much as
15214 information possible on each requested units, including special
15215 characteristics such as:
15218 @item Preelaborable
15219 The unit is preelaborable in the Ada sense.
15222 No elaboration code has been produced by the compiler for this unit.
15225 The unit is pure in the Ada sense.
15227 @item Elaborate_Body
15228 The unit contains a pragma Elaborate_Body.
15231 The unit contains a pragma Remote_Types.
15233 @item Shared_Passive
15234 The unit contains a pragma Shared_Passive.
15237 This unit is part of the predefined environment and cannot be modified
15240 @item Remote_Call_Interface
15241 The unit contains a pragma Remote_Call_Interface.
15247 @node Examples of gnatls Usage
15248 @section Example of @code{gnatls} Usage
15252 Example of using the verbose switch. Note how the source and
15253 object paths are affected by the -I switch.
15256 $ gnatls -v -I.. demo1.o
15258 GNATLS 5.03w (20041123-34)
15259 Copyright 1997-2004 Free Software Foundation, Inc.
15261 Source Search Path:
15262 <Current_Directory>
15264 /home/comar/local/adainclude/
15266 Object Search Path:
15267 <Current_Directory>
15269 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
15271 Project Search Path:
15272 <Current_Directory>
15273 /home/comar/local/lib/gnat/
15278 Kind => subprogram body
15279 Flags => No_Elab_Code
15280 Source => demo1.adb modified
15284 The following is an example of use of the dependency list.
15285 Note the use of the -s switch
15286 which gives a straight list of source files. This can be useful for
15287 building specialized scripts.
15290 $ gnatls -d demo2.o
15291 ./demo2.o demo2 OK demo2.adb
15297 $ gnatls -d -s -a demo1.o
15299 /home/comar/local/adainclude/ada.ads
15300 /home/comar/local/adainclude/a-finali.ads
15301 /home/comar/local/adainclude/a-filico.ads
15302 /home/comar/local/adainclude/a-stream.ads
15303 /home/comar/local/adainclude/a-tags.ads
15306 /home/comar/local/adainclude/gnat.ads
15307 /home/comar/local/adainclude/g-io.ads
15309 /home/comar/local/adainclude/system.ads
15310 /home/comar/local/adainclude/s-exctab.ads
15311 /home/comar/local/adainclude/s-finimp.ads
15312 /home/comar/local/adainclude/s-finroo.ads
15313 /home/comar/local/adainclude/s-secsta.ads
15314 /home/comar/local/adainclude/s-stalib.ads
15315 /home/comar/local/adainclude/s-stoele.ads
15316 /home/comar/local/adainclude/s-stratt.ads
15317 /home/comar/local/adainclude/s-tasoli.ads
15318 /home/comar/local/adainclude/s-unstyp.ads
15319 /home/comar/local/adainclude/unchconv.ads
15325 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
15327 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
15328 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
15329 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
15330 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
15331 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
15335 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
15336 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
15338 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
15339 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
15340 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
15341 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
15342 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
15343 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
15344 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
15345 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
15346 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
15347 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
15348 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
15352 @node Cleaning Up Using gnatclean
15353 @chapter Cleaning Up Using @code{gnatclean}
15355 @cindex Cleaning tool
15358 @code{gnatclean} is a tool that allows the deletion of files produced by the
15359 compiler, binder and linker, including ALI files, object files, tree files,
15360 expanded source files, library files, interface copy source files, binder
15361 generated files and executable files.
15364 * Running gnatclean::
15365 * Switches for gnatclean::
15366 @c * Examples of gnatclean Usage::
15369 @node Running gnatclean
15370 @section Running @code{gnatclean}
15373 The @code{gnatclean} command has the form:
15376 $ gnatclean switches @var{names}
15380 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
15381 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
15382 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
15385 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
15386 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
15387 the linker. In informative-only mode, specified by switch
15388 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
15389 normal mode is listed, but no file is actually deleted.
15391 @node Switches for gnatclean
15392 @section Switches for @code{gnatclean}
15395 @code{gnatclean} recognizes the following switches:
15399 @cindex @option{--version} @command{gnatclean}
15400 Display Copyright and version, then exit disregarding all other options.
15403 @cindex @option{--help} @command{gnatclean}
15404 If @option{--version} was not used, display usage, then exit disregarding
15407 @item ^--subdirs^/SUBDIRS^=subdir
15408 Actual object directory of each project file is the subdirectory subdir of the
15409 object directory specified or defauted in the project file.
15411 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
15412 By default, shared library projects are not allowed to import static library
15413 projects. When this switch is used on the command line, this restriction is
15416 @item ^-c^/COMPILER_FILES_ONLY^
15417 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
15418 Only attempt to delete the files produced by the compiler, not those produced
15419 by the binder or the linker. The files that are not to be deleted are library
15420 files, interface copy files, binder generated files and executable files.
15422 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
15423 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
15424 Indicate that ALI and object files should normally be found in directory
15427 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
15428 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
15429 When using project files, if some errors or warnings are detected during
15430 parsing and verbose mode is not in effect (no use of switch
15431 ^-v^/VERBOSE^), then error lines start with the full path name of the project
15432 file, rather than its simple file name.
15435 @cindex @option{^-h^/HELP^} (@code{gnatclean})
15436 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
15438 @item ^-n^/NODELETE^
15439 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
15440 Informative-only mode. Do not delete any files. Output the list of the files
15441 that would have been deleted if this switch was not specified.
15443 @item ^-P^/PROJECT_FILE=^@var{project}
15444 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
15445 Use project file @var{project}. Only one such switch can be used.
15446 When cleaning a project file, the files produced by the compilation of the
15447 immediate sources or inherited sources of the project files are to be
15448 deleted. This is not depending on the presence or not of executable names
15449 on the command line.
15452 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
15453 Quiet output. If there are no errors, do not output anything, except in
15454 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
15455 (switch ^-n^/NODELETE^).
15457 @item ^-r^/RECURSIVE^
15458 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
15459 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
15460 clean all imported and extended project files, recursively. If this switch
15461 is not specified, only the files related to the main project file are to be
15462 deleted. This switch has no effect if no project file is specified.
15464 @item ^-v^/VERBOSE^
15465 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
15468 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
15469 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
15470 Indicates the verbosity of the parsing of GNAT project files.
15471 @xref{Switches Related to Project Files}.
15473 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
15474 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
15475 Indicates that external variable @var{name} has the value @var{value}.
15476 The Project Manager will use this value for occurrences of
15477 @code{external(name)} when parsing the project file.
15478 @xref{Switches Related to Project Files}.
15480 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15481 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
15482 When searching for ALI and object files, look in directory
15485 @item ^-I^/SEARCH=^@var{dir}
15486 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
15487 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
15489 @item ^-I-^/NOCURRENT_DIRECTORY^
15490 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
15491 @cindex Source files, suppressing search
15492 Do not look for ALI or object files in the directory
15493 where @code{gnatclean} was invoked.
15497 @c @node Examples of gnatclean Usage
15498 @c @section Examples of @code{gnatclean} Usage
15501 @node GNAT and Libraries
15502 @chapter GNAT and Libraries
15503 @cindex Library, building, installing, using
15506 This chapter describes how to build and use libraries with GNAT, and also shows
15507 how to recompile the GNAT run-time library. You should be familiar with the
15508 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
15512 * Introduction to Libraries in GNAT::
15513 * General Ada Libraries::
15514 * Stand-alone Ada Libraries::
15515 * Rebuilding the GNAT Run-Time Library::
15518 @node Introduction to Libraries in GNAT
15519 @section Introduction to Libraries in GNAT
15522 A library is, conceptually, a collection of objects which does not have its
15523 own main thread of execution, but rather provides certain services to the
15524 applications that use it. A library can be either statically linked with the
15525 application, in which case its code is directly included in the application,
15526 or, on platforms that support it, be dynamically linked, in which case
15527 its code is shared by all applications making use of this library.
15529 GNAT supports both types of libraries.
15530 In the static case, the compiled code can be provided in different ways. The
15531 simplest approach is to provide directly the set of objects resulting from
15532 compilation of the library source files. Alternatively, you can group the
15533 objects into an archive using whatever commands are provided by the operating
15534 system. For the latter case, the objects are grouped into a shared library.
15536 In the GNAT environment, a library has three types of components:
15542 @xref{The Ada Library Information Files}.
15544 Object files, an archive or a shared library.
15548 A GNAT library may expose all its source files, which is useful for
15549 documentation purposes. Alternatively, it may expose only the units needed by
15550 an external user to make use of the library. That is to say, the specs
15551 reflecting the library services along with all the units needed to compile
15552 those specs, which can include generic bodies or any body implementing an
15553 inlined routine. In the case of @emph{stand-alone libraries} those exposed
15554 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
15556 All compilation units comprising an application, including those in a library,
15557 need to be elaborated in an order partially defined by Ada's semantics. GNAT
15558 computes the elaboration order from the @file{ALI} files and this is why they
15559 constitute a mandatory part of GNAT libraries.
15560 @emph{Stand-alone libraries} are the exception to this rule because a specific
15561 library elaboration routine is produced independently of the application(s)
15564 @node General Ada Libraries
15565 @section General Ada Libraries
15568 * Building a library::
15569 * Installing a library::
15570 * Using a library::
15573 @node Building a library
15574 @subsection Building a library
15577 The easiest way to build a library is to use the Project Manager,
15578 which supports a special type of project called a @emph{Library Project}
15579 (@pxref{Library Projects}).
15581 A project is considered a library project, when two project-level attributes
15582 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
15583 control different aspects of library configuration, additional optional
15584 project-level attributes can be specified:
15587 This attribute controls whether the library is to be static or dynamic
15589 @item Library_Version
15590 This attribute specifies the library version; this value is used
15591 during dynamic linking of shared libraries to determine if the currently
15592 installed versions of the binaries are compatible.
15594 @item Library_Options
15596 These attributes specify additional low-level options to be used during
15597 library generation, and redefine the actual application used to generate
15602 The GNAT Project Manager takes full care of the library maintenance task,
15603 including recompilation of the source files for which objects do not exist
15604 or are not up to date, assembly of the library archive, and installation of
15605 the library (i.e., copying associated source, object and @file{ALI} files
15606 to the specified location).
15608 Here is a simple library project file:
15609 @smallexample @c ada
15611 for Source_Dirs use ("src1", "src2");
15612 for Object_Dir use "obj";
15613 for Library_Name use "mylib";
15614 for Library_Dir use "lib";
15615 for Library_Kind use "dynamic";
15620 and the compilation command to build and install the library:
15622 @smallexample @c ada
15623 $ gnatmake -Pmy_lib
15627 It is not entirely trivial to perform manually all the steps required to
15628 produce a library. We recommend that you use the GNAT Project Manager
15629 for this task. In special cases where this is not desired, the necessary
15630 steps are discussed below.
15632 There are various possibilities for compiling the units that make up the
15633 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
15634 with a conventional script. For simple libraries, it is also possible to create
15635 a dummy main program which depends upon all the packages that comprise the
15636 interface of the library. This dummy main program can then be given to
15637 @command{gnatmake}, which will ensure that all necessary objects are built.
15639 After this task is accomplished, you should follow the standard procedure
15640 of the underlying operating system to produce the static or shared library.
15642 Here is an example of such a dummy program:
15643 @smallexample @c ada
15645 with My_Lib.Service1;
15646 with My_Lib.Service2;
15647 with My_Lib.Service3;
15648 procedure My_Lib_Dummy is
15656 Here are the generic commands that will build an archive or a shared library.
15659 # compiling the library
15660 $ gnatmake -c my_lib_dummy.adb
15662 # we don't need the dummy object itself
15663 $ rm my_lib_dummy.o my_lib_dummy.ali
15665 # create an archive with the remaining objects
15666 $ ar rc libmy_lib.a *.o
15667 # some systems may require "ranlib" to be run as well
15669 # or create a shared library
15670 $ gcc -shared -o libmy_lib.so *.o
15671 # some systems may require the code to have been compiled with -fPIC
15673 # remove the object files that are now in the library
15676 # Make the ALI files read-only so that gnatmake will not try to
15677 # regenerate the objects that are in the library
15682 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
15683 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
15684 be accessed by the directive @option{-l@var{xxx}} at link time.
15686 @node Installing a library
15687 @subsection Installing a library
15688 @cindex @code{ADA_PROJECT_PATH}
15689 @cindex @code{GPR_PROJECT_PATH}
15692 If you use project files, library installation is part of the library build
15693 process (@pxref{Installing a library with project files}).
15695 When project files are not an option, it is also possible, but not recommended,
15696 to install the library so that the sources needed to use the library are on the
15697 Ada source path and the ALI files & libraries be on the Ada Object path (see
15698 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
15699 administrator can place general-purpose libraries in the default compiler
15700 paths, by specifying the libraries' location in the configuration files
15701 @file{ada_source_path} and @file{ada_object_path}. These configuration files
15702 must be located in the GNAT installation tree at the same place as the gcc spec
15703 file. The location of the gcc spec file can be determined as follows:
15709 The configuration files mentioned above have a simple format: each line
15710 must contain one unique directory name.
15711 Those names are added to the corresponding path
15712 in their order of appearance in the file. The names can be either absolute
15713 or relative; in the latter case, they are relative to where theses files
15716 The files @file{ada_source_path} and @file{ada_object_path} might not be
15718 GNAT installation, in which case, GNAT will look for its run-time library in
15719 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
15720 objects and @file{ALI} files). When the files exist, the compiler does not
15721 look in @file{adainclude} and @file{adalib}, and thus the
15722 @file{ada_source_path} file
15723 must contain the location for the GNAT run-time sources (which can simply
15724 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
15725 contain the location for the GNAT run-time objects (which can simply
15728 You can also specify a new default path to the run-time library at compilation
15729 time with the switch @option{--RTS=rts-path}. You can thus choose / change
15730 the run-time library you want your program to be compiled with. This switch is
15731 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
15732 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
15734 It is possible to install a library before or after the standard GNAT
15735 library, by reordering the lines in the configuration files. In general, a
15736 library must be installed before the GNAT library if it redefines
15739 @node Using a library
15740 @subsection Using a library
15742 @noindent Once again, the project facility greatly simplifies the use of
15743 libraries. In this context, using a library is just a matter of adding a
15744 @code{with} clause in the user project. For instance, to make use of the
15745 library @code{My_Lib} shown in examples in earlier sections, you can
15748 @smallexample @c projectfile
15755 Even if you have a third-party, non-Ada library, you can still use GNAT's
15756 Project Manager facility to provide a wrapper for it. For example, the
15757 following project, when @code{with}ed by your main project, will link with the
15758 third-party library @file{liba.a}:
15760 @smallexample @c projectfile
15763 for Externally_Built use "true";
15764 for Source_Files use ();
15765 for Library_Dir use "lib";
15766 for Library_Name use "a";
15767 for Library_Kind use "static";
15771 This is an alternative to the use of @code{pragma Linker_Options}. It is
15772 especially interesting in the context of systems with several interdependent
15773 static libraries where finding a proper linker order is not easy and best be
15774 left to the tools having visibility over project dependence information.
15777 In order to use an Ada library manually, you need to make sure that this
15778 library is on both your source and object path
15779 (see @ref{Search Paths and the Run-Time Library (RTL)}
15780 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
15781 in an archive or a shared library, you need to specify the desired
15782 library at link time.
15784 For example, you can use the library @file{mylib} installed in
15785 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
15788 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
15793 This can be expressed more simply:
15798 when the following conditions are met:
15801 @file{/dir/my_lib_src} has been added by the user to the environment
15802 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
15803 @file{ada_source_path}
15805 @file{/dir/my_lib_obj} has been added by the user to the environment
15806 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
15807 @file{ada_object_path}
15809 a pragma @code{Linker_Options} has been added to one of the sources.
15812 @smallexample @c ada
15813 pragma Linker_Options ("-lmy_lib");
15817 @node Stand-alone Ada Libraries
15818 @section Stand-alone Ada Libraries
15819 @cindex Stand-alone library, building, using
15822 * Introduction to Stand-alone Libraries::
15823 * Building a Stand-alone Library::
15824 * Creating a Stand-alone Library to be used in a non-Ada context::
15825 * Restrictions in Stand-alone Libraries::
15828 @node Introduction to Stand-alone Libraries
15829 @subsection Introduction to Stand-alone Libraries
15832 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
15834 elaborate the Ada units that are included in the library. In contrast with
15835 an ordinary library, which consists of all sources, objects and @file{ALI}
15837 library, a SAL may specify a restricted subset of compilation units
15838 to serve as a library interface. In this case, the fully
15839 self-sufficient set of files will normally consist of an objects
15840 archive, the sources of interface units' specs, and the @file{ALI}
15841 files of interface units.
15842 If an interface spec contains a generic unit or an inlined subprogram,
15844 source must also be provided; if the units that must be provided in the source
15845 form depend on other units, the source and @file{ALI} files of those must
15848 The main purpose of a SAL is to minimize the recompilation overhead of client
15849 applications when a new version of the library is installed. Specifically,
15850 if the interface sources have not changed, client applications do not need to
15851 be recompiled. If, furthermore, a SAL is provided in the shared form and its
15852 version, controlled by @code{Library_Version} attribute, is not changed,
15853 then the clients do not need to be relinked.
15855 SALs also allow the library providers to minimize the amount of library source
15856 text exposed to the clients. Such ``information hiding'' might be useful or
15857 necessary for various reasons.
15859 Stand-alone libraries are also well suited to be used in an executable whose
15860 main routine is not written in Ada.
15862 @node Building a Stand-alone Library
15863 @subsection Building a Stand-alone Library
15866 GNAT's Project facility provides a simple way of building and installing
15867 stand-alone libraries; see @ref{Stand-alone Library Projects}.
15868 To be a Stand-alone Library Project, in addition to the two attributes
15869 that make a project a Library Project (@code{Library_Name} and
15870 @code{Library_Dir}; see @ref{Library Projects}), the attribute
15871 @code{Library_Interface} must be defined. For example:
15873 @smallexample @c projectfile
15875 for Library_Dir use "lib_dir";
15876 for Library_Name use "dummy";
15877 for Library_Interface use ("int1", "int1.child");
15882 Attribute @code{Library_Interface} has a non-empty string list value,
15883 each string in the list designating a unit contained in an immediate source
15884 of the project file.
15886 When a Stand-alone Library is built, first the binder is invoked to build
15887 a package whose name depends on the library name
15888 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
15889 This binder-generated package includes initialization and
15890 finalization procedures whose
15891 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
15893 above). The object corresponding to this package is included in the library.
15895 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
15896 calling of these procedures if a static SAL is built, or if a shared SAL
15898 with the project-level attribute @code{Library_Auto_Init} set to
15901 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
15902 (those that are listed in attribute @code{Library_Interface}) are copied to
15903 the Library Directory. As a consequence, only the Interface Units may be
15904 imported from Ada units outside of the library. If other units are imported,
15905 the binding phase will fail.
15907 The attribute @code{Library_Src_Dir} may be specified for a
15908 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
15909 single string value. Its value must be the path (absolute or relative to the
15910 project directory) of an existing directory. This directory cannot be the
15911 object directory or one of the source directories, but it can be the same as
15912 the library directory. The sources of the Interface
15913 Units of the library that are needed by an Ada client of the library will be
15914 copied to the designated directory, called the Interface Copy directory.
15915 These sources include the specs of the Interface Units, but they may also
15916 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
15917 are used, or when there is a generic unit in the spec. Before the sources
15918 are copied to the Interface Copy directory, an attempt is made to delete all
15919 files in the Interface Copy directory.
15921 Building stand-alone libraries by hand is somewhat tedious, but for those
15922 occasions when it is necessary here are the steps that you need to perform:
15925 Compile all library sources.
15928 Invoke the binder with the switch @option{-n} (No Ada main program),
15929 with all the @file{ALI} files of the interfaces, and
15930 with the switch @option{-L} to give specific names to the @code{init}
15931 and @code{final} procedures. For example:
15933 gnatbind -n int1.ali int2.ali -Lsal1
15937 Compile the binder generated file:
15943 Link the dynamic library with all the necessary object files,
15944 indicating to the linker the names of the @code{init} (and possibly
15945 @code{final}) procedures for automatic initialization (and finalization).
15946 The built library should be placed in a directory different from
15947 the object directory.
15950 Copy the @code{ALI} files of the interface to the library directory,
15951 add in this copy an indication that it is an interface to a SAL
15952 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
15953 with letter ``P'') and make the modified copy of the @file{ALI} file
15958 Using SALs is not different from using other libraries
15959 (see @ref{Using a library}).
15961 @node Creating a Stand-alone Library to be used in a non-Ada context
15962 @subsection Creating a Stand-alone Library to be used in a non-Ada context
15965 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
15968 The only extra step required is to ensure that library interface subprograms
15969 are compatible with the main program, by means of @code{pragma Export}
15970 or @code{pragma Convention}.
15972 Here is an example of simple library interface for use with C main program:
15974 @smallexample @c ada
15975 package My_Package is
15977 procedure Do_Something;
15978 pragma Export (C, Do_Something, "do_something");
15980 procedure Do_Something_Else;
15981 pragma Export (C, Do_Something_Else, "do_something_else");
15987 On the foreign language side, you must provide a ``foreign'' view of the
15988 library interface; remember that it should contain elaboration routines in
15989 addition to interface subprograms.
15991 The example below shows the content of @code{mylib_interface.h} (note
15992 that there is no rule for the naming of this file, any name can be used)
15994 /* the library elaboration procedure */
15995 extern void mylibinit (void);
15997 /* the library finalization procedure */
15998 extern void mylibfinal (void);
16000 /* the interface exported by the library */
16001 extern void do_something (void);
16002 extern void do_something_else (void);
16006 Libraries built as explained above can be used from any program, provided
16007 that the elaboration procedures (named @code{mylibinit} in the previous
16008 example) are called before the library services are used. Any number of
16009 libraries can be used simultaneously, as long as the elaboration
16010 procedure of each library is called.
16012 Below is an example of a C program that uses the @code{mylib} library.
16015 #include "mylib_interface.h"
16020 /* First, elaborate the library before using it */
16023 /* Main program, using the library exported entities */
16025 do_something_else ();
16027 /* Library finalization at the end of the program */
16034 Note that invoking any library finalization procedure generated by
16035 @code{gnatbind} shuts down the Ada run-time environment.
16037 finalization of all Ada libraries must be performed at the end of the program.
16038 No call to these libraries or to the Ada run-time library should be made
16039 after the finalization phase.
16041 @node Restrictions in Stand-alone Libraries
16042 @subsection Restrictions in Stand-alone Libraries
16045 The pragmas listed below should be used with caution inside libraries,
16046 as they can create incompatibilities with other Ada libraries:
16048 @item pragma @code{Locking_Policy}
16049 @item pragma @code{Queuing_Policy}
16050 @item pragma @code{Task_Dispatching_Policy}
16051 @item pragma @code{Unreserve_All_Interrupts}
16055 When using a library that contains such pragmas, the user must make sure
16056 that all libraries use the same pragmas with the same values. Otherwise,
16057 @code{Program_Error} will
16058 be raised during the elaboration of the conflicting
16059 libraries. The usage of these pragmas and its consequences for the user
16060 should therefore be well documented.
16062 Similarly, the traceback in the exception occurrence mechanism should be
16063 enabled or disabled in a consistent manner across all libraries.
16064 Otherwise, Program_Error will be raised during the elaboration of the
16065 conflicting libraries.
16067 If the @code{Version} or @code{Body_Version}
16068 attributes are used inside a library, then you need to
16069 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
16070 libraries, so that version identifiers can be properly computed.
16071 In practice these attributes are rarely used, so this is unlikely
16072 to be a consideration.
16074 @node Rebuilding the GNAT Run-Time Library
16075 @section Rebuilding the GNAT Run-Time Library
16076 @cindex GNAT Run-Time Library, rebuilding
16077 @cindex Building the GNAT Run-Time Library
16078 @cindex Rebuilding the GNAT Run-Time Library
16079 @cindex Run-Time Library, rebuilding
16082 It may be useful to recompile the GNAT library in various contexts, the
16083 most important one being the use of partition-wide configuration pragmas
16084 such as @code{Normalize_Scalars}. A special Makefile called
16085 @code{Makefile.adalib} is provided to that effect and can be found in
16086 the directory containing the GNAT library. The location of this
16087 directory depends on the way the GNAT environment has been installed and can
16088 be determined by means of the command:
16095 The last entry in the object search path usually contains the
16096 gnat library. This Makefile contains its own documentation and in
16097 particular the set of instructions needed to rebuild a new library and
16100 @node Using the GNU make Utility
16101 @chapter Using the GNU @code{make} Utility
16105 This chapter offers some examples of makefiles that solve specific
16106 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
16107 make, make, GNU @code{make}}), nor does it try to replace the
16108 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
16110 All the examples in this section are specific to the GNU version of
16111 make. Although @command{make} is a standard utility, and the basic language
16112 is the same, these examples use some advanced features found only in
16116 * Using gnatmake in a Makefile::
16117 * Automatically Creating a List of Directories::
16118 * Generating the Command Line Switches::
16119 * Overcoming Command Line Length Limits::
16122 @node Using gnatmake in a Makefile
16123 @section Using gnatmake in a Makefile
16128 Complex project organizations can be handled in a very powerful way by
16129 using GNU make combined with gnatmake. For instance, here is a Makefile
16130 which allows you to build each subsystem of a big project into a separate
16131 shared library. Such a makefile allows you to significantly reduce the link
16132 time of very big applications while maintaining full coherence at
16133 each step of the build process.
16135 The list of dependencies are handled automatically by
16136 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
16137 the appropriate directories.
16139 Note that you should also read the example on how to automatically
16140 create the list of directories
16141 (@pxref{Automatically Creating a List of Directories})
16142 which might help you in case your project has a lot of subdirectories.
16147 @font@heightrm=cmr8
16150 ## This Makefile is intended to be used with the following directory
16152 ## - The sources are split into a series of csc (computer software components)
16153 ## Each of these csc is put in its own directory.
16154 ## Their name are referenced by the directory names.
16155 ## They will be compiled into shared library (although this would also work
16156 ## with static libraries
16157 ## - The main program (and possibly other packages that do not belong to any
16158 ## csc is put in the top level directory (where the Makefile is).
16159 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
16160 ## \_ second_csc (sources) __ lib (will contain the library)
16162 ## Although this Makefile is build for shared library, it is easy to modify
16163 ## to build partial link objects instead (modify the lines with -shared and
16166 ## With this makefile, you can change any file in the system or add any new
16167 ## file, and everything will be recompiled correctly (only the relevant shared
16168 ## objects will be recompiled, and the main program will be re-linked).
16170 # The list of computer software component for your project. This might be
16171 # generated automatically.
16174 # Name of the main program (no extension)
16177 # If we need to build objects with -fPIC, uncomment the following line
16180 # The following variable should give the directory containing libgnat.so
16181 # You can get this directory through 'gnatls -v'. This is usually the last
16182 # directory in the Object_Path.
16185 # The directories for the libraries
16186 # (This macro expands the list of CSC to the list of shared libraries, you
16187 # could simply use the expanded form:
16188 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16189 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16191 $@{MAIN@}: objects $@{LIB_DIR@}
16192 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16193 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16196 # recompile the sources
16197 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16199 # Note: In a future version of GNAT, the following commands will be simplified
16200 # by a new tool, gnatmlib
16202 mkdir -p $@{dir $@@ @}
16203 cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16204 cd $@{dir $@@ @} && cp -f ../*.ali .
16206 # The dependencies for the modules
16207 # Note that we have to force the expansion of *.o, since in some cases
16208 # make won't be able to do it itself.
16209 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16210 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16211 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16213 # Make sure all of the shared libraries are in the path before starting the
16216 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16219 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16220 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16221 $@{RM@} $@{CSC_LIST:%=%/*.o@}
16222 $@{RM@} *.o *.ali $@{MAIN@}
16225 @node Automatically Creating a List of Directories
16226 @section Automatically Creating a List of Directories
16229 In most makefiles, you will have to specify a list of directories, and
16230 store it in a variable. For small projects, it is often easier to
16231 specify each of them by hand, since you then have full control over what
16232 is the proper order for these directories, which ones should be
16235 However, in larger projects, which might involve hundreds of
16236 subdirectories, it might be more convenient to generate this list
16239 The example below presents two methods. The first one, although less
16240 general, gives you more control over the list. It involves wildcard
16241 characters, that are automatically expanded by @command{make}. Its
16242 shortcoming is that you need to explicitly specify some of the
16243 organization of your project, such as for instance the directory tree
16244 depth, whether some directories are found in a separate tree, @enddots{}
16246 The second method is the most general one. It requires an external
16247 program, called @command{find}, which is standard on all Unix systems. All
16248 the directories found under a given root directory will be added to the
16254 @font@heightrm=cmr8
16257 # The examples below are based on the following directory hierarchy:
16258 # All the directories can contain any number of files
16259 # ROOT_DIRECTORY -> a -> aa -> aaa
16262 # -> b -> ba -> baa
16265 # This Makefile creates a variable called DIRS, that can be reused any time
16266 # you need this list (see the other examples in this section)
16268 # The root of your project's directory hierarchy
16272 # First method: specify explicitly the list of directories
16273 # This allows you to specify any subset of all the directories you need.
16276 DIRS := a/aa/ a/ab/ b/ba/
16279 # Second method: use wildcards
16280 # Note that the argument(s) to wildcard below should end with a '/'.
16281 # Since wildcards also return file names, we have to filter them out
16282 # to avoid duplicate directory names.
16283 # We thus use make's @code{dir} and @code{sort} functions.
16284 # It sets DIRs to the following value (note that the directories aaa and baa
16285 # are not given, unless you change the arguments to wildcard).
16286 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16289 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16290 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16293 # Third method: use an external program
16294 # This command is much faster if run on local disks, avoiding NFS slowdowns.
16295 # This is the most complete command: it sets DIRs to the following value:
16296 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16299 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16303 @node Generating the Command Line Switches
16304 @section Generating the Command Line Switches
16307 Once you have created the list of directories as explained in the
16308 previous section (@pxref{Automatically Creating a List of Directories}),
16309 you can easily generate the command line arguments to pass to gnatmake.
16311 For the sake of completeness, this example assumes that the source path
16312 is not the same as the object path, and that you have two separate lists
16316 # see "Automatically creating a list of directories" to create
16321 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16322 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16325 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16328 @node Overcoming Command Line Length Limits
16329 @section Overcoming Command Line Length Limits
16332 One problem that might be encountered on big projects is that many
16333 operating systems limit the length of the command line. It is thus hard to give
16334 gnatmake the list of source and object directories.
16336 This example shows how you can set up environment variables, which will
16337 make @command{gnatmake} behave exactly as if the directories had been
16338 specified on the command line, but have a much higher length limit (or
16339 even none on most systems).
16341 It assumes that you have created a list of directories in your Makefile,
16342 using one of the methods presented in
16343 @ref{Automatically Creating a List of Directories}.
16344 For the sake of completeness, we assume that the object
16345 path (where the ALI files are found) is different from the sources patch.
16347 Note a small trick in the Makefile below: for efficiency reasons, we
16348 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16349 expanded immediately by @code{make}. This way we overcome the standard
16350 make behavior which is to expand the variables only when they are
16353 On Windows, if you are using the standard Windows command shell, you must
16354 replace colons with semicolons in the assignments to these variables.
16359 @font@heightrm=cmr8
16362 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
16363 # This is the same thing as putting the -I arguments on the command line.
16364 # (the equivalent of using -aI on the command line would be to define
16365 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
16366 # You can of course have different values for these variables.
16368 # Note also that we need to keep the previous values of these variables, since
16369 # they might have been set before running 'make' to specify where the GNAT
16370 # library is installed.
16372 # see "Automatically creating a list of directories" to create these
16378 space:=$@{empty@} $@{empty@}
16379 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16380 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16381 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16382 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
16383 export ADA_INCLUDE_PATH
16384 export ADA_OBJECT_PATH
16391 @node Memory Management Issues
16392 @chapter Memory Management Issues
16395 This chapter describes some useful memory pools provided in the GNAT library
16396 and in particular the GNAT Debug Pool facility, which can be used to detect
16397 incorrect uses of access values (including ``dangling references'').
16399 It also describes the @command{gnatmem} tool, which can be used to track down
16404 * Some Useful Memory Pools::
16405 * The GNAT Debug Pool Facility::
16407 * The gnatmem Tool::
16411 @node Some Useful Memory Pools
16412 @section Some Useful Memory Pools
16413 @findex Memory Pool
16414 @cindex storage, pool
16417 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
16418 storage pool. Allocations use the standard system call @code{malloc} while
16419 deallocations use the standard system call @code{free}. No reclamation is
16420 performed when the pool goes out of scope. For performance reasons, the
16421 standard default Ada allocators/deallocators do not use any explicit storage
16422 pools but if they did, they could use this storage pool without any change in
16423 behavior. That is why this storage pool is used when the user
16424 manages to make the default implicit allocator explicit as in this example:
16425 @smallexample @c ada
16426 type T1 is access Something;
16427 -- no Storage pool is defined for T2
16428 type T2 is access Something_Else;
16429 for T2'Storage_Pool use T1'Storage_Pool;
16430 -- the above is equivalent to
16431 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
16435 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
16436 pool. The allocation strategy is similar to @code{Pool_Local}'s
16437 except that the all
16438 storage allocated with this pool is reclaimed when the pool object goes out of
16439 scope. This pool provides a explicit mechanism similar to the implicit one
16440 provided by several Ada 83 compilers for allocations performed through a local
16441 access type and whose purpose was to reclaim memory when exiting the
16442 scope of a given local access. As an example, the following program does not
16443 leak memory even though it does not perform explicit deallocation:
16445 @smallexample @c ada
16446 with System.Pool_Local;
16447 procedure Pooloc1 is
16448 procedure Internal is
16449 type A is access Integer;
16450 X : System.Pool_Local.Unbounded_Reclaim_Pool;
16451 for A'Storage_Pool use X;
16454 for I in 1 .. 50 loop
16459 for I in 1 .. 100 loop
16466 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
16467 @code{Storage_Size} is specified for an access type.
16468 The whole storage for the pool is
16469 allocated at once, usually on the stack at the point where the access type is
16470 elaborated. It is automatically reclaimed when exiting the scope where the
16471 access type is defined. This package is not intended to be used directly by the
16472 user and it is implicitly used for each such declaration:
16474 @smallexample @c ada
16475 type T1 is access Something;
16476 for T1'Storage_Size use 10_000;
16479 @node The GNAT Debug Pool Facility
16480 @section The GNAT Debug Pool Facility
16482 @cindex storage, pool, memory corruption
16485 The use of unchecked deallocation and unchecked conversion can easily
16486 lead to incorrect memory references. The problems generated by such
16487 references are usually difficult to tackle because the symptoms can be
16488 very remote from the origin of the problem. In such cases, it is
16489 very helpful to detect the problem as early as possible. This is the
16490 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
16492 In order to use the GNAT specific debugging pool, the user must
16493 associate a debug pool object with each of the access types that may be
16494 related to suspected memory problems. See Ada Reference Manual 13.11.
16495 @smallexample @c ada
16496 type Ptr is access Some_Type;
16497 Pool : GNAT.Debug_Pools.Debug_Pool;
16498 for Ptr'Storage_Pool use Pool;
16502 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
16503 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
16504 allow the user to redefine allocation and deallocation strategies. They
16505 also provide a checkpoint for each dereference, through the use of
16506 the primitive operation @code{Dereference} which is implicitly called at
16507 each dereference of an access value.
16509 Once an access type has been associated with a debug pool, operations on
16510 values of the type may raise four distinct exceptions,
16511 which correspond to four potential kinds of memory corruption:
16514 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
16516 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
16518 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
16520 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
16524 For types associated with a Debug_Pool, dynamic allocation is performed using
16525 the standard GNAT allocation routine. References to all allocated chunks of
16526 memory are kept in an internal dictionary. Several deallocation strategies are
16527 provided, whereupon the user can choose to release the memory to the system,
16528 keep it allocated for further invalid access checks, or fill it with an easily
16529 recognizable pattern for debug sessions. The memory pattern is the old IBM
16530 hexadecimal convention: @code{16#DEADBEEF#}.
16532 See the documentation in the file g-debpoo.ads for more information on the
16533 various strategies.
16535 Upon each dereference, a check is made that the access value denotes a
16536 properly allocated memory location. Here is a complete example of use of
16537 @code{Debug_Pools}, that includes typical instances of memory corruption:
16538 @smallexample @c ada
16542 with Gnat.Io; use Gnat.Io;
16543 with Unchecked_Deallocation;
16544 with Unchecked_Conversion;
16545 with GNAT.Debug_Pools;
16546 with System.Storage_Elements;
16547 with Ada.Exceptions; use Ada.Exceptions;
16548 procedure Debug_Pool_Test is
16550 type T is access Integer;
16551 type U is access all T;
16553 P : GNAT.Debug_Pools.Debug_Pool;
16554 for T'Storage_Pool use P;
16556 procedure Free is new Unchecked_Deallocation (Integer, T);
16557 function UC is new Unchecked_Conversion (U, T);
16560 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
16570 Put_Line (Integer'Image(B.all));
16572 when E : others => Put_Line ("raised: " & Exception_Name (E));
16577 when E : others => Put_Line ("raised: " & Exception_Name (E));
16581 Put_Line (Integer'Image(B.all));
16583 when E : others => Put_Line ("raised: " & Exception_Name (E));
16588 when E : others => Put_Line ("raised: " & Exception_Name (E));
16591 end Debug_Pool_Test;
16595 The debug pool mechanism provides the following precise diagnostics on the
16596 execution of this erroneous program:
16599 Total allocated bytes : 0
16600 Total deallocated bytes : 0
16601 Current Water Mark: 0
16605 Total allocated bytes : 8
16606 Total deallocated bytes : 0
16607 Current Water Mark: 8
16610 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
16611 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
16612 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
16613 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
16615 Total allocated bytes : 8
16616 Total deallocated bytes : 4
16617 Current Water Mark: 4
16622 @node The gnatmem Tool
16623 @section The @command{gnatmem} Tool
16627 The @code{gnatmem} utility monitors dynamic allocation and
16628 deallocation activity in a program, and displays information about
16629 incorrect deallocations and possible sources of memory leaks.
16630 It is designed to work in association with a static runtime library
16631 only and in this context provides three types of information:
16634 General information concerning memory management, such as the total
16635 number of allocations and deallocations, the amount of allocated
16636 memory and the high water mark, i.e.@: the largest amount of allocated
16637 memory in the course of program execution.
16640 Backtraces for all incorrect deallocations, that is to say deallocations
16641 which do not correspond to a valid allocation.
16644 Information on each allocation that is potentially the origin of a memory
16649 * Running gnatmem::
16650 * Switches for gnatmem::
16651 * Example of gnatmem Usage::
16654 @node Running gnatmem
16655 @subsection Running @code{gnatmem}
16658 @code{gnatmem} makes use of the output created by the special version of
16659 allocation and deallocation routines that record call information. This
16660 allows to obtain accurate dynamic memory usage history at a minimal cost to
16661 the execution speed. Note however, that @code{gnatmem} is not supported on
16662 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
16663 Solaris and Windows NT/2000/XP (x86).
16666 The @code{gnatmem} command has the form
16669 @c $ gnatmem @ovar{switches} user_program
16670 @c Expanding @ovar macro inline (explanation in macro def comments)
16671 $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
16675 The program must have been linked with the instrumented version of the
16676 allocation and deallocation routines. This is done by linking with the
16677 @file{libgmem.a} library. For correct symbolic backtrace information,
16678 the user program should be compiled with debugging options
16679 (see @ref{Switches for gcc}). For example to build @file{my_program}:
16682 $ gnatmake -g my_program -largs -lgmem
16686 As library @file{libgmem.a} contains an alternate body for package
16687 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
16688 when an executable is linked with library @file{libgmem.a}. It is then not
16689 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
16692 When @file{my_program} is executed, the file @file{gmem.out} is produced.
16693 This file contains information about all allocations and deallocations
16694 performed by the program. It is produced by the instrumented allocations and
16695 deallocations routines and will be used by @code{gnatmem}.
16697 In order to produce symbolic backtrace information for allocations and
16698 deallocations performed by the GNAT run-time library, you need to use a
16699 version of that library that has been compiled with the @option{-g} switch
16700 (see @ref{Rebuilding the GNAT Run-Time Library}).
16702 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
16703 examine. If the location of @file{gmem.out} file was not explicitly supplied by
16704 @option{-i} switch, gnatmem will assume that this file can be found in the
16705 current directory. For example, after you have executed @file{my_program},
16706 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
16709 $ gnatmem my_program
16713 This will produce the output with the following format:
16715 *************** debut cc
16717 $ gnatmem my_program
16721 Total number of allocations : 45
16722 Total number of deallocations : 6
16723 Final Water Mark (non freed mem) : 11.29 Kilobytes
16724 High Water Mark : 11.40 Kilobytes
16729 Allocation Root # 2
16730 -------------------
16731 Number of non freed allocations : 11
16732 Final Water Mark (non freed mem) : 1.16 Kilobytes
16733 High Water Mark : 1.27 Kilobytes
16735 my_program.adb:23 my_program.alloc
16741 The first block of output gives general information. In this case, the
16742 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
16743 Unchecked_Deallocation routine occurred.
16746 Subsequent paragraphs display information on all allocation roots.
16747 An allocation root is a specific point in the execution of the program
16748 that generates some dynamic allocation, such as a ``@code{@b{new}}''
16749 construct. This root is represented by an execution backtrace (or subprogram
16750 call stack). By default the backtrace depth for allocations roots is 1, so
16751 that a root corresponds exactly to a source location. The backtrace can
16752 be made deeper, to make the root more specific.
16754 @node Switches for gnatmem
16755 @subsection Switches for @code{gnatmem}
16758 @code{gnatmem} recognizes the following switches:
16763 @cindex @option{-q} (@code{gnatmem})
16764 Quiet. Gives the minimum output needed to identify the origin of the
16765 memory leaks. Omits statistical information.
16768 @cindex @var{N} (@code{gnatmem})
16769 N is an integer literal (usually between 1 and 10) which controls the
16770 depth of the backtraces defining allocation root. The default value for
16771 N is 1. The deeper the backtrace, the more precise the localization of
16772 the root. Note that the total number of roots can depend on this
16773 parameter. This parameter must be specified @emph{before} the name of the
16774 executable to be analyzed, to avoid ambiguity.
16777 @cindex @option{-b} (@code{gnatmem})
16778 This switch has the same effect as just depth parameter.
16780 @item -i @var{file}
16781 @cindex @option{-i} (@code{gnatmem})
16782 Do the @code{gnatmem} processing starting from @file{file}, rather than
16783 @file{gmem.out} in the current directory.
16786 @cindex @option{-m} (@code{gnatmem})
16787 This switch causes @code{gnatmem} to mask the allocation roots that have less
16788 than n leaks. The default value is 1. Specifying the value of 0 will allow to
16789 examine even the roots that didn't result in leaks.
16792 @cindex @option{-s} (@code{gnatmem})
16793 This switch causes @code{gnatmem} to sort the allocation roots according to the
16794 specified order of sort criteria, each identified by a single letter. The
16795 currently supported criteria are @code{n, h, w} standing respectively for
16796 number of unfreed allocations, high watermark, and final watermark
16797 corresponding to a specific root. The default order is @code{nwh}.
16801 @node Example of gnatmem Usage
16802 @subsection Example of @code{gnatmem} Usage
16805 The following example shows the use of @code{gnatmem}
16806 on a simple memory-leaking program.
16807 Suppose that we have the following Ada program:
16809 @smallexample @c ada
16812 with Unchecked_Deallocation;
16813 procedure Test_Gm is
16815 type T is array (1..1000) of Integer;
16816 type Ptr is access T;
16817 procedure Free is new Unchecked_Deallocation (T, Ptr);
16820 procedure My_Alloc is
16825 procedure My_DeAlloc is
16833 for I in 1 .. 5 loop
16834 for J in I .. 5 loop
16845 The program needs to be compiled with debugging option and linked with
16846 @code{gmem} library:
16849 $ gnatmake -g test_gm -largs -lgmem
16853 Then we execute the program as usual:
16860 Then @code{gnatmem} is invoked simply with
16866 which produces the following output (result may vary on different platforms):
16871 Total number of allocations : 18
16872 Total number of deallocations : 5
16873 Final Water Mark (non freed mem) : 53.00 Kilobytes
16874 High Water Mark : 56.90 Kilobytes
16876 Allocation Root # 1
16877 -------------------
16878 Number of non freed allocations : 11
16879 Final Water Mark (non freed mem) : 42.97 Kilobytes
16880 High Water Mark : 46.88 Kilobytes
16882 test_gm.adb:11 test_gm.my_alloc
16884 Allocation Root # 2
16885 -------------------
16886 Number of non freed allocations : 1
16887 Final Water Mark (non freed mem) : 10.02 Kilobytes
16888 High Water Mark : 10.02 Kilobytes
16890 s-secsta.adb:81 system.secondary_stack.ss_init
16892 Allocation Root # 3
16893 -------------------
16894 Number of non freed allocations : 1
16895 Final Water Mark (non freed mem) : 12 Bytes
16896 High Water Mark : 12 Bytes
16898 s-secsta.adb:181 system.secondary_stack.ss_init
16902 Note that the GNAT run time contains itself a certain number of
16903 allocations that have no corresponding deallocation,
16904 as shown here for root #2 and root
16905 #3. This is a normal behavior when the number of non-freed allocations
16906 is one, it allocates dynamic data structures that the run time needs for
16907 the complete lifetime of the program. Note also that there is only one
16908 allocation root in the user program with a single line back trace:
16909 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
16910 program shows that 'My_Alloc' is called at 2 different points in the
16911 source (line 21 and line 24). If those two allocation roots need to be
16912 distinguished, the backtrace depth parameter can be used:
16915 $ gnatmem 3 test_gm
16919 which will give the following output:
16924 Total number of allocations : 18
16925 Total number of deallocations : 5
16926 Final Water Mark (non freed mem) : 53.00 Kilobytes
16927 High Water Mark : 56.90 Kilobytes
16929 Allocation Root # 1
16930 -------------------
16931 Number of non freed allocations : 10
16932 Final Water Mark (non freed mem) : 39.06 Kilobytes
16933 High Water Mark : 42.97 Kilobytes
16935 test_gm.adb:11 test_gm.my_alloc
16936 test_gm.adb:24 test_gm
16937 b_test_gm.c:52 main
16939 Allocation Root # 2
16940 -------------------
16941 Number of non freed allocations : 1
16942 Final Water Mark (non freed mem) : 10.02 Kilobytes
16943 High Water Mark : 10.02 Kilobytes
16945 s-secsta.adb:81 system.secondary_stack.ss_init
16946 s-secsta.adb:283 <system__secondary_stack___elabb>
16947 b_test_gm.c:33 adainit
16949 Allocation Root # 3
16950 -------------------
16951 Number of non freed allocations : 1
16952 Final Water Mark (non freed mem) : 3.91 Kilobytes
16953 High Water Mark : 3.91 Kilobytes
16955 test_gm.adb:11 test_gm.my_alloc
16956 test_gm.adb:21 test_gm
16957 b_test_gm.c:52 main
16959 Allocation Root # 4
16960 -------------------
16961 Number of non freed allocations : 1
16962 Final Water Mark (non freed mem) : 12 Bytes
16963 High Water Mark : 12 Bytes
16965 s-secsta.adb:181 system.secondary_stack.ss_init
16966 s-secsta.adb:283 <system__secondary_stack___elabb>
16967 b_test_gm.c:33 adainit
16971 The allocation root #1 of the first example has been split in 2 roots #1
16972 and #3 thanks to the more precise associated backtrace.
16976 @node Stack Related Facilities
16977 @chapter Stack Related Facilities
16980 This chapter describes some useful tools associated with stack
16981 checking and analysis. In
16982 particular, it deals with dynamic and static stack usage measurements.
16985 * Stack Overflow Checking::
16986 * Static Stack Usage Analysis::
16987 * Dynamic Stack Usage Analysis::
16990 @node Stack Overflow Checking
16991 @section Stack Overflow Checking
16992 @cindex Stack Overflow Checking
16993 @cindex -fstack-check
16996 For most operating systems, @command{gcc} does not perform stack overflow
16997 checking by default. This means that if the main environment task or
16998 some other task exceeds the available stack space, then unpredictable
16999 behavior will occur. Most native systems offer some level of protection by
17000 adding a guard page at the end of each task stack. This mechanism is usually
17001 not enough for dealing properly with stack overflow situations because
17002 a large local variable could ``jump'' above the guard page.
17003 Furthermore, when the
17004 guard page is hit, there may not be any space left on the stack for executing
17005 the exception propagation code. Enabling stack checking avoids
17008 To activate stack checking, compile all units with the gcc option
17009 @option{-fstack-check}. For example:
17012 gcc -c -fstack-check package1.adb
17016 Units compiled with this option will generate extra instructions to check
17017 that any use of the stack (for procedure calls or for declaring local
17018 variables in declare blocks) does not exceed the available stack space.
17019 If the space is exceeded, then a @code{Storage_Error} exception is raised.
17021 For declared tasks, the stack size is controlled by the size
17022 given in an applicable @code{Storage_Size} pragma or by the value specified
17023 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
17024 the default size as defined in the GNAT runtime otherwise.
17026 For the environment task, the stack size depends on
17027 system defaults and is unknown to the compiler. Stack checking
17028 may still work correctly if a fixed
17029 size stack is allocated, but this cannot be guaranteed.
17031 To ensure that a clean exception is signalled for stack
17032 overflow, set the environment variable
17033 @env{GNAT_STACK_LIMIT} to indicate the maximum
17034 stack area that can be used, as in:
17035 @cindex GNAT_STACK_LIMIT
17038 SET GNAT_STACK_LIMIT 1600
17042 The limit is given in kilobytes, so the above declaration would
17043 set the stack limit of the environment task to 1.6 megabytes.
17044 Note that the only purpose of this usage is to limit the amount
17045 of stack used by the environment task. If it is necessary to
17046 increase the amount of stack for the environment task, then this
17047 is an operating systems issue, and must be addressed with the
17048 appropriate operating systems commands.
17051 To have a fixed size stack in the environment task, the stack must be put
17052 in the P0 address space and its size specified. Use these switches to
17056 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
17060 The quotes are required to keep case. The number after @samp{STACK=} is the
17061 size of the environmental task stack in pagelets (512 bytes). In this example
17062 the stack size is about 2 megabytes.
17065 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
17066 be placed in P0 space. Refer to @cite{HP OpenVMS Linker Utility Manual} for
17067 more details about the @option{/p0image} qualifier and the @option{stack}
17071 @node Static Stack Usage Analysis
17072 @section Static Stack Usage Analysis
17073 @cindex Static Stack Usage Analysis
17074 @cindex -fstack-usage
17077 A unit compiled with @option{-fstack-usage} will generate an extra file
17079 the maximum amount of stack used, on a per-function basis.
17080 The file has the same
17081 basename as the target object file with a @file{.su} extension.
17082 Each line of this file is made up of three fields:
17086 The name of the function.
17090 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
17093 The second field corresponds to the size of the known part of the function
17096 The qualifier @code{static} means that the function frame size
17098 It usually means that all local variables have a static size.
17099 In this case, the second field is a reliable measure of the function stack
17102 The qualifier @code{dynamic} means that the function frame size is not static.
17103 It happens mainly when some local variables have a dynamic size. When this
17104 qualifier appears alone, the second field is not a reliable measure
17105 of the function stack analysis. When it is qualified with @code{bounded}, it
17106 means that the second field is a reliable maximum of the function stack
17109 @node Dynamic Stack Usage Analysis
17110 @section Dynamic Stack Usage Analysis
17113 It is possible to measure the maximum amount of stack used by a task, by
17114 adding a switch to @command{gnatbind}, as:
17117 $ gnatbind -u0 file
17121 With this option, at each task termination, its stack usage is output on
17123 It is not always convenient to output the stack usage when the program
17124 is still running. Hence, it is possible to delay this output until program
17125 termination. for a given number of tasks specified as the argument of the
17126 @option{-u} option. For instance:
17129 $ gnatbind -u100 file
17133 will buffer the stack usage information of the first 100 tasks to terminate and
17134 output this info at program termination. Results are displayed in four
17138 Index | Task Name | Stack Size | Stack Usage [Value +/- Variation]
17145 is a number associated with each task.
17148 is the name of the task analyzed.
17151 is the maximum size for the stack.
17154 is the measure done by the stack analyzer. In order to prevent overflow, the stack
17155 is not entirely analyzed, and it's not possible to know exactly how
17156 much has actually been used. The report thus contains the theoretical stack usage
17157 (Value) and the possible variation (Variation) around this value.
17162 The environment task stack, e.g., the stack that contains the main unit, is
17163 only processed when the environment variable GNAT_STACK_LIMIT is set.
17166 @c *********************************
17168 @c *********************************
17169 @node Verifying Properties Using gnatcheck
17170 @chapter Verifying Properties Using @command{gnatcheck}
17172 @cindex @command{gnatcheck}
17175 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
17176 of Ada source files according to a given set of semantic rules.
17179 In order to check compliance with a given rule, @command{gnatcheck} has to
17180 semantically analyze the Ada sources.
17181 Therefore, checks can only be performed on
17182 legal Ada units. Moreover, when a unit depends semantically upon units located
17183 outside the current directory, the source search path has to be provided when
17184 calling @command{gnatcheck}, either through a specified project file or
17185 through @command{gnatcheck} switches as described below.
17187 A number of rules are predefined in @command{gnatcheck} and are described
17188 later in this chapter.
17189 You can also add new rules, by modifying the @command{gnatcheck} code and
17190 rebuilding the tool. In order to add a simple rule making some local checks,
17191 a small amount of straightforward ASIS-based programming is usually needed.
17193 Project support for @command{gnatcheck} is provided by the GNAT
17194 driver (see @ref{The GNAT Driver and Project Files}).
17196 Invoking @command{gnatcheck} on the command line has the form:
17199 @c $ gnatcheck @ovar{switches} @{@var{filename}@}
17200 @c @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
17201 @c @r{[}-cargs @var{gcc_switches}@r{]} -rules @var{rule_options}
17202 @c Expanding @ovar macro inline (explanation in macro def comments)
17203 $ gnatcheck @r{[}@var{switches}@r{]} @{@var{filename}@}
17204 @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
17205 @r{[}-cargs @var{gcc_switches}@r{]} -rules @var{rule_options}
17212 @var{switches} specify the general tool options
17215 Each @var{filename} is the name (including the extension) of a source
17216 file to process. ``Wildcards'' are allowed, and
17217 the file name may contain path information.
17220 Each @var{arg_list_filename} is the name (including the extension) of a text
17221 file containing the names of the source files to process, separated by spaces
17225 @var{gcc_switches} is a list of switches for
17226 @command{gcc}. They will be passed on to all compiler invocations made by
17227 @command{gnatcheck} to generate the ASIS trees. Here you can provide
17228 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17229 and use the @option{-gnatec} switch to set the configuration file,
17230 use the @option{-gnat05} switch if sources should be compiled in
17234 @var{rule_options} is a list of options for controlling a set of
17235 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
17239 Either a @file{@var{filename}} or an @file{@var{arg_list_filename}} must be
17243 * Format of the Report File::
17244 * General gnatcheck Switches::
17245 * gnatcheck Rule Options::
17246 * Adding the Results of Compiler Checks to gnatcheck Output::
17247 * Project-Wide Checks::
17249 * Predefined Rules::
17250 * Example of gnatcheck Usage::
17253 @node Format of the Report File
17254 @section Format of the Report File
17255 @cindex Report file (for @code{gnatcheck})
17258 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
17260 It also creates a text file that
17261 contains the complete report of the last gnatcheck run. By default this file
17262 is named named @file{^gnatcheck.out^GNATCHECK.OUT^} and it is located in the
17263 current directory; the @option{^-o^/OUTPUT^} option can be used to change the
17264 name and/or location of the report file. This report contains:
17266 @item date and time of @command{gnatcheck} run, the version of
17267 the tool that has generated this report and the full parameters
17268 of the @command{gnatcheck} invocation;
17269 @item list of enabled rules;
17270 @item total number of detected violations;
17271 @item list of source files where rule violations have been detected;
17272 @item list of source files where no violations have been detected.
17275 @node General gnatcheck Switches
17276 @section General @command{gnatcheck} Switches
17279 The following switches control the general @command{gnatcheck} behavior
17283 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
17285 Process all units including those with read-only ALI files such as
17286 those from the GNAT Run-Time library.
17290 @cindex @option{-d} (@command{gnatcheck})
17295 @cindex @option{-dd} (@command{gnatcheck})
17297 Progress indicator mode (for use in GPS).
17300 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
17302 List the predefined and user-defined rules. For more details see
17303 @ref{Predefined Rules}.
17305 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
17307 Use full source locations references in the report file. For a construct from
17308 a generic instantiation a full source location is a chain from the location
17309 of this construct in the generic unit to the place where this unit is
17312 @cindex @option{^-log^/LOG^} (@command{gnatcheck})
17314 Duplicate all the output sent to @file{stderr} into a log file. The log file
17315 is named @file{gnatcheck.log} and is located in the current directory.
17317 @cindex @option{^-m^/DIAGNOSTIC_LIMIT^} (@command{gnatcheck})
17318 @item ^-m@i{nnnn}^/DIAGNOSTIC_LIMIT=@i{nnnn}^
17319 Maximum number of diagnostics to be sent to @file{stdout}, where @i{nnnn} is in
17320 the range 0@dots{}1000;
17321 the default value is 500. Zero means that there is no limitation on
17322 the number of diagnostic messages to be output.
17324 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
17326 Quiet mode. All the diagnostics about rule violations are placed in the
17327 @command{gnatcheck} report file only, without duplication on @file{stdout}.
17329 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
17331 Short format of the report file (no version information, no list of applied
17332 rules, no list of checked sources is included)
17334 @cindex @option{^--include-file=@var{file}^/INCLUDE_FILE=@var{file}^} (@command{gnatcheck})
17335 @item ^--include-file^/INCLUDE_FILE^
17336 Append the content of the specified text file to the report file
17338 @cindex @option{^-t^/TIME^} (@command{gnatcheck})
17340 Print out execution time.
17342 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
17343 @item ^-v^/VERBOSE^
17344 Verbose mode; @command{gnatcheck} generates version information and then
17345 a trace of sources being processed.
17347 @cindex @option{^-o ^/OUTPUT^} (@command{gnatcheck})
17348 @item ^-o ^/OUTPUT=^@var{report_file}
17349 Set name of report file file to @var{report_file} .
17353 @node gnatcheck Rule Options
17354 @section @command{gnatcheck} Rule Options
17357 The following options control the processing performed by
17358 @command{gnatcheck}.
17361 @cindex @option{+ALL} (@command{gnatcheck})
17363 Turn all the rule checks ON.
17365 @cindex @option{-ALL} (@command{gnatcheck})
17367 Turn all the rule checks OFF.
17369 @cindex @option{+R} (@command{gnatcheck})
17370 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
17371 Turn on the check for a specified rule with the specified parameter, if any.
17372 @var{rule_id} must be the identifier of one of the currently implemented rules
17373 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
17374 are not case-sensitive. The @var{param} item must
17375 be a string representing a valid parameter(s) for the specified rule.
17376 If it contains any space characters then this string must be enclosed in
17379 @cindex @option{-R} (@command{gnatcheck})
17380 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
17381 Turn off the check for a specified rule with the specified parameter, if any.
17383 @cindex @option{-from} (@command{gnatcheck})
17384 @item -from=@var{rule_option_filename}
17385 Read the rule options from the text file @var{rule_option_filename}, referred
17386 to as a ``coding standard file'' below.
17391 The default behavior is that all the rule checks are disabled.
17393 A coding standard file is a text file that contains a set of rule options
17395 @cindex Coding standard file (for @code{gnatcheck})
17396 The file may contain empty lines and Ada-style comments (comment
17397 lines and end-of-line comments). There can be several rule options on a
17398 single line (separated by a space).
17400 A coding standard file may reference other coding standard files by including
17401 more @option{-from=@var{rule_option_filename}}
17402 options, each such option being replaced with the content of the
17403 corresponding coding standard file during processing. In case a
17404 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
17405 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
17406 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
17407 processing fails with an error message.
17410 @node Adding the Results of Compiler Checks to gnatcheck Output
17411 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
17414 The @command{gnatcheck} tool can include in the generated diagnostic messages
17416 the report file the results of the checks performed by the compiler. Though
17417 disabled by default, this effect may be obtained by using @option{+R} with
17418 the following rule identifiers and parameters:
17422 To record restrictions violations (which are performed by the compiler if the
17423 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
17424 use the @code{Restrictions} rule
17425 with the same parameters as pragma
17426 @code{Restrictions} or @code{Restriction_Warnings}.
17429 To record compiler style checks (@pxref{Style Checking}), use the
17430 @code{Style_Checks} rule.
17431 This rule takes a parameter in one of the following forms:
17435 which enables the standard style checks corresponding to the @option{-gnatyy}
17436 GNAT style check option, or
17439 a string with the same
17440 structure and semantics as the @code{string_LITERAL} parameter of the
17441 GNAT pragma @code{Style_Checks}
17442 (for further information about this pragma,
17443 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}).
17448 @code{+RStyle_Checks:O} rule option activates
17449 the compiler style check that corresponds to
17450 @code{-gnatyO} style check option.
17453 To record compiler warnings (@pxref{Warning Message Control}), use the
17454 @code{Warnings} rule with a parameter that is a valid
17455 @i{static_string_expression} argument of the GNAT pragma @code{Warnings}
17456 (for further information about this pragma,
17457 @pxref{Pragma Warnings,,,gnat_rm, GNAT Reference Manual}).
17458 Note that in case of gnatcheck
17459 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
17460 all the specific warnings, but not suppresses the warning mode,
17461 and 'e' parameter, corresponding to @option{-gnatwe} that means
17462 "treat warnings as errors", does not have any effect.
17466 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
17467 option with the corresponding restriction name as a parameter. @code{-R} is
17468 not available for @code{Style_Checks} and @code{Warnings} options, to disable
17469 warnings and style checks, use the corresponding warning and style options.
17471 @node Project-Wide Checks
17472 @section Project-Wide Checks
17473 @cindex Project-wide checks (for @command{gnatcheck})
17476 In order to perform checks on all units of a given project, you can use
17477 the GNAT driver along with the @option{-P} option:
17479 gnat check -Pproj -rules -from=my_rules
17483 If the project @code{proj} depends upon other projects, you can perform
17484 checks on the project closure using the @option{-U} option:
17486 gnat check -Pproj -U -rules -from=my_rules
17490 Finally, if not all the units are relevant to a particular main
17491 program in the project closure, you can perform checks for the set
17492 of units needed to create a given main program (unit closure) using
17493 the @option{-U} option followed by the name of the main unit:
17495 gnat check -Pproj -U main -rules -from=my_rules
17499 @node Rule exemption
17500 @section Rule exemption
17501 @cindex Rule exemption (for @command{gnatcheck})
17504 One of the most useful applications of @command{gnatcheck} is to
17505 automate the enforcement of project-specific coding standards,
17506 for example in safety-critical systems where particular features
17507 must be restricted in order to simplify the certification effort.
17508 However, it may sometimes be appropriate to violate a coding standard rule,
17509 and in such cases the rationale for the violation should be provided
17510 in the source program itself so that the individuals
17511 reviewing or maintaining the program can immediately understand the intent.
17513 The @command{gnatcheck} tool supports this practice with the notion of
17514 a ``rule exemption'' covering a specific source code section. Normally
17515 rule violation messages are issued both on @file{stderr}
17516 and in a report file. In contrast, exempted violations are not listed on
17517 @file{stderr}; thus users invoking @command{gnatcheck} interactively
17518 (e.g. in its GPS interface) do not need to pay attention to known and
17519 justified violations. However, exempted violations along with their
17520 justification are documented in a special section of the report file that
17521 @command{gnatcheck} generates.
17524 * Using pragma Annotate to Control Rule Exemption::
17525 * gnatcheck Annotations Rules::
17528 @node Using pragma Annotate to Control Rule Exemption
17529 @subsection Using pragma @code{Annotate} to Control Rule Exemption
17530 @cindex Using pragma Annotate to control rule exemption
17533 Rule exemption is controlled by pragma @code{Annotate} when its first
17534 argument is ``gnatcheck''. The syntax of @command{gnatcheck}'s
17535 exemption control annotations is as follows:
17537 @smallexample @c ada
17539 pragma Annotate (gnatcheck, @i{exemption_control}, @i{Rule_Name}, [@i{justification}]);
17541 @i{exemption_control} ::= Exempt_On | Exempt_Off
17543 @i{Rule_Name} ::= string_literal
17545 @i{justification} ::= string_literal
17550 When a @command{gnatcheck} annotation has more then four arguments,
17551 @command{gnatcheck} issues a warning and ignores the additional arguments.
17552 If the additional arguments do not follow the syntax above,
17553 @command{gnatcheck} emits a warning and ignores the annotation.
17555 The @i{@code{Rule_Name}} argument should be the name of some existing
17556 @command{gnatcheck} rule.
17557 Otherwise a warning message is generated and the pragma is
17558 ignored. If @code{Rule_Name} denotes a rule that is not activated by the given
17559 @command{gnatcheck} call, the pragma is ignored and no warning is issued.
17561 A source code section where an exemption is active for a given rule is
17562 delimited by an @code{exempt_on} and @code{exempt_off} annotation pair:
17564 @smallexample @c ada
17565 pragma Annotate (gnatcheck, Exempt_On, Rule_Name, "justification");
17566 -- source code section
17567 pragma Annotate (gnatcheck, Exempt_Off, Rule_Name);
17571 @node gnatcheck Annotations Rules
17572 @subsection @command{gnatcheck} Annotations Rules
17573 @cindex @command{gnatcheck} annotations rules
17578 An ``Exempt_Off'' annotation can only appear after a corresponding
17579 ``Exempt_On'' annotation.
17582 Exempted source code sections are only based on the source location of the
17583 annotations. Any source construct between the two
17584 annotations is part of the exempted source code section.
17587 Exempted source code sections for different rules are independent. They can
17588 be nested or intersect with one another without limitation.
17589 Creating nested or intersecting source code sections for the same rule is
17593 Malformed exempted source code sections are reported by a warning, and
17594 the corresponding rule exemptions are ignored.
17597 When an exempted source code section does not contain at least one violation
17598 of the exempted rule, a warning is emitted on @file{stderr}.
17601 If an ``Exempt_On'' annotation pragma does not have a matching
17602 ``Exempt_Off'' annotation pragma in the same compilation unit, then the
17603 exemption for the given rule is ignored and a warning is issued.
17607 @node Predefined Rules
17608 @section Predefined Rules
17609 @cindex Predefined rules (for @command{gnatcheck})
17612 @c (Jan 2007) Since the global rules are still under development and are not
17613 @c documented, there is no point in explaining the difference between
17614 @c global and local rules
17616 A rule in @command{gnatcheck} is either local or global.
17617 A @emph{local rule} is a rule that applies to a well-defined section
17618 of a program and that can be checked by analyzing only this section.
17619 A @emph{global rule} requires analysis of some global properties of the
17620 whole program (mostly related to the program call graph).
17621 As of @value{NOW}, the implementation of global rules should be
17622 considered to be at a preliminary stage. You can use the
17623 @option{+GLOBAL} option to enable all the global rules, and the
17624 @option{-GLOBAL} rule option to disable all the global rules.
17626 All the global rules in the list below are
17627 so indicated by marking them ``GLOBAL''.
17628 This +GLOBAL and -GLOBAL options are not
17629 included in the list of gnatcheck options above, because at the moment they
17630 are considered as a temporary debug options.
17632 @command{gnatcheck} performs rule checks for generic
17633 instances only for global rules. This limitation may be relaxed in a later
17638 The predefined rules implemented in @command{gnatcheck}
17639 are described in a companion document,
17640 @cite{GNATcheck Reference Manual -- Predefined Rules}.
17641 The rule identifier is
17642 used as a parameter of @command{gnatcheck}'s @option{+R} or @option{-R}
17646 @node Example of gnatcheck Usage
17647 @section Example of @command{gnatcheck} Usage
17650 Here is a simple example. Suppose that in the current directory we have a
17651 project file named @file{gnatcheck_example.gpr} with the following content:
17653 @smallexample @c projectfile
17654 project Gnatcheck_Example is
17656 for Source_Dirs use ("src");
17657 for Object_Dir use "obj";
17658 for Main use ("main.adb");
17661 for Default_Switches ("ada") use ("-rules", "-from=coding_standard");
17664 end Gnatcheck_Example;
17668 And the file named @file{coding_standard} is also located in the current
17669 directory and has the following content:
17672 -----------------------------------------------------
17673 -- This is a sample gnatcheck coding standard file --
17674 -----------------------------------------------------
17676 -- First, turning on rules, that are directly implemented in gnatcheck
17677 +RAbstract_Type_Declarations
17680 +RFloat_Equality_Checks
17681 +REXIT_Statements_With_No_Loop_Name
17683 -- Then, activating compiler checks of interest:
17685 -- This style check checks if a unit name is present on END keyword that
17686 -- is the end of the unit declaration
17690 And the subdirectory @file{src} contains the following Ada sources:
17694 @smallexample @c ada
17696 type T is abstract tagged private;
17697 procedure P (X : T) is abstract;
17700 type My_Float is digits 8;
17701 function Is_Equal (L, R : My_Float) return Boolean;
17704 type T is abstract tagged null record;
17711 @smallexample @c ada
17712 package body Pack is
17713 package body Inner is
17714 function Is_Equal (L, R : My_Float) return Boolean is
17723 and @file{main.adb}
17725 @smallexample @c ada
17726 with Pack; use Pack;
17730 (gnatcheck, Exempt_On, "Anonymous_Arrays", "this one is fine");
17731 Float_Array : array (1 .. 10) of Inner.My_Float;
17732 pragma Annotate (gnatcheck, Exempt_Off, "Anonymous_Arrays");
17734 Another_Float_Array : array (1 .. 10) of Inner.My_Float;
17738 B : Boolean := False;
17741 for J in Float_Array'Range loop
17742 if Is_Equal (Float_Array (J), Another_Float_Array (J)) then
17751 And suppose we call @command{gnatcheck} from the current directory using
17752 the @command{gnat} driver:
17755 gnat check -Pgnatcheck_example.gpr
17759 As a result, @command{gnatcheck} is called to check all the files from the
17760 project @file{gnatcheck_example.gpr} using the coding standard defined by
17761 the file @file{coding_standard}. As the result, the @command{gnatcheck}
17762 report file named @file{gnatcheck.out} will be created in the current
17763 directory, and it will have the following content:
17766 RULE CHECKING REPORT
17770 Date and time of execution: 2009.10.28 14:17
17771 Tool version: GNATCHECK (built with ASIS 2.0.R for GNAT Pro 6.3.0w (20091016))
17774 gnatcheck -files=.../GNAT-TEMP-000004.TMP -cargs -gnatec=.../GNAT-TEMP-000003.TMP -rules -from=coding_standard
17776 Coding standard (applied rules):
17777 Abstract_Type_Declarations
17779 EXIT_Statements_With_No_Loop_Name
17780 Float_Equality_Checks
17783 Compiler style checks: -gnatye
17785 Number of coding standard violations: 6
17786 Number of exempted coding standard violations: 1
17788 2. DETECTED RULE VIOLATIONS
17790 2.1. NON-EXEMPTED VIOLATIONS
17792 Source files with non-exempted violations
17797 List of violations grouped by files, and ordered by increasing source location:
17799 pack.ads:2:4: declaration of abstract type
17800 pack.ads:5:4: declaration of local package
17801 pack.ads:10:30: declaration of abstract type
17802 pack.ads:11:1: (style) "end Pack" required
17803 pack.adb:5:19: use of equality operation for float values
17804 pack.adb:6:7: (style) "end Is_Equal" required
17805 main.adb:9:26: anonymous array type
17806 main.adb:19:10: exit statement with no loop name
17808 2.2. EXEMPTED VIOLATIONS
17810 Source files with exempted violations
17813 List of violations grouped by files, and ordered by increasing source location:
17815 main.adb:6:18: anonymous array type
17818 2.3. SOURCE FILES WITH NO VIOLATION
17820 No files without violations
17826 @c *********************************
17827 @node Creating Sample Bodies Using gnatstub
17828 @chapter Creating Sample Bodies Using @command{gnatstub}
17832 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
17833 for library unit declarations.
17835 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
17836 driver (see @ref{The GNAT Driver and Project Files}).
17838 To create a body stub, @command{gnatstub} has to compile the library
17839 unit declaration. Therefore, bodies can be created only for legal
17840 library units. Moreover, if a library unit depends semantically upon
17841 units located outside the current directory, you have to provide
17842 the source search path when calling @command{gnatstub}, see the description
17843 of @command{gnatstub} switches below.
17845 By default, all the program unit body stubs generated by @code{gnatstub}
17846 raise the predefined @code{Program_Error} exception, which will catch
17847 accidental calls of generated stubs. This behavior can be changed with
17848 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
17851 * Running gnatstub::
17852 * Switches for gnatstub::
17855 @node Running gnatstub
17856 @section Running @command{gnatstub}
17859 @command{gnatstub} has the command-line interface of the form
17862 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
17863 @c Expanding @ovar macro inline (explanation in macro def comments)
17864 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
17871 is the name of the source file that contains a library unit declaration
17872 for which a body must be created. The file name may contain the path
17874 The file name does not have to follow the GNAT file name conventions. If the
17876 does not follow GNAT file naming conventions, the name of the body file must
17878 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
17879 If the file name follows the GNAT file naming
17880 conventions and the name of the body file is not provided,
17883 of the body file from the argument file name by replacing the @file{.ads}
17885 with the @file{.adb} suffix.
17888 indicates the directory in which the body stub is to be placed (the default
17892 @item @samp{@var{gcc_switches}} is a list of switches for
17893 @command{gcc}. They will be passed on to all compiler invocations made by
17894 @command{gnatelim} to generate the ASIS trees. Here you can provide
17895 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17896 use the @option{-gnatec} switch to set the configuration file,
17897 use the @option{-gnat05} switch if sources should be compiled in
17901 is an optional sequence of switches as described in the next section
17904 @node Switches for gnatstub
17905 @section Switches for @command{gnatstub}
17911 @cindex @option{^-f^/FULL^} (@command{gnatstub})
17912 If the destination directory already contains a file with the name of the
17914 for the argument spec file, replace it with the generated body stub.
17916 @item ^-hs^/HEADER=SPEC^
17917 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
17918 Put the comment header (i.e., all the comments preceding the
17919 compilation unit) from the source of the library unit declaration
17920 into the body stub.
17922 @item ^-hg^/HEADER=GENERAL^
17923 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
17924 Put a sample comment header into the body stub.
17926 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
17927 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
17928 Use the content of the file as the comment header for a generated body stub.
17932 @cindex @option{-IDIR} (@command{gnatstub})
17934 @cindex @option{-I-} (@command{gnatstub})
17937 @item /NOCURRENT_DIRECTORY
17938 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
17940 ^These switches have ^This switch has^ the same meaning as in calls to
17942 ^They define ^It defines ^ the source search path in the call to
17943 @command{gcc} issued
17944 by @command{gnatstub} to compile an argument source file.
17946 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
17947 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
17948 This switch has the same meaning as in calls to @command{gcc}.
17949 It defines the additional configuration file to be passed to the call to
17950 @command{gcc} issued
17951 by @command{gnatstub} to compile an argument source file.
17953 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
17954 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
17955 (@var{n} is a non-negative integer). Set the maximum line length in the
17956 body stub to @var{n}; the default is 79. The maximum value that can be
17957 specified is 32767. Note that in the special case of configuration
17958 pragma files, the maximum is always 32767 regardless of whether or
17959 not this switch appears.
17961 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
17962 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
17963 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
17964 the generated body sample to @var{n}.
17965 The default indentation is 3.
17967 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
17968 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
17969 Order local bodies alphabetically. (By default local bodies are ordered
17970 in the same way as the corresponding local specs in the argument spec file.)
17972 @item ^-i^/INDENTATION=^@var{n}
17973 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
17974 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
17976 @item ^-k^/TREE_FILE=SAVE^
17977 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
17978 Do not remove the tree file (i.e., the snapshot of the compiler internal
17979 structures used by @command{gnatstub}) after creating the body stub.
17981 @item ^-l^/LINE_LENGTH=^@var{n}
17982 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
17983 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
17985 @item ^--no-exception^/NO_EXCEPTION^
17986 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
17987 Avoind raising PROGRAM_ERROR in the generated bodies of program unit stubs.
17988 This is not always possible for function stubs.
17990 @item ^--no-local-header^/NO_LOCAL_HEADER^
17991 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
17992 Do not place local comment header with unit name before body stub for a
17995 @item ^-o ^/BODY=^@var{body-name}
17996 @cindex @option{^-o^/BODY^} (@command{gnatstub})
17997 Body file name. This should be set if the argument file name does not
17999 the GNAT file naming
18000 conventions. If this switch is omitted the default name for the body will be
18002 from the argument file name according to the GNAT file naming conventions.
18005 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
18006 Quiet mode: do not generate a confirmation when a body is
18007 successfully created, and do not generate a message when a body is not
18011 @item ^-r^/TREE_FILE=REUSE^
18012 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
18013 Reuse the tree file (if it exists) instead of creating it. Instead of
18014 creating the tree file for the library unit declaration, @command{gnatstub}
18015 tries to find it in the current directory and use it for creating
18016 a body. If the tree file is not found, no body is created. This option
18017 also implies @option{^-k^/SAVE^}, whether or not
18018 the latter is set explicitly.
18020 @item ^-t^/TREE_FILE=OVERWRITE^
18021 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
18022 Overwrite the existing tree file. If the current directory already
18023 contains the file which, according to the GNAT file naming rules should
18024 be considered as a tree file for the argument source file,
18026 will refuse to create the tree file needed to create a sample body
18027 unless this option is set.
18029 @item ^-v^/VERBOSE^
18030 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
18031 Verbose mode: generate version information.
18035 @c *********************************
18036 @node Generating Ada Bindings for C and C++ headers
18037 @chapter Generating Ada Bindings for C and C++ headers
18041 GNAT now comes with a binding generator for C and C++ headers which is
18042 intended to do 95% of the tedious work of generating Ada specs from C
18043 or C++ header files.
18045 Note that this capability is not intended to generate 100% correct Ada specs,
18046 and will is some cases require manual adjustments, although it can often
18047 be used out of the box in practice.
18049 Some of the known limitations include:
18052 @item only very simple character constant macros are translated into Ada
18053 constants. Function macros (macros with arguments) are partially translated
18054 as comments, to be completed manually if needed.
18055 @item some extensions (e.g. vector types) are not supported
18056 @item pointers to pointers or complex structures are mapped to System.Address
18059 The code generated is using the Ada 2005 syntax, which makes it
18060 easier to interface with other languages than previous versions of Ada.
18063 * Running the binding generator::
18064 * Generating bindings for C++ headers::
18068 @node Running the binding generator
18069 @section Running the binding generator
18072 The binding generator is part of the @command{gcc} compiler and can be
18073 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
18074 spec files for the header files specified on the command line, and all
18075 header files needed by these files transitivitely. For example:
18078 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
18079 $ gcc -c -gnat05 *.ads
18082 will generate, under GNU/Linux, the following files: @file{time_h.ads},
18083 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
18084 correspond to the files @file{/usr/include/time.h},
18085 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
18086 mode these Ada specs.
18088 The @code{-C} switch tells @command{gcc} to extract comments from headers,
18089 and will attempt to generate corresponding Ada comments.
18091 If you want to generate a single Ada file and not the transitive closure, you
18092 can use instead the @option{-fdump-ada-spec-slim} switch.
18094 Note that we recommend when possible to use the @command{g++} driver to
18095 generate bindings, even for most C headers, since this will in general
18096 generate better Ada specs. For generating bindings for C++ headers, it is
18097 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
18098 is equivalent in this case. If @command{g++} cannot work on your C headers
18099 because of incompatibilities between C and C++, then you can fallback to
18100 @command{gcc} instead.
18102 For an example of better bindings generated from the C++ front-end,
18103 the name of the parameters (when available) are actually ignored by the C
18104 front-end. Consider the following C header:
18107 extern void foo (int variable);
18110 with the C front-end, @code{variable} is ignored, and the above is handled as:
18113 extern void foo (int);
18116 generating a generic:
18119 procedure foo (param1 : int);
18122 with the C++ front-end, the name is available, and we generate:
18125 procedure foo (variable : int);
18128 In some cases, the generated bindings will be more complete or more meaningful
18129 when defining some macros, which you can do via the @option{-D} switch. This
18130 is for example the case with @file{Xlib.h} under GNU/Linux:
18133 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
18136 The above will generate more complete bindings than a straight call without
18137 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
18139 In other cases, it is not possible to parse a header file in a stand alone
18140 manner, because other include files need to be included first. In this
18141 case, the solution is to create a small header file including the needed
18142 @code{#include} and possible @code{#define} directives. For example, to
18143 generate Ada bindings for @file{readline/readline.h}, you need to first
18144 include @file{stdio.h}, so you can create a file with the following two
18145 lines in e.g. @file{readline1.h}:
18149 #include <readline/readline.h>
18152 and then generate Ada bindings from this file:
18155 $ g++ -c -fdump-ada-spec readline1.h
18158 @node Generating bindings for C++ headers
18159 @section Generating bindings for C++ headers
18162 Generating bindings for C++ headers is done using the same options, always
18163 with the @command{g++} compiler.
18165 In this mode, C++ classes will be mapped to Ada tagged types, constructors
18166 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
18167 multiple inheritance of abstract classes will be mapped to Ada interfaces
18168 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
18169 information on interfacing to C++).
18171 For example, given the following C++ header file:
18178 virtual int Number_Of_Teeth () = 0;
18183 virtual void Set_Owner (char* Name) = 0;
18189 virtual void Set_Age (int New_Age);
18192 class Dog : Animal, Carnivore, Domestic @{
18197 virtual int Number_Of_Teeth ();
18198 virtual void Set_Owner (char* Name);
18206 The corresponding Ada code is generated:
18208 @smallexample @c ada
18211 package Class_Carnivore is
18212 type Carnivore is limited interface;
18213 pragma Import (CPP, Carnivore);
18215 function Number_Of_Teeth (this : access Carnivore) return int is abstract;
18217 use Class_Carnivore;
18219 package Class_Domestic is
18220 type Domestic is limited interface;
18221 pragma Import (CPP, Domestic);
18223 procedure Set_Owner
18224 (this : access Domestic;
18225 Name : Interfaces.C.Strings.chars_ptr) is abstract;
18227 use Class_Domestic;
18229 package Class_Animal is
18230 type Animal is tagged limited record
18231 Age_Count : aliased int;
18233 pragma Import (CPP, Animal);
18235 procedure Set_Age (this : access Animal; New_Age : int);
18236 pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
18240 package Class_Dog is
18241 type Dog is new Animal and Carnivore and Domestic with record
18242 Tooth_Count : aliased int;
18243 Owner : Interfaces.C.Strings.chars_ptr;
18245 pragma Import (CPP, Dog);
18247 function Number_Of_Teeth (this : access Dog) return int;
18248 pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
18250 procedure Set_Owner
18251 (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
18252 pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
18254 function New_Dog return Dog;
18255 pragma CPP_Constructor (New_Dog);
18256 pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
18267 @item -fdump-ada-spec
18268 @cindex @option{-fdump-ada-spec} (@command{gcc})
18269 Generate Ada spec files for the given header files transitively (including
18270 all header files that these headers depend upon).
18272 @item -fdump-ada-spec-slim
18273 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
18274 Generate Ada spec files for the header files specified on the command line
18278 @cindex @option{-C} (@command{gcc})
18279 Extract comments from headers and generate Ada comments in the Ada spec files.
18282 @node Other Utility Programs
18283 @chapter Other Utility Programs
18286 This chapter discusses some other utility programs available in the Ada
18290 * Using Other Utility Programs with GNAT::
18291 * The External Symbol Naming Scheme of GNAT::
18292 * Converting Ada Files to html with gnathtml::
18293 * Installing gnathtml::
18300 @node Using Other Utility Programs with GNAT
18301 @section Using Other Utility Programs with GNAT
18304 The object files generated by GNAT are in standard system format and in
18305 particular the debugging information uses this format. This means
18306 programs generated by GNAT can be used with existing utilities that
18307 depend on these formats.
18310 In general, any utility program that works with C will also often work with
18311 Ada programs generated by GNAT. This includes software utilities such as
18312 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
18316 @node The External Symbol Naming Scheme of GNAT
18317 @section The External Symbol Naming Scheme of GNAT
18320 In order to interpret the output from GNAT, when using tools that are
18321 originally intended for use with other languages, it is useful to
18322 understand the conventions used to generate link names from the Ada
18325 All link names are in all lowercase letters. With the exception of library
18326 procedure names, the mechanism used is simply to use the full expanded
18327 Ada name with dots replaced by double underscores. For example, suppose
18328 we have the following package spec:
18330 @smallexample @c ada
18341 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
18342 the corresponding link name is @code{qrs__mn}.
18344 Of course if a @code{pragma Export} is used this may be overridden:
18346 @smallexample @c ada
18351 pragma Export (Var1, C, External_Name => "var1_name");
18353 pragma Export (Var2, C, Link_Name => "var2_link_name");
18360 In this case, the link name for @var{Var1} is whatever link name the
18361 C compiler would assign for the C function @var{var1_name}. This typically
18362 would be either @var{var1_name} or @var{_var1_name}, depending on operating
18363 system conventions, but other possibilities exist. The link name for
18364 @var{Var2} is @var{var2_link_name}, and this is not operating system
18368 One exception occurs for library level procedures. A potential ambiguity
18369 arises between the required name @code{_main} for the C main program,
18370 and the name we would otherwise assign to an Ada library level procedure
18371 called @code{Main} (which might well not be the main program).
18373 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
18374 names. So if we have a library level procedure such as
18376 @smallexample @c ada
18379 procedure Hello (S : String);
18385 the external name of this procedure will be @var{_ada_hello}.
18388 @node Converting Ada Files to html with gnathtml
18389 @section Converting Ada Files to HTML with @code{gnathtml}
18392 This @code{Perl} script allows Ada source files to be browsed using
18393 standard Web browsers. For installation procedure, see the section
18394 @xref{Installing gnathtml}.
18396 Ada reserved keywords are highlighted in a bold font and Ada comments in
18397 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
18398 switch to suppress the generation of cross-referencing information, user
18399 defined variables and types will appear in a different color; you will
18400 be able to click on any identifier and go to its declaration.
18402 The command line is as follow:
18404 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
18405 @c Expanding @ovar macro inline (explanation in macro def comments)
18406 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
18410 You can pass it as many Ada files as you want. @code{gnathtml} will generate
18411 an html file for every ada file, and a global file called @file{index.htm}.
18412 This file is an index of every identifier defined in the files.
18414 The available ^switches^options^ are the following ones:
18418 @cindex @option{-83} (@code{gnathtml})
18419 Only the Ada 83 subset of keywords will be highlighted.
18421 @item -cc @var{color}
18422 @cindex @option{-cc} (@code{gnathtml})
18423 This option allows you to change the color used for comments. The default
18424 value is green. The color argument can be any name accepted by html.
18427 @cindex @option{-d} (@code{gnathtml})
18428 If the Ada files depend on some other files (for instance through
18429 @code{with} clauses, the latter files will also be converted to html.
18430 Only the files in the user project will be converted to html, not the files
18431 in the run-time library itself.
18434 @cindex @option{-D} (@code{gnathtml})
18435 This command is the same as @option{-d} above, but @command{gnathtml} will
18436 also look for files in the run-time library, and generate html files for them.
18438 @item -ext @var{extension}
18439 @cindex @option{-ext} (@code{gnathtml})
18440 This option allows you to change the extension of the generated HTML files.
18441 If you do not specify an extension, it will default to @file{htm}.
18444 @cindex @option{-f} (@code{gnathtml})
18445 By default, gnathtml will generate html links only for global entities
18446 ('with'ed units, global variables and types,@dots{}). If you specify
18447 @option{-f} on the command line, then links will be generated for local
18450 @item -l @var{number}
18451 @cindex @option{-l} (@code{gnathtml})
18452 If this ^switch^option^ is provided and @var{number} is not 0, then
18453 @code{gnathtml} will number the html files every @var{number} line.
18456 @cindex @option{-I} (@code{gnathtml})
18457 Specify a directory to search for library files (@file{.ALI} files) and
18458 source files. You can provide several -I switches on the command line,
18459 and the directories will be parsed in the order of the command line.
18462 @cindex @option{-o} (@code{gnathtml})
18463 Specify the output directory for html files. By default, gnathtml will
18464 saved the generated html files in a subdirectory named @file{html/}.
18466 @item -p @var{file}
18467 @cindex @option{-p} (@code{gnathtml})
18468 If you are using Emacs and the most recent Emacs Ada mode, which provides
18469 a full Integrated Development Environment for compiling, checking,
18470 running and debugging applications, you may use @file{.gpr} files
18471 to give the directories where Emacs can find sources and object files.
18473 Using this ^switch^option^, you can tell gnathtml to use these files.
18474 This allows you to get an html version of your application, even if it
18475 is spread over multiple directories.
18477 @item -sc @var{color}
18478 @cindex @option{-sc} (@code{gnathtml})
18479 This ^switch^option^ allows you to change the color used for symbol
18481 The default value is red. The color argument can be any name accepted by html.
18483 @item -t @var{file}
18484 @cindex @option{-t} (@code{gnathtml})
18485 This ^switch^option^ provides the name of a file. This file contains a list of
18486 file names to be converted, and the effect is exactly as though they had
18487 appeared explicitly on the command line. This
18488 is the recommended way to work around the command line length limit on some
18493 @node Installing gnathtml
18494 @section Installing @code{gnathtml}
18497 @code{Perl} needs to be installed on your machine to run this script.
18498 @code{Perl} is freely available for almost every architecture and
18499 Operating System via the Internet.
18501 On Unix systems, you may want to modify the first line of the script
18502 @code{gnathtml}, to explicitly tell the Operating system where Perl
18503 is. The syntax of this line is:
18505 #!full_path_name_to_perl
18509 Alternatively, you may run the script using the following command line:
18512 @c $ perl gnathtml.pl @ovar{switches} @var{files}
18513 @c Expanding @ovar macro inline (explanation in macro def comments)
18514 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
18523 The GNAT distribution provides an Ada 95 template for the HP Language
18524 Sensitive Editor (LSE), a component of DECset. In order to
18525 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
18532 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
18533 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
18534 the collection phase with the /DEBUG qualifier.
18537 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
18538 $ DEFINE LIB$DEBUG PCA$COLLECTOR
18539 $ RUN/DEBUG <PROGRAM_NAME>
18545 @c ******************************
18546 @node Code Coverage and Profiling
18547 @chapter Code Coverage and Profiling
18548 @cindex Code Coverage
18552 This chapter describes how to use @code{gcov} - coverage testing tool - and
18553 @code{gprof} - profiler tool - on your Ada programs.
18556 * Code Coverage of Ada Programs using gcov::
18557 * Profiling an Ada Program using gprof::
18560 @node Code Coverage of Ada Programs using gcov
18561 @section Code Coverage of Ada Programs using gcov
18563 @cindex -fprofile-arcs
18564 @cindex -ftest-coverage
18566 @cindex Code Coverage
18569 @code{gcov} is a test coverage program: it analyzes the execution of a given
18570 program on selected tests, to help you determine the portions of the program
18571 that are still untested.
18573 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
18574 User's Guide. You can refer to this documentation for a more complete
18577 This chapter provides a quick startup guide, and
18578 details some Gnat-specific features.
18581 * Quick startup guide::
18585 @node Quick startup guide
18586 @subsection Quick startup guide
18588 In order to perform coverage analysis of a program using @code{gcov}, 3
18593 Code instrumentation during the compilation process
18595 Execution of the instrumented program
18597 Execution of the @code{gcov} tool to generate the result.
18600 The code instrumentation needed by gcov is created at the object level:
18601 The source code is not modified in any way, because the instrumentation code is
18602 inserted by gcc during the compilation process. To compile your code with code
18603 coverage activated, you need to recompile your whole project using the
18605 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
18606 @code{-fprofile-arcs}.
18609 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
18610 -largs -fprofile-arcs
18613 This compilation process will create @file{.gcno} files together with
18614 the usual object files.
18616 Once the program is compiled with coverage instrumentation, you can
18617 run it as many times as needed - on portions of a test suite for
18618 example. The first execution will produce @file{.gcda} files at the
18619 same location as the @file{.gcno} files. The following executions
18620 will update those files, so that a cumulative result of the covered
18621 portions of the program is generated.
18623 Finally, you need to call the @code{gcov} tool. The different options of
18624 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
18626 This will create annotated source files with a @file{.gcov} extension:
18627 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
18629 @node Gnat specifics
18630 @subsection Gnat specifics
18632 Because Ada semantics, portions of the source code may be shared among
18633 several object files. This is the case for example when generics are
18634 involved, when inlining is active or when declarations generate initialisation
18635 calls. In order to take
18636 into account this shared code, you need to call @code{gcov} on all
18637 source files of the tested program at once.
18639 The list of source files might exceed the system's maximum command line
18640 length. In order to bypass this limitation, a new mechanism has been
18641 implemented in @code{gcov}: you can now list all your project's files into a
18642 text file, and provide this file to gcov as a parameter, preceded by a @@
18643 (e.g. @samp{gcov @@mysrclist.txt}).
18645 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
18646 not supported as there can be unresolved symbols during the final link.
18648 @node Profiling an Ada Program using gprof
18649 @section Profiling an Ada Program using gprof
18655 This section is not meant to be an exhaustive documentation of @code{gprof}.
18656 Full documentation for it can be found in the GNU Profiler User's Guide
18657 documentation that is part of this GNAT distribution.
18659 Profiling a program helps determine the parts of a program that are executed
18660 most often, and are therefore the most time-consuming.
18662 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
18663 better handle Ada programs and multitasking.
18664 It is currently supported on the following platforms
18669 solaris sparc/sparc64/x86
18675 In order to profile a program using @code{gprof}, 3 steps are needed:
18679 Code instrumentation, requiring a full recompilation of the project with the
18682 Execution of the program under the analysis conditions, i.e. with the desired
18685 Analysis of the results using the @code{gprof} tool.
18689 The following sections detail the different steps, and indicate how
18690 to interpret the results:
18692 * Compilation for profiling::
18693 * Program execution::
18695 * Interpretation of profiling results::
18698 @node Compilation for profiling
18699 @subsection Compilation for profiling
18703 In order to profile a program the first step is to tell the compiler
18704 to generate the necessary profiling information. The compiler switch to be used
18705 is @code{-pg}, which must be added to other compilation switches. This
18706 switch needs to be specified both during compilation and link stages, and can
18707 be specified once when using gnatmake:
18710 gnatmake -f -pg -P my_project
18714 Note that only the objects that were compiled with the @samp{-pg} switch will
18715 be profiled; if you need to profile your whole project, use the @samp{-f}
18716 gnatmake switch to force full recompilation.
18718 @node Program execution
18719 @subsection Program execution
18722 Once the program has been compiled for profiling, you can run it as usual.
18724 The only constraint imposed by profiling is that the program must terminate
18725 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
18728 Once the program completes execution, a data file called @file{gmon.out} is
18729 generated in the directory where the program was launched from. If this file
18730 already exists, it will be overwritten.
18732 @node Running gprof
18733 @subsection Running gprof
18736 The @code{gprof} tool is called as follow:
18739 gprof my_prog gmon.out
18750 The complete form of the gprof command line is the following:
18753 gprof [^switches^options^] [executable [data-file]]
18757 @code{gprof} supports numerous ^switch^options^. The order of these
18758 ^switch^options^ does not matter. The full list of options can be found in
18759 the GNU Profiler User's Guide documentation that comes with this documentation.
18761 The following is the subset of those switches that is most relevant:
18765 @item --demangle[=@var{style}]
18766 @itemx --no-demangle
18767 @cindex @option{--demangle} (@code{gprof})
18768 These options control whether symbol names should be demangled when
18769 printing output. The default is to demangle C++ symbols. The
18770 @code{--no-demangle} option may be used to turn off demangling. Different
18771 compilers have different mangling styles. The optional demangling style
18772 argument can be used to choose an appropriate demangling style for your
18773 compiler, in particular Ada symbols generated by GNAT can be demangled using
18774 @code{--demangle=gnat}.
18776 @item -e @var{function_name}
18777 @cindex @option{-e} (@code{gprof})
18778 The @samp{-e @var{function}} option tells @code{gprof} not to print
18779 information about the function @var{function_name} (and its
18780 children@dots{}) in the call graph. The function will still be listed
18781 as a child of any functions that call it, but its index number will be
18782 shown as @samp{[not printed]}. More than one @samp{-e} option may be
18783 given; only one @var{function_name} may be indicated with each @samp{-e}
18786 @item -E @var{function_name}
18787 @cindex @option{-E} (@code{gprof})
18788 The @code{-E @var{function}} option works like the @code{-e} option, but
18789 execution time spent in the function (and children who were not called from
18790 anywhere else), will not be used to compute the percentages-of-time for
18791 the call graph. More than one @samp{-E} option may be given; only one
18792 @var{function_name} may be indicated with each @samp{-E} option.
18794 @item -f @var{function_name}
18795 @cindex @option{-f} (@code{gprof})
18796 The @samp{-f @var{function}} option causes @code{gprof} to limit the
18797 call graph to the function @var{function_name} and its children (and
18798 their children@dots{}). More than one @samp{-f} option may be given;
18799 only one @var{function_name} may be indicated with each @samp{-f}
18802 @item -F @var{function_name}
18803 @cindex @option{-F} (@code{gprof})
18804 The @samp{-F @var{function}} option works like the @code{-f} option, but
18805 only time spent in the function and its children (and their
18806 children@dots{}) will be used to determine total-time and
18807 percentages-of-time for the call graph. More than one @samp{-F} option
18808 may be given; only one @var{function_name} may be indicated with each
18809 @samp{-F} option. The @samp{-F} option overrides the @samp{-E} option.
18813 @node Interpretation of profiling results
18814 @subsection Interpretation of profiling results
18818 The results of the profiling analysis are represented by two arrays: the
18819 'flat profile' and the 'call graph'. Full documentation of those outputs
18820 can be found in the GNU Profiler User's Guide.
18822 The flat profile shows the time spent in each function of the program, and how
18823 many time it has been called. This allows you to locate easily the most
18824 time-consuming functions.
18826 The call graph shows, for each subprogram, the subprograms that call it,
18827 and the subprograms that it calls. It also provides an estimate of the time
18828 spent in each of those callers/called subprograms.
18831 @c ******************************
18832 @node Running and Debugging Ada Programs
18833 @chapter Running and Debugging Ada Programs
18837 This chapter discusses how to debug Ada programs.
18839 It applies to GNAT on the Alpha OpenVMS platform;
18840 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
18841 since HP has implemented Ada support in the OpenVMS debugger on I64.
18844 An incorrect Ada program may be handled in three ways by the GNAT compiler:
18848 The illegality may be a violation of the static semantics of Ada. In
18849 that case GNAT diagnoses the constructs in the program that are illegal.
18850 It is then a straightforward matter for the user to modify those parts of
18854 The illegality may be a violation of the dynamic semantics of Ada. In
18855 that case the program compiles and executes, but may generate incorrect
18856 results, or may terminate abnormally with some exception.
18859 When presented with a program that contains convoluted errors, GNAT
18860 itself may terminate abnormally without providing full diagnostics on
18861 the incorrect user program.
18865 * The GNAT Debugger GDB::
18867 * Introduction to GDB Commands::
18868 * Using Ada Expressions::
18869 * Calling User-Defined Subprograms::
18870 * Using the Next Command in a Function::
18873 * Debugging Generic Units::
18874 * Remote Debugging using gdbserver::
18875 * GNAT Abnormal Termination or Failure to Terminate::
18876 * Naming Conventions for GNAT Source Files::
18877 * Getting Internal Debugging Information::
18878 * Stack Traceback::
18884 @node The GNAT Debugger GDB
18885 @section The GNAT Debugger GDB
18888 @code{GDB} is a general purpose, platform-independent debugger that
18889 can be used to debug mixed-language programs compiled with @command{gcc},
18890 and in particular is capable of debugging Ada programs compiled with
18891 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
18892 complex Ada data structures.
18894 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
18896 located in the GNU:[DOCS] directory,
18898 for full details on the usage of @code{GDB}, including a section on
18899 its usage on programs. This manual should be consulted for full
18900 details. The section that follows is a brief introduction to the
18901 philosophy and use of @code{GDB}.
18903 When GNAT programs are compiled, the compiler optionally writes debugging
18904 information into the generated object file, including information on
18905 line numbers, and on declared types and variables. This information is
18906 separate from the generated code. It makes the object files considerably
18907 larger, but it does not add to the size of the actual executable that
18908 will be loaded into memory, and has no impact on run-time performance. The
18909 generation of debug information is triggered by the use of the
18910 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
18911 used to carry out the compilations. It is important to emphasize that
18912 the use of these options does not change the generated code.
18914 The debugging information is written in standard system formats that
18915 are used by many tools, including debuggers and profilers. The format
18916 of the information is typically designed to describe C types and
18917 semantics, but GNAT implements a translation scheme which allows full
18918 details about Ada types and variables to be encoded into these
18919 standard C formats. Details of this encoding scheme may be found in
18920 the file exp_dbug.ads in the GNAT source distribution. However, the
18921 details of this encoding are, in general, of no interest to a user,
18922 since @code{GDB} automatically performs the necessary decoding.
18924 When a program is bound and linked, the debugging information is
18925 collected from the object files, and stored in the executable image of
18926 the program. Again, this process significantly increases the size of
18927 the generated executable file, but it does not increase the size of
18928 the executable program itself. Furthermore, if this program is run in
18929 the normal manner, it runs exactly as if the debug information were
18930 not present, and takes no more actual memory.
18932 However, if the program is run under control of @code{GDB}, the
18933 debugger is activated. The image of the program is loaded, at which
18934 point it is ready to run. If a run command is given, then the program
18935 will run exactly as it would have if @code{GDB} were not present. This
18936 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
18937 entirely non-intrusive until a breakpoint is encountered. If no
18938 breakpoint is ever hit, the program will run exactly as it would if no
18939 debugger were present. When a breakpoint is hit, @code{GDB} accesses
18940 the debugging information and can respond to user commands to inspect
18941 variables, and more generally to report on the state of execution.
18945 @section Running GDB
18948 This section describes how to initiate the debugger.
18949 @c The above sentence is really just filler, but it was otherwise
18950 @c clumsy to get the first paragraph nonindented given the conditional
18951 @c nature of the description
18954 The debugger can be launched from a @code{GPS} menu or
18955 directly from the command line. The description below covers the latter use.
18956 All the commands shown can be used in the @code{GPS} debug console window,
18957 but there are usually more GUI-based ways to achieve the same effect.
18960 The command to run @code{GDB} is
18963 $ ^gdb program^GDB PROGRAM^
18967 where @code{^program^PROGRAM^} is the name of the executable file. This
18968 activates the debugger and results in a prompt for debugger commands.
18969 The simplest command is simply @code{run}, which causes the program to run
18970 exactly as if the debugger were not present. The following section
18971 describes some of the additional commands that can be given to @code{GDB}.
18973 @c *******************************
18974 @node Introduction to GDB Commands
18975 @section Introduction to GDB Commands
18978 @code{GDB} contains a large repertoire of commands. @xref{Top,,
18979 Debugging with GDB, gdb, Debugging with GDB},
18981 located in the GNU:[DOCS] directory,
18983 for extensive documentation on the use
18984 of these commands, together with examples of their use. Furthermore,
18985 the command @command{help} invoked from within GDB activates a simple help
18986 facility which summarizes the available commands and their options.
18987 In this section we summarize a few of the most commonly
18988 used commands to give an idea of what @code{GDB} is about. You should create
18989 a simple program with debugging information and experiment with the use of
18990 these @code{GDB} commands on the program as you read through the
18994 @item set args @var{arguments}
18995 The @var{arguments} list above is a list of arguments to be passed to
18996 the program on a subsequent run command, just as though the arguments
18997 had been entered on a normal invocation of the program. The @code{set args}
18998 command is not needed if the program does not require arguments.
19001 The @code{run} command causes execution of the program to start from
19002 the beginning. If the program is already running, that is to say if
19003 you are currently positioned at a breakpoint, then a prompt will ask
19004 for confirmation that you want to abandon the current execution and
19007 @item breakpoint @var{location}
19008 The breakpoint command sets a breakpoint, that is to say a point at which
19009 execution will halt and @code{GDB} will await further
19010 commands. @var{location} is
19011 either a line number within a file, given in the format @code{file:linenumber},
19012 or it is the name of a subprogram. If you request that a breakpoint be set on
19013 a subprogram that is overloaded, a prompt will ask you to specify on which of
19014 those subprograms you want to breakpoint. You can also
19015 specify that all of them should be breakpointed. If the program is run
19016 and execution encounters the breakpoint, then the program
19017 stops and @code{GDB} signals that the breakpoint was encountered by
19018 printing the line of code before which the program is halted.
19020 @item catch exception @var{name}
19021 This command causes the program execution to stop whenever exception
19022 @var{name} is raised. If @var{name} is omitted, then the execution is
19023 suspended when any exception is raised.
19025 @item print @var{expression}
19026 This will print the value of the given expression. Most simple
19027 Ada expression formats are properly handled by @code{GDB}, so the expression
19028 can contain function calls, variables, operators, and attribute references.
19031 Continues execution following a breakpoint, until the next breakpoint or the
19032 termination of the program.
19035 Executes a single line after a breakpoint. If the next statement
19036 is a subprogram call, execution continues into (the first statement of)
19037 the called subprogram.
19040 Executes a single line. If this line is a subprogram call, executes and
19041 returns from the call.
19044 Lists a few lines around the current source location. In practice, it
19045 is usually more convenient to have a separate edit window open with the
19046 relevant source file displayed. Successive applications of this command
19047 print subsequent lines. The command can be given an argument which is a
19048 line number, in which case it displays a few lines around the specified one.
19051 Displays a backtrace of the call chain. This command is typically
19052 used after a breakpoint has occurred, to examine the sequence of calls that
19053 leads to the current breakpoint. The display includes one line for each
19054 activation record (frame) corresponding to an active subprogram.
19057 At a breakpoint, @code{GDB} can display the values of variables local
19058 to the current frame. The command @code{up} can be used to
19059 examine the contents of other active frames, by moving the focus up
19060 the stack, that is to say from callee to caller, one frame at a time.
19063 Moves the focus of @code{GDB} down from the frame currently being
19064 examined to the frame of its callee (the reverse of the previous command),
19066 @item frame @var{n}
19067 Inspect the frame with the given number. The value 0 denotes the frame
19068 of the current breakpoint, that is to say the top of the call stack.
19073 The above list is a very short introduction to the commands that
19074 @code{GDB} provides. Important additional capabilities, including conditional
19075 breakpoints, the ability to execute command sequences on a breakpoint,
19076 the ability to debug at the machine instruction level and many other
19077 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
19078 Debugging with GDB}. Note that most commands can be abbreviated
19079 (for example, c for continue, bt for backtrace).
19081 @node Using Ada Expressions
19082 @section Using Ada Expressions
19083 @cindex Ada expressions
19086 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
19087 extensions. The philosophy behind the design of this subset is
19091 That @code{GDB} should provide basic literals and access to operations for
19092 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19093 leaving more sophisticated computations to subprograms written into the
19094 program (which therefore may be called from @code{GDB}).
19097 That type safety and strict adherence to Ada language restrictions
19098 are not particularly important to the @code{GDB} user.
19101 That brevity is important to the @code{GDB} user.
19105 Thus, for brevity, the debugger acts as if there were
19106 implicit @code{with} and @code{use} clauses in effect for all user-written
19107 packages, thus making it unnecessary to fully qualify most names with
19108 their packages, regardless of context. Where this causes ambiguity,
19109 @code{GDB} asks the user's intent.
19111 For details on the supported Ada syntax, see @ref{Top,, Debugging with
19112 GDB, gdb, Debugging with GDB}.
19114 @node Calling User-Defined Subprograms
19115 @section Calling User-Defined Subprograms
19118 An important capability of @code{GDB} is the ability to call user-defined
19119 subprograms while debugging. This is achieved simply by entering
19120 a subprogram call statement in the form:
19123 call subprogram-name (parameters)
19127 The keyword @code{call} can be omitted in the normal case where the
19128 @code{subprogram-name} does not coincide with any of the predefined
19129 @code{GDB} commands.
19131 The effect is to invoke the given subprogram, passing it the
19132 list of parameters that is supplied. The parameters can be expressions and
19133 can include variables from the program being debugged. The
19134 subprogram must be defined
19135 at the library level within your program, and @code{GDB} will call the
19136 subprogram within the environment of your program execution (which
19137 means that the subprogram is free to access or even modify variables
19138 within your program).
19140 The most important use of this facility is in allowing the inclusion of
19141 debugging routines that are tailored to particular data structures
19142 in your program. Such debugging routines can be written to provide a suitably
19143 high-level description of an abstract type, rather than a low-level dump
19144 of its physical layout. After all, the standard
19145 @code{GDB print} command only knows the physical layout of your
19146 types, not their abstract meaning. Debugging routines can provide information
19147 at the desired semantic level and are thus enormously useful.
19149 For example, when debugging GNAT itself, it is crucial to have access to
19150 the contents of the tree nodes used to represent the program internally.
19151 But tree nodes are represented simply by an integer value (which in turn
19152 is an index into a table of nodes).
19153 Using the @code{print} command on a tree node would simply print this integer
19154 value, which is not very useful. But the PN routine (defined in file
19155 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19156 a useful high level representation of the tree node, which includes the
19157 syntactic category of the node, its position in the source, the integers
19158 that denote descendant nodes and parent node, as well as varied
19159 semantic information. To study this example in more detail, you might want to
19160 look at the body of the PN procedure in the stated file.
19162 @node Using the Next Command in a Function
19163 @section Using the Next Command in a Function
19166 When you use the @code{next} command in a function, the current source
19167 location will advance to the next statement as usual. A special case
19168 arises in the case of a @code{return} statement.
19170 Part of the code for a return statement is the ``epilog'' of the function.
19171 This is the code that returns to the caller. There is only one copy of
19172 this epilog code, and it is typically associated with the last return
19173 statement in the function if there is more than one return. In some
19174 implementations, this epilog is associated with the first statement
19177 The result is that if you use the @code{next} command from a return
19178 statement that is not the last return statement of the function you
19179 may see a strange apparent jump to the last return statement or to
19180 the start of the function. You should simply ignore this odd jump.
19181 The value returned is always that from the first return statement
19182 that was stepped through.
19184 @node Ada Exceptions
19185 @section Stopping when Ada Exceptions are Raised
19189 You can set catchpoints that stop the program execution when your program
19190 raises selected exceptions.
19193 @item catch exception
19194 Set a catchpoint that stops execution whenever (any task in the) program
19195 raises any exception.
19197 @item catch exception @var{name}
19198 Set a catchpoint that stops execution whenever (any task in the) program
19199 raises the exception @var{name}.
19201 @item catch exception unhandled
19202 Set a catchpoint that stops executino whenever (any task in the) program
19203 raises an exception for which there is no handler.
19205 @item info exceptions
19206 @itemx info exceptions @var{regexp}
19207 The @code{info exceptions} command permits the user to examine all defined
19208 exceptions within Ada programs. With a regular expression, @var{regexp}, as
19209 argument, prints out only those exceptions whose name matches @var{regexp}.
19217 @code{GDB} allows the following task-related commands:
19221 This command shows a list of current Ada tasks, as in the following example:
19228 ID TID P-ID Thread Pri State Name
19229 1 8088000 0 807e000 15 Child Activation Wait main_task
19230 2 80a4000 1 80ae000 15 Accept/Select Wait b
19231 3 809a800 1 80a4800 15 Child Activation Wait a
19232 * 4 80ae800 3 80b8000 15 Running c
19236 In this listing, the asterisk before the first task indicates it to be the
19237 currently running task. The first column lists the task ID that is used
19238 to refer to tasks in the following commands.
19240 @item break @var{linespec} task @var{taskid}
19241 @itemx break @var{linespec} task @var{taskid} if @dots{}
19242 @cindex Breakpoints and tasks
19243 These commands are like the @code{break @dots{} thread @dots{}}.
19244 @var{linespec} specifies source lines.
19246 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
19247 to specify that you only want @code{GDB} to stop the program when a
19248 particular Ada task reaches this breakpoint. @var{taskid} is one of the
19249 numeric task identifiers assigned by @code{GDB}, shown in the first
19250 column of the @samp{info tasks} display.
19252 If you do not specify @samp{task @var{taskid}} when you set a
19253 breakpoint, the breakpoint applies to @emph{all} tasks of your
19256 You can use the @code{task} qualifier on conditional breakpoints as
19257 well; in this case, place @samp{task @var{taskid}} before the
19258 breakpoint condition (before the @code{if}).
19260 @item task @var{taskno}
19261 @cindex Task switching
19263 This command allows to switch to the task referred by @var{taskno}. In
19264 particular, This allows to browse the backtrace of the specified
19265 task. It is advised to switch back to the original task before
19266 continuing execution otherwise the scheduling of the program may be
19271 For more detailed information on the tasking support,
19272 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
19274 @node Debugging Generic Units
19275 @section Debugging Generic Units
19276 @cindex Debugging Generic Units
19280 GNAT always uses code expansion for generic instantiation. This means that
19281 each time an instantiation occurs, a complete copy of the original code is
19282 made, with appropriate substitutions of formals by actuals.
19284 It is not possible to refer to the original generic entities in
19285 @code{GDB}, but it is always possible to debug a particular instance of
19286 a generic, by using the appropriate expanded names. For example, if we have
19288 @smallexample @c ada
19293 generic package k is
19294 procedure kp (v1 : in out integer);
19298 procedure kp (v1 : in out integer) is
19304 package k1 is new k;
19305 package k2 is new k;
19307 var : integer := 1;
19320 Then to break on a call to procedure kp in the k2 instance, simply
19324 (gdb) break g.k2.kp
19328 When the breakpoint occurs, you can step through the code of the
19329 instance in the normal manner and examine the values of local variables, as for
19332 @node Remote Debugging using gdbserver
19333 @section Remote Debugging using gdbserver
19334 @cindex Remote Debugging using gdbserver
19337 On platforms where gdbserver is supported, it is possible to use this tool
19338 to debug your application remotely. This can be useful in situations
19339 where the program needs to be run on a target host that is different
19340 from the host used for development, particularly when the target has
19341 a limited amount of resources (either CPU and/or memory).
19343 To do so, start your program using gdbserver on the target machine.
19344 gdbserver then automatically suspends the execution of your program
19345 at its entry point, waiting for a debugger to connect to it. The
19346 following commands starts an application and tells gdbserver to
19347 wait for a connection with the debugger on localhost port 4444.
19350 $ gdbserver localhost:4444 program
19351 Process program created; pid = 5685
19352 Listening on port 4444
19355 Once gdbserver has started listening, we can tell the debugger to establish
19356 a connection with this gdbserver, and then start the same debugging session
19357 as if the program was being debugged on the same host, directly under
19358 the control of GDB.
19362 (gdb) target remote targethost:4444
19363 Remote debugging using targethost:4444
19364 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
19366 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
19370 Breakpoint 1, foo () at foo.adb:4
19374 It is also possible to use gdbserver to attach to an already running
19375 program, in which case the execution of that program is simply suspended
19376 until the connection between the debugger and gdbserver is established.
19378 For more information on how to use gdbserver, @ref{Top, Server, Using
19379 the gdbserver Program, gdb, Debugging with GDB}. GNAT Pro provides support
19380 for gdbserver on x86-linux, x86-windows and x86_64-linux.
19382 @node GNAT Abnormal Termination or Failure to Terminate
19383 @section GNAT Abnormal Termination or Failure to Terminate
19384 @cindex GNAT Abnormal Termination or Failure to Terminate
19387 When presented with programs that contain serious errors in syntax
19389 GNAT may on rare occasions experience problems in operation, such
19391 segmentation fault or illegal memory access, raising an internal
19392 exception, terminating abnormally, or failing to terminate at all.
19393 In such cases, you can activate
19394 various features of GNAT that can help you pinpoint the construct in your
19395 program that is the likely source of the problem.
19397 The following strategies are presented in increasing order of
19398 difficulty, corresponding to your experience in using GNAT and your
19399 familiarity with compiler internals.
19403 Run @command{gcc} with the @option{-gnatf}. This first
19404 switch causes all errors on a given line to be reported. In its absence,
19405 only the first error on a line is displayed.
19407 The @option{-gnatdO} switch causes errors to be displayed as soon as they
19408 are encountered, rather than after compilation is terminated. If GNAT
19409 terminates prematurely or goes into an infinite loop, the last error
19410 message displayed may help to pinpoint the culprit.
19413 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
19414 mode, @command{gcc} produces ongoing information about the progress of the
19415 compilation and provides the name of each procedure as code is
19416 generated. This switch allows you to find which Ada procedure was being
19417 compiled when it encountered a code generation problem.
19420 @cindex @option{-gnatdc} switch
19421 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
19422 switch that does for the front-end what @option{^-v^VERBOSE^} does
19423 for the back end. The system prints the name of each unit,
19424 either a compilation unit or nested unit, as it is being analyzed.
19426 Finally, you can start
19427 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19428 front-end of GNAT, and can be run independently (normally it is just
19429 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
19430 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
19431 @code{where} command is the first line of attack; the variable
19432 @code{lineno} (seen by @code{print lineno}), used by the second phase of
19433 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
19434 which the execution stopped, and @code{input_file name} indicates the name of
19438 @node Naming Conventions for GNAT Source Files
19439 @section Naming Conventions for GNAT Source Files
19442 In order to examine the workings of the GNAT system, the following
19443 brief description of its organization may be helpful:
19447 Files with prefix @file{^sc^SC^} contain the lexical scanner.
19450 All files prefixed with @file{^par^PAR^} are components of the parser. The
19451 numbers correspond to chapters of the Ada Reference Manual. For example,
19452 parsing of select statements can be found in @file{par-ch9.adb}.
19455 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
19456 numbers correspond to chapters of the Ada standard. For example, all
19457 issues involving context clauses can be found in @file{sem_ch10.adb}. In
19458 addition, some features of the language require sufficient special processing
19459 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19460 dynamic dispatching, etc.
19463 All files prefixed with @file{^exp^EXP^} perform normalization and
19464 expansion of the intermediate representation (abstract syntax tree, or AST).
19465 these files use the same numbering scheme as the parser and semantics files.
19466 For example, the construction of record initialization procedures is done in
19467 @file{exp_ch3.adb}.
19470 The files prefixed with @file{^bind^BIND^} implement the binder, which
19471 verifies the consistency of the compilation, determines an order of
19472 elaboration, and generates the bind file.
19475 The files @file{atree.ads} and @file{atree.adb} detail the low-level
19476 data structures used by the front-end.
19479 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
19480 the abstract syntax tree as produced by the parser.
19483 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
19484 all entities, computed during semantic analysis.
19487 Library management issues are dealt with in files with prefix
19493 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
19494 defined in Annex A.
19499 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
19500 defined in Annex B.
19504 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
19505 both language-defined children and GNAT run-time routines.
19509 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
19510 general-purpose packages, fully documented in their specs. All
19511 the other @file{.c} files are modifications of common @command{gcc} files.
19514 @node Getting Internal Debugging Information
19515 @section Getting Internal Debugging Information
19518 Most compilers have internal debugging switches and modes. GNAT
19519 does also, except GNAT internal debugging switches and modes are not
19520 secret. A summary and full description of all the compiler and binder
19521 debug flags are in the file @file{debug.adb}. You must obtain the
19522 sources of the compiler to see the full detailed effects of these flags.
19524 The switches that print the source of the program (reconstructed from
19525 the internal tree) are of general interest for user programs, as are the
19527 the full internal tree, and the entity table (the symbol table
19528 information). The reconstructed source provides a readable version of the
19529 program after the front-end has completed analysis and expansion,
19530 and is useful when studying the performance of specific constructs.
19531 For example, constraint checks are indicated, complex aggregates
19532 are replaced with loops and assignments, and tasking primitives
19533 are replaced with run-time calls.
19535 @node Stack Traceback
19536 @section Stack Traceback
19538 @cindex stack traceback
19539 @cindex stack unwinding
19542 Traceback is a mechanism to display the sequence of subprogram calls that
19543 leads to a specified execution point in a program. Often (but not always)
19544 the execution point is an instruction at which an exception has been raised.
19545 This mechanism is also known as @i{stack unwinding} because it obtains
19546 its information by scanning the run-time stack and recovering the activation
19547 records of all active subprograms. Stack unwinding is one of the most
19548 important tools for program debugging.
19550 The first entry stored in traceback corresponds to the deepest calling level,
19551 that is to say the subprogram currently executing the instruction
19552 from which we want to obtain the traceback.
19554 Note that there is no runtime performance penalty when stack traceback
19555 is enabled, and no exception is raised during program execution.
19558 * Non-Symbolic Traceback::
19559 * Symbolic Traceback::
19562 @node Non-Symbolic Traceback
19563 @subsection Non-Symbolic Traceback
19564 @cindex traceback, non-symbolic
19567 Note: this feature is not supported on all platforms. See
19568 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
19572 * Tracebacks From an Unhandled Exception::
19573 * Tracebacks From Exception Occurrences (non-symbolic)::
19574 * Tracebacks From Anywhere in a Program (non-symbolic)::
19577 @node Tracebacks From an Unhandled Exception
19578 @subsubsection Tracebacks From an Unhandled Exception
19581 A runtime non-symbolic traceback is a list of addresses of call instructions.
19582 To enable this feature you must use the @option{-E}
19583 @code{gnatbind}'s option. With this option a stack traceback is stored as part
19584 of exception information. You can retrieve this information using the
19585 @code{addr2line} tool.
19587 Here is a simple example:
19589 @smallexample @c ada
19595 raise Constraint_Error;
19610 $ gnatmake stb -bargs -E
19613 Execution terminated by unhandled exception
19614 Exception name: CONSTRAINT_ERROR
19616 Call stack traceback locations:
19617 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19621 As we see the traceback lists a sequence of addresses for the unhandled
19622 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19623 guess that this exception come from procedure P1. To translate these
19624 addresses into the source lines where the calls appear, the
19625 @code{addr2line} tool, described below, is invaluable. The use of this tool
19626 requires the program to be compiled with debug information.
19629 $ gnatmake -g stb -bargs -E
19632 Execution terminated by unhandled exception
19633 Exception name: CONSTRAINT_ERROR
19635 Call stack traceback locations:
19636 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19638 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19639 0x4011f1 0x77e892a4
19641 00401373 at d:/stb/stb.adb:5
19642 0040138B at d:/stb/stb.adb:10
19643 0040139C at d:/stb/stb.adb:14
19644 00401335 at d:/stb/b~stb.adb:104
19645 004011C4 at /build/@dots{}/crt1.c:200
19646 004011F1 at /build/@dots{}/crt1.c:222
19647 77E892A4 in ?? at ??:0
19651 The @code{addr2line} tool has several other useful options:
19655 to get the function name corresponding to any location
19657 @item --demangle=gnat
19658 to use the gnat decoding mode for the function names. Note that
19659 for binutils version 2.9.x the option is simply @option{--demangle}.
19663 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
19664 0x40139c 0x401335 0x4011c4 0x4011f1
19666 00401373 in stb.p1 at d:/stb/stb.adb:5
19667 0040138B in stb.p2 at d:/stb/stb.adb:10
19668 0040139C in stb at d:/stb/stb.adb:14
19669 00401335 in main at d:/stb/b~stb.adb:104
19670 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
19671 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
19675 From this traceback we can see that the exception was raised in
19676 @file{stb.adb} at line 5, which was reached from a procedure call in
19677 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
19678 which contains the call to the main program.
19679 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
19680 and the output will vary from platform to platform.
19682 It is also possible to use @code{GDB} with these traceback addresses to debug
19683 the program. For example, we can break at a given code location, as reported
19684 in the stack traceback:
19690 Furthermore, this feature is not implemented inside Windows DLL. Only
19691 the non-symbolic traceback is reported in this case.
19694 (gdb) break *0x401373
19695 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19699 It is important to note that the stack traceback addresses
19700 do not change when debug information is included. This is particularly useful
19701 because it makes it possible to release software without debug information (to
19702 minimize object size), get a field report that includes a stack traceback
19703 whenever an internal bug occurs, and then be able to retrieve the sequence
19704 of calls with the same program compiled with debug information.
19706 @node Tracebacks From Exception Occurrences (non-symbolic)
19707 @subsubsection Tracebacks From Exception Occurrences
19710 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
19711 The stack traceback is attached to the exception information string, and can
19712 be retrieved in an exception handler within the Ada program, by means of the
19713 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19715 @smallexample @c ada
19717 with Ada.Exceptions;
19722 use Ada.Exceptions;
19730 Text_IO.Put_Line (Exception_Information (E));
19744 This program will output:
19749 Exception name: CONSTRAINT_ERROR
19750 Message: stb.adb:12
19751 Call stack traceback locations:
19752 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19755 @node Tracebacks From Anywhere in a Program (non-symbolic)
19756 @subsubsection Tracebacks From Anywhere in a Program
19759 It is also possible to retrieve a stack traceback from anywhere in a
19760 program. For this you need to
19761 use the @code{GNAT.Traceback} API. This package includes a procedure called
19762 @code{Call_Chain} that computes a complete stack traceback, as well as useful
19763 display procedures described below. It is not necessary to use the
19764 @option{-E gnatbind} option in this case, because the stack traceback mechanism
19765 is invoked explicitly.
19768 In the following example we compute a traceback at a specific location in
19769 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
19770 convert addresses to strings:
19772 @smallexample @c ada
19774 with GNAT.Traceback;
19775 with GNAT.Debug_Utilities;
19781 use GNAT.Traceback;
19784 TB : Tracebacks_Array (1 .. 10);
19785 -- We are asking for a maximum of 10 stack frames.
19787 -- Len will receive the actual number of stack frames returned.
19789 Call_Chain (TB, Len);
19791 Text_IO.Put ("In STB.P1 : ");
19793 for K in 1 .. Len loop
19794 Text_IO.Put (Debug_Utilities.Image (TB (K)));
19815 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
19816 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
19820 You can then get further information by invoking the @code{addr2line}
19821 tool as described earlier (note that the hexadecimal addresses
19822 need to be specified in C format, with a leading ``0x'').
19824 @node Symbolic Traceback
19825 @subsection Symbolic Traceback
19826 @cindex traceback, symbolic
19829 A symbolic traceback is a stack traceback in which procedure names are
19830 associated with each code location.
19833 Note that this feature is not supported on all platforms. See
19834 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
19835 list of currently supported platforms.
19838 Note that the symbolic traceback requires that the program be compiled
19839 with debug information. If it is not compiled with debug information
19840 only the non-symbolic information will be valid.
19843 * Tracebacks From Exception Occurrences (symbolic)::
19844 * Tracebacks From Anywhere in a Program (symbolic)::
19847 @node Tracebacks From Exception Occurrences (symbolic)
19848 @subsubsection Tracebacks From Exception Occurrences
19850 @smallexample @c ada
19852 with GNAT.Traceback.Symbolic;
19858 raise Constraint_Error;
19875 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
19880 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
19883 0040149F in stb.p1 at stb.adb:8
19884 004014B7 in stb.p2 at stb.adb:13
19885 004014CF in stb.p3 at stb.adb:18
19886 004015DD in ada.stb at stb.adb:22
19887 00401461 in main at b~stb.adb:168
19888 004011C4 in __mingw_CRTStartup at crt1.c:200
19889 004011F1 in mainCRTStartup at crt1.c:222
19890 77E892A4 in ?? at ??:0
19894 In the above example the ``.\'' syntax in the @command{gnatmake} command
19895 is currently required by @command{addr2line} for files that are in
19896 the current working directory.
19897 Moreover, the exact sequence of linker options may vary from platform
19899 The above @option{-largs} section is for Windows platforms. By contrast,
19900 under Unix there is no need for the @option{-largs} section.
19901 Differences across platforms are due to details of linker implementation.
19903 @node Tracebacks From Anywhere in a Program (symbolic)
19904 @subsubsection Tracebacks From Anywhere in a Program
19907 It is possible to get a symbolic stack traceback
19908 from anywhere in a program, just as for non-symbolic tracebacks.
19909 The first step is to obtain a non-symbolic
19910 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
19911 information. Here is an example:
19913 @smallexample @c ada
19915 with GNAT.Traceback;
19916 with GNAT.Traceback.Symbolic;
19921 use GNAT.Traceback;
19922 use GNAT.Traceback.Symbolic;
19925 TB : Tracebacks_Array (1 .. 10);
19926 -- We are asking for a maximum of 10 stack frames.
19928 -- Len will receive the actual number of stack frames returned.
19930 Call_Chain (TB, Len);
19931 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
19944 @c ******************************
19946 @node Compatibility with HP Ada
19947 @chapter Compatibility with HP Ada
19948 @cindex Compatibility
19953 @cindex Compatibility between GNAT and HP Ada
19954 This chapter compares HP Ada (formerly known as ``DEC Ada'')
19955 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
19956 GNAT is highly compatible
19957 with HP Ada, and it should generally be straightforward to port code
19958 from the HP Ada environment to GNAT. However, there are a few language
19959 and implementation differences of which the user must be aware. These
19960 differences are discussed in this chapter. In
19961 addition, the operating environment and command structure for the
19962 compiler are different, and these differences are also discussed.
19964 For further details on these and other compatibility issues,
19965 see Appendix E of the HP publication
19966 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
19968 Except where otherwise indicated, the description of GNAT for OpenVMS
19969 applies to both the Alpha and I64 platforms.
19971 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
19972 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
19974 The discussion in this chapter addresses specifically the implementation
19975 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
19976 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
19977 GNAT always follows the Alpha implementation.
19979 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
19980 attributes are recognized, although only a subset of them can sensibly
19981 be implemented. The description of pragmas in
19982 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
19983 indicates whether or not they are applicable to non-VMS systems.
19986 * Ada Language Compatibility::
19987 * Differences in the Definition of Package System::
19988 * Language-Related Features::
19989 * The Package STANDARD::
19990 * The Package SYSTEM::
19991 * Tasking and Task-Related Features::
19992 * Pragmas and Pragma-Related Features::
19993 * Library of Predefined Units::
19995 * Main Program Definition::
19996 * Implementation-Defined Attributes::
19997 * Compiler and Run-Time Interfacing::
19998 * Program Compilation and Library Management::
20000 * Implementation Limits::
20001 * Tools and Utilities::
20004 @node Ada Language Compatibility
20005 @section Ada Language Compatibility
20008 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
20009 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
20010 with Ada 83, and therefore Ada 83 programs will compile
20011 and run under GNAT with
20012 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
20013 provides details on specific incompatibilities.
20015 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
20016 as well as the pragma @code{ADA_83}, to force the compiler to
20017 operate in Ada 83 mode. This mode does not guarantee complete
20018 conformance to Ada 83, but in practice is sufficient to
20019 eliminate most sources of incompatibilities.
20020 In particular, it eliminates the recognition of the
20021 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
20022 in Ada 83 programs is legal, and handles the cases of packages
20023 with optional bodies, and generics that instantiate unconstrained
20024 types without the use of @code{(<>)}.
20026 @node Differences in the Definition of Package System
20027 @section Differences in the Definition of Package @code{System}
20030 An Ada compiler is allowed to add
20031 implementation-dependent declarations to package @code{System}.
20033 GNAT does not take advantage of this permission, and the version of
20034 @code{System} provided by GNAT exactly matches that defined in the Ada
20037 However, HP Ada adds an extensive set of declarations to package
20039 as fully documented in the HP Ada manuals. To minimize changes required
20040 for programs that make use of these extensions, GNAT provides the pragma
20041 @code{Extend_System} for extending the definition of package System. By using:
20042 @cindex pragma @code{Extend_System}
20043 @cindex @code{Extend_System} pragma
20045 @smallexample @c ada
20048 pragma Extend_System (Aux_DEC);
20054 the set of definitions in @code{System} is extended to include those in
20055 package @code{System.Aux_DEC}.
20056 @cindex @code{System.Aux_DEC} package
20057 @cindex @code{Aux_DEC} package (child of @code{System})
20058 These definitions are incorporated directly into package @code{System},
20059 as though they had been declared there. For a
20060 list of the declarations added, see the spec of this package,
20061 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
20062 @cindex @file{s-auxdec.ads} file
20063 The pragma @code{Extend_System} is a configuration pragma, which means that
20064 it can be placed in the file @file{gnat.adc}, so that it will automatically
20065 apply to all subsequent compilations. See @ref{Configuration Pragmas},
20066 for further details.
20068 An alternative approach that avoids the use of the non-standard
20069 @code{Extend_System} pragma is to add a context clause to the unit that
20070 references these facilities:
20072 @smallexample @c ada
20074 with System.Aux_DEC;
20075 use System.Aux_DEC;
20080 The effect is not quite semantically identical to incorporating
20081 the declarations directly into package @code{System},
20082 but most programs will not notice a difference
20083 unless they use prefix notation (e.g.@: @code{System.Integer_8})
20084 to reference the entities directly in package @code{System}.
20085 For units containing such references,
20086 the prefixes must either be removed, or the pragma @code{Extend_System}
20089 @node Language-Related Features
20090 @section Language-Related Features
20093 The following sections highlight differences in types,
20094 representations of types, operations, alignment, and
20098 * Integer Types and Representations::
20099 * Floating-Point Types and Representations::
20100 * Pragmas Float_Representation and Long_Float::
20101 * Fixed-Point Types and Representations::
20102 * Record and Array Component Alignment::
20103 * Address Clauses::
20104 * Other Representation Clauses::
20107 @node Integer Types and Representations
20108 @subsection Integer Types and Representations
20111 The set of predefined integer types is identical in HP Ada and GNAT.
20112 Furthermore the representation of these integer types is also identical,
20113 including the capability of size clauses forcing biased representation.
20116 HP Ada for OpenVMS Alpha systems has defined the
20117 following additional integer types in package @code{System}:
20134 @code{LARGEST_INTEGER}
20138 In GNAT, the first four of these types may be obtained from the
20139 standard Ada package @code{Interfaces}.
20140 Alternatively, by use of the pragma @code{Extend_System}, identical
20141 declarations can be referenced directly in package @code{System}.
20142 On both GNAT and HP Ada, the maximum integer size is 64 bits.
20144 @node Floating-Point Types and Representations
20145 @subsection Floating-Point Types and Representations
20146 @cindex Floating-Point types
20149 The set of predefined floating-point types is identical in HP Ada and GNAT.
20150 Furthermore the representation of these floating-point
20151 types is also identical. One important difference is that the default
20152 representation for HP Ada is @code{VAX_Float}, but the default representation
20155 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
20156 pragma @code{Float_Representation} as described in the HP Ada
20158 For example, the declarations:
20160 @smallexample @c ada
20162 type F_Float is digits 6;
20163 pragma Float_Representation (VAX_Float, F_Float);
20168 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
20170 This set of declarations actually appears in @code{System.Aux_DEC},
20172 the full set of additional floating-point declarations provided in
20173 the HP Ada version of package @code{System}.
20174 This and similar declarations may be accessed in a user program
20175 by using pragma @code{Extend_System}. The use of this
20176 pragma, and the related pragma @code{Long_Float} is described in further
20177 detail in the following section.
20179 @node Pragmas Float_Representation and Long_Float
20180 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
20183 HP Ada provides the pragma @code{Float_Representation}, which
20184 acts as a program library switch to allow control over
20185 the internal representation chosen for the predefined
20186 floating-point types declared in the package @code{Standard}.
20187 The format of this pragma is as follows:
20189 @smallexample @c ada
20191 pragma Float_Representation(VAX_Float | IEEE_Float);
20196 This pragma controls the representation of floating-point
20201 @code{VAX_Float} specifies that floating-point
20202 types are represented by default with the VAX system hardware types
20203 @code{F-floating}, @code{D-floating}, @code{G-floating}.
20204 Note that the @code{H-floating}
20205 type was available only on VAX systems, and is not available
20206 in either HP Ada or GNAT.
20209 @code{IEEE_Float} specifies that floating-point
20210 types are represented by default with the IEEE single and
20211 double floating-point types.
20215 GNAT provides an identical implementation of the pragma
20216 @code{Float_Representation}, except that it functions as a
20217 configuration pragma. Note that the
20218 notion of configuration pragma corresponds closely to the
20219 HP Ada notion of a program library switch.
20221 When no pragma is used in GNAT, the default is @code{IEEE_Float},
20223 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
20224 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
20225 advisable to change the format of numbers passed to standard library
20226 routines, and if necessary explicit type conversions may be needed.
20228 The use of @code{IEEE_Float} is recommended in GNAT since it is more
20229 efficient, and (given that it conforms to an international standard)
20230 potentially more portable.
20231 The situation in which @code{VAX_Float} may be useful is in interfacing
20232 to existing code and data that expect the use of @code{VAX_Float}.
20233 In such a situation use the predefined @code{VAX_Float}
20234 types in package @code{System}, as extended by
20235 @code{Extend_System}. For example, use @code{System.F_Float}
20236 to specify the 32-bit @code{F-Float} format.
20239 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
20240 to allow control over the internal representation chosen
20241 for the predefined type @code{Long_Float} and for floating-point
20242 type declarations with digits specified in the range 7 .. 15.
20243 The format of this pragma is as follows:
20245 @smallexample @c ada
20247 pragma Long_Float (D_FLOAT | G_FLOAT);
20251 @node Fixed-Point Types and Representations
20252 @subsection Fixed-Point Types and Representations
20255 On HP Ada for OpenVMS Alpha systems, rounding is
20256 away from zero for both positive and negative numbers.
20257 Therefore, @code{+0.5} rounds to @code{1},
20258 and @code{-0.5} rounds to @code{-1}.
20260 On GNAT the results of operations
20261 on fixed-point types are in accordance with the Ada
20262 rules. In particular, results of operations on decimal
20263 fixed-point types are truncated.
20265 @node Record and Array Component Alignment
20266 @subsection Record and Array Component Alignment
20269 On HP Ada for OpenVMS Alpha, all non-composite components
20270 are aligned on natural boundaries. For example, 1-byte
20271 components are aligned on byte boundaries, 2-byte
20272 components on 2-byte boundaries, 4-byte components on 4-byte
20273 byte boundaries, and so on. The OpenVMS Alpha hardware
20274 runs more efficiently with naturally aligned data.
20276 On GNAT, alignment rules are compatible
20277 with HP Ada for OpenVMS Alpha.
20279 @node Address Clauses
20280 @subsection Address Clauses
20283 In HP Ada and GNAT, address clauses are supported for
20284 objects and imported subprograms.
20285 The predefined type @code{System.Address} is a private type
20286 in both compilers on Alpha OpenVMS, with the same representation
20287 (it is simply a machine pointer). Addition, subtraction, and comparison
20288 operations are available in the standard Ada package
20289 @code{System.Storage_Elements}, or in package @code{System}
20290 if it is extended to include @code{System.Aux_DEC} using a
20291 pragma @code{Extend_System} as previously described.
20293 Note that code that @code{with}'s both this extended package @code{System}
20294 and the package @code{System.Storage_Elements} should not @code{use}
20295 both packages, or ambiguities will result. In general it is better
20296 not to mix these two sets of facilities. The Ada package was
20297 designed specifically to provide the kind of features that HP Ada
20298 adds directly to package @code{System}.
20300 The type @code{System.Address} is a 64-bit integer type in GNAT for
20301 I64 OpenVMS. For more information,
20302 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
20304 GNAT is compatible with HP Ada in its handling of address
20305 clauses, except for some limitations in
20306 the form of address clauses for composite objects with
20307 initialization. Such address clauses are easily replaced
20308 by the use of an explicitly-defined constant as described
20309 in the Ada Reference Manual (13.1(22)). For example, the sequence
20312 @smallexample @c ada
20314 X, Y : Integer := Init_Func;
20315 Q : String (X .. Y) := "abc";
20317 for Q'Address use Compute_Address;
20322 will be rejected by GNAT, since the address cannot be computed at the time
20323 that @code{Q} is declared. To achieve the intended effect, write instead:
20325 @smallexample @c ada
20328 X, Y : Integer := Init_Func;
20329 Q_Address : constant Address := Compute_Address;
20330 Q : String (X .. Y) := "abc";
20332 for Q'Address use Q_Address;
20338 which will be accepted by GNAT (and other Ada compilers), and is also
20339 compatible with Ada 83. A fuller description of the restrictions
20340 on address specifications is found in @ref{Top, GNAT Reference Manual,
20341 About This Guide, gnat_rm, GNAT Reference Manual}.
20343 @node Other Representation Clauses
20344 @subsection Other Representation Clauses
20347 GNAT implements in a compatible manner all the representation
20348 clauses supported by HP Ada. In addition, GNAT
20349 implements the representation clause forms that were introduced in Ada 95,
20350 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
20352 @node The Package STANDARD
20353 @section The Package @code{STANDARD}
20356 The package @code{STANDARD}, as implemented by HP Ada, is fully
20357 described in the @cite{Ada Reference Manual} and in the
20358 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
20359 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
20361 In addition, HP Ada supports the Latin-1 character set in
20362 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
20363 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
20364 the type @code{WIDE_CHARACTER}.
20366 The floating-point types supported by GNAT are those
20367 supported by HP Ada, but the defaults are different, and are controlled by
20368 pragmas. See @ref{Floating-Point Types and Representations}, for details.
20370 @node The Package SYSTEM
20371 @section The Package @code{SYSTEM}
20374 HP Ada provides a specific version of the package
20375 @code{SYSTEM} for each platform on which the language is implemented.
20376 For the complete spec of the package @code{SYSTEM}, see
20377 Appendix F of the @cite{HP Ada Language Reference Manual}.
20379 On HP Ada, the package @code{SYSTEM} includes the following conversion
20382 @item @code{TO_ADDRESS(INTEGER)}
20384 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
20386 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
20388 @item @code{TO_INTEGER(ADDRESS)}
20390 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
20392 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
20393 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
20397 By default, GNAT supplies a version of @code{SYSTEM} that matches
20398 the definition given in the @cite{Ada Reference Manual}.
20400 is a subset of the HP system definitions, which is as
20401 close as possible to the original definitions. The only difference
20402 is that the definition of @code{SYSTEM_NAME} is different:
20404 @smallexample @c ada
20406 type Name is (SYSTEM_NAME_GNAT);
20407 System_Name : constant Name := SYSTEM_NAME_GNAT;
20412 Also, GNAT adds the Ada declarations for
20413 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
20415 However, the use of the following pragma causes GNAT
20416 to extend the definition of package @code{SYSTEM} so that it
20417 encompasses the full set of HP-specific extensions,
20418 including the functions listed above:
20420 @smallexample @c ada
20422 pragma Extend_System (Aux_DEC);
20427 The pragma @code{Extend_System} is a configuration pragma that
20428 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
20429 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
20431 HP Ada does not allow the recompilation of the package
20432 @code{SYSTEM}. Instead HP Ada provides several pragmas
20433 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
20434 to modify values in the package @code{SYSTEM}.
20435 On OpenVMS Alpha systems, the pragma
20436 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
20437 its single argument.
20439 GNAT does permit the recompilation of package @code{SYSTEM} using
20440 the special switch @option{-gnatg}, and this switch can be used if
20441 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
20442 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
20443 or @code{MEMORY_SIZE} by any other means.
20445 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
20446 enumeration literal @code{SYSTEM_NAME_GNAT}.
20448 The definitions provided by the use of
20450 @smallexample @c ada
20451 pragma Extend_System (AUX_Dec);
20455 are virtually identical to those provided by the HP Ada 83 package
20456 @code{SYSTEM}. One important difference is that the name of the
20458 function for type @code{UNSIGNED_LONGWORD} is changed to
20459 @code{TO_ADDRESS_LONG}.
20460 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
20461 discussion of why this change was necessary.
20464 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
20466 an extension to Ada 83 not strictly compatible with the reference manual.
20467 GNAT, in order to be exactly compatible with the standard,
20468 does not provide this capability. In HP Ada 83, the
20469 point of this definition is to deal with a call like:
20471 @smallexample @c ada
20472 TO_ADDRESS (16#12777#);
20476 Normally, according to Ada 83 semantics, one would expect this to be
20477 ambiguous, since it matches both the @code{INTEGER} and
20478 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
20479 However, in HP Ada 83, there is no ambiguity, since the
20480 definition using @i{universal_integer} takes precedence.
20482 In GNAT, since the version with @i{universal_integer} cannot be supplied,
20484 not possible to be 100% compatible. Since there are many programs using
20485 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
20487 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
20488 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
20490 @smallexample @c ada
20491 function To_Address (X : Integer) return Address;
20492 pragma Pure_Function (To_Address);
20494 function To_Address_Long (X : Unsigned_Longword) return Address;
20495 pragma Pure_Function (To_Address_Long);
20499 This means that programs using @code{TO_ADDRESS} for
20500 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
20502 @node Tasking and Task-Related Features
20503 @section Tasking and Task-Related Features
20506 This section compares the treatment of tasking in GNAT
20507 and in HP Ada for OpenVMS Alpha.
20508 The GNAT description applies to both Alpha and I64 OpenVMS.
20509 For detailed information on tasking in
20510 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
20511 relevant run-time reference manual.
20514 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
20515 * Assigning Task IDs::
20516 * Task IDs and Delays::
20517 * Task-Related Pragmas::
20518 * Scheduling and Task Priority::
20520 * External Interrupts::
20523 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20524 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20527 On OpenVMS Alpha systems, each Ada task (except a passive
20528 task) is implemented as a single stream of execution
20529 that is created and managed by the kernel. On these
20530 systems, HP Ada tasking support is based on DECthreads,
20531 an implementation of the POSIX standard for threads.
20533 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
20534 code that calls DECthreads routines can be used together.
20535 The interaction between Ada tasks and DECthreads routines
20536 can have some benefits. For example when on OpenVMS Alpha,
20537 HP Ada can call C code that is already threaded.
20539 GNAT uses the facilities of DECthreads,
20540 and Ada tasks are mapped to threads.
20542 @node Assigning Task IDs
20543 @subsection Assigning Task IDs
20546 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
20547 the environment task that executes the main program. On
20548 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
20549 that have been created but are not yet activated.
20551 On OpenVMS Alpha systems, task IDs are assigned at
20552 activation. On GNAT systems, task IDs are also assigned at
20553 task creation but do not have the same form or values as
20554 task ID values in HP Ada. There is no null task, and the
20555 environment task does not have a specific task ID value.
20557 @node Task IDs and Delays
20558 @subsection Task IDs and Delays
20561 On OpenVMS Alpha systems, tasking delays are implemented
20562 using Timer System Services. The Task ID is used for the
20563 identification of the timer request (the @code{REQIDT} parameter).
20564 If Timers are used in the application take care not to use
20565 @code{0} for the identification, because cancelling such a timer
20566 will cancel all timers and may lead to unpredictable results.
20568 @node Task-Related Pragmas
20569 @subsection Task-Related Pragmas
20572 Ada supplies the pragma @code{TASK_STORAGE}, which allows
20573 specification of the size of the guard area for a task
20574 stack. (The guard area forms an area of memory that has no
20575 read or write access and thus helps in the detection of
20576 stack overflow.) On OpenVMS Alpha systems, if the pragma
20577 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
20578 area is created. In the absence of a pragma @code{TASK_STORAGE},
20579 a default guard area is created.
20581 GNAT supplies the following task-related pragmas:
20584 @item @code{TASK_INFO}
20586 This pragma appears within a task definition and
20587 applies to the task in which it appears. The argument
20588 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
20590 @item @code{TASK_STORAGE}
20592 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
20593 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
20594 @code{SUPPRESS}, and @code{VOLATILE}.
20596 @node Scheduling and Task Priority
20597 @subsection Scheduling and Task Priority
20600 HP Ada implements the Ada language requirement that
20601 when two tasks are eligible for execution and they have
20602 different priorities, the lower priority task does not
20603 execute while the higher priority task is waiting. The HP
20604 Ada Run-Time Library keeps a task running until either the
20605 task is suspended or a higher priority task becomes ready.
20607 On OpenVMS Alpha systems, the default strategy is round-
20608 robin with preemption. Tasks of equal priority take turns
20609 at the processor. A task is run for a certain period of
20610 time and then placed at the tail of the ready queue for
20611 its priority level.
20613 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
20614 which can be used to enable or disable round-robin
20615 scheduling of tasks with the same priority.
20616 See the relevant HP Ada run-time reference manual for
20617 information on using the pragmas to control HP Ada task
20620 GNAT follows the scheduling rules of Annex D (Real-Time
20621 Annex) of the @cite{Ada Reference Manual}. In general, this
20622 scheduling strategy is fully compatible with HP Ada
20623 although it provides some additional constraints (as
20624 fully documented in Annex D).
20625 GNAT implements time slicing control in a manner compatible with
20626 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
20627 are identical to the HP Ada 83 pragma of the same name.
20628 Note that it is not possible to mix GNAT tasking and
20629 HP Ada 83 tasking in the same program, since the two run-time
20630 libraries are not compatible.
20632 @node The Task Stack
20633 @subsection The Task Stack
20636 In HP Ada, a task stack is allocated each time a
20637 non-passive task is activated. As soon as the task is
20638 terminated, the storage for the task stack is deallocated.
20639 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
20640 a default stack size is used. Also, regardless of the size
20641 specified, some additional space is allocated for task
20642 management purposes. On OpenVMS Alpha systems, at least
20643 one page is allocated.
20645 GNAT handles task stacks in a similar manner. In accordance with
20646 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
20647 an alternative method for controlling the task stack size.
20648 The specification of the attribute @code{T'STORAGE_SIZE} is also
20649 supported in a manner compatible with HP Ada.
20651 @node External Interrupts
20652 @subsection External Interrupts
20655 On HP Ada, external interrupts can be associated with task entries.
20656 GNAT is compatible with HP Ada in its handling of external interrupts.
20658 @node Pragmas and Pragma-Related Features
20659 @section Pragmas and Pragma-Related Features
20662 Both HP Ada and GNAT supply all language-defined pragmas
20663 as specified by the Ada 83 standard. GNAT also supplies all
20664 language-defined pragmas introduced by Ada 95 and Ada 2005.
20665 In addition, GNAT implements the implementation-defined pragmas
20669 @item @code{AST_ENTRY}
20671 @item @code{COMMON_OBJECT}
20673 @item @code{COMPONENT_ALIGNMENT}
20675 @item @code{EXPORT_EXCEPTION}
20677 @item @code{EXPORT_FUNCTION}
20679 @item @code{EXPORT_OBJECT}
20681 @item @code{EXPORT_PROCEDURE}
20683 @item @code{EXPORT_VALUED_PROCEDURE}
20685 @item @code{FLOAT_REPRESENTATION}
20689 @item @code{IMPORT_EXCEPTION}
20691 @item @code{IMPORT_FUNCTION}
20693 @item @code{IMPORT_OBJECT}
20695 @item @code{IMPORT_PROCEDURE}
20697 @item @code{IMPORT_VALUED_PROCEDURE}
20699 @item @code{INLINE_GENERIC}
20701 @item @code{INTERFACE_NAME}
20703 @item @code{LONG_FLOAT}
20705 @item @code{MAIN_STORAGE}
20707 @item @code{PASSIVE}
20709 @item @code{PSECT_OBJECT}
20711 @item @code{SHARE_GENERIC}
20713 @item @code{SUPPRESS_ALL}
20715 @item @code{TASK_STORAGE}
20717 @item @code{TIME_SLICE}
20723 These pragmas are all fully implemented, with the exception of @code{TITLE},
20724 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
20725 recognized, but which have no
20726 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
20727 use of Ada protected objects. In GNAT, all generics are inlined.
20729 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
20730 a separate subprogram specification which must appear before the
20733 GNAT also supplies a number of implementation-defined pragmas including the
20737 @item @code{ABORT_DEFER}
20739 @item @code{ADA_83}
20741 @item @code{ADA_95}
20743 @item @code{ADA_05}
20745 @item @code{Ada_2005}
20747 @item @code{Ada_12}
20749 @item @code{Ada_2012}
20751 @item @code{ANNOTATE}
20753 @item @code{ASSERT}
20755 @item @code{C_PASS_BY_COPY}
20757 @item @code{CPP_CLASS}
20759 @item @code{CPP_CONSTRUCTOR}
20761 @item @code{CPP_DESTRUCTOR}
20765 @item @code{EXTEND_SYSTEM}
20767 @item @code{LINKER_ALIAS}
20769 @item @code{LINKER_SECTION}
20771 @item @code{MACHINE_ATTRIBUTE}
20773 @item @code{NO_RETURN}
20775 @item @code{PURE_FUNCTION}
20777 @item @code{SOURCE_FILE_NAME}
20779 @item @code{SOURCE_REFERENCE}
20781 @item @code{TASK_INFO}
20783 @item @code{UNCHECKED_UNION}
20785 @item @code{UNIMPLEMENTED_UNIT}
20787 @item @code{UNIVERSAL_DATA}
20789 @item @code{UNSUPPRESS}
20791 @item @code{WARNINGS}
20793 @item @code{WEAK_EXTERNAL}
20797 For full details on these and other GNAT implementation-defined pragmas,
20798 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
20802 * Restrictions on the Pragma INLINE::
20803 * Restrictions on the Pragma INTERFACE::
20804 * Restrictions on the Pragma SYSTEM_NAME::
20807 @node Restrictions on the Pragma INLINE
20808 @subsection Restrictions on Pragma @code{INLINE}
20811 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
20813 @item Parameters cannot have a task type.
20815 @item Function results cannot be task types, unconstrained
20816 array types, or unconstrained types with discriminants.
20818 @item Bodies cannot declare the following:
20820 @item Subprogram body or stub (imported subprogram is allowed)
20824 @item Generic declarations
20826 @item Instantiations
20830 @item Access types (types derived from access types allowed)
20832 @item Array or record types
20834 @item Dependent tasks
20836 @item Direct recursive calls of subprogram or containing
20837 subprogram, directly or via a renaming
20843 In GNAT, the only restriction on pragma @code{INLINE} is that the
20844 body must occur before the call if both are in the same
20845 unit, and the size must be appropriately small. There are
20846 no other specific restrictions which cause subprograms to
20847 be incapable of being inlined.
20849 @node Restrictions on the Pragma INTERFACE
20850 @subsection Restrictions on Pragma @code{INTERFACE}
20853 The following restrictions on pragma @code{INTERFACE}
20854 are enforced by both HP Ada and GNAT:
20856 @item Languages accepted: Ada, Bliss, C, Fortran, Default.
20857 Default is the default on OpenVMS Alpha systems.
20859 @item Parameter passing: Language specifies default
20860 mechanisms but can be overridden with an @code{EXPORT} pragma.
20863 @item Ada: Use internal Ada rules.
20865 @item Bliss, C: Parameters must be mode @code{in}; cannot be
20866 record or task type. Result cannot be a string, an
20867 array, or a record.
20869 @item Fortran: Parameters cannot have a task type. Result cannot
20870 be a string, an array, or a record.
20875 GNAT is entirely upwards compatible with HP Ada, and in addition allows
20876 record parameters for all languages.
20878 @node Restrictions on the Pragma SYSTEM_NAME
20879 @subsection Restrictions on Pragma @code{SYSTEM_NAME}
20882 For HP Ada for OpenVMS Alpha, the enumeration literal
20883 for the type @code{NAME} is @code{OPENVMS_AXP}.
20884 In GNAT, the enumeration
20885 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
20887 @node Library of Predefined Units
20888 @section Library of Predefined Units
20891 A library of predefined units is provided as part of the
20892 HP Ada and GNAT implementations. HP Ada does not provide
20893 the package @code{MACHINE_CODE} but instead recommends importing
20896 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
20897 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
20899 The HP Ada Predefined Library units are modified to remove post-Ada 83
20900 incompatibilities and to make them interoperable with GNAT
20901 (@pxref{Changes to DECLIB}, for details).
20902 The units are located in the @file{DECLIB} directory.
20904 The GNAT RTL is contained in
20905 the @file{ADALIB} directory, and
20906 the default search path is set up to find @code{DECLIB} units in preference
20907 to @code{ADALIB} units with the same name (@code{TEXT_IO},
20908 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
20911 * Changes to DECLIB::
20914 @node Changes to DECLIB
20915 @subsection Changes to @code{DECLIB}
20918 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
20919 compatibility are minor and include the following:
20922 @item Adjusting the location of pragmas and record representation
20923 clauses to obey Ada 95 (and thus Ada 2005) rules
20925 @item Adding the proper notation to generic formal parameters
20926 that take unconstrained types in instantiation
20928 @item Adding pragma @code{ELABORATE_BODY} to package specs
20929 that have package bodies not otherwise allowed
20931 @item Replacing occurrences of the identifier ``@code{PROTECTED}'' by
20932 ``@code{PROTECTD}''.
20933 Currently these are found only in the @code{STARLET} package spec.
20935 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
20936 where the address size is constrained to 32 bits.
20940 None of the above changes is visible to users.
20946 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
20949 @item Command Language Interpreter (CLI interface)
20951 @item DECtalk Run-Time Library (DTK interface)
20953 @item Librarian utility routines (LBR interface)
20955 @item General Purpose Run-Time Library (LIB interface)
20957 @item Math Run-Time Library (MTH interface)
20959 @item National Character Set Run-Time Library (NCS interface)
20961 @item Compiled Code Support Run-Time Library (OTS interface)
20963 @item Parallel Processing Run-Time Library (PPL interface)
20965 @item Screen Management Run-Time Library (SMG interface)
20967 @item Sort Run-Time Library (SOR interface)
20969 @item String Run-Time Library (STR interface)
20971 @item STARLET System Library
20974 @item X Window System Version 11R4 and 11R5 (X, XLIB interface)
20976 @item X Windows Toolkit (XT interface)
20978 @item X/Motif Version 1.1.3 and 1.2 (XM interface)
20982 GNAT provides implementations of these HP bindings in the @code{DECLIB}
20983 directory, on both the Alpha and I64 OpenVMS platforms.
20985 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
20987 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
20988 A pragma @code{Linker_Options} has been added to packages @code{Xm},
20989 @code{Xt}, and @code{X_Lib}
20990 causing the default X/Motif sharable image libraries to be linked in. This
20991 is done via options files named @file{xm.opt}, @file{xt.opt}, and
20992 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
20994 It may be necessary to edit these options files to update or correct the
20995 library names if, for example, the newer X/Motif bindings from
20996 @file{ADA$EXAMPLES}
20997 had been (previous to installing GNAT) copied and renamed to supersede the
20998 default @file{ADA$PREDEFINED} versions.
21001 * Shared Libraries and Options Files::
21002 * Interfaces to C::
21005 @node Shared Libraries and Options Files
21006 @subsection Shared Libraries and Options Files
21009 When using the HP Ada
21010 predefined X and Motif bindings, the linking with their sharable images is
21011 done automatically by @command{GNAT LINK}.
21012 When using other X and Motif bindings, you need
21013 to add the corresponding sharable images to the command line for
21014 @code{GNAT LINK}. When linking with shared libraries, or with
21015 @file{.OPT} files, you must
21016 also add them to the command line for @command{GNAT LINK}.
21018 A shared library to be used with GNAT is built in the same way as other
21019 libraries under VMS. The VMS Link command can be used in standard fashion.
21021 @node Interfaces to C
21022 @subsection Interfaces to C
21026 provides the following Ada types and operations:
21029 @item C types package (@code{C_TYPES})
21031 @item C strings (@code{C_TYPES.NULL_TERMINATED})
21033 @item Other_types (@code{SHORT_INT})
21037 Interfacing to C with GNAT, you can use the above approach
21038 described for HP Ada or the facilities of Annex B of
21039 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
21040 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
21041 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
21043 The @option{-gnatF} qualifier forces default and explicit
21044 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
21045 to be uppercased for compatibility with the default behavior
21046 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
21048 @node Main Program Definition
21049 @section Main Program Definition
21052 The following section discusses differences in the
21053 definition of main programs on HP Ada and GNAT.
21054 On HP Ada, main programs are defined to meet the
21055 following conditions:
21057 @item Procedure with no formal parameters (returns @code{0} upon
21060 @item Procedure with no formal parameters (returns @code{42} when
21061 an unhandled exception is raised)
21063 @item Function with no formal parameters whose returned value
21064 is of a discrete type
21066 @item Procedure with one @code{out} formal of a discrete type for
21067 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
21072 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
21073 a main function or main procedure returns a discrete
21074 value whose size is less than 64 bits (32 on VAX systems),
21075 the value is zero- or sign-extended as appropriate.
21076 On GNAT, main programs are defined as follows:
21078 @item Must be a non-generic, parameterless subprogram that
21079 is either a procedure or function returning an Ada
21080 @code{STANDARD.INTEGER} (the predefined type)
21082 @item Cannot be a generic subprogram or an instantiation of a
21086 @node Implementation-Defined Attributes
21087 @section Implementation-Defined Attributes
21090 GNAT provides all HP Ada implementation-defined
21093 @node Compiler and Run-Time Interfacing
21094 @section Compiler and Run-Time Interfacing
21097 HP Ada provides the following qualifiers to pass options to the linker
21100 @item @option{/WAIT} and @option{/SUBMIT}
21102 @item @option{/COMMAND}
21104 @item @option{/@r{[}NO@r{]}MAP}
21106 @item @option{/OUTPUT=@var{file-spec}}
21108 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21112 To pass options to the linker, GNAT provides the following
21116 @item @option{/EXECUTABLE=@var{exec-name}}
21118 @item @option{/VERBOSE}
21120 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21124 For more information on these switches, see
21125 @ref{Switches for gnatlink}.
21126 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
21127 to control optimization. HP Ada also supplies the
21130 @item @code{OPTIMIZE}
21132 @item @code{INLINE}
21134 @item @code{INLINE_GENERIC}
21136 @item @code{SUPPRESS_ALL}
21138 @item @code{PASSIVE}
21142 In GNAT, optimization is controlled strictly by command
21143 line parameters, as described in the corresponding section of this guide.
21144 The HP pragmas for control of optimization are
21145 recognized but ignored.
21147 Note that in GNAT, the default is optimization off, whereas in HP Ada
21148 the default is that optimization is turned on.
21150 @node Program Compilation and Library Management
21151 @section Program Compilation and Library Management
21154 HP Ada and GNAT provide a comparable set of commands to
21155 build programs. HP Ada also provides a program library,
21156 which is a concept that does not exist on GNAT. Instead,
21157 GNAT provides directories of sources that are compiled as
21160 The following table summarizes
21161 the HP Ada commands and provides
21162 equivalent GNAT commands. In this table, some GNAT
21163 equivalents reflect the fact that GNAT does not use the
21164 concept of a program library. Instead, it uses a model
21165 in which collections of source and object files are used
21166 in a manner consistent with other languages like C and
21167 Fortran. Therefore, standard system file commands are used
21168 to manipulate these elements. Those GNAT commands are marked with
21170 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
21173 @multitable @columnfractions .35 .65
21175 @item @emph{HP Ada Command}
21176 @tab @emph{GNAT Equivalent / Description}
21178 @item @command{ADA}
21179 @tab @command{GNAT COMPILE}@*
21180 Invokes the compiler to compile one or more Ada source files.
21182 @item @command{ACS ATTACH}@*
21183 @tab [No equivalent]@*
21184 Switches control of terminal from current process running the program
21187 @item @command{ACS CHECK}
21188 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
21189 Forms the execution closure of one
21190 or more compiled units and checks completeness and currency.
21192 @item @command{ACS COMPILE}
21193 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21194 Forms the execution closure of one or
21195 more specified units, checks completeness and currency,
21196 identifies units that have revised source files, compiles same,
21197 and recompiles units that are or will become obsolete.
21198 Also completes incomplete generic instantiations.
21200 @item @command{ACS COPY FOREIGN}
21202 Copies a foreign object file into the program library as a
21205 @item @command{ACS COPY UNIT}
21207 Copies a compiled unit from one program library to another.
21209 @item @command{ACS CREATE LIBRARY}
21210 @tab Create /directory (*)@*
21211 Creates a program library.
21213 @item @command{ACS CREATE SUBLIBRARY}
21214 @tab Create /directory (*)@*
21215 Creates a program sublibrary.
21217 @item @command{ACS DELETE LIBRARY}
21219 Deletes a program library and its contents.
21221 @item @command{ACS DELETE SUBLIBRARY}
21223 Deletes a program sublibrary and its contents.
21225 @item @command{ACS DELETE UNIT}
21226 @tab Delete file (*)@*
21227 On OpenVMS systems, deletes one or more compiled units from
21228 the current program library.
21230 @item @command{ACS DIRECTORY}
21231 @tab Directory (*)@*
21232 On OpenVMS systems, lists units contained in the current
21235 @item @command{ACS ENTER FOREIGN}
21237 Allows the import of a foreign body as an Ada library
21238 spec and enters a reference to a pointer.
21240 @item @command{ACS ENTER UNIT}
21242 Enters a reference (pointer) from the current program library to
21243 a unit compiled into another program library.
21245 @item @command{ACS EXIT}
21246 @tab [No equivalent]@*
21247 Exits from the program library manager.
21249 @item @command{ACS EXPORT}
21251 Creates an object file that contains system-specific object code
21252 for one or more units. With GNAT, object files can simply be copied
21253 into the desired directory.
21255 @item @command{ACS EXTRACT SOURCE}
21257 Allows access to the copied source file for each Ada compilation unit
21259 @item @command{ACS HELP}
21260 @tab @command{HELP GNAT}@*
21261 Provides online help.
21263 @item @command{ACS LINK}
21264 @tab @command{GNAT LINK}@*
21265 Links an object file containing Ada units into an executable file.
21267 @item @command{ACS LOAD}
21269 Loads (partially compiles) Ada units into the program library.
21270 Allows loading a program from a collection of files into a library
21271 without knowing the relationship among units.
21273 @item @command{ACS MERGE}
21275 Merges into the current program library, one or more units from
21276 another library where they were modified.
21278 @item @command{ACS RECOMPILE}
21279 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21280 Recompiles from external or copied source files any obsolete
21281 unit in the closure. Also, completes any incomplete generic
21284 @item @command{ACS REENTER}
21285 @tab @command{GNAT MAKE}@*
21286 Reenters current references to units compiled after last entered
21287 with the @command{ACS ENTER UNIT} command.
21289 @item @command{ACS SET LIBRARY}
21290 @tab Set default (*)@*
21291 Defines a program library to be the compilation context as well
21292 as the target library for compiler output and commands in general.
21294 @item @command{ACS SET PRAGMA}
21295 @tab Edit @file{gnat.adc} (*)@*
21296 Redefines specified values of the library characteristics
21297 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
21298 and @code{Float_Representation}.
21300 @item @command{ACS SET SOURCE}
21301 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
21302 Defines the source file search list for the @command{ACS COMPILE} command.
21304 @item @command{ACS SHOW LIBRARY}
21305 @tab Directory (*)@*
21306 Lists information about one or more program libraries.
21308 @item @command{ACS SHOW PROGRAM}
21309 @tab [No equivalent]@*
21310 Lists information about the execution closure of one or
21311 more units in the program library.
21313 @item @command{ACS SHOW SOURCE}
21314 @tab Show logical @code{ADA_INCLUDE_PATH}@*
21315 Shows the source file search used when compiling units.
21317 @item @command{ACS SHOW VERSION}
21318 @tab Compile with @option{VERBOSE} option
21319 Displays the version number of the compiler and program library
21322 @item @command{ACS SPAWN}
21323 @tab [No equivalent]@*
21324 Creates a subprocess of the current process (same as @command{DCL SPAWN}
21327 @item @command{ACS VERIFY}
21328 @tab [No equivalent]@*
21329 Performs a series of consistency checks on a program library to
21330 determine whether the library structure and library files are in
21337 @section Input-Output
21340 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
21341 Management Services (RMS) to perform operations on
21345 HP Ada and GNAT predefine an identical set of input-
21346 output packages. To make the use of the
21347 generic @code{TEXT_IO} operations more convenient, HP Ada
21348 provides predefined library packages that instantiate the
21349 integer and floating-point operations for the predefined
21350 integer and floating-point types as shown in the following table.
21352 @multitable @columnfractions .45 .55
21353 @item @emph{Package Name} @tab Instantiation
21355 @item @code{INTEGER_TEXT_IO}
21356 @tab @code{INTEGER_IO(INTEGER)}
21358 @item @code{SHORT_INTEGER_TEXT_IO}
21359 @tab @code{INTEGER_IO(SHORT_INTEGER)}
21361 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
21362 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
21364 @item @code{FLOAT_TEXT_IO}
21365 @tab @code{FLOAT_IO(FLOAT)}
21367 @item @code{LONG_FLOAT_TEXT_IO}
21368 @tab @code{FLOAT_IO(LONG_FLOAT)}
21372 The HP Ada predefined packages and their operations
21373 are implemented using OpenVMS Alpha files and input-output
21374 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
21375 Familiarity with the following is recommended:
21377 @item RMS file organizations and access methods
21379 @item OpenVMS file specifications and directories
21381 @item OpenVMS File Definition Language (FDL)
21385 GNAT provides I/O facilities that are completely
21386 compatible with HP Ada. The distribution includes the
21387 standard HP Ada versions of all I/O packages, operating
21388 in a manner compatible with HP Ada. In particular, the
21389 following packages are by default the HP Ada (Ada 83)
21390 versions of these packages rather than the renamings
21391 suggested in Annex J of the Ada Reference Manual:
21393 @item @code{TEXT_IO}
21395 @item @code{SEQUENTIAL_IO}
21397 @item @code{DIRECT_IO}
21401 The use of the standard child package syntax (for
21402 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
21404 GNAT provides HP-compatible predefined instantiations
21405 of the @code{TEXT_IO} packages, and also
21406 provides the standard predefined instantiations required
21407 by the @cite{Ada Reference Manual}.
21409 For further information on how GNAT interfaces to the file
21410 system or how I/O is implemented in programs written in
21411 mixed languages, see @ref{Implementation of the Standard I/O,,,
21412 gnat_rm, GNAT Reference Manual}.
21413 This chapter covers the following:
21415 @item Standard I/O packages
21417 @item @code{FORM} strings
21419 @item @code{ADA.DIRECT_IO}
21421 @item @code{ADA.SEQUENTIAL_IO}
21423 @item @code{ADA.TEXT_IO}
21425 @item Stream pointer positioning
21427 @item Reading and writing non-regular files
21429 @item @code{GET_IMMEDIATE}
21431 @item Treating @code{TEXT_IO} files as streams
21438 @node Implementation Limits
21439 @section Implementation Limits
21442 The following table lists implementation limits for HP Ada
21444 @multitable @columnfractions .60 .20 .20
21446 @item @emph{Compilation Parameter}
21451 @item In a subprogram or entry declaration, maximum number of
21452 formal parameters that are of an unconstrained record type
21457 @item Maximum identifier length (number of characters)
21462 @item Maximum number of characters in a source line
21467 @item Maximum collection size (number of bytes)
21472 @item Maximum number of discriminants for a record type
21477 @item Maximum number of formal parameters in an entry or
21478 subprogram declaration
21483 @item Maximum number of dimensions in an array type
21488 @item Maximum number of library units and subunits in a compilation.
21493 @item Maximum number of library units and subunits in an execution.
21498 @item Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
21499 or @code{PSECT_OBJECT}
21504 @item Maximum number of enumeration literals in an enumeration type
21510 @item Maximum number of lines in a source file
21515 @item Maximum number of bits in any object
21520 @item Maximum size of the static portion of a stack frame (approximate)
21525 @node Tools and Utilities
21526 @section Tools and Utilities
21529 The following table lists some of the OpenVMS development tools
21530 available for HP Ada, and the corresponding tools for
21531 use with @value{EDITION} on Alpha and I64 platforms.
21532 Aside from the debugger, all the OpenVMS tools identified are part
21533 of the DECset package.
21536 @c Specify table in TeX since Texinfo does a poor job
21540 \settabs\+Language-Sensitive Editor\quad
21541 &Product with HP Ada\quad
21544 &\it Product with HP Ada
21545 & \it Product with GNAT Pro\cr
21547 \+Code Management System
21551 \+Language-Sensitive Editor
21553 & emacs or HP LSE (Alpha)\cr
21563 & OpenVMS Debug (I64)\cr
21565 \+Source Code Analyzer /
21582 \+Coverage Analyzer
21586 \+Module Management
21588 & Not applicable\cr
21598 @c This is the Texinfo version of the table. It renders poorly in pdf, hence
21599 @c the TeX version above for the printed version
21601 @c @multitable @columnfractions .3 .4 .4
21602 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
21604 @tab @i{Tool with HP Ada}
21605 @tab @i{Tool with @value{EDITION}}
21606 @item Code Management@*System
21609 @item Language-Sensitive@*Editor
21611 @tab emacs or HP LSE (Alpha)
21620 @tab OpenVMS Debug (I64)
21621 @item Source Code Analyzer /@*Cross Referencer
21625 @tab HP Digital Test@*Manager (DTM)
21627 @item Performance and@*Coverage Analyzer
21630 @item Module Management@*System
21632 @tab Not applicable
21639 @c **************************************
21640 @node Platform-Specific Information for the Run-Time Libraries
21641 @appendix Platform-Specific Information for the Run-Time Libraries
21642 @cindex Tasking and threads libraries
21643 @cindex Threads libraries and tasking
21644 @cindex Run-time libraries (platform-specific information)
21647 The GNAT run-time implementation may vary with respect to both the
21648 underlying threads library and the exception handling scheme.
21649 For threads support, one or more of the following are supplied:
21651 @item @b{native threads library}, a binding to the thread package from
21652 the underlying operating system
21654 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
21655 POSIX thread package
21659 For exception handling, either or both of two models are supplied:
21661 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
21662 Most programs should experience a substantial speed improvement by
21663 being compiled with a ZCX run-time.
21664 This is especially true for
21665 tasking applications or applications with many exception handlers.}
21666 @cindex Zero-Cost Exceptions
21667 @cindex ZCX (Zero-Cost Exceptions)
21668 which uses binder-generated tables that
21669 are interrogated at run time to locate a handler
21671 @item @b{setjmp / longjmp} (``SJLJ''),
21672 @cindex setjmp/longjmp Exception Model
21673 @cindex SJLJ (setjmp/longjmp Exception Model)
21674 which uses dynamically-set data to establish
21675 the set of handlers
21679 This appendix summarizes which combinations of threads and exception support
21680 are supplied on various GNAT platforms.
21681 It then shows how to select a particular library either
21682 permanently or temporarily,
21683 explains the properties of (and tradeoffs among) the various threads
21684 libraries, and provides some additional
21685 information about several specific platforms.
21688 * Summary of Run-Time Configurations::
21689 * Specifying a Run-Time Library::
21690 * Choosing the Scheduling Policy::
21691 * Solaris-Specific Considerations::
21692 * Linux-Specific Considerations::
21693 * AIX-Specific Considerations::
21694 * Irix-Specific Considerations::
21695 * RTX-Specific Considerations::
21696 * HP-UX-Specific Considerations::
21699 @node Summary of Run-Time Configurations
21700 @section Summary of Run-Time Configurations
21702 @multitable @columnfractions .30 .70
21703 @item @b{alpha-openvms}
21704 @item @code{@ @ }@i{rts-native (default)}
21705 @item @code{@ @ @ @ }Tasking @tab native VMS threads
21706 @item @code{@ @ @ @ }Exceptions @tab ZCX
21708 @item @b{alpha-tru64}
21709 @item @code{@ @ }@i{rts-native (default)}
21710 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
21711 @item @code{@ @ @ @ }Exceptions @tab ZCX
21713 @item @code{@ @ }@i{rts-sjlj}
21714 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
21715 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21717 @item @b{ia64-hp_linux}
21718 @item @code{@ @ }@i{rts-native (default)}
21719 @item @code{@ @ @ @ }Tasking @tab pthread library
21720 @item @code{@ @ @ @ }Exceptions @tab ZCX
21722 @item @b{ia64-hpux}
21723 @item @code{@ @ }@i{rts-native (default)}
21724 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
21725 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21727 @item @b{ia64-openvms}
21728 @item @code{@ @ }@i{rts-native (default)}
21729 @item @code{@ @ @ @ }Tasking @tab native VMS threads
21730 @item @code{@ @ @ @ }Exceptions @tab ZCX
21732 @item @b{ia64-sgi_linux}
21733 @item @code{@ @ }@i{rts-native (default)}
21734 @item @code{@ @ @ @ }Tasking @tab pthread library
21735 @item @code{@ @ @ @ }Exceptions @tab ZCX
21737 @item @b{mips-irix}
21738 @item @code{@ @ }@i{rts-native (default)}
21739 @item @code{@ @ @ @ }Tasking @tab native IRIX threads
21740 @item @code{@ @ @ @ }Exceptions @tab ZCX
21743 @item @code{@ @ }@i{rts-native (default)}
21744 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
21745 @item @code{@ @ @ @ }Exceptions @tab ZCX
21747 @item @code{@ @ }@i{rts-sjlj}
21748 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
21749 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21752 @item @code{@ @ }@i{rts-native (default)}
21753 @item @code{@ @ @ @ }Tasking @tab native AIX threads
21754 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21756 @item @b{ppc-darwin}
21757 @item @code{@ @ }@i{rts-native (default)}
21758 @item @code{@ @ @ @ }Tasking @tab native MacOS threads
21759 @item @code{@ @ @ @ }Exceptions @tab ZCX
21761 @item @b{sparc-solaris} @tab
21762 @item @code{@ @ }@i{rts-native (default)}
21763 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
21764 @item @code{@ @ @ @ }Exceptions @tab ZCX
21766 @item @code{@ @ }@i{rts-pthread}
21767 @item @code{@ @ @ @ }Tasking @tab pthread library
21768 @item @code{@ @ @ @ }Exceptions @tab ZCX
21770 @item @code{@ @ }@i{rts-sjlj}
21771 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
21772 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21774 @item @b{sparc64-solaris} @tab
21775 @item @code{@ @ }@i{rts-native (default)}
21776 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
21777 @item @code{@ @ @ @ }Exceptions @tab ZCX
21779 @item @b{x86-linux}
21780 @item @code{@ @ }@i{rts-native (default)}
21781 @item @code{@ @ @ @ }Tasking @tab pthread library
21782 @item @code{@ @ @ @ }Exceptions @tab ZCX
21784 @item @code{@ @ }@i{rts-sjlj}
21785 @item @code{@ @ @ @ }Tasking @tab pthread library
21786 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21789 @item @code{@ @ }@i{rts-native (default)}
21790 @item @code{@ @ @ @ }Tasking @tab native LynxOS threads
21791 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21793 @item @b{x86-solaris}
21794 @item @code{@ @ }@i{rts-native (default)}
21795 @item @code{@ @ @ @ }Tasking @tab native Solaris threads
21796 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21798 @item @b{x86-windows}
21799 @item @code{@ @ }@i{rts-native (default)}
21800 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
21801 @item @code{@ @ @ @ }Exceptions @tab ZCX
21803 @item @code{@ @ }@i{rts-sjlj (default)}
21804 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
21805 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21807 @item @b{x86-windows-rtx}
21808 @item @code{@ @ }@i{rts-rtx-rtss (default)}
21809 @item @code{@ @ @ @ }Tasking @tab RTX real-time subsystem RTSS threads (kernel mode)
21810 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21812 @item @code{@ @ }@i{rts-rtx-w32}
21813 @item @code{@ @ @ @ }Tasking @tab RTX Win32 threads (user mode)
21814 @item @code{@ @ @ @ }Exceptions @tab ZCX
21816 @item @b{x86_64-linux}
21817 @item @code{@ @ }@i{rts-native (default)}
21818 @item @code{@ @ @ @ }Tasking @tab pthread library
21819 @item @code{@ @ @ @ }Exceptions @tab ZCX
21821 @item @code{@ @ }@i{rts-sjlj}
21822 @item @code{@ @ @ @ }Tasking @tab pthread library
21823 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21827 @node Specifying a Run-Time Library
21828 @section Specifying a Run-Time Library
21831 The @file{adainclude} subdirectory containing the sources of the GNAT
21832 run-time library, and the @file{adalib} subdirectory containing the
21833 @file{ALI} files and the static and/or shared GNAT library, are located
21834 in the gcc target-dependent area:
21837 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
21841 As indicated above, on some platforms several run-time libraries are supplied.
21842 These libraries are installed in the target dependent area and
21843 contain a complete source and binary subdirectory. The detailed description
21844 below explains the differences between the different libraries in terms of
21845 their thread support.
21847 The default run-time library (when GNAT is installed) is @emph{rts-native}.
21848 This default run time is selected by the means of soft links.
21849 For example on x86-linux:
21855 +--- adainclude----------+
21857 +--- adalib-----------+ |
21859 +--- rts-native | |
21861 | +--- adainclude <---+
21863 | +--- adalib <----+
21874 If the @i{rts-sjlj} library is to be selected on a permanent basis,
21875 these soft links can be modified with the following commands:
21879 $ rm -f adainclude adalib
21880 $ ln -s rts-sjlj/adainclude adainclude
21881 $ ln -s rts-sjlj/adalib adalib
21885 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
21886 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
21887 @file{$target/ada_object_path}.
21889 Selecting another run-time library temporarily can be
21890 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
21891 @cindex @option{--RTS} option
21893 @node Choosing the Scheduling Policy
21894 @section Choosing the Scheduling Policy
21897 When using a POSIX threads implementation, you have a choice of several
21898 scheduling policies: @code{SCHED_FIFO},
21899 @cindex @code{SCHED_FIFO} scheduling policy
21901 @cindex @code{SCHED_RR} scheduling policy
21902 and @code{SCHED_OTHER}.
21903 @cindex @code{SCHED_OTHER} scheduling policy
21904 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
21905 or @code{SCHED_RR} requires special (e.g., root) privileges.
21907 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
21909 @cindex @code{SCHED_FIFO} scheduling policy
21910 you can use one of the following:
21914 @code{pragma Time_Slice (0.0)}
21915 @cindex pragma Time_Slice
21917 the corresponding binder option @option{-T0}
21918 @cindex @option{-T0} option
21920 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21921 @cindex pragma Task_Dispatching_Policy
21925 To specify @code{SCHED_RR},
21926 @cindex @code{SCHED_RR} scheduling policy
21927 you should use @code{pragma Time_Slice} with a
21928 value greater than @code{0.0}, or else use the corresponding @option{-T}
21931 @node Solaris-Specific Considerations
21932 @section Solaris-Specific Considerations
21933 @cindex Solaris Sparc threads libraries
21936 This section addresses some topics related to the various threads libraries
21940 * Solaris Threads Issues::
21943 @node Solaris Threads Issues
21944 @subsection Solaris Threads Issues
21947 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
21948 library based on POSIX threads --- @emph{rts-pthread}.
21949 @cindex rts-pthread threads library
21950 This run-time library has the advantage of being mostly shared across all
21951 POSIX-compliant thread implementations, and it also provides under
21952 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
21953 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
21954 and @code{PTHREAD_PRIO_PROTECT}
21955 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
21956 semantics that can be selected using the predefined pragma
21957 @code{Locking_Policy}
21958 @cindex pragma Locking_Policy (under rts-pthread)
21960 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
21961 @cindex @code{Inheritance_Locking} (under rts-pthread)
21962 @cindex @code{Ceiling_Locking} (under rts-pthread)
21964 As explained above, the native run-time library is based on the Solaris thread
21965 library (@code{libthread}) and is the default library.
21967 When the Solaris threads library is used (this is the default), programs
21968 compiled with GNAT can automatically take advantage of
21969 and can thus execute on multiple processors.
21970 The user can alternatively specify a processor on which the program should run
21971 to emulate a single-processor system. The multiprocessor / uniprocessor choice
21973 setting the environment variable @env{GNAT_PROCESSOR}
21974 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
21975 to one of the following:
21979 Use the default configuration (run the program on all
21980 available processors) - this is the same as having @code{GNAT_PROCESSOR}
21984 Let the run-time implementation choose one processor and run the program on
21987 @item 0 .. Last_Proc
21988 Run the program on the specified processor.
21989 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
21990 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
21993 @node Linux-Specific Considerations
21994 @section Linux-Specific Considerations
21995 @cindex Linux threads libraries
21998 On GNU/Linux without NPTL support (usually system with GNU C Library
21999 older than 2.3), the signal model is not POSIX compliant, which means
22000 that to send a signal to the process, you need to send the signal to all
22001 threads, e.g.@: by using @code{killpg()}.
22003 @node AIX-Specific Considerations
22004 @section AIX-Specific Considerations
22005 @cindex AIX resolver library
22008 On AIX, the resolver library initializes some internal structure on
22009 the first call to @code{get*by*} functions, which are used to implement
22010 @code{GNAT.Sockets.Get_Host_By_Name} and
22011 @code{GNAT.Sockets.Get_Host_By_Address}.
22012 If such initialization occurs within an Ada task, and the stack size for
22013 the task is the default size, a stack overflow may occur.
22015 To avoid this overflow, the user should either ensure that the first call
22016 to @code{GNAT.Sockets.Get_Host_By_Name} or
22017 @code{GNAT.Sockets.Get_Host_By_Addrss}
22018 occurs in the environment task, or use @code{pragma Storage_Size} to
22019 specify a sufficiently large size for the stack of the task that contains
22022 @node Irix-Specific Considerations
22023 @section Irix-Specific Considerations
22024 @cindex Irix libraries
22027 The GCC support libraries coming with the Irix compiler have moved to
22028 their canonical place with respect to the general Irix ABI related
22029 conventions. Running applications built with the default shared GNAT
22030 run-time now requires the LD_LIBRARY_PATH environment variable to
22031 include this location. A possible way to achieve this is to issue the
22032 following command line on a bash prompt:
22036 $ LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
22040 @node RTX-Specific Considerations
22041 @section RTX-Specific Considerations
22042 @cindex RTX libraries
22045 The Real-time Extension (RTX) to Windows is based on the Windows Win32
22046 API. Applications can be built to work in two different modes:
22050 Windows executables that run in Ring 3 to utilize memory protection
22051 (@emph{rts-rtx-w32}).
22054 Real-time subsystem (RTSS) executables that run in Ring 0, where
22055 performance can be optimized with RTSS applications taking precedent
22056 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
22057 the Microsoft linker to handle RTSS libraries.
22061 @node HP-UX-Specific Considerations
22062 @section HP-UX-Specific Considerations
22063 @cindex HP-UX Scheduling
22066 On HP-UX, appropriate privileges are required to change the scheduling
22067 parameters of a task. The calling process must have appropriate
22068 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
22069 successfully change the scheduling parameters.
22071 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
22072 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
22073 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
22075 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
22076 one of the following:
22080 @code{pragma Time_Slice (0.0)}
22081 @cindex pragma Time_Slice
22083 the corresponding binder option @option{-T0}
22084 @cindex @option{-T0} option
22086 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22087 @cindex pragma Task_Dispatching_Policy
22091 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
22092 you should use @code{pragma Time_Slice} with a
22093 value greater than @code{0.0}, or use the corresponding @option{-T}
22094 binder option, or set the @code{pragma Task_Dispatching_Policy
22095 (Round_Robin_Within_Priorities)}.
22097 @c *******************************
22098 @node Example of Binder Output File
22099 @appendix Example of Binder Output File
22102 This Appendix displays the source code for @command{gnatbind}'s output
22103 file generated for a simple ``Hello World'' program.
22104 Comments have been added for clarification purposes.
22106 @smallexample @c adanocomment
22110 -- The package is called Ada_Main unless this name is actually used
22111 -- as a unit name in the partition, in which case some other unique
22115 package ada_main is
22117 Elab_Final_Code : Integer;
22118 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
22120 -- The main program saves the parameters (argument count,
22121 -- argument values, environment pointer) in global variables
22122 -- for later access by other units including
22123 -- Ada.Command_Line.
22125 gnat_argc : Integer;
22126 gnat_argv : System.Address;
22127 gnat_envp : System.Address;
22129 -- The actual variables are stored in a library routine. This
22130 -- is useful for some shared library situations, where there
22131 -- are problems if variables are not in the library.
22133 pragma Import (C, gnat_argc);
22134 pragma Import (C, gnat_argv);
22135 pragma Import (C, gnat_envp);
22137 -- The exit status is similarly an external location
22139 gnat_exit_status : Integer;
22140 pragma Import (C, gnat_exit_status);
22142 GNAT_Version : constant String :=
22143 "GNAT Version: 6.0.0w (20061115)";
22144 pragma Export (C, GNAT_Version, "__gnat_version");
22146 -- This is the generated adafinal routine that performs
22147 -- finalization at the end of execution. In the case where
22148 -- Ada is the main program, this main program makes a call
22149 -- to adafinal at program termination.
22151 procedure adafinal;
22152 pragma Export (C, adafinal, "adafinal");
22154 -- This is the generated adainit routine that performs
22155 -- initialization at the start of execution. In the case
22156 -- where Ada is the main program, this main program makes
22157 -- a call to adainit at program startup.
22160 pragma Export (C, adainit, "adainit");
22162 -- This routine is called at the start of execution. It is
22163 -- a dummy routine that is used by the debugger to breakpoint
22164 -- at the start of execution.
22166 procedure Break_Start;
22167 pragma Import (C, Break_Start, "__gnat_break_start");
22169 -- This is the actual generated main program (it would be
22170 -- suppressed if the no main program switch were used). As
22171 -- required by standard system conventions, this program has
22172 -- the external name main.
22176 argv : System.Address;
22177 envp : System.Address)
22179 pragma Export (C, main, "main");
22181 -- The following set of constants give the version
22182 -- identification values for every unit in the bound
22183 -- partition. This identification is computed from all
22184 -- dependent semantic units, and corresponds to the
22185 -- string that would be returned by use of the
22186 -- Body_Version or Version attributes.
22188 type Version_32 is mod 2 ** 32;
22189 u00001 : constant Version_32 := 16#7880BEB3#;
22190 u00002 : constant Version_32 := 16#0D24CBD0#;
22191 u00003 : constant Version_32 := 16#3283DBEB#;
22192 u00004 : constant Version_32 := 16#2359F9ED#;
22193 u00005 : constant Version_32 := 16#664FB847#;
22194 u00006 : constant Version_32 := 16#68E803DF#;
22195 u00007 : constant Version_32 := 16#5572E604#;
22196 u00008 : constant Version_32 := 16#46B173D8#;
22197 u00009 : constant Version_32 := 16#156A40CF#;
22198 u00010 : constant Version_32 := 16#033DABE0#;
22199 u00011 : constant Version_32 := 16#6AB38FEA#;
22200 u00012 : constant Version_32 := 16#22B6217D#;
22201 u00013 : constant Version_32 := 16#68A22947#;
22202 u00014 : constant Version_32 := 16#18CC4A56#;
22203 u00015 : constant Version_32 := 16#08258E1B#;
22204 u00016 : constant Version_32 := 16#367D5222#;
22205 u00017 : constant Version_32 := 16#20C9ECA4#;
22206 u00018 : constant Version_32 := 16#50D32CB6#;
22207 u00019 : constant Version_32 := 16#39A8BB77#;
22208 u00020 : constant Version_32 := 16#5CF8FA2B#;
22209 u00021 : constant Version_32 := 16#2F1EB794#;
22210 u00022 : constant Version_32 := 16#31AB6444#;
22211 u00023 : constant Version_32 := 16#1574B6E9#;
22212 u00024 : constant Version_32 := 16#5109C189#;
22213 u00025 : constant Version_32 := 16#56D770CD#;
22214 u00026 : constant Version_32 := 16#02F9DE3D#;
22215 u00027 : constant Version_32 := 16#08AB6B2C#;
22216 u00028 : constant Version_32 := 16#3FA37670#;
22217 u00029 : constant Version_32 := 16#476457A0#;
22218 u00030 : constant Version_32 := 16#731E1B6E#;
22219 u00031 : constant Version_32 := 16#23C2E789#;
22220 u00032 : constant Version_32 := 16#0F1BD6A1#;
22221 u00033 : constant Version_32 := 16#7C25DE96#;
22222 u00034 : constant Version_32 := 16#39ADFFA2#;
22223 u00035 : constant Version_32 := 16#571DE3E7#;
22224 u00036 : constant Version_32 := 16#5EB646AB#;
22225 u00037 : constant Version_32 := 16#4249379B#;
22226 u00038 : constant Version_32 := 16#0357E00A#;
22227 u00039 : constant Version_32 := 16#3784FB72#;
22228 u00040 : constant Version_32 := 16#2E723019#;
22229 u00041 : constant Version_32 := 16#623358EA#;
22230 u00042 : constant Version_32 := 16#107F9465#;
22231 u00043 : constant Version_32 := 16#6843F68A#;
22232 u00044 : constant Version_32 := 16#63305874#;
22233 u00045 : constant Version_32 := 16#31E56CE1#;
22234 u00046 : constant Version_32 := 16#02917970#;
22235 u00047 : constant Version_32 := 16#6CCBA70E#;
22236 u00048 : constant Version_32 := 16#41CD4204#;
22237 u00049 : constant Version_32 := 16#572E3F58#;
22238 u00050 : constant Version_32 := 16#20729FF5#;
22239 u00051 : constant Version_32 := 16#1D4F93E8#;
22240 u00052 : constant Version_32 := 16#30B2EC3D#;
22241 u00053 : constant Version_32 := 16#34054F96#;
22242 u00054 : constant Version_32 := 16#5A199860#;
22243 u00055 : constant Version_32 := 16#0E7F912B#;
22244 u00056 : constant Version_32 := 16#5760634A#;
22245 u00057 : constant Version_32 := 16#5D851835#;
22247 -- The following Export pragmas export the version numbers
22248 -- with symbolic names ending in B (for body) or S
22249 -- (for spec) so that they can be located in a link. The
22250 -- information provided here is sufficient to track down
22251 -- the exact versions of units used in a given build.
22253 pragma Export (C, u00001, "helloB");
22254 pragma Export (C, u00002, "system__standard_libraryB");
22255 pragma Export (C, u00003, "system__standard_libraryS");
22256 pragma Export (C, u00004, "adaS");
22257 pragma Export (C, u00005, "ada__text_ioB");
22258 pragma Export (C, u00006, "ada__text_ioS");
22259 pragma Export (C, u00007, "ada__exceptionsB");
22260 pragma Export (C, u00008, "ada__exceptionsS");
22261 pragma Export (C, u00009, "gnatS");
22262 pragma Export (C, u00010, "gnat__heap_sort_aB");
22263 pragma Export (C, u00011, "gnat__heap_sort_aS");
22264 pragma Export (C, u00012, "systemS");
22265 pragma Export (C, u00013, "system__exception_tableB");
22266 pragma Export (C, u00014, "system__exception_tableS");
22267 pragma Export (C, u00015, "gnat__htableB");
22268 pragma Export (C, u00016, "gnat__htableS");
22269 pragma Export (C, u00017, "system__exceptionsS");
22270 pragma Export (C, u00018, "system__machine_state_operationsB");
22271 pragma Export (C, u00019, "system__machine_state_operationsS");
22272 pragma Export (C, u00020, "system__machine_codeS");
22273 pragma Export (C, u00021, "system__storage_elementsB");
22274 pragma Export (C, u00022, "system__storage_elementsS");
22275 pragma Export (C, u00023, "system__secondary_stackB");
22276 pragma Export (C, u00024, "system__secondary_stackS");
22277 pragma Export (C, u00025, "system__parametersB");
22278 pragma Export (C, u00026, "system__parametersS");
22279 pragma Export (C, u00027, "system__soft_linksB");
22280 pragma Export (C, u00028, "system__soft_linksS");
22281 pragma Export (C, u00029, "system__stack_checkingB");
22282 pragma Export (C, u00030, "system__stack_checkingS");
22283 pragma Export (C, u00031, "system__tracebackB");
22284 pragma Export (C, u00032, "system__tracebackS");
22285 pragma Export (C, u00033, "ada__streamsS");
22286 pragma Export (C, u00034, "ada__tagsB");
22287 pragma Export (C, u00035, "ada__tagsS");
22288 pragma Export (C, u00036, "system__string_opsB");
22289 pragma Export (C, u00037, "system__string_opsS");
22290 pragma Export (C, u00038, "interfacesS");
22291 pragma Export (C, u00039, "interfaces__c_streamsB");
22292 pragma Export (C, u00040, "interfaces__c_streamsS");
22293 pragma Export (C, u00041, "system__file_ioB");
22294 pragma Export (C, u00042, "system__file_ioS");
22295 pragma Export (C, u00043, "ada__finalizationB");
22296 pragma Export (C, u00044, "ada__finalizationS");
22297 pragma Export (C, u00045, "system__finalization_rootB");
22298 pragma Export (C, u00046, "system__finalization_rootS");
22299 pragma Export (C, u00047, "system__finalization_implementationB");
22300 pragma Export (C, u00048, "system__finalization_implementationS");
22301 pragma Export (C, u00049, "system__string_ops_concat_3B");
22302 pragma Export (C, u00050, "system__string_ops_concat_3S");
22303 pragma Export (C, u00051, "system__stream_attributesB");
22304 pragma Export (C, u00052, "system__stream_attributesS");
22305 pragma Export (C, u00053, "ada__io_exceptionsS");
22306 pragma Export (C, u00054, "system__unsigned_typesS");
22307 pragma Export (C, u00055, "system__file_control_blockS");
22308 pragma Export (C, u00056, "ada__finalization__list_controllerB");
22309 pragma Export (C, u00057, "ada__finalization__list_controllerS");
22311 -- BEGIN ELABORATION ORDER
22314 -- gnat.heap_sort_a (spec)
22315 -- gnat.heap_sort_a (body)
22316 -- gnat.htable (spec)
22317 -- gnat.htable (body)
22318 -- interfaces (spec)
22320 -- system.machine_code (spec)
22321 -- system.parameters (spec)
22322 -- system.parameters (body)
22323 -- interfaces.c_streams (spec)
22324 -- interfaces.c_streams (body)
22325 -- system.standard_library (spec)
22326 -- ada.exceptions (spec)
22327 -- system.exception_table (spec)
22328 -- system.exception_table (body)
22329 -- ada.io_exceptions (spec)
22330 -- system.exceptions (spec)
22331 -- system.storage_elements (spec)
22332 -- system.storage_elements (body)
22333 -- system.machine_state_operations (spec)
22334 -- system.machine_state_operations (body)
22335 -- system.secondary_stack (spec)
22336 -- system.stack_checking (spec)
22337 -- system.soft_links (spec)
22338 -- system.soft_links (body)
22339 -- system.stack_checking (body)
22340 -- system.secondary_stack (body)
22341 -- system.standard_library (body)
22342 -- system.string_ops (spec)
22343 -- system.string_ops (body)
22346 -- ada.streams (spec)
22347 -- system.finalization_root (spec)
22348 -- system.finalization_root (body)
22349 -- system.string_ops_concat_3 (spec)
22350 -- system.string_ops_concat_3 (body)
22351 -- system.traceback (spec)
22352 -- system.traceback (body)
22353 -- ada.exceptions (body)
22354 -- system.unsigned_types (spec)
22355 -- system.stream_attributes (spec)
22356 -- system.stream_attributes (body)
22357 -- system.finalization_implementation (spec)
22358 -- system.finalization_implementation (body)
22359 -- ada.finalization (spec)
22360 -- ada.finalization (body)
22361 -- ada.finalization.list_controller (spec)
22362 -- ada.finalization.list_controller (body)
22363 -- system.file_control_block (spec)
22364 -- system.file_io (spec)
22365 -- system.file_io (body)
22366 -- ada.text_io (spec)
22367 -- ada.text_io (body)
22369 -- END ELABORATION ORDER
22373 -- The following source file name pragmas allow the generated file
22374 -- names to be unique for different main programs. They are needed
22375 -- since the package name will always be Ada_Main.
22377 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
22378 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
22380 -- Generated package body for Ada_Main starts here
22382 package body ada_main is
22384 -- The actual finalization is performed by calling the
22385 -- library routine in System.Standard_Library.Adafinal
22387 procedure Do_Finalize;
22388 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
22395 procedure adainit is
22397 -- These booleans are set to True once the associated unit has
22398 -- been elaborated. It is also used to avoid elaborating the
22399 -- same unit twice.
22402 pragma Import (Ada, E040, "interfaces__c_streams_E");
22405 pragma Import (Ada, E008, "ada__exceptions_E");
22408 pragma Import (Ada, E014, "system__exception_table_E");
22411 pragma Import (Ada, E053, "ada__io_exceptions_E");
22414 pragma Import (Ada, E017, "system__exceptions_E");
22417 pragma Import (Ada, E024, "system__secondary_stack_E");
22420 pragma Import (Ada, E030, "system__stack_checking_E");
22423 pragma Import (Ada, E028, "system__soft_links_E");
22426 pragma Import (Ada, E035, "ada__tags_E");
22429 pragma Import (Ada, E033, "ada__streams_E");
22432 pragma Import (Ada, E046, "system__finalization_root_E");
22435 pragma Import (Ada, E048, "system__finalization_implementation_E");
22438 pragma Import (Ada, E044, "ada__finalization_E");
22441 pragma Import (Ada, E057, "ada__finalization__list_controller_E");
22444 pragma Import (Ada, E055, "system__file_control_block_E");
22447 pragma Import (Ada, E042, "system__file_io_E");
22450 pragma Import (Ada, E006, "ada__text_io_E");
22452 -- Set_Globals is a library routine that stores away the
22453 -- value of the indicated set of global values in global
22454 -- variables within the library.
22456 procedure Set_Globals
22457 (Main_Priority : Integer;
22458 Time_Slice_Value : Integer;
22459 WC_Encoding : Character;
22460 Locking_Policy : Character;
22461 Queuing_Policy : Character;
22462 Task_Dispatching_Policy : Character;
22463 Adafinal : System.Address;
22464 Unreserve_All_Interrupts : Integer;
22465 Exception_Tracebacks : Integer);
22466 @findex __gnat_set_globals
22467 pragma Import (C, Set_Globals, "__gnat_set_globals");
22469 -- SDP_Table_Build is a library routine used to build the
22470 -- exception tables. See unit Ada.Exceptions in files
22471 -- a-except.ads/adb for full details of how zero cost
22472 -- exception handling works. This procedure, the call to
22473 -- it, and the two following tables are all omitted if the
22474 -- build is in longjmp/setjmp exception mode.
22476 @findex SDP_Table_Build
22477 @findex Zero Cost Exceptions
22478 procedure SDP_Table_Build
22479 (SDP_Addresses : System.Address;
22480 SDP_Count : Natural;
22481 Elab_Addresses : System.Address;
22482 Elab_Addr_Count : Natural);
22483 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22485 -- Table of Unit_Exception_Table addresses. Used for zero
22486 -- cost exception handling to build the top level table.
22488 ST : aliased constant array (1 .. 23) of System.Address := (
22490 Ada.Text_Io'UET_Address,
22491 Ada.Exceptions'UET_Address,
22492 Gnat.Heap_Sort_A'UET_Address,
22493 System.Exception_Table'UET_Address,
22494 System.Machine_State_Operations'UET_Address,
22495 System.Secondary_Stack'UET_Address,
22496 System.Parameters'UET_Address,
22497 System.Soft_Links'UET_Address,
22498 System.Stack_Checking'UET_Address,
22499 System.Traceback'UET_Address,
22500 Ada.Streams'UET_Address,
22501 Ada.Tags'UET_Address,
22502 System.String_Ops'UET_Address,
22503 Interfaces.C_Streams'UET_Address,
22504 System.File_Io'UET_Address,
22505 Ada.Finalization'UET_Address,
22506 System.Finalization_Root'UET_Address,
22507 System.Finalization_Implementation'UET_Address,
22508 System.String_Ops_Concat_3'UET_Address,
22509 System.Stream_Attributes'UET_Address,
22510 System.File_Control_Block'UET_Address,
22511 Ada.Finalization.List_Controller'UET_Address);
22513 -- Table of addresses of elaboration routines. Used for
22514 -- zero cost exception handling to make sure these
22515 -- addresses are included in the top level procedure
22518 EA : aliased constant array (1 .. 23) of System.Address := (
22519 adainit'Code_Address,
22520 Do_Finalize'Code_Address,
22521 Ada.Exceptions'Elab_Spec'Address,
22522 System.Exceptions'Elab_Spec'Address,
22523 Interfaces.C_Streams'Elab_Spec'Address,
22524 System.Exception_Table'Elab_Body'Address,
22525 Ada.Io_Exceptions'Elab_Spec'Address,
22526 System.Stack_Checking'Elab_Spec'Address,
22527 System.Soft_Links'Elab_Body'Address,
22528 System.Secondary_Stack'Elab_Body'Address,
22529 Ada.Tags'Elab_Spec'Address,
22530 Ada.Tags'Elab_Body'Address,
22531 Ada.Streams'Elab_Spec'Address,
22532 System.Finalization_Root'Elab_Spec'Address,
22533 Ada.Exceptions'Elab_Body'Address,
22534 System.Finalization_Implementation'Elab_Spec'Address,
22535 System.Finalization_Implementation'Elab_Body'Address,
22536 Ada.Finalization'Elab_Spec'Address,
22537 Ada.Finalization.List_Controller'Elab_Spec'Address,
22538 System.File_Control_Block'Elab_Spec'Address,
22539 System.File_Io'Elab_Body'Address,
22540 Ada.Text_Io'Elab_Spec'Address,
22541 Ada.Text_Io'Elab_Body'Address);
22543 -- Start of processing for adainit
22547 -- Call SDP_Table_Build to build the top level procedure
22548 -- table for zero cost exception handling (omitted in
22549 -- longjmp/setjmp mode).
22551 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
22553 -- Call Set_Globals to record various information for
22554 -- this partition. The values are derived by the binder
22555 -- from information stored in the ali files by the compiler.
22557 @findex __gnat_set_globals
22559 (Main_Priority => -1,
22560 -- Priority of main program, -1 if no pragma Priority used
22562 Time_Slice_Value => -1,
22563 -- Time slice from Time_Slice pragma, -1 if none used
22565 WC_Encoding => 'b',
22566 -- Wide_Character encoding used, default is brackets
22568 Locking_Policy => ' ',
22569 -- Locking_Policy used, default of space means not
22570 -- specified, otherwise it is the first character of
22571 -- the policy name.
22573 Queuing_Policy => ' ',
22574 -- Queuing_Policy used, default of space means not
22575 -- specified, otherwise it is the first character of
22576 -- the policy name.
22578 Task_Dispatching_Policy => ' ',
22579 -- Task_Dispatching_Policy used, default of space means
22580 -- not specified, otherwise first character of the
22583 Adafinal => System.Null_Address,
22584 -- Address of Adafinal routine, not used anymore
22586 Unreserve_All_Interrupts => 0,
22587 -- Set true if pragma Unreserve_All_Interrupts was used
22589 Exception_Tracebacks => 0);
22590 -- Indicates if exception tracebacks are enabled
22592 Elab_Final_Code := 1;
22594 -- Now we have the elaboration calls for all units in the partition.
22595 -- The Elab_Spec and Elab_Body attributes generate references to the
22596 -- implicit elaboration procedures generated by the compiler for
22597 -- each unit that requires elaboration.
22600 Interfaces.C_Streams'Elab_Spec;
22604 Ada.Exceptions'Elab_Spec;
22607 System.Exception_Table'Elab_Body;
22611 Ada.Io_Exceptions'Elab_Spec;
22615 System.Exceptions'Elab_Spec;
22619 System.Stack_Checking'Elab_Spec;
22622 System.Soft_Links'Elab_Body;
22627 System.Secondary_Stack'Elab_Body;
22631 Ada.Tags'Elab_Spec;
22634 Ada.Tags'Elab_Body;
22638 Ada.Streams'Elab_Spec;
22642 System.Finalization_Root'Elab_Spec;
22646 Ada.Exceptions'Elab_Body;
22650 System.Finalization_Implementation'Elab_Spec;
22653 System.Finalization_Implementation'Elab_Body;
22657 Ada.Finalization'Elab_Spec;
22661 Ada.Finalization.List_Controller'Elab_Spec;
22665 System.File_Control_Block'Elab_Spec;
22669 System.File_Io'Elab_Body;
22673 Ada.Text_Io'Elab_Spec;
22676 Ada.Text_Io'Elab_Body;
22680 Elab_Final_Code := 0;
22688 procedure adafinal is
22697 -- main is actually a function, as in the ANSI C standard,
22698 -- defined to return the exit status. The three parameters
22699 -- are the argument count, argument values and environment
22702 @findex Main Program
22705 argv : System.Address;
22706 envp : System.Address)
22709 -- The initialize routine performs low level system
22710 -- initialization using a standard library routine which
22711 -- sets up signal handling and performs any other
22712 -- required setup. The routine can be found in file
22715 @findex __gnat_initialize
22716 procedure initialize;
22717 pragma Import (C, initialize, "__gnat_initialize");
22719 -- The finalize routine performs low level system
22720 -- finalization using a standard library routine. The
22721 -- routine is found in file a-final.c and in the standard
22722 -- distribution is a dummy routine that does nothing, so
22723 -- really this is a hook for special user finalization.
22725 @findex __gnat_finalize
22726 procedure finalize;
22727 pragma Import (C, finalize, "__gnat_finalize");
22729 -- We get to the main program of the partition by using
22730 -- pragma Import because if we try to with the unit and
22731 -- call it Ada style, then not only do we waste time
22732 -- recompiling it, but also, we don't really know the right
22733 -- switches (e.g.@: identifier character set) to be used
22736 procedure Ada_Main_Program;
22737 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
22739 -- Start of processing for main
22742 -- Save global variables
22748 -- Call low level system initialization
22752 -- Call our generated Ada initialization routine
22756 -- This is the point at which we want the debugger to get
22761 -- Now we call the main program of the partition
22765 -- Perform Ada finalization
22769 -- Perform low level system finalization
22773 -- Return the proper exit status
22774 return (gnat_exit_status);
22777 -- This section is entirely comments, so it has no effect on the
22778 -- compilation of the Ada_Main package. It provides the list of
22779 -- object files and linker options, as well as some standard
22780 -- libraries needed for the link. The gnatlink utility parses
22781 -- this b~hello.adb file to read these comment lines to generate
22782 -- the appropriate command line arguments for the call to the
22783 -- system linker. The BEGIN/END lines are used for sentinels for
22784 -- this parsing operation.
22786 -- The exact file names will of course depend on the environment,
22787 -- host/target and location of files on the host system.
22789 @findex Object file list
22790 -- BEGIN Object file/option list
22793 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
22794 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22795 -- END Object file/option list
22801 The Ada code in the above example is exactly what is generated by the
22802 binder. We have added comments to more clearly indicate the function
22803 of each part of the generated @code{Ada_Main} package.
22805 The code is standard Ada in all respects, and can be processed by any
22806 tools that handle Ada. In particular, it is possible to use the debugger
22807 in Ada mode to debug the generated @code{Ada_Main} package. For example,
22808 suppose that for reasons that you do not understand, your program is crashing
22809 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
22810 you can place a breakpoint on the call:
22812 @smallexample @c ada
22813 Ada.Text_Io'Elab_Body;
22817 and trace the elaboration routine for this package to find out where
22818 the problem might be (more usually of course you would be debugging
22819 elaboration code in your own application).
22821 @node Elaboration Order Handling in GNAT
22822 @appendix Elaboration Order Handling in GNAT
22823 @cindex Order of elaboration
22824 @cindex Elaboration control
22827 * Elaboration Code::
22828 * Checking the Elaboration Order::
22829 * Controlling the Elaboration Order::
22830 * Controlling Elaboration in GNAT - Internal Calls::
22831 * Controlling Elaboration in GNAT - External Calls::
22832 * Default Behavior in GNAT - Ensuring Safety::
22833 * Treatment of Pragma Elaborate::
22834 * Elaboration Issues for Library Tasks::
22835 * Mixing Elaboration Models::
22836 * What to Do If the Default Elaboration Behavior Fails::
22837 * Elaboration for Access-to-Subprogram Values::
22838 * Summary of Procedures for Elaboration Control::
22839 * Other Elaboration Order Considerations::
22843 This chapter describes the handling of elaboration code in Ada and
22844 in GNAT, and discusses how the order of elaboration of program units can
22845 be controlled in GNAT, either automatically or with explicit programming
22848 @node Elaboration Code
22849 @section Elaboration Code
22852 Ada provides rather general mechanisms for executing code at elaboration
22853 time, that is to say before the main program starts executing. Such code arises
22857 @item Initializers for variables.
22858 Variables declared at the library level, in package specs or bodies, can
22859 require initialization that is performed at elaboration time, as in:
22860 @smallexample @c ada
22862 Sqrt_Half : Float := Sqrt (0.5);
22866 @item Package initialization code
22867 Code in a @code{BEGIN-END} section at the outer level of a package body is
22868 executed as part of the package body elaboration code.
22870 @item Library level task allocators
22871 Tasks that are declared using task allocators at the library level
22872 start executing immediately and hence can execute at elaboration time.
22876 Subprogram calls are possible in any of these contexts, which means that
22877 any arbitrary part of the program may be executed as part of the elaboration
22878 code. It is even possible to write a program which does all its work at
22879 elaboration time, with a null main program, although stylistically this
22880 would usually be considered an inappropriate way to structure
22883 An important concern arises in the context of elaboration code:
22884 we have to be sure that it is executed in an appropriate order. What we
22885 have is a series of elaboration code sections, potentially one section
22886 for each unit in the program. It is important that these execute
22887 in the correct order. Correctness here means that, taking the above
22888 example of the declaration of @code{Sqrt_Half},
22889 if some other piece of
22890 elaboration code references @code{Sqrt_Half},
22891 then it must run after the
22892 section of elaboration code that contains the declaration of
22895 There would never be any order of elaboration problem if we made a rule
22896 that whenever you @code{with} a unit, you must elaborate both the spec and body
22897 of that unit before elaborating the unit doing the @code{with}'ing:
22899 @smallexample @c ada
22903 package Unit_2 is @dots{}
22909 would require that both the body and spec of @code{Unit_1} be elaborated
22910 before the spec of @code{Unit_2}. However, a rule like that would be far too
22911 restrictive. In particular, it would make it impossible to have routines
22912 in separate packages that were mutually recursive.
22914 You might think that a clever enough compiler could look at the actual
22915 elaboration code and determine an appropriate correct order of elaboration,
22916 but in the general case, this is not possible. Consider the following
22919 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
22921 the variable @code{Sqrt_1}, which is declared in the elaboration code
22922 of the body of @code{Unit_1}:
22924 @smallexample @c ada
22926 Sqrt_1 : Float := Sqrt (0.1);
22931 The elaboration code of the body of @code{Unit_1} also contains:
22933 @smallexample @c ada
22936 if expression_1 = 1 then
22937 Q := Unit_2.Func_2;
22944 @code{Unit_2} is exactly parallel,
22945 it has a procedure @code{Func_2} that references
22946 the variable @code{Sqrt_2}, which is declared in the elaboration code of
22947 the body @code{Unit_2}:
22949 @smallexample @c ada
22951 Sqrt_2 : Float := Sqrt (0.1);
22956 The elaboration code of the body of @code{Unit_2} also contains:
22958 @smallexample @c ada
22961 if expression_2 = 2 then
22962 Q := Unit_1.Func_1;
22969 Now the question is, which of the following orders of elaboration is
22994 If you carefully analyze the flow here, you will see that you cannot tell
22995 at compile time the answer to this question.
22996 If @code{expression_1} is not equal to 1,
22997 and @code{expression_2} is not equal to 2,
22998 then either order is acceptable, because neither of the function calls is
22999 executed. If both tests evaluate to true, then neither order is acceptable
23000 and in fact there is no correct order.
23002 If one of the two expressions is true, and the other is false, then one
23003 of the above orders is correct, and the other is incorrect. For example,
23004 if @code{expression_1} /= 1 and @code{expression_2} = 2,
23005 then the call to @code{Func_1}
23006 will occur, but not the call to @code{Func_2.}
23007 This means that it is essential
23008 to elaborate the body of @code{Unit_1} before
23009 the body of @code{Unit_2}, so the first
23010 order of elaboration is correct and the second is wrong.
23012 By making @code{expression_1} and @code{expression_2}
23013 depend on input data, or perhaps
23014 the time of day, we can make it impossible for the compiler or binder
23015 to figure out which of these expressions will be true, and hence it
23016 is impossible to guarantee a safe order of elaboration at run time.
23018 @node Checking the Elaboration Order
23019 @section Checking the Elaboration Order
23022 In some languages that involve the same kind of elaboration problems,
23023 e.g.@: Java and C++, the programmer is expected to worry about these
23024 ordering problems himself, and it is common to
23025 write a program in which an incorrect elaboration order gives
23026 surprising results, because it references variables before they
23028 Ada is designed to be a safe language, and a programmer-beware approach is
23029 clearly not sufficient. Consequently, the language provides three lines
23033 @item Standard rules
23034 Some standard rules restrict the possible choice of elaboration
23035 order. In particular, if you @code{with} a unit, then its spec is always
23036 elaborated before the unit doing the @code{with}. Similarly, a parent
23037 spec is always elaborated before the child spec, and finally
23038 a spec is always elaborated before its corresponding body.
23040 @item Dynamic elaboration checks
23041 @cindex Elaboration checks
23042 @cindex Checks, elaboration
23043 Dynamic checks are made at run time, so that if some entity is accessed
23044 before it is elaborated (typically by means of a subprogram call)
23045 then the exception (@code{Program_Error}) is raised.
23047 @item Elaboration control
23048 Facilities are provided for the programmer to specify the desired order
23052 Let's look at these facilities in more detail. First, the rules for
23053 dynamic checking. One possible rule would be simply to say that the
23054 exception is raised if you access a variable which has not yet been
23055 elaborated. The trouble with this approach is that it could require
23056 expensive checks on every variable reference. Instead Ada has two
23057 rules which are a little more restrictive, but easier to check, and
23061 @item Restrictions on calls
23062 A subprogram can only be called at elaboration time if its body
23063 has been elaborated. The rules for elaboration given above guarantee
23064 that the spec of the subprogram has been elaborated before the
23065 call, but not the body. If this rule is violated, then the
23066 exception @code{Program_Error} is raised.
23068 @item Restrictions on instantiations
23069 A generic unit can only be instantiated if the body of the generic
23070 unit has been elaborated. Again, the rules for elaboration given above
23071 guarantee that the spec of the generic unit has been elaborated
23072 before the instantiation, but not the body. If this rule is
23073 violated, then the exception @code{Program_Error} is raised.
23077 The idea is that if the body has been elaborated, then any variables
23078 it references must have been elaborated; by checking for the body being
23079 elaborated we guarantee that none of its references causes any
23080 trouble. As we noted above, this is a little too restrictive, because a
23081 subprogram that has no non-local references in its body may in fact be safe
23082 to call. However, it really would be unsafe to rely on this, because
23083 it would mean that the caller was aware of details of the implementation
23084 in the body. This goes against the basic tenets of Ada.
23086 A plausible implementation can be described as follows.
23087 A Boolean variable is associated with each subprogram
23088 and each generic unit. This variable is initialized to False, and is set to
23089 True at the point body is elaborated. Every call or instantiation checks the
23090 variable, and raises @code{Program_Error} if the variable is False.
23092 Note that one might think that it would be good enough to have one Boolean
23093 variable for each package, but that would not deal with cases of trying
23094 to call a body in the same package as the call
23095 that has not been elaborated yet.
23096 Of course a compiler may be able to do enough analysis to optimize away
23097 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
23098 does such optimizations, but still the easiest conceptual model is to
23099 think of there being one variable per subprogram.
23101 @node Controlling the Elaboration Order
23102 @section Controlling the Elaboration Order
23105 In the previous section we discussed the rules in Ada which ensure
23106 that @code{Program_Error} is raised if an incorrect elaboration order is
23107 chosen. This prevents erroneous executions, but we need mechanisms to
23108 specify a correct execution and avoid the exception altogether.
23109 To achieve this, Ada provides a number of features for controlling
23110 the order of elaboration. We discuss these features in this section.
23112 First, there are several ways of indicating to the compiler that a given
23113 unit has no elaboration problems:
23116 @item packages that do not require a body
23117 A library package that does not require a body does not permit
23118 a body (this rule was introduced in Ada 95).
23119 Thus if we have a such a package, as in:
23121 @smallexample @c ada
23124 package Definitions is
23126 type m is new integer;
23128 type a is array (1 .. 10) of m;
23129 type b is array (1 .. 20) of m;
23137 A package that @code{with}'s @code{Definitions} may safely instantiate
23138 @code{Definitions.Subp} because the compiler can determine that there
23139 definitely is no package body to worry about in this case
23142 @cindex pragma Pure
23144 Places sufficient restrictions on a unit to guarantee that
23145 no call to any subprogram in the unit can result in an
23146 elaboration problem. This means that the compiler does not need
23147 to worry about the point of elaboration of such units, and in
23148 particular, does not need to check any calls to any subprograms
23151 @item pragma Preelaborate
23152 @findex Preelaborate
23153 @cindex pragma Preelaborate
23154 This pragma places slightly less stringent restrictions on a unit than
23156 but these restrictions are still sufficient to ensure that there
23157 are no elaboration problems with any calls to the unit.
23159 @item pragma Elaborate_Body
23160 @findex Elaborate_Body
23161 @cindex pragma Elaborate_Body
23162 This pragma requires that the body of a unit be elaborated immediately
23163 after its spec. Suppose a unit @code{A} has such a pragma,
23164 and unit @code{B} does
23165 a @code{with} of unit @code{A}. Recall that the standard rules require
23166 the spec of unit @code{A}
23167 to be elaborated before the @code{with}'ing unit; given the pragma in
23168 @code{A}, we also know that the body of @code{A}
23169 will be elaborated before @code{B}, so
23170 that calls to @code{A} are safe and do not need a check.
23175 unlike pragma @code{Pure} and pragma @code{Preelaborate},
23177 @code{Elaborate_Body} does not guarantee that the program is
23178 free of elaboration problems, because it may not be possible
23179 to satisfy the requested elaboration order.
23180 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
23182 marks @code{Unit_1} as @code{Elaborate_Body},
23183 and not @code{Unit_2,} then the order of
23184 elaboration will be:
23196 Now that means that the call to @code{Func_1} in @code{Unit_2}
23197 need not be checked,
23198 it must be safe. But the call to @code{Func_2} in
23199 @code{Unit_1} may still fail if
23200 @code{Expression_1} is equal to 1,
23201 and the programmer must still take
23202 responsibility for this not being the case.
23204 If all units carry a pragma @code{Elaborate_Body}, then all problems are
23205 eliminated, except for calls entirely within a body, which are
23206 in any case fully under programmer control. However, using the pragma
23207 everywhere is not always possible.
23208 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
23209 we marked both of them as having pragma @code{Elaborate_Body}, then
23210 clearly there would be no possible elaboration order.
23212 The above pragmas allow a server to guarantee safe use by clients, and
23213 clearly this is the preferable approach. Consequently a good rule
23214 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
23215 and if this is not possible,
23216 mark them as @code{Elaborate_Body} if possible.
23217 As we have seen, there are situations where neither of these
23218 three pragmas can be used.
23219 So we also provide methods for clients to control the
23220 order of elaboration of the servers on which they depend:
23223 @item pragma Elaborate (unit)
23225 @cindex pragma Elaborate
23226 This pragma is placed in the context clause, after a @code{with} clause,
23227 and it requires that the body of the named unit be elaborated before
23228 the unit in which the pragma occurs. The idea is to use this pragma
23229 if the current unit calls at elaboration time, directly or indirectly,
23230 some subprogram in the named unit.
23232 @item pragma Elaborate_All (unit)
23233 @findex Elaborate_All
23234 @cindex pragma Elaborate_All
23235 This is a stronger version of the Elaborate pragma. Consider the
23239 Unit A @code{with}'s unit B and calls B.Func in elab code
23240 Unit B @code{with}'s unit C, and B.Func calls C.Func
23244 Now if we put a pragma @code{Elaborate (B)}
23245 in unit @code{A}, this ensures that the
23246 body of @code{B} is elaborated before the call, but not the
23247 body of @code{C}, so
23248 the call to @code{C.Func} could still cause @code{Program_Error} to
23251 The effect of a pragma @code{Elaborate_All} is stronger, it requires
23252 not only that the body of the named unit be elaborated before the
23253 unit doing the @code{with}, but also the bodies of all units that the
23254 named unit uses, following @code{with} links transitively. For example,
23255 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
23257 not only that the body of @code{B} be elaborated before @code{A},
23259 body of @code{C}, because @code{B} @code{with}'s @code{C}.
23263 We are now in a position to give a usage rule in Ada for avoiding
23264 elaboration problems, at least if dynamic dispatching and access to
23265 subprogram values are not used. We will handle these cases separately
23268 The rule is simple. If a unit has elaboration code that can directly or
23269 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
23270 a generic package in a @code{with}'ed unit,
23271 then if the @code{with}'ed unit does not have
23272 pragma @code{Pure} or @code{Preelaborate}, then the client should have
23273 a pragma @code{Elaborate_All}
23274 for the @code{with}'ed unit. By following this rule a client is
23275 assured that calls can be made without risk of an exception.
23277 For generic subprogram instantiations, the rule can be relaxed to
23278 require only a pragma @code{Elaborate} since elaborating the body
23279 of a subprogram cannot cause any transitive elaboration (we are
23280 not calling the subprogram in this case, just elaborating its
23283 If this rule is not followed, then a program may be in one of four
23287 @item No order exists
23288 No order of elaboration exists which follows the rules, taking into
23289 account any @code{Elaborate}, @code{Elaborate_All},
23290 or @code{Elaborate_Body} pragmas. In
23291 this case, an Ada compiler must diagnose the situation at bind
23292 time, and refuse to build an executable program.
23294 @item One or more orders exist, all incorrect
23295 One or more acceptable elaboration orders exist, and all of them
23296 generate an elaboration order problem. In this case, the binder
23297 can build an executable program, but @code{Program_Error} will be raised
23298 when the program is run.
23300 @item Several orders exist, some right, some incorrect
23301 One or more acceptable elaboration orders exists, and some of them
23302 work, and some do not. The programmer has not controlled
23303 the order of elaboration, so the binder may or may not pick one of
23304 the correct orders, and the program may or may not raise an
23305 exception when it is run. This is the worst case, because it means
23306 that the program may fail when moved to another compiler, or even
23307 another version of the same compiler.
23309 @item One or more orders exists, all correct
23310 One ore more acceptable elaboration orders exist, and all of them
23311 work. In this case the program runs successfully. This state of
23312 affairs can be guaranteed by following the rule we gave above, but
23313 may be true even if the rule is not followed.
23317 Note that one additional advantage of following our rules on the use
23318 of @code{Elaborate} and @code{Elaborate_All}
23319 is that the program continues to stay in the ideal (all orders OK) state
23320 even if maintenance
23321 changes some bodies of some units. Conversely, if a program that does
23322 not follow this rule happens to be safe at some point, this state of affairs
23323 may deteriorate silently as a result of maintenance changes.
23325 You may have noticed that the above discussion did not mention
23326 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
23327 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
23328 code in the body makes calls to some other unit, so it is still necessary
23329 to use @code{Elaborate_All} on such units.
23331 @node Controlling Elaboration in GNAT - Internal Calls
23332 @section Controlling Elaboration in GNAT - Internal Calls
23335 In the case of internal calls, i.e., calls within a single package, the
23336 programmer has full control over the order of elaboration, and it is up
23337 to the programmer to elaborate declarations in an appropriate order. For
23340 @smallexample @c ada
23343 function One return Float;
23347 function One return Float is
23356 will obviously raise @code{Program_Error} at run time, because function
23357 One will be called before its body is elaborated. In this case GNAT will
23358 generate a warning that the call will raise @code{Program_Error}:
23364 2. function One return Float;
23366 4. Q : Float := One;
23368 >>> warning: cannot call "One" before body is elaborated
23369 >>> warning: Program_Error will be raised at run time
23372 6. function One return Float is
23385 Note that in this particular case, it is likely that the call is safe, because
23386 the function @code{One} does not access any global variables.
23387 Nevertheless in Ada, we do not want the validity of the check to depend on
23388 the contents of the body (think about the separate compilation case), so this
23389 is still wrong, as we discussed in the previous sections.
23391 The error is easily corrected by rearranging the declarations so that the
23392 body of @code{One} appears before the declaration containing the call
23393 (note that in Ada 95 and Ada 2005,
23394 declarations can appear in any order, so there is no restriction that
23395 would prevent this reordering, and if we write:
23397 @smallexample @c ada
23400 function One return Float;
23402 function One return Float is
23413 then all is well, no warning is generated, and no
23414 @code{Program_Error} exception
23416 Things are more complicated when a chain of subprograms is executed:
23418 @smallexample @c ada
23421 function A return Integer;
23422 function B return Integer;
23423 function C return Integer;
23425 function B return Integer is begin return A; end;
23426 function C return Integer is begin return B; end;
23430 function A return Integer is begin return 1; end;
23436 Now the call to @code{C}
23437 at elaboration time in the declaration of @code{X} is correct, because
23438 the body of @code{C} is already elaborated,
23439 and the call to @code{B} within the body of
23440 @code{C} is correct, but the call
23441 to @code{A} within the body of @code{B} is incorrect, because the body
23442 of @code{A} has not been elaborated, so @code{Program_Error}
23443 will be raised on the call to @code{A}.
23444 In this case GNAT will generate a
23445 warning that @code{Program_Error} may be
23446 raised at the point of the call. Let's look at the warning:
23452 2. function A return Integer;
23453 3. function B return Integer;
23454 4. function C return Integer;
23456 6. function B return Integer is begin return A; end;
23458 >>> warning: call to "A" before body is elaborated may
23459 raise Program_Error
23460 >>> warning: "B" called at line 7
23461 >>> warning: "C" called at line 9
23463 7. function C return Integer is begin return B; end;
23465 9. X : Integer := C;
23467 11. function A return Integer is begin return 1; end;
23477 Note that the message here says ``may raise'', instead of the direct case,
23478 where the message says ``will be raised''. That's because whether
23480 actually called depends in general on run-time flow of control.
23481 For example, if the body of @code{B} said
23483 @smallexample @c ada
23486 function B return Integer is
23488 if some-condition-depending-on-input-data then
23499 then we could not know until run time whether the incorrect call to A would
23500 actually occur, so @code{Program_Error} might
23501 or might not be raised. It is possible for a compiler to
23502 do a better job of analyzing bodies, to
23503 determine whether or not @code{Program_Error}
23504 might be raised, but it certainly
23505 couldn't do a perfect job (that would require solving the halting problem
23506 and is provably impossible), and because this is a warning anyway, it does
23507 not seem worth the effort to do the analysis. Cases in which it
23508 would be relevant are rare.
23510 In practice, warnings of either of the forms given
23511 above will usually correspond to
23512 real errors, and should be examined carefully and eliminated.
23513 In the rare case where a warning is bogus, it can be suppressed by any of
23514 the following methods:
23518 Compile with the @option{-gnatws} switch set
23521 Suppress @code{Elaboration_Check} for the called subprogram
23524 Use pragma @code{Warnings_Off} to turn warnings off for the call
23528 For the internal elaboration check case,
23529 GNAT by default generates the
23530 necessary run-time checks to ensure
23531 that @code{Program_Error} is raised if any
23532 call fails an elaboration check. Of course this can only happen if a
23533 warning has been issued as described above. The use of pragma
23534 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23535 some of these checks, meaning that it may be possible (but is not
23536 guaranteed) for a program to be able to call a subprogram whose body
23537 is not yet elaborated, without raising a @code{Program_Error} exception.
23539 @node Controlling Elaboration in GNAT - External Calls
23540 @section Controlling Elaboration in GNAT - External Calls
23543 The previous section discussed the case in which the execution of a
23544 particular thread of elaboration code occurred entirely within a
23545 single unit. This is the easy case to handle, because a programmer
23546 has direct and total control over the order of elaboration, and
23547 furthermore, checks need only be generated in cases which are rare
23548 and which the compiler can easily detect.
23549 The situation is more complex when separate compilation is taken into account.
23550 Consider the following:
23552 @smallexample @c ada
23556 function Sqrt (Arg : Float) return Float;
23559 package body Math is
23560 function Sqrt (Arg : Float) return Float is
23569 X : Float := Math.Sqrt (0.5);
23582 where @code{Main} is the main program. When this program is executed, the
23583 elaboration code must first be executed, and one of the jobs of the
23584 binder is to determine the order in which the units of a program are
23585 to be elaborated. In this case we have four units: the spec and body
23587 the spec of @code{Stuff} and the body of @code{Main}).
23588 In what order should the four separate sections of elaboration code
23591 There are some restrictions in the order of elaboration that the binder
23592 can choose. In particular, if unit U has a @code{with}
23593 for a package @code{X}, then you
23594 are assured that the spec of @code{X}
23595 is elaborated before U , but you are
23596 not assured that the body of @code{X}
23597 is elaborated before U.
23598 This means that in the above case, the binder is allowed to choose the
23609 but that's not good, because now the call to @code{Math.Sqrt}
23610 that happens during
23611 the elaboration of the @code{Stuff}
23612 spec happens before the body of @code{Math.Sqrt} is
23613 elaborated, and hence causes @code{Program_Error} exception to be raised.
23614 At first glance, one might say that the binder is misbehaving, because
23615 obviously you want to elaborate the body of something you @code{with}
23617 that is not a general rule that can be followed in all cases. Consider
23619 @smallexample @c ada
23622 package X is @dots{}
23624 package Y is @dots{}
23627 package body Y is @dots{}
23630 package body X is @dots{}
23636 This is a common arrangement, and, apart from the order of elaboration
23637 problems that might arise in connection with elaboration code, this works fine.
23638 A rule that says that you must first elaborate the body of anything you
23639 @code{with} cannot work in this case:
23640 the body of @code{X} @code{with}'s @code{Y},
23641 which means you would have to
23642 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
23644 you have to elaborate the body of @code{X} first, but @dots{} and we have a
23645 loop that cannot be broken.
23647 It is true that the binder can in many cases guess an order of elaboration
23648 that is unlikely to cause a @code{Program_Error}
23649 exception to be raised, and it tries to do so (in the
23650 above example of @code{Math/Stuff/Spec}, the GNAT binder will
23652 elaborate the body of @code{Math} right after its spec, so all will be well).
23654 However, a program that blindly relies on the binder to be helpful can
23655 get into trouble, as we discussed in the previous sections, so
23657 provides a number of facilities for assisting the programmer in
23658 developing programs that are robust with respect to elaboration order.
23660 @node Default Behavior in GNAT - Ensuring Safety
23661 @section Default Behavior in GNAT - Ensuring Safety
23664 The default behavior in GNAT ensures elaboration safety. In its
23665 default mode GNAT implements the
23666 rule we previously described as the right approach. Let's restate it:
23670 @emph{If a unit has elaboration code that can directly or indirectly make a
23671 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
23672 package in a @code{with}'ed unit, then if the @code{with}'ed unit
23673 does not have pragma @code{Pure} or
23674 @code{Preelaborate}, then the client should have an
23675 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
23677 @emph{In the case of instantiating a generic subprogram, it is always
23678 sufficient to have only an @code{Elaborate} pragma for the
23679 @code{with}'ed unit.}
23683 By following this rule a client is assured that calls and instantiations
23684 can be made without risk of an exception.
23686 In this mode GNAT traces all calls that are potentially made from
23687 elaboration code, and puts in any missing implicit @code{Elaborate}
23688 and @code{Elaborate_All} pragmas.
23689 The advantage of this approach is that no elaboration problems
23690 are possible if the binder can find an elaboration order that is
23691 consistent with these implicit @code{Elaborate} and
23692 @code{Elaborate_All} pragmas. The
23693 disadvantage of this approach is that no such order may exist.
23695 If the binder does not generate any diagnostics, then it means that it has
23696 found an elaboration order that is guaranteed to be safe. However, the binder
23697 may still be relying on implicitly generated @code{Elaborate} and
23698 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
23701 If it is important to guarantee portability, then the compilations should
23704 (warn on elaboration problems) switch. This will cause warning messages
23705 to be generated indicating the missing @code{Elaborate} and
23706 @code{Elaborate_All} pragmas.
23707 Consider the following source program:
23709 @smallexample @c ada
23714 m : integer := k.r;
23721 where it is clear that there
23722 should be a pragma @code{Elaborate_All}
23723 for unit @code{k}. An implicit pragma will be generated, and it is
23724 likely that the binder will be able to honor it. However, if you want
23725 to port this program to some other Ada compiler than GNAT.
23726 it is safer to include the pragma explicitly in the source. If this
23727 unit is compiled with the
23729 switch, then the compiler outputs a warning:
23736 3. m : integer := k.r;
23738 >>> warning: call to "r" may raise Program_Error
23739 >>> warning: missing pragma Elaborate_All for "k"
23747 and these warnings can be used as a guide for supplying manually
23748 the missing pragmas. It is usually a bad idea to use this warning
23749 option during development. That's because it will warn you when
23750 you need to put in a pragma, but cannot warn you when it is time
23751 to take it out. So the use of pragma @code{Elaborate_All} may lead to
23752 unnecessary dependencies and even false circularities.
23754 This default mode is more restrictive than the Ada Reference
23755 Manual, and it is possible to construct programs which will compile
23756 using the dynamic model described there, but will run into a
23757 circularity using the safer static model we have described.
23759 Of course any Ada compiler must be able to operate in a mode
23760 consistent with the requirements of the Ada Reference Manual,
23761 and in particular must have the capability of implementing the
23762 standard dynamic model of elaboration with run-time checks.
23764 In GNAT, this standard mode can be achieved either by the use of
23765 the @option{-gnatE} switch on the compiler (@command{gcc} or
23766 @command{gnatmake}) command, or by the use of the configuration pragma:
23768 @smallexample @c ada
23769 pragma Elaboration_Checks (DYNAMIC);
23773 Either approach will cause the unit affected to be compiled using the
23774 standard dynamic run-time elaboration checks described in the Ada
23775 Reference Manual. The static model is generally preferable, since it
23776 is clearly safer to rely on compile and link time checks rather than
23777 run-time checks. However, in the case of legacy code, it may be
23778 difficult to meet the requirements of the static model. This
23779 issue is further discussed in
23780 @ref{What to Do If the Default Elaboration Behavior Fails}.
23782 Note that the static model provides a strict subset of the allowed
23783 behavior and programs of the Ada Reference Manual, so if you do
23784 adhere to the static model and no circularities exist,
23785 then you are assured that your program will
23786 work using the dynamic model, providing that you remove any
23787 pragma Elaborate statements from the source.
23789 @node Treatment of Pragma Elaborate
23790 @section Treatment of Pragma Elaborate
23791 @cindex Pragma Elaborate
23794 The use of @code{pragma Elaborate}
23795 should generally be avoided in Ada 95 and Ada 2005 programs,
23796 since there is no guarantee that transitive calls
23797 will be properly handled. Indeed at one point, this pragma was placed
23798 in Annex J (Obsolescent Features), on the grounds that it is never useful.
23800 Now that's a bit restrictive. In practice, the case in which
23801 @code{pragma Elaborate} is useful is when the caller knows that there
23802 are no transitive calls, or that the called unit contains all necessary
23803 transitive @code{pragma Elaborate} statements, and legacy code often
23804 contains such uses.
23806 Strictly speaking the static mode in GNAT should ignore such pragmas,
23807 since there is no assurance at compile time that the necessary safety
23808 conditions are met. In practice, this would cause GNAT to be incompatible
23809 with correctly written Ada 83 code that had all necessary
23810 @code{pragma Elaborate} statements in place. Consequently, we made the
23811 decision that GNAT in its default mode will believe that if it encounters
23812 a @code{pragma Elaborate} then the programmer knows what they are doing,
23813 and it will trust that no elaboration errors can occur.
23815 The result of this decision is two-fold. First to be safe using the
23816 static mode, you should remove all @code{pragma Elaborate} statements.
23817 Second, when fixing circularities in existing code, you can selectively
23818 use @code{pragma Elaborate} statements to convince the static mode of
23819 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
23822 When using the static mode with @option{-gnatwl}, any use of
23823 @code{pragma Elaborate} will generate a warning about possible
23826 @node Elaboration Issues for Library Tasks
23827 @section Elaboration Issues for Library Tasks
23828 @cindex Library tasks, elaboration issues
23829 @cindex Elaboration of library tasks
23832 In this section we examine special elaboration issues that arise for
23833 programs that declare library level tasks.
23835 Generally the model of execution of an Ada program is that all units are
23836 elaborated, and then execution of the program starts. However, the
23837 declaration of library tasks definitely does not fit this model. The
23838 reason for this is that library tasks start as soon as they are declared
23839 (more precisely, as soon as the statement part of the enclosing package
23840 body is reached), that is to say before elaboration
23841 of the program is complete. This means that if such a task calls a
23842 subprogram, or an entry in another task, the callee may or may not be
23843 elaborated yet, and in the standard
23844 Reference Manual model of dynamic elaboration checks, you can even
23845 get timing dependent Program_Error exceptions, since there can be
23846 a race between the elaboration code and the task code.
23848 The static model of elaboration in GNAT seeks to avoid all such
23849 dynamic behavior, by being conservative, and the conservative
23850 approach in this particular case is to assume that all the code
23851 in a task body is potentially executed at elaboration time if
23852 a task is declared at the library level.
23854 This can definitely result in unexpected circularities. Consider
23855 the following example
23857 @smallexample @c ada
23863 type My_Int is new Integer;
23865 function Ident (M : My_Int) return My_Int;
23869 package body Decls is
23870 task body Lib_Task is
23876 function Ident (M : My_Int) return My_Int is
23884 procedure Put_Val (Arg : Decls.My_Int);
23888 package body Utils is
23889 procedure Put_Val (Arg : Decls.My_Int) is
23891 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23898 Decls.Lib_Task.Start;
23903 If the above example is compiled in the default static elaboration
23904 mode, then a circularity occurs. The circularity comes from the call
23905 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
23906 this call occurs in elaboration code, we need an implicit pragma
23907 @code{Elaborate_All} for @code{Utils}. This means that not only must
23908 the spec and body of @code{Utils} be elaborated before the body
23909 of @code{Decls}, but also the spec and body of any unit that is
23910 @code{with'ed} by the body of @code{Utils} must also be elaborated before
23911 the body of @code{Decls}. This is the transitive implication of
23912 pragma @code{Elaborate_All} and it makes sense, because in general
23913 the body of @code{Put_Val} might have a call to something in a
23914 @code{with'ed} unit.
23916 In this case, the body of Utils (actually its spec) @code{with's}
23917 @code{Decls}. Unfortunately this means that the body of @code{Decls}
23918 must be elaborated before itself, in case there is a call from the
23919 body of @code{Utils}.
23921 Here is the exact chain of events we are worrying about:
23925 In the body of @code{Decls} a call is made from within the body of a library
23926 task to a subprogram in the package @code{Utils}. Since this call may
23927 occur at elaboration time (given that the task is activated at elaboration
23928 time), we have to assume the worst, i.e., that the
23929 call does happen at elaboration time.
23932 This means that the body and spec of @code{Util} must be elaborated before
23933 the body of @code{Decls} so that this call does not cause an access before
23937 Within the body of @code{Util}, specifically within the body of
23938 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
23942 One such @code{with}'ed package is package @code{Decls}, so there
23943 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
23944 In fact there is such a call in this example, but we would have to
23945 assume that there was such a call even if it were not there, since
23946 we are not supposed to write the body of @code{Decls} knowing what
23947 is in the body of @code{Utils}; certainly in the case of the
23948 static elaboration model, the compiler does not know what is in
23949 other bodies and must assume the worst.
23952 This means that the spec and body of @code{Decls} must also be
23953 elaborated before we elaborate the unit containing the call, but
23954 that unit is @code{Decls}! This means that the body of @code{Decls}
23955 must be elaborated before itself, and that's a circularity.
23959 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
23960 the body of @code{Decls} you will get a true Ada Reference Manual
23961 circularity that makes the program illegal.
23963 In practice, we have found that problems with the static model of
23964 elaboration in existing code often arise from library tasks, so
23965 we must address this particular situation.
23967 Note that if we compile and run the program above, using the dynamic model of
23968 elaboration (that is to say use the @option{-gnatE} switch),
23969 then it compiles, binds,
23970 links, and runs, printing the expected result of 2. Therefore in some sense
23971 the circularity here is only apparent, and we need to capture
23972 the properties of this program that distinguish it from other library-level
23973 tasks that have real elaboration problems.
23975 We have four possible answers to this question:
23980 Use the dynamic model of elaboration.
23982 If we use the @option{-gnatE} switch, then as noted above, the program works.
23983 Why is this? If we examine the task body, it is apparent that the task cannot
23985 @code{accept} statement until after elaboration has been completed, because
23986 the corresponding entry call comes from the main program, not earlier.
23987 This is why the dynamic model works here. But that's really giving
23988 up on a precise analysis, and we prefer to take this approach only if we cannot
23990 problem in any other manner. So let us examine two ways to reorganize
23991 the program to avoid the potential elaboration problem.
23994 Split library tasks into separate packages.
23996 Write separate packages, so that library tasks are isolated from
23997 other declarations as much as possible. Let us look at a variation on
24000 @smallexample @c ada
24008 package body Decls1 is
24009 task body Lib_Task is
24017 type My_Int is new Integer;
24018 function Ident (M : My_Int) return My_Int;
24022 package body Decls2 is
24023 function Ident (M : My_Int) return My_Int is
24031 procedure Put_Val (Arg : Decls2.My_Int);
24035 package body Utils is
24036 procedure Put_Val (Arg : Decls2.My_Int) is
24038 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
24045 Decls1.Lib_Task.Start;
24050 All we have done is to split @code{Decls} into two packages, one
24051 containing the library task, and one containing everything else. Now
24052 there is no cycle, and the program compiles, binds, links and executes
24053 using the default static model of elaboration.
24056 Declare separate task types.
24058 A significant part of the problem arises because of the use of the
24059 single task declaration form. This means that the elaboration of
24060 the task type, and the elaboration of the task itself (i.e.@: the
24061 creation of the task) happen at the same time. A good rule
24062 of style in Ada is to always create explicit task types. By
24063 following the additional step of placing task objects in separate
24064 packages from the task type declaration, many elaboration problems
24065 are avoided. Here is another modified example of the example program:
24067 @smallexample @c ada
24069 task type Lib_Task_Type is
24073 type My_Int is new Integer;
24075 function Ident (M : My_Int) return My_Int;
24079 package body Decls is
24080 task body Lib_Task_Type is
24086 function Ident (M : My_Int) return My_Int is
24094 procedure Put_Val (Arg : Decls.My_Int);
24098 package body Utils is
24099 procedure Put_Val (Arg : Decls.My_Int) is
24101 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24107 Lib_Task : Decls.Lib_Task_Type;
24113 Declst.Lib_Task.Start;
24118 What we have done here is to replace the @code{task} declaration in
24119 package @code{Decls} with a @code{task type} declaration. Then we
24120 introduce a separate package @code{Declst} to contain the actual
24121 task object. This separates the elaboration issues for
24122 the @code{task type}
24123 declaration, which causes no trouble, from the elaboration issues
24124 of the task object, which is also unproblematic, since it is now independent
24125 of the elaboration of @code{Utils}.
24126 This separation of concerns also corresponds to
24127 a generally sound engineering principle of separating declarations
24128 from instances. This version of the program also compiles, binds, links,
24129 and executes, generating the expected output.
24132 Use No_Entry_Calls_In_Elaboration_Code restriction.
24133 @cindex No_Entry_Calls_In_Elaboration_Code
24135 The previous two approaches described how a program can be restructured
24136 to avoid the special problems caused by library task bodies. in practice,
24137 however, such restructuring may be difficult to apply to existing legacy code,
24138 so we must consider solutions that do not require massive rewriting.
24140 Let us consider more carefully why our original sample program works
24141 under the dynamic model of elaboration. The reason is that the code
24142 in the task body blocks immediately on the @code{accept}
24143 statement. Now of course there is nothing to prohibit elaboration
24144 code from making entry calls (for example from another library level task),
24145 so we cannot tell in isolation that
24146 the task will not execute the accept statement during elaboration.
24148 However, in practice it is very unusual to see elaboration code
24149 make any entry calls, and the pattern of tasks starting
24150 at elaboration time and then immediately blocking on @code{accept} or
24151 @code{select} statements is very common. What this means is that
24152 the compiler is being too pessimistic when it analyzes the
24153 whole package body as though it might be executed at elaboration
24156 If we know that the elaboration code contains no entry calls, (a very safe
24157 assumption most of the time, that could almost be made the default
24158 behavior), then we can compile all units of the program under control
24159 of the following configuration pragma:
24162 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
24166 This pragma can be placed in the @file{gnat.adc} file in the usual
24167 manner. If we take our original unmodified program and compile it
24168 in the presence of a @file{gnat.adc} containing the above pragma,
24169 then once again, we can compile, bind, link, and execute, obtaining
24170 the expected result. In the presence of this pragma, the compiler does
24171 not trace calls in a task body, that appear after the first @code{accept}
24172 or @code{select} statement, and therefore does not report a potential
24173 circularity in the original program.
24175 The compiler will check to the extent it can that the above
24176 restriction is not violated, but it is not always possible to do a
24177 complete check at compile time, so it is important to use this
24178 pragma only if the stated restriction is in fact met, that is to say
24179 no task receives an entry call before elaboration of all units is completed.
24183 @node Mixing Elaboration Models
24184 @section Mixing Elaboration Models
24186 So far, we have assumed that the entire program is either compiled
24187 using the dynamic model or static model, ensuring consistency. It
24188 is possible to mix the two models, but rules have to be followed
24189 if this mixing is done to ensure that elaboration checks are not
24192 The basic rule is that @emph{a unit compiled with the static model cannot
24193 be @code{with'ed} by a unit compiled with the dynamic model}. The
24194 reason for this is that in the static model, a unit assumes that
24195 its clients guarantee to use (the equivalent of) pragma
24196 @code{Elaborate_All} so that no elaboration checks are required
24197 in inner subprograms, and this assumption is violated if the
24198 client is compiled with dynamic checks.
24200 The precise rule is as follows. A unit that is compiled with dynamic
24201 checks can only @code{with} a unit that meets at least one of the
24202 following criteria:
24207 The @code{with'ed} unit is itself compiled with dynamic elaboration
24208 checks (that is with the @option{-gnatE} switch.
24211 The @code{with'ed} unit is an internal GNAT implementation unit from
24212 the System, Interfaces, Ada, or GNAT hierarchies.
24215 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
24218 The @code{with'ing} unit (that is the client) has an explicit pragma
24219 @code{Elaborate_All} for the @code{with'ed} unit.
24224 If this rule is violated, that is if a unit with dynamic elaboration
24225 checks @code{with's} a unit that does not meet one of the above four
24226 criteria, then the binder (@code{gnatbind}) will issue a warning
24227 similar to that in the following example:
24230 warning: "x.ads" has dynamic elaboration checks and with's
24231 warning: "y.ads" which has static elaboration checks
24235 These warnings indicate that the rule has been violated, and that as a result
24236 elaboration checks may be missed in the resulting executable file.
24237 This warning may be suppressed using the @option{-ws} binder switch
24238 in the usual manner.
24240 One useful application of this mixing rule is in the case of a subsystem
24241 which does not itself @code{with} units from the remainder of the
24242 application. In this case, the entire subsystem can be compiled with
24243 dynamic checks to resolve a circularity in the subsystem, while
24244 allowing the main application that uses this subsystem to be compiled
24245 using the more reliable default static model.
24247 @node What to Do If the Default Elaboration Behavior Fails
24248 @section What to Do If the Default Elaboration Behavior Fails
24251 If the binder cannot find an acceptable order, it outputs detailed
24252 diagnostics. For example:
24258 error: elaboration circularity detected
24259 info: "proc (body)" must be elaborated before "pack (body)"
24260 info: reason: Elaborate_All probably needed in unit "pack (body)"
24261 info: recompile "pack (body)" with -gnatwl
24262 info: for full details
24263 info: "proc (body)"
24264 info: is needed by its spec:
24265 info: "proc (spec)"
24266 info: which is withed by:
24267 info: "pack (body)"
24268 info: "pack (body)" must be elaborated before "proc (body)"
24269 info: reason: pragma Elaborate in unit "proc (body)"
24275 In this case we have a cycle that the binder cannot break. On the one
24276 hand, there is an explicit pragma Elaborate in @code{proc} for
24277 @code{pack}. This means that the body of @code{pack} must be elaborated
24278 before the body of @code{proc}. On the other hand, there is elaboration
24279 code in @code{pack} that calls a subprogram in @code{proc}. This means
24280 that for maximum safety, there should really be a pragma
24281 Elaborate_All in @code{pack} for @code{proc} which would require that
24282 the body of @code{proc} be elaborated before the body of
24283 @code{pack}. Clearly both requirements cannot be satisfied.
24284 Faced with a circularity of this kind, you have three different options.
24287 @item Fix the program
24288 The most desirable option from the point of view of long-term maintenance
24289 is to rearrange the program so that the elaboration problems are avoided.
24290 One useful technique is to place the elaboration code into separate
24291 child packages. Another is to move some of the initialization code to
24292 explicitly called subprograms, where the program controls the order
24293 of initialization explicitly. Although this is the most desirable option,
24294 it may be impractical and involve too much modification, especially in
24295 the case of complex legacy code.
24297 @item Perform dynamic checks
24298 If the compilations are done using the
24300 (dynamic elaboration check) switch, then GNAT behaves in a quite different
24301 manner. Dynamic checks are generated for all calls that could possibly result
24302 in raising an exception. With this switch, the compiler does not generate
24303 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
24304 exactly as specified in the @cite{Ada Reference Manual}.
24305 The binder will generate
24306 an executable program that may or may not raise @code{Program_Error}, and then
24307 it is the programmer's job to ensure that it does not raise an exception. Note
24308 that it is important to compile all units with the switch, it cannot be used
24311 @item Suppress checks
24312 The drawback of dynamic checks is that they generate a
24313 significant overhead at run time, both in space and time. If you
24314 are absolutely sure that your program cannot raise any elaboration
24315 exceptions, and you still want to use the dynamic elaboration model,
24316 then you can use the configuration pragma
24317 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
24318 example this pragma could be placed in the @file{gnat.adc} file.
24320 @item Suppress checks selectively
24321 When you know that certain calls or instantiations in elaboration code cannot
24322 possibly lead to an elaboration error, and the binder nevertheless complains
24323 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
24324 elaboration circularities, it is possible to remove those warnings locally and
24325 obtain a program that will bind. Clearly this can be unsafe, and it is the
24326 responsibility of the programmer to make sure that the resulting program has no
24327 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
24328 used with different granularity to suppress warnings and break elaboration
24333 Place the pragma that names the called subprogram in the declarative part
24334 that contains the call.
24337 Place the pragma in the declarative part, without naming an entity. This
24338 disables warnings on all calls in the corresponding declarative region.
24341 Place the pragma in the package spec that declares the called subprogram,
24342 and name the subprogram. This disables warnings on all elaboration calls to
24346 Place the pragma in the package spec that declares the called subprogram,
24347 without naming any entity. This disables warnings on all elaboration calls to
24348 all subprograms declared in this spec.
24350 @item Use Pragma Elaborate
24351 As previously described in section @xref{Treatment of Pragma Elaborate},
24352 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
24353 that no elaboration checks are required on calls to the designated unit.
24354 There may be cases in which the caller knows that no transitive calls
24355 can occur, so that a @code{pragma Elaborate} will be sufficient in a
24356 case where @code{pragma Elaborate_All} would cause a circularity.
24360 These five cases are listed in order of decreasing safety, and therefore
24361 require increasing programmer care in their application. Consider the
24364 @smallexample @c adanocomment
24366 function F1 return Integer;
24371 function F2 return Integer;
24372 function Pure (x : integer) return integer;
24373 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
24374 -- pragma Suppress (Elaboration_Check); -- (4)
24378 package body Pack1 is
24379 function F1 return Integer is
24383 Val : integer := Pack2.Pure (11); -- Elab. call (1)
24386 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
24387 -- pragma Suppress(Elaboration_Check); -- (2)
24389 X1 := Pack2.F2 + 1; -- Elab. call (2)
24394 package body Pack2 is
24395 function F2 return Integer is
24399 function Pure (x : integer) return integer is
24401 return x ** 3 - 3 * x;
24405 with Pack1, Ada.Text_IO;
24408 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24411 In the absence of any pragmas, an attempt to bind this program produces
24412 the following diagnostics:
24418 error: elaboration circularity detected
24419 info: "pack1 (body)" must be elaborated before "pack1 (body)"
24420 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
24421 info: recompile "pack1 (body)" with -gnatwl for full details
24422 info: "pack1 (body)"
24423 info: must be elaborated along with its spec:
24424 info: "pack1 (spec)"
24425 info: which is withed by:
24426 info: "pack2 (body)"
24427 info: which must be elaborated along with its spec:
24428 info: "pack2 (spec)"
24429 info: which is withed by:
24430 info: "pack1 (body)"
24433 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24434 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24435 F2 is safe, even though F2 calls F1, because the call appears after the
24436 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24437 remove the warning on the call. It is also possible to use pragma (2)
24438 because there are no other potentially unsafe calls in the block.
24441 The call to @code{Pure} is safe because this function does not depend on the
24442 state of @code{Pack2}. Therefore any call to this function is safe, and it
24443 is correct to place pragma (3) in the corresponding package spec.
24446 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24447 warnings on all calls to functions declared therein. Note that this is not
24448 necessarily safe, and requires more detailed examination of the subprogram
24449 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24450 be already elaborated.
24454 It is hard to generalize on which of these four approaches should be
24455 taken. Obviously if it is possible to fix the program so that the default
24456 treatment works, this is preferable, but this may not always be practical.
24457 It is certainly simple enough to use
24459 but the danger in this case is that, even if the GNAT binder
24460 finds a correct elaboration order, it may not always do so,
24461 and certainly a binder from another Ada compiler might not. A
24462 combination of testing and analysis (for which the warnings generated
24465 switch can be useful) must be used to ensure that the program is free
24466 of errors. One switch that is useful in this testing is the
24467 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
24470 Normally the binder tries to find an order that has the best chance
24471 of avoiding elaboration problems. However, if this switch is used, the binder
24472 plays a devil's advocate role, and tries to choose the order that
24473 has the best chance of failing. If your program works even with this
24474 switch, then it has a better chance of being error free, but this is still
24477 For an example of this approach in action, consider the C-tests (executable
24478 tests) from the ACVC suite. If these are compiled and run with the default
24479 treatment, then all but one of them succeed without generating any error
24480 diagnostics from the binder. However, there is one test that fails, and
24481 this is not surprising, because the whole point of this test is to ensure
24482 that the compiler can handle cases where it is impossible to determine
24483 a correct order statically, and it checks that an exception is indeed
24484 raised at run time.
24486 This one test must be compiled and run using the
24488 switch, and then it passes. Alternatively, the entire suite can
24489 be run using this switch. It is never wrong to run with the dynamic
24490 elaboration switch if your code is correct, and we assume that the
24491 C-tests are indeed correct (it is less efficient, but efficiency is
24492 not a factor in running the ACVC tests.)
24494 @node Elaboration for Access-to-Subprogram Values
24495 @section Elaboration for Access-to-Subprogram Values
24496 @cindex Access-to-subprogram
24499 Access-to-subprogram types (introduced in Ada 95) complicate
24500 the handling of elaboration. The trouble is that it becomes
24501 impossible to tell at compile time which procedure
24502 is being called. This means that it is not possible for the binder
24503 to analyze the elaboration requirements in this case.
24505 If at the point at which the access value is created
24506 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
24507 the body of the subprogram is
24508 known to have been elaborated, then the access value is safe, and its use
24509 does not require a check. This may be achieved by appropriate arrangement
24510 of the order of declarations if the subprogram is in the current unit,
24511 or, if the subprogram is in another unit, by using pragma
24512 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
24513 on the referenced unit.
24515 If the referenced body is not known to have been elaborated at the point
24516 the access value is created, then any use of the access value must do a
24517 dynamic check, and this dynamic check will fail and raise a
24518 @code{Program_Error} exception if the body has not been elaborated yet.
24519 GNAT will generate the necessary checks, and in addition, if the
24521 switch is set, will generate warnings that such checks are required.
24523 The use of dynamic dispatching for tagged types similarly generates
24524 a requirement for dynamic checks, and premature calls to any primitive
24525 operation of a tagged type before the body of the operation has been
24526 elaborated, will result in the raising of @code{Program_Error}.
24528 @node Summary of Procedures for Elaboration Control
24529 @section Summary of Procedures for Elaboration Control
24530 @cindex Elaboration control
24533 First, compile your program with the default options, using none of
24534 the special elaboration control switches. If the binder successfully
24535 binds your program, then you can be confident that, apart from issues
24536 raised by the use of access-to-subprogram types and dynamic dispatching,
24537 the program is free of elaboration errors. If it is important that the
24538 program be portable, then use the
24540 switch to generate warnings about missing @code{Elaborate} or
24541 @code{Elaborate_All} pragmas, and supply the missing pragmas.
24543 If the program fails to bind using the default static elaboration
24544 handling, then you can fix the program to eliminate the binder
24545 message, or recompile the entire program with the
24546 @option{-gnatE} switch to generate dynamic elaboration checks,
24547 and, if you are sure there really are no elaboration problems,
24548 use a global pragma @code{Suppress (Elaboration_Check)}.
24550 @node Other Elaboration Order Considerations
24551 @section Other Elaboration Order Considerations
24553 This section has been entirely concerned with the issue of finding a valid
24554 elaboration order, as defined by the Ada Reference Manual. In a case
24555 where several elaboration orders are valid, the task is to find one
24556 of the possible valid elaboration orders (and the static model in GNAT
24557 will ensure that this is achieved).
24559 The purpose of the elaboration rules in the Ada Reference Manual is to
24560 make sure that no entity is accessed before it has been elaborated. For
24561 a subprogram, this means that the spec and body must have been elaborated
24562 before the subprogram is called. For an object, this means that the object
24563 must have been elaborated before its value is read or written. A violation
24564 of either of these two requirements is an access before elaboration order,
24565 and this section has been all about avoiding such errors.
24567 In the case where more than one order of elaboration is possible, in the
24568 sense that access before elaboration errors are avoided, then any one of
24569 the orders is ``correct'' in the sense that it meets the requirements of
24570 the Ada Reference Manual, and no such error occurs.
24572 However, it may be the case for a given program, that there are
24573 constraints on the order of elaboration that come not from consideration
24574 of avoiding elaboration errors, but rather from extra-lingual logic
24575 requirements. Consider this example:
24577 @smallexample @c ada
24578 with Init_Constants;
24579 package Constants is
24584 package Init_Constants is
24585 procedure P; -- require a body
24586 end Init_Constants;
24589 package body Init_Constants is
24590 procedure P is begin null; end;
24594 end Init_Constants;
24598 Z : Integer := Constants.X + Constants.Y;
24602 with Text_IO; use Text_IO;
24605 Put_Line (Calc.Z'Img);
24610 In this example, there is more than one valid order of elaboration. For
24611 example both the following are correct orders:
24614 Init_Constants spec
24617 Init_Constants body
24622 Init_Constants spec
24623 Init_Constants body
24630 There is no language rule to prefer one or the other, both are correct
24631 from an order of elaboration point of view. But the programmatic effects
24632 of the two orders are very different. In the first, the elaboration routine
24633 of @code{Calc} initializes @code{Z} to zero, and then the main program
24634 runs with this value of zero. But in the second order, the elaboration
24635 routine of @code{Calc} runs after the body of Init_Constants has set
24636 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
24639 One could perhaps by applying pretty clever non-artificial intelligence
24640 to the situation guess that it is more likely that the second order of
24641 elaboration is the one desired, but there is no formal linguistic reason
24642 to prefer one over the other. In fact in this particular case, GNAT will
24643 prefer the second order, because of the rule that bodies are elaborated
24644 as soon as possible, but it's just luck that this is what was wanted
24645 (if indeed the second order was preferred).
24647 If the program cares about the order of elaboration routines in a case like
24648 this, it is important to specify the order required. In this particular
24649 case, that could have been achieved by adding to the spec of Calc:
24651 @smallexample @c ada
24652 pragma Elaborate_All (Constants);
24656 which requires that the body (if any) and spec of @code{Constants},
24657 as well as the body and spec of any unit @code{with}'ed by
24658 @code{Constants} be elaborated before @code{Calc} is elaborated.
24660 Clearly no automatic method can always guess which alternative you require,
24661 and if you are working with legacy code that had constraints of this kind
24662 which were not properly specified by adding @code{Elaborate} or
24663 @code{Elaborate_All} pragmas, then indeed it is possible that two different
24664 compilers can choose different orders.
24666 However, GNAT does attempt to diagnose the common situation where there
24667 are uninitialized variables in the visible part of a package spec, and the
24668 corresponding package body has an elaboration block that directly or
24669 indirectly initialized one or more of these variables. This is the situation
24670 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
24671 a warning that suggests this addition if it detects this situation.
24673 The @code{gnatbind}
24674 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
24675 out problems. This switch causes bodies to be elaborated as late as possible
24676 instead of as early as possible. In the example above, it would have forced
24677 the choice of the first elaboration order. If you get different results
24678 when using this switch, and particularly if one set of results is right,
24679 and one is wrong as far as you are concerned, it shows that you have some
24680 missing @code{Elaborate} pragmas. For the example above, we have the
24684 gnatmake -f -q main
24687 gnatmake -f -q main -bargs -p
24693 It is of course quite unlikely that both these results are correct, so
24694 it is up to you in a case like this to investigate the source of the
24695 difference, by looking at the two elaboration orders that are chosen,
24696 and figuring out which is correct, and then adding the necessary
24697 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
24701 @c *******************************
24702 @node Conditional Compilation
24703 @appendix Conditional Compilation
24704 @c *******************************
24705 @cindex Conditional compilation
24708 It is often necessary to arrange for a single source program
24709 to serve multiple purposes, where it is compiled in different
24710 ways to achieve these different goals. Some examples of the
24711 need for this feature are
24714 @item Adapting a program to a different hardware environment
24715 @item Adapting a program to a different target architecture
24716 @item Turning debugging features on and off
24717 @item Arranging for a program to compile with different compilers
24721 In C, or C++, the typical approach would be to use the preprocessor
24722 that is defined as part of the language. The Ada language does not
24723 contain such a feature. This is not an oversight, but rather a very
24724 deliberate design decision, based on the experience that overuse of
24725 the preprocessing features in C and C++ can result in programs that
24726 are extremely difficult to maintain. For example, if we have ten
24727 switches that can be on or off, this means that there are a thousand
24728 separate programs, any one of which might not even be syntactically
24729 correct, and even if syntactically correct, the resulting program
24730 might not work correctly. Testing all combinations can quickly become
24733 Nevertheless, the need to tailor programs certainly exists, and in
24734 this Appendix we will discuss how this can
24735 be achieved using Ada in general, and GNAT in particular.
24738 * Use of Boolean Constants::
24739 * Debugging - A Special Case::
24740 * Conditionalizing Declarations::
24741 * Use of Alternative Implementations::
24745 @node Use of Boolean Constants
24746 @section Use of Boolean Constants
24749 In the case where the difference is simply which code
24750 sequence is executed, the cleanest solution is to use Boolean
24751 constants to control which code is executed.
24753 @smallexample @c ada
24755 FP_Initialize_Required : constant Boolean := True;
24757 if FP_Initialize_Required then
24764 Not only will the code inside the @code{if} statement not be executed if
24765 the constant Boolean is @code{False}, but it will also be completely
24766 deleted from the program.
24767 However, the code is only deleted after the @code{if} statement
24768 has been checked for syntactic and semantic correctness.
24769 (In contrast, with preprocessors the code is deleted before the
24770 compiler ever gets to see it, so it is not checked until the switch
24772 @cindex Preprocessors (contrasted with conditional compilation)
24774 Typically the Boolean constants will be in a separate package,
24777 @smallexample @c ada
24780 FP_Initialize_Required : constant Boolean := True;
24781 Reset_Available : constant Boolean := False;
24788 The @code{Config} package exists in multiple forms for the various targets,
24789 with an appropriate script selecting the version of @code{Config} needed.
24790 Then any other unit requiring conditional compilation can do a @code{with}
24791 of @code{Config} to make the constants visible.
24794 @node Debugging - A Special Case
24795 @section Debugging - A Special Case
24798 A common use of conditional code is to execute statements (for example
24799 dynamic checks, or output of intermediate results) under control of a
24800 debug switch, so that the debugging behavior can be turned on and off.
24801 This can be done using a Boolean constant to control whether the code
24804 @smallexample @c ada
24807 Put_Line ("got to the first stage!");
24815 @smallexample @c ada
24817 if Debugging and then Temperature > 999.0 then
24818 raise Temperature_Crazy;
24824 Since this is a common case, there are special features to deal with
24825 this in a convenient manner. For the case of tests, Ada 2005 has added
24826 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
24827 @cindex pragma @code{Assert}
24828 on the @code{Assert} pragma that has always been available in GNAT, so this
24829 feature may be used with GNAT even if you are not using Ada 2005 features.
24830 The use of pragma @code{Assert} is described in
24831 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
24832 example, the last test could be written:
24834 @smallexample @c ada
24835 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
24841 @smallexample @c ada
24842 pragma Assert (Temperature <= 999.0);
24846 In both cases, if assertions are active and the temperature is excessive,
24847 the exception @code{Assert_Failure} will be raised, with the given string in
24848 the first case or a string indicating the location of the pragma in the second
24849 case used as the exception message.
24851 You can turn assertions on and off by using the @code{Assertion_Policy}
24853 @cindex pragma @code{Assertion_Policy}
24854 This is an Ada 2005 pragma which is implemented in all modes by
24855 GNAT, but only in the latest versions of GNAT which include Ada 2005
24856 capability. Alternatively, you can use the @option{-gnata} switch
24857 @cindex @option{-gnata} switch
24858 to enable assertions from the command line (this is recognized by all versions
24861 For the example above with the @code{Put_Line}, the GNAT-specific pragma
24862 @code{Debug} can be used:
24863 @cindex pragma @code{Debug}
24865 @smallexample @c ada
24866 pragma Debug (Put_Line ("got to the first stage!"));
24870 If debug pragmas are enabled, the argument, which must be of the form of
24871 a procedure call, is executed (in this case, @code{Put_Line} will be called).
24872 Only one call can be present, but of course a special debugging procedure
24873 containing any code you like can be included in the program and then
24874 called in a pragma @code{Debug} argument as needed.
24876 One advantage of pragma @code{Debug} over the @code{if Debugging then}
24877 construct is that pragma @code{Debug} can appear in declarative contexts,
24878 such as at the very beginning of a procedure, before local declarations have
24881 Debug pragmas are enabled using either the @option{-gnata} switch that also
24882 controls assertions, or with a separate Debug_Policy pragma.
24883 @cindex pragma @code{Debug_Policy}
24884 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
24885 in Ada 95 and Ada 83 programs as well), and is analogous to
24886 pragma @code{Assertion_Policy} to control assertions.
24888 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
24889 and thus they can appear in @file{gnat.adc} if you are not using a
24890 project file, or in the file designated to contain configuration pragmas
24892 They then apply to all subsequent compilations. In practice the use of
24893 the @option{-gnata} switch is often the most convenient method of controlling
24894 the status of these pragmas.
24896 Note that a pragma is not a statement, so in contexts where a statement
24897 sequence is required, you can't just write a pragma on its own. You have
24898 to add a @code{null} statement.
24900 @smallexample @c ada
24903 @dots{} -- some statements
24905 pragma Assert (Num_Cases < 10);
24912 @node Conditionalizing Declarations
24913 @section Conditionalizing Declarations
24916 In some cases, it may be necessary to conditionalize declarations to meet
24917 different requirements. For example we might want a bit string whose length
24918 is set to meet some hardware message requirement.
24920 In some cases, it may be possible to do this using declare blocks controlled
24921 by conditional constants:
24923 @smallexample @c ada
24925 if Small_Machine then
24927 X : Bit_String (1 .. 10);
24933 X : Large_Bit_String (1 .. 1000);
24942 Note that in this approach, both declarations are analyzed by the
24943 compiler so this can only be used where both declarations are legal,
24944 even though one of them will not be used.
24946 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
24947 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
24948 that are parameterized by these constants. For example
24950 @smallexample @c ada
24953 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
24959 If @code{Bits_Per_Word} is set to 32, this generates either
24961 @smallexample @c ada
24964 Field1 at 0 range 0 .. 32;
24970 for the big endian case, or
24972 @smallexample @c ada
24975 Field1 at 0 range 10 .. 32;
24981 for the little endian case. Since a powerful subset of Ada expression
24982 notation is usable for creating static constants, clever use of this
24983 feature can often solve quite difficult problems in conditionalizing
24984 compilation (note incidentally that in Ada 95, the little endian
24985 constant was introduced as @code{System.Default_Bit_Order}, so you do not
24986 need to define this one yourself).
24989 @node Use of Alternative Implementations
24990 @section Use of Alternative Implementations
24993 In some cases, none of the approaches described above are adequate. This
24994 can occur for example if the set of declarations required is radically
24995 different for two different configurations.
24997 In this situation, the official Ada way of dealing with conditionalizing
24998 such code is to write separate units for the different cases. As long as
24999 this does not result in excessive duplication of code, this can be done
25000 without creating maintenance problems. The approach is to share common
25001 code as far as possible, and then isolate the code and declarations
25002 that are different. Subunits are often a convenient method for breaking
25003 out a piece of a unit that is to be conditionalized, with separate files
25004 for different versions of the subunit for different targets, where the
25005 build script selects the right one to give to the compiler.
25006 @cindex Subunits (and conditional compilation)
25008 As an example, consider a situation where a new feature in Ada 2005
25009 allows something to be done in a really nice way. But your code must be able
25010 to compile with an Ada 95 compiler. Conceptually you want to say:
25012 @smallexample @c ada
25015 @dots{} neat Ada 2005 code
25017 @dots{} not quite as neat Ada 95 code
25023 where @code{Ada_2005} is a Boolean constant.
25025 But this won't work when @code{Ada_2005} is set to @code{False},
25026 since the @code{then} clause will be illegal for an Ada 95 compiler.
25027 (Recall that although such unreachable code would eventually be deleted
25028 by the compiler, it still needs to be legal. If it uses features
25029 introduced in Ada 2005, it will be illegal in Ada 95.)
25031 So instead we write
25033 @smallexample @c ada
25034 procedure Insert is separate;
25038 Then we have two files for the subunit @code{Insert}, with the two sets of
25040 If the package containing this is called @code{File_Queries}, then we might
25044 @item @file{file_queries-insert-2005.adb}
25045 @item @file{file_queries-insert-95.adb}
25049 and the build script renames the appropriate file to
25052 file_queries-insert.adb
25056 and then carries out the compilation.
25058 This can also be done with project files' naming schemes. For example:
25060 @smallexample @c project
25061 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
25065 Note also that with project files it is desirable to use a different extension
25066 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
25067 conflict may arise through another commonly used feature: to declare as part
25068 of the project a set of directories containing all the sources obeying the
25069 default naming scheme.
25071 The use of alternative units is certainly feasible in all situations,
25072 and for example the Ada part of the GNAT run-time is conditionalized
25073 based on the target architecture using this approach. As a specific example,
25074 consider the implementation of the AST feature in VMS. There is one
25082 which is the same for all architectures, and three bodies:
25086 used for all non-VMS operating systems
25087 @item s-asthan-vms-alpha.adb
25088 used for VMS on the Alpha
25089 @item s-asthan-vms-ia64.adb
25090 used for VMS on the ia64
25094 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
25095 this operating system feature is not available, and the two remaining
25096 versions interface with the corresponding versions of VMS to provide
25097 VMS-compatible AST handling. The GNAT build script knows the architecture
25098 and operating system, and automatically selects the right version,
25099 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
25101 Another style for arranging alternative implementations is through Ada's
25102 access-to-subprogram facility.
25103 In case some functionality is to be conditionally included,
25104 you can declare an access-to-procedure variable @code{Ref} that is initialized
25105 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
25107 In some library package, set @code{Ref} to @code{Proc'Access} for some
25108 procedure @code{Proc} that performs the relevant processing.
25109 The initialization only occurs if the library package is included in the
25111 The same idea can also be implemented using tagged types and dispatching
25115 @node Preprocessing
25116 @section Preprocessing
25117 @cindex Preprocessing
25120 Although it is quite possible to conditionalize code without the use of
25121 C-style preprocessing, as described earlier in this section, it is
25122 nevertheless convenient in some cases to use the C approach. Moreover,
25123 older Ada compilers have often provided some preprocessing capability,
25124 so legacy code may depend on this approach, even though it is not
25127 To accommodate such use, GNAT provides a preprocessor (modeled to a large
25128 extent on the various preprocessors that have been used
25129 with legacy code on other compilers, to enable easier transition).
25131 The preprocessor may be used in two separate modes. It can be used quite
25132 separately from the compiler, to generate a separate output source file
25133 that is then fed to the compiler as a separate step. This is the
25134 @code{gnatprep} utility, whose use is fully described in
25135 @ref{Preprocessing Using gnatprep}.
25136 @cindex @code{gnatprep}
25138 The preprocessing language allows such constructs as
25142 #if DEBUG or PRIORITY > 4 then
25143 bunch of declarations
25145 completely different bunch of declarations
25151 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
25152 defined either on the command line or in a separate file.
25154 The other way of running the preprocessor is even closer to the C style and
25155 often more convenient. In this approach the preprocessing is integrated into
25156 the compilation process. The compiler is fed the preprocessor input which
25157 includes @code{#if} lines etc, and then the compiler carries out the
25158 preprocessing internally and processes the resulting output.
25159 For more details on this approach, see @ref{Integrated Preprocessing}.
25162 @c *******************************
25163 @node Inline Assembler
25164 @appendix Inline Assembler
25165 @c *******************************
25168 If you need to write low-level software that interacts directly
25169 with the hardware, Ada provides two ways to incorporate assembly
25170 language code into your program. First, you can import and invoke
25171 external routines written in assembly language, an Ada feature fully
25172 supported by GNAT@. However, for small sections of code it may be simpler
25173 or more efficient to include assembly language statements directly
25174 in your Ada source program, using the facilities of the implementation-defined
25175 package @code{System.Machine_Code}, which incorporates the gcc
25176 Inline Assembler. The Inline Assembler approach offers a number of advantages,
25177 including the following:
25180 @item No need to use non-Ada tools
25181 @item Consistent interface over different targets
25182 @item Automatic usage of the proper calling conventions
25183 @item Access to Ada constants and variables
25184 @item Definition of intrinsic routines
25185 @item Possibility of inlining a subprogram comprising assembler code
25186 @item Code optimizer can take Inline Assembler code into account
25189 This chapter presents a series of examples to show you how to use
25190 the Inline Assembler. Although it focuses on the Intel x86,
25191 the general approach applies also to other processors.
25192 It is assumed that you are familiar with Ada
25193 and with assembly language programming.
25196 * Basic Assembler Syntax::
25197 * A Simple Example of Inline Assembler::
25198 * Output Variables in Inline Assembler::
25199 * Input Variables in Inline Assembler::
25200 * Inlining Inline Assembler Code::
25201 * Other Asm Functionality::
25204 @c ---------------------------------------------------------------------------
25205 @node Basic Assembler Syntax
25206 @section Basic Assembler Syntax
25209 The assembler used by GNAT and gcc is based not on the Intel assembly
25210 language, but rather on a language that descends from the AT&T Unix
25211 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
25212 The following table summarizes the main features of @emph{as} syntax
25213 and points out the differences from the Intel conventions.
25214 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
25215 pre-processor) documentation for further information.
25218 @item Register names
25219 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
25221 Intel: No extra punctuation; for example @code{eax}
25223 @item Immediate operand
25224 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
25226 Intel: No extra punctuation; for example @code{4}
25229 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
25231 Intel: No extra punctuation; for example @code{loc}
25233 @item Memory contents
25234 gcc / @emph{as}: No extra punctuation; for example @code{loc}
25236 Intel: Square brackets; for example @code{[loc]}
25238 @item Register contents
25239 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
25241 Intel: Square brackets; for example @code{[eax]}
25243 @item Hexadecimal numbers
25244 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
25246 Intel: Trailing ``h''; for example @code{A0h}
25249 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
25252 Intel: Implicit, deduced by assembler; for example @code{mov}
25254 @item Instruction repetition
25255 gcc / @emph{as}: Split into two lines; for example
25261 Intel: Keep on one line; for example @code{rep stosl}
25263 @item Order of operands
25264 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
25266 Intel: Destination first; for example @code{mov eax, 4}
25269 @c ---------------------------------------------------------------------------
25270 @node A Simple Example of Inline Assembler
25271 @section A Simple Example of Inline Assembler
25274 The following example will generate a single assembly language statement,
25275 @code{nop}, which does nothing. Despite its lack of run-time effect,
25276 the example will be useful in illustrating the basics of
25277 the Inline Assembler facility.
25279 @smallexample @c ada
25281 with System.Machine_Code; use System.Machine_Code;
25282 procedure Nothing is
25289 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
25290 here it takes one parameter, a @emph{template string} that must be a static
25291 expression and that will form the generated instruction.
25292 @code{Asm} may be regarded as a compile-time procedure that parses
25293 the template string and additional parameters (none here),
25294 from which it generates a sequence of assembly language instructions.
25296 The examples in this chapter will illustrate several of the forms
25297 for invoking @code{Asm}; a complete specification of the syntax
25298 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
25301 Under the standard GNAT conventions, the @code{Nothing} procedure
25302 should be in a file named @file{nothing.adb}.
25303 You can build the executable in the usual way:
25307 However, the interesting aspect of this example is not its run-time behavior
25308 but rather the generated assembly code.
25309 To see this output, invoke the compiler as follows:
25311 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
25313 where the options are:
25317 compile only (no bind or link)
25319 generate assembler listing
25320 @item -fomit-frame-pointer
25321 do not set up separate stack frames
25323 do not add runtime checks
25326 This gives a human-readable assembler version of the code. The resulting
25327 file will have the same name as the Ada source file, but with a @code{.s}
25328 extension. In our example, the file @file{nothing.s} has the following
25333 .file "nothing.adb"
25335 ___gnu_compiled_ada:
25338 .globl __ada_nothing
25350 The assembly code you included is clearly indicated by
25351 the compiler, between the @code{#APP} and @code{#NO_APP}
25352 delimiters. The character before the 'APP' and 'NOAPP'
25353 can differ on different targets. For example, GNU/Linux uses '#APP' while
25354 on NT you will see '/APP'.
25356 If you make a mistake in your assembler code (such as using the
25357 wrong size modifier, or using a wrong operand for the instruction) GNAT
25358 will report this error in a temporary file, which will be deleted when
25359 the compilation is finished. Generating an assembler file will help
25360 in such cases, since you can assemble this file separately using the
25361 @emph{as} assembler that comes with gcc.
25363 Assembling the file using the command
25366 as @file{nothing.s}
25369 will give you error messages whose lines correspond to the assembler
25370 input file, so you can easily find and correct any mistakes you made.
25371 If there are no errors, @emph{as} will generate an object file
25372 @file{nothing.out}.
25374 @c ---------------------------------------------------------------------------
25375 @node Output Variables in Inline Assembler
25376 @section Output Variables in Inline Assembler
25379 The examples in this section, showing how to access the processor flags,
25380 illustrate how to specify the destination operands for assembly language
25383 @smallexample @c ada
25385 with Interfaces; use Interfaces;
25386 with Ada.Text_IO; use Ada.Text_IO;
25387 with System.Machine_Code; use System.Machine_Code;
25388 procedure Get_Flags is
25389 Flags : Unsigned_32;
25392 Asm ("pushfl" & LF & HT & -- push flags on stack
25393 "popl %%eax" & LF & HT & -- load eax with flags
25394 "movl %%eax, %0", -- store flags in variable
25395 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25396 Put_Line ("Flags register:" & Flags'Img);
25401 In order to have a nicely aligned assembly listing, we have separated
25402 multiple assembler statements in the Asm template string with linefeed
25403 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
25404 The resulting section of the assembly output file is:
25411 movl %eax, -40(%ebp)
25416 It would have been legal to write the Asm invocation as:
25419 Asm ("pushfl popl %%eax movl %%eax, %0")
25422 but in the generated assembler file, this would come out as:
25426 pushfl popl %eax movl %eax, -40(%ebp)
25430 which is not so convenient for the human reader.
25432 We use Ada comments
25433 at the end of each line to explain what the assembler instructions
25434 actually do. This is a useful convention.
25436 When writing Inline Assembler instructions, you need to precede each register
25437 and variable name with a percent sign. Since the assembler already requires
25438 a percent sign at the beginning of a register name, you need two consecutive
25439 percent signs for such names in the Asm template string, thus @code{%%eax}.
25440 In the generated assembly code, one of the percent signs will be stripped off.
25442 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
25443 variables: operands you later define using @code{Input} or @code{Output}
25444 parameters to @code{Asm}.
25445 An output variable is illustrated in
25446 the third statement in the Asm template string:
25450 The intent is to store the contents of the eax register in a variable that can
25451 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
25452 necessarily work, since the compiler might optimize by using a register
25453 to hold Flags, and the expansion of the @code{movl} instruction would not be
25454 aware of this optimization. The solution is not to store the result directly
25455 but rather to advise the compiler to choose the correct operand form;
25456 that is the purpose of the @code{%0} output variable.
25458 Information about the output variable is supplied in the @code{Outputs}
25459 parameter to @code{Asm}:
25461 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25464 The output is defined by the @code{Asm_Output} attribute of the target type;
25465 the general format is
25467 Type'Asm_Output (constraint_string, variable_name)
25470 The constraint string directs the compiler how
25471 to store/access the associated variable. In the example
25473 Unsigned_32'Asm_Output ("=m", Flags);
25475 the @code{"m"} (memory) constraint tells the compiler that the variable
25476 @code{Flags} should be stored in a memory variable, thus preventing
25477 the optimizer from keeping it in a register. In contrast,
25479 Unsigned_32'Asm_Output ("=r", Flags);
25481 uses the @code{"r"} (register) constraint, telling the compiler to
25482 store the variable in a register.
25484 If the constraint is preceded by the equal character (@strong{=}), it tells
25485 the compiler that the variable will be used to store data into it.
25487 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
25488 allowing the optimizer to choose whatever it deems best.
25490 There are a fairly large number of constraints, but the ones that are
25491 most useful (for the Intel x86 processor) are the following:
25497 global (i.e.@: can be stored anywhere)
25515 use one of eax, ebx, ecx or edx
25517 use one of eax, ebx, ecx, edx, esi or edi
25520 The full set of constraints is described in the gcc and @emph{as}
25521 documentation; note that it is possible to combine certain constraints
25522 in one constraint string.
25524 You specify the association of an output variable with an assembler operand
25525 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
25527 @smallexample @c ada
25529 Asm ("pushfl" & LF & HT & -- push flags on stack
25530 "popl %%eax" & LF & HT & -- load eax with flags
25531 "movl %%eax, %0", -- store flags in variable
25532 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25536 @code{%0} will be replaced in the expanded code by the appropriate operand,
25538 the compiler decided for the @code{Flags} variable.
25540 In general, you may have any number of output variables:
25543 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
25545 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
25546 of @code{Asm_Output} attributes
25550 @smallexample @c ada
25552 Asm ("movl %%eax, %0" & LF & HT &
25553 "movl %%ebx, %1" & LF & HT &
25555 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
25556 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
25557 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
25561 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
25562 in the Ada program.
25564 As a variation on the @code{Get_Flags} example, we can use the constraints
25565 string to direct the compiler to store the eax register into the @code{Flags}
25566 variable, instead of including the store instruction explicitly in the
25567 @code{Asm} template string:
25569 @smallexample @c ada
25571 with Interfaces; use Interfaces;
25572 with Ada.Text_IO; use Ada.Text_IO;
25573 with System.Machine_Code; use System.Machine_Code;
25574 procedure Get_Flags_2 is
25575 Flags : Unsigned_32;
25578 Asm ("pushfl" & LF & HT & -- push flags on stack
25579 "popl %%eax", -- save flags in eax
25580 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
25581 Put_Line ("Flags register:" & Flags'Img);
25587 The @code{"a"} constraint tells the compiler that the @code{Flags}
25588 variable will come from the eax register. Here is the resulting code:
25596 movl %eax,-40(%ebp)
25601 The compiler generated the store of eax into Flags after
25602 expanding the assembler code.
25604 Actually, there was no need to pop the flags into the eax register;
25605 more simply, we could just pop the flags directly into the program variable:
25607 @smallexample @c ada
25609 with Interfaces; use Interfaces;
25610 with Ada.Text_IO; use Ada.Text_IO;
25611 with System.Machine_Code; use System.Machine_Code;
25612 procedure Get_Flags_3 is
25613 Flags : Unsigned_32;
25616 Asm ("pushfl" & LF & HT & -- push flags on stack
25617 "pop %0", -- save flags in Flags
25618 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25619 Put_Line ("Flags register:" & Flags'Img);
25624 @c ---------------------------------------------------------------------------
25625 @node Input Variables in Inline Assembler
25626 @section Input Variables in Inline Assembler
25629 The example in this section illustrates how to specify the source operands
25630 for assembly language statements.
25631 The program simply increments its input value by 1:
25633 @smallexample @c ada
25635 with Interfaces; use Interfaces;
25636 with Ada.Text_IO; use Ada.Text_IO;
25637 with System.Machine_Code; use System.Machine_Code;
25638 procedure Increment is
25640 function Incr (Value : Unsigned_32) return Unsigned_32 is
25641 Result : Unsigned_32;
25644 Inputs => Unsigned_32'Asm_Input ("a", Value),
25645 Outputs => Unsigned_32'Asm_Output ("=a", Result));
25649 Value : Unsigned_32;
25653 Put_Line ("Value before is" & Value'Img);
25654 Value := Incr (Value);
25655 Put_Line ("Value after is" & Value'Img);
25660 The @code{Outputs} parameter to @code{Asm} specifies
25661 that the result will be in the eax register and that it is to be stored
25662 in the @code{Result} variable.
25664 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
25665 but with an @code{Asm_Input} attribute.
25666 The @code{"="} constraint, indicating an output value, is not present.
25668 You can have multiple input variables, in the same way that you can have more
25669 than one output variable.
25671 The parameter count (%0, %1) etc, now starts at the first input
25672 statement, and continues with the output statements.
25673 When both parameters use the same variable, the
25674 compiler will treat them as the same %n operand, which is the case here.
25676 Just as the @code{Outputs} parameter causes the register to be stored into the
25677 target variable after execution of the assembler statements, so does the
25678 @code{Inputs} parameter cause its variable to be loaded into the register
25679 before execution of the assembler statements.
25681 Thus the effect of the @code{Asm} invocation is:
25683 @item load the 32-bit value of @code{Value} into eax
25684 @item execute the @code{incl %eax} instruction
25685 @item store the contents of eax into the @code{Result} variable
25688 The resulting assembler file (with @option{-O2} optimization) contains:
25691 _increment__incr.1:
25704 @c ---------------------------------------------------------------------------
25705 @node Inlining Inline Assembler Code
25706 @section Inlining Inline Assembler Code
25709 For a short subprogram such as the @code{Incr} function in the previous
25710 section, the overhead of the call and return (creating / deleting the stack
25711 frame) can be significant, compared to the amount of code in the subprogram
25712 body. A solution is to apply Ada's @code{Inline} pragma to the subprogram,
25713 which directs the compiler to expand invocations of the subprogram at the
25714 point(s) of call, instead of setting up a stack frame for out-of-line calls.
25715 Here is the resulting program:
25717 @smallexample @c ada
25719 with Interfaces; use Interfaces;
25720 with Ada.Text_IO; use Ada.Text_IO;
25721 with System.Machine_Code; use System.Machine_Code;
25722 procedure Increment_2 is
25724 function Incr (Value : Unsigned_32) return Unsigned_32 is
25725 Result : Unsigned_32;
25728 Inputs => Unsigned_32'Asm_Input ("a", Value),
25729 Outputs => Unsigned_32'Asm_Output ("=a", Result));
25732 pragma Inline (Increment);
25734 Value : Unsigned_32;
25738 Put_Line ("Value before is" & Value'Img);
25739 Value := Increment (Value);
25740 Put_Line ("Value after is" & Value'Img);
25745 Compile the program with both optimization (@option{-O2}) and inlining
25746 (@option{-gnatn}) enabled.
25748 The @code{Incr} function is still compiled as usual, but at the
25749 point in @code{Increment} where our function used to be called:
25754 call _increment__incr.1
25759 the code for the function body directly appears:
25772 thus saving the overhead of stack frame setup and an out-of-line call.
25774 @c ---------------------------------------------------------------------------
25775 @node Other Asm Functionality
25776 @section Other @code{Asm} Functionality
25779 This section describes two important parameters to the @code{Asm}
25780 procedure: @code{Clobber}, which identifies register usage;
25781 and @code{Volatile}, which inhibits unwanted optimizations.
25784 * The Clobber Parameter::
25785 * The Volatile Parameter::
25788 @c ---------------------------------------------------------------------------
25789 @node The Clobber Parameter
25790 @subsection The @code{Clobber} Parameter
25793 One of the dangers of intermixing assembly language and a compiled language
25794 such as Ada is that the compiler needs to be aware of which registers are
25795 being used by the assembly code. In some cases, such as the earlier examples,
25796 the constraint string is sufficient to indicate register usage (e.g.,
25798 the eax register). But more generally, the compiler needs an explicit
25799 identification of the registers that are used by the Inline Assembly
25802 Using a register that the compiler doesn't know about
25803 could be a side effect of an instruction (like @code{mull}
25804 storing its result in both eax and edx).
25805 It can also arise from explicit register usage in your
25806 assembly code; for example:
25809 Asm ("movl %0, %%ebx" & LF & HT &
25811 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
25812 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
25816 where the compiler (since it does not analyze the @code{Asm} template string)
25817 does not know you are using the ebx register.
25819 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
25820 to identify the registers that will be used by your assembly code:
25824 Asm ("movl %0, %%ebx" & LF & HT &
25826 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
25827 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
25832 The Clobber parameter is a static string expression specifying the
25833 register(s) you are using. Note that register names are @emph{not} prefixed
25834 by a percent sign. Also, if more than one register is used then their names
25835 are separated by commas; e.g., @code{"eax, ebx"}
25837 The @code{Clobber} parameter has several additional uses:
25839 @item Use ``register'' name @code{cc} to indicate that flags might have changed
25840 @item Use ``register'' name @code{memory} if you changed a memory location
25843 @c ---------------------------------------------------------------------------
25844 @node The Volatile Parameter
25845 @subsection The @code{Volatile} Parameter
25846 @cindex Volatile parameter
25849 Compiler optimizations in the presence of Inline Assembler may sometimes have
25850 unwanted effects. For example, when an @code{Asm} invocation with an input
25851 variable is inside a loop, the compiler might move the loading of the input
25852 variable outside the loop, regarding it as a one-time initialization.
25854 If this effect is not desired, you can disable such optimizations by setting
25855 the @code{Volatile} parameter to @code{True}; for example:
25857 @smallexample @c ada
25859 Asm ("movl %0, %%ebx" & LF & HT &
25861 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
25862 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
25868 By default, @code{Volatile} is set to @code{False} unless there is no
25869 @code{Outputs} parameter.
25871 Although setting @code{Volatile} to @code{True} prevents unwanted
25872 optimizations, it will also disable other optimizations that might be
25873 important for efficiency. In general, you should set @code{Volatile}
25874 to @code{True} only if the compiler's optimizations have created
25876 @c END OF INLINE ASSEMBLER CHAPTER
25877 @c ===============================
25879 @c ***********************************
25880 @c * Compatibility and Porting Guide *
25881 @c ***********************************
25882 @node Compatibility and Porting Guide
25883 @appendix Compatibility and Porting Guide
25886 This chapter describes the compatibility issues that may arise between
25887 GNAT and other Ada compilation systems (including those for Ada 83),
25888 and shows how GNAT can expedite porting
25889 applications developed in other Ada environments.
25892 * Compatibility with Ada 83::
25893 * Compatibility between Ada 95 and Ada 2005::
25894 * Implementation-dependent characteristics::
25895 * Compatibility with Other Ada Systems::
25896 * Representation Clauses::
25898 @c Brief section is only in non-VMS version
25899 @c Full chapter is in VMS version
25900 * Compatibility with HP Ada 83::
25903 * Transitioning to 64-Bit GNAT for OpenVMS::
25907 @node Compatibility with Ada 83
25908 @section Compatibility with Ada 83
25909 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
25912 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83. In
25913 particular, the design intention was that the difficulties associated
25914 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
25915 that occur when moving from one Ada 83 system to another.
25917 However, there are a number of points at which there are minor
25918 incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains
25919 full details of these issues,
25920 and should be consulted for a complete treatment.
25922 following subsections treat the most likely issues to be encountered.
25925 * Legal Ada 83 programs that are illegal in Ada 95::
25926 * More deterministic semantics::
25927 * Changed semantics::
25928 * Other language compatibility issues::
25931 @node Legal Ada 83 programs that are illegal in Ada 95
25932 @subsection Legal Ada 83 programs that are illegal in Ada 95
25934 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
25935 Ada 95 and thus also in Ada 2005:
25938 @item Character literals
25939 Some uses of character literals are ambiguous. Since Ada 95 has introduced
25940 @code{Wide_Character} as a new predefined character type, some uses of
25941 character literals that were legal in Ada 83 are illegal in Ada 95.
25943 @smallexample @c ada
25944 for Char in 'A' .. 'Z' loop @dots{} end loop;
25948 The problem is that @code{'A'} and @code{'Z'} could be from either
25949 @code{Character} or @code{Wide_Character}. The simplest correction
25950 is to make the type explicit; e.g.:
25951 @smallexample @c ada
25952 for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
25955 @item New reserved words
25956 The identifiers @code{abstract}, @code{aliased}, @code{protected},
25957 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
25958 Existing Ada 83 code using any of these identifiers must be edited to
25959 use some alternative name.
25961 @item Freezing rules
25962 The rules in Ada 95 are slightly different with regard to the point at
25963 which entities are frozen, and representation pragmas and clauses are
25964 not permitted past the freeze point. This shows up most typically in
25965 the form of an error message complaining that a representation item
25966 appears too late, and the appropriate corrective action is to move
25967 the item nearer to the declaration of the entity to which it refers.
25969 A particular case is that representation pragmas
25972 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
25974 cannot be applied to a subprogram body. If necessary, a separate subprogram
25975 declaration must be introduced to which the pragma can be applied.
25977 @item Optional bodies for library packages
25978 In Ada 83, a package that did not require a package body was nevertheless
25979 allowed to have one. This lead to certain surprises in compiling large
25980 systems (situations in which the body could be unexpectedly ignored by the
25981 binder). In Ada 95, if a package does not require a body then it is not
25982 permitted to have a body. To fix this problem, simply remove a redundant
25983 body if it is empty, or, if it is non-empty, introduce a dummy declaration
25984 into the spec that makes the body required. One approach is to add a private
25985 part to the package declaration (if necessary), and define a parameterless
25986 procedure called @code{Requires_Body}, which must then be given a dummy
25987 procedure body in the package body, which then becomes required.
25988 Another approach (assuming that this does not introduce elaboration
25989 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
25990 since one effect of this pragma is to require the presence of a package body.
25992 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
25993 In Ada 95, the exception @code{Numeric_Error} is a renaming of
25994 @code{Constraint_Error}.
25995 This means that it is illegal to have separate exception handlers for
25996 the two exceptions. The fix is simply to remove the handler for the
25997 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
25998 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
26000 @item Indefinite subtypes in generics
26001 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
26002 as the actual for a generic formal private type, but then the instantiation
26003 would be illegal if there were any instances of declarations of variables
26004 of this type in the generic body. In Ada 95, to avoid this clear violation
26005 of the methodological principle known as the ``contract model'',
26006 the generic declaration explicitly indicates whether
26007 or not such instantiations are permitted. If a generic formal parameter
26008 has explicit unknown discriminants, indicated by using @code{(<>)} after the
26009 type name, then it can be instantiated with indefinite types, but no
26010 stand-alone variables can be declared of this type. Any attempt to declare
26011 such a variable will result in an illegality at the time the generic is
26012 declared. If the @code{(<>)} notation is not used, then it is illegal
26013 to instantiate the generic with an indefinite type.
26014 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
26015 It will show up as a compile time error, and
26016 the fix is usually simply to add the @code{(<>)} to the generic declaration.
26019 @node More deterministic semantics
26020 @subsection More deterministic semantics
26024 Conversions from real types to integer types round away from 0. In Ada 83
26025 the conversion Integer(2.5) could deliver either 2 or 3 as its value. This
26026 implementation freedom was intended to support unbiased rounding in
26027 statistical applications, but in practice it interfered with portability.
26028 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
26029 is required. Numeric code may be affected by this change in semantics.
26030 Note, though, that this issue is no worse than already existed in Ada 83
26031 when porting code from one vendor to another.
26034 The Real-Time Annex introduces a set of policies that define the behavior of
26035 features that were implementation dependent in Ada 83, such as the order in
26036 which open select branches are executed.
26039 @node Changed semantics
26040 @subsection Changed semantics
26043 The worst kind of incompatibility is one where a program that is legal in
26044 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
26045 possible in Ada 83. Fortunately this is extremely rare, but the one
26046 situation that you should be alert to is the change in the predefined type
26047 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
26050 @item Range of type @code{Character}
26051 The range of @code{Standard.Character} is now the full 256 characters
26052 of Latin-1, whereas in most Ada 83 implementations it was restricted
26053 to 128 characters. Although some of the effects of
26054 this change will be manifest in compile-time rejection of legal
26055 Ada 83 programs it is possible for a working Ada 83 program to have
26056 a different effect in Ada 95, one that was not permitted in Ada 83.
26057 As an example, the expression
26058 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
26059 delivers @code{255} as its value.
26060 In general, you should look at the logic of any
26061 character-processing Ada 83 program and see whether it needs to be adapted
26062 to work correctly with Latin-1. Note that the predefined Ada 95 API has a
26063 character handling package that may be relevant if code needs to be adapted
26064 to account for the additional Latin-1 elements.
26065 The desirable fix is to
26066 modify the program to accommodate the full character set, but in some cases
26067 it may be convenient to define a subtype or derived type of Character that
26068 covers only the restricted range.
26072 @node Other language compatibility issues
26073 @subsection Other language compatibility issues
26076 @item @option{-gnat83} switch
26077 All implementations of GNAT provide a switch that causes GNAT to operate
26078 in Ada 83 mode. In this mode, some but not all compatibility problems
26079 of the type described above are handled automatically. For example, the
26080 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
26081 as identifiers as in Ada 83.
26083 in practice, it is usually advisable to make the necessary modifications
26084 to the program to remove the need for using this switch.
26085 See @ref{Compiling Different Versions of Ada}.
26087 @item Support for removed Ada 83 pragmas and attributes
26088 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
26089 generally because they were replaced by other mechanisms. Ada 95 and Ada 2005
26090 compilers are allowed, but not required, to implement these missing
26091 elements. In contrast with some other compilers, GNAT implements all
26092 such pragmas and attributes, eliminating this compatibility concern. These
26093 include @code{pragma Interface} and the floating point type attributes
26094 (@code{Emax}, @code{Mantissa}, etc.), among other items.
26098 @node Compatibility between Ada 95 and Ada 2005
26099 @section Compatibility between Ada 95 and Ada 2005
26100 @cindex Compatibility between Ada 95 and Ada 2005
26103 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
26104 a number of incompatibilities. Several are enumerated below;
26105 for a complete description please see the
26106 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
26107 @cite{Rationale for Ada 2005}.
26110 @item New reserved words.
26111 The words @code{interface}, @code{overriding} and @code{synchronized} are
26112 reserved in Ada 2005.
26113 A pre-Ada 2005 program that uses any of these as an identifier will be
26116 @item New declarations in predefined packages.
26117 A number of packages in the predefined environment contain new declarations:
26118 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
26119 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
26120 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
26121 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
26122 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
26123 If an Ada 95 program does a @code{with} and @code{use} of any of these
26124 packages, the new declarations may cause name clashes.
26126 @item Access parameters.
26127 A nondispatching subprogram with an access parameter cannot be renamed
26128 as a dispatching operation. This was permitted in Ada 95.
26130 @item Access types, discriminants, and constraints.
26131 Rule changes in this area have led to some incompatibilities; for example,
26132 constrained subtypes of some access types are not permitted in Ada 2005.
26134 @item Aggregates for limited types.
26135 The allowance of aggregates for limited types in Ada 2005 raises the
26136 possibility of ambiguities in legal Ada 95 programs, since additional types
26137 now need to be considered in expression resolution.
26139 @item Fixed-point multiplication and division.
26140 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
26141 were legal in Ada 95 and invoked the predefined versions of these operations,
26143 The ambiguity may be resolved either by applying a type conversion to the
26144 expression, or by explicitly invoking the operation from package
26147 @item Return-by-reference types.
26148 The Ada 95 return-by-reference mechanism has been removed. Instead, the user
26149 can declare a function returning a value from an anonymous access type.
26153 @node Implementation-dependent characteristics
26154 @section Implementation-dependent characteristics
26156 Although the Ada language defines the semantics of each construct as
26157 precisely as practical, in some situations (for example for reasons of
26158 efficiency, or where the effect is heavily dependent on the host or target
26159 platform) the implementation is allowed some freedom. In porting Ada 83
26160 code to GNAT, you need to be aware of whether / how the existing code
26161 exercised such implementation dependencies. Such characteristics fall into
26162 several categories, and GNAT offers specific support in assisting the
26163 transition from certain Ada 83 compilers.
26166 * Implementation-defined pragmas::
26167 * Implementation-defined attributes::
26169 * Elaboration order::
26170 * Target-specific aspects::
26173 @node Implementation-defined pragmas
26174 @subsection Implementation-defined pragmas
26177 Ada compilers are allowed to supplement the language-defined pragmas, and
26178 these are a potential source of non-portability. All GNAT-defined pragmas
26179 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
26180 Reference Manual}, and these include several that are specifically
26181 intended to correspond to other vendors' Ada 83 pragmas.
26182 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
26183 For compatibility with HP Ada 83, GNAT supplies the pragmas
26184 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
26185 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
26186 and @code{Volatile}.
26187 Other relevant pragmas include @code{External} and @code{Link_With}.
26188 Some vendor-specific
26189 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
26191 avoiding compiler rejection of units that contain such pragmas; they are not
26192 relevant in a GNAT context and hence are not otherwise implemented.
26194 @node Implementation-defined attributes
26195 @subsection Implementation-defined attributes
26197 Analogous to pragmas, the set of attributes may be extended by an
26198 implementation. All GNAT-defined attributes are described in
26199 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
26200 Manual}, and these include several that are specifically intended
26201 to correspond to other vendors' Ada 83 attributes. For migrating from VADS,
26202 the attribute @code{VADS_Size} may be useful. For compatibility with HP
26203 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
26207 @subsection Libraries
26209 Vendors may supply libraries to supplement the standard Ada API. If Ada 83
26210 code uses vendor-specific libraries then there are several ways to manage
26211 this in Ada 95 or Ada 2005:
26214 If the source code for the libraries (specs and bodies) are
26215 available, then the libraries can be migrated in the same way as the
26218 If the source code for the specs but not the bodies are
26219 available, then you can reimplement the bodies.
26221 Some features introduced by Ada 95 obviate the need for library support. For
26222 example most Ada 83 vendors supplied a package for unsigned integers. The
26223 Ada 95 modular type feature is the preferred way to handle this need, so
26224 instead of migrating or reimplementing the unsigned integer package it may
26225 be preferable to retrofit the application using modular types.
26228 @node Elaboration order
26229 @subsection Elaboration order
26231 The implementation can choose any elaboration order consistent with the unit
26232 dependency relationship. This freedom means that some orders can result in
26233 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
26234 to invoke a subprogram its body has been elaborated, or to instantiate a
26235 generic before the generic body has been elaborated. By default GNAT
26236 attempts to choose a safe order (one that will not encounter access before
26237 elaboration problems) by implicitly inserting @code{Elaborate} or
26238 @code{Elaborate_All} pragmas where
26239 needed. However, this can lead to the creation of elaboration circularities
26240 and a resulting rejection of the program by gnatbind. This issue is
26241 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
26242 In brief, there are several
26243 ways to deal with this situation:
26247 Modify the program to eliminate the circularities, e.g.@: by moving
26248 elaboration-time code into explicitly-invoked procedures
26250 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
26251 @code{Elaborate} pragmas, and then inhibit the generation of implicit
26252 @code{Elaborate_All}
26253 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
26254 (by selectively suppressing elaboration checks via pragma
26255 @code{Suppress(Elaboration_Check)} when it is safe to do so).
26258 @node Target-specific aspects
26259 @subsection Target-specific aspects
26261 Low-level applications need to deal with machine addresses, data
26262 representations, interfacing with assembler code, and similar issues. If
26263 such an Ada 83 application is being ported to different target hardware (for
26264 example where the byte endianness has changed) then you will need to
26265 carefully examine the program logic; the porting effort will heavily depend
26266 on the robustness of the original design. Moreover, Ada 95 (and thus
26267 Ada 2005) are sometimes
26268 incompatible with typical Ada 83 compiler practices regarding implicit
26269 packing, the meaning of the Size attribute, and the size of access values.
26270 GNAT's approach to these issues is described in @ref{Representation Clauses}.
26272 @node Compatibility with Other Ada Systems
26273 @section Compatibility with Other Ada Systems
26276 If programs avoid the use of implementation dependent and
26277 implementation defined features, as documented in the @cite{Ada
26278 Reference Manual}, there should be a high degree of portability between
26279 GNAT and other Ada systems. The following are specific items which
26280 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
26281 compilers, but do not affect porting code to GNAT@.
26282 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
26283 the following issues may or may not arise for Ada 2005 programs
26284 when other compilers appear.)
26287 @item Ada 83 Pragmas and Attributes
26288 Ada 95 compilers are allowed, but not required, to implement the missing
26289 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
26290 GNAT implements all such pragmas and attributes, eliminating this as
26291 a compatibility concern, but some other Ada 95 compilers reject these
26292 pragmas and attributes.
26294 @item Specialized Needs Annexes
26295 GNAT implements the full set of special needs annexes. At the
26296 current time, it is the only Ada 95 compiler to do so. This means that
26297 programs making use of these features may not be portable to other Ada
26298 95 compilation systems.
26300 @item Representation Clauses
26301 Some other Ada 95 compilers implement only the minimal set of
26302 representation clauses required by the Ada 95 reference manual. GNAT goes
26303 far beyond this minimal set, as described in the next section.
26306 @node Representation Clauses
26307 @section Representation Clauses
26310 The Ada 83 reference manual was quite vague in describing both the minimal
26311 required implementation of representation clauses, and also their precise
26312 effects. Ada 95 (and thus also Ada 2005) are much more explicit, but the
26313 minimal set of capabilities required is still quite limited.
26315 GNAT implements the full required set of capabilities in
26316 Ada 95 and Ada 2005, but also goes much further, and in particular
26317 an effort has been made to be compatible with existing Ada 83 usage to the
26318 greatest extent possible.
26320 A few cases exist in which Ada 83 compiler behavior is incompatible with
26321 the requirements in Ada 95 (and thus also Ada 2005). These are instances of
26322 intentional or accidental dependence on specific implementation dependent
26323 characteristics of these Ada 83 compilers. The following is a list of
26324 the cases most likely to arise in existing Ada 83 code.
26327 @item Implicit Packing
26328 Some Ada 83 compilers allowed a Size specification to cause implicit
26329 packing of an array or record. This could cause expensive implicit
26330 conversions for change of representation in the presence of derived
26331 types, and the Ada design intends to avoid this possibility.
26332 Subsequent AI's were issued to make it clear that such implicit
26333 change of representation in response to a Size clause is inadvisable,
26334 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
26335 Reference Manuals as implementation advice that is followed by GNAT@.
26336 The problem will show up as an error
26337 message rejecting the size clause. The fix is simply to provide
26338 the explicit pragma @code{Pack}, or for more fine tuned control, provide
26339 a Component_Size clause.
26341 @item Meaning of Size Attribute
26342 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
26343 the minimal number of bits required to hold values of the type. For example,
26344 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
26345 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and
26346 some 32 in this situation. This problem will usually show up as a compile
26347 time error, but not always. It is a good idea to check all uses of the
26348 'Size attribute when porting Ada 83 code. The GNAT specific attribute
26349 Object_Size can provide a useful way of duplicating the behavior of
26350 some Ada 83 compiler systems.
26352 @item Size of Access Types
26353 A common assumption in Ada 83 code is that an access type is in fact a pointer,
26354 and that therefore it will be the same size as a System.Address value. This
26355 assumption is true for GNAT in most cases with one exception. For the case of
26356 a pointer to an unconstrained array type (where the bounds may vary from one
26357 value of the access type to another), the default is to use a ``fat pointer'',
26358 which is represented as two separate pointers, one to the bounds, and one to
26359 the array. This representation has a number of advantages, including improved
26360 efficiency. However, it may cause some difficulties in porting existing Ada 83
26361 code which makes the assumption that, for example, pointers fit in 32 bits on
26362 a machine with 32-bit addressing.
26364 To get around this problem, GNAT also permits the use of ``thin pointers'' for
26365 access types in this case (where the designated type is an unconstrained array
26366 type). These thin pointers are indeed the same size as a System.Address value.
26367 To specify a thin pointer, use a size clause for the type, for example:
26369 @smallexample @c ada
26370 type X is access all String;
26371 for X'Size use Standard'Address_Size;
26375 which will cause the type X to be represented using a single pointer.
26376 When using this representation, the bounds are right behind the array.
26377 This representation is slightly less efficient, and does not allow quite
26378 such flexibility in the use of foreign pointers or in using the
26379 Unrestricted_Access attribute to create pointers to non-aliased objects.
26380 But for any standard portable use of the access type it will work in
26381 a functionally correct manner and allow porting of existing code.
26382 Note that another way of forcing a thin pointer representation
26383 is to use a component size clause for the element size in an array,
26384 or a record representation clause for an access field in a record.
26388 @c This brief section is only in the non-VMS version
26389 @c The complete chapter on HP Ada is in the VMS version
26390 @node Compatibility with HP Ada 83
26391 @section Compatibility with HP Ada 83
26394 The VMS version of GNAT fully implements all the pragmas and attributes
26395 provided by HP Ada 83, as well as providing the standard HP Ada 83
26396 libraries, including Starlet. In addition, data layouts and parameter
26397 passing conventions are highly compatible. This means that porting
26398 existing HP Ada 83 code to GNAT in VMS systems should be easier than
26399 most other porting efforts. The following are some of the most
26400 significant differences between GNAT and HP Ada 83.
26403 @item Default floating-point representation
26404 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
26405 it is VMS format. GNAT does implement the necessary pragmas
26406 (Long_Float, Float_Representation) for changing this default.
26409 The package System in GNAT exactly corresponds to the definition in the
26410 Ada 95 reference manual, which means that it excludes many of the
26411 HP Ada 83 extensions. However, a separate package Aux_DEC is provided
26412 that contains the additional definitions, and a special pragma,
26413 Extend_System allows this package to be treated transparently as an
26414 extension of package System.
26417 The definitions provided by Aux_DEC are exactly compatible with those
26418 in the HP Ada 83 version of System, with one exception.
26419 HP Ada provides the following declarations:
26421 @smallexample @c ada
26422 TO_ADDRESS (INTEGER)
26423 TO_ADDRESS (UNSIGNED_LONGWORD)
26424 TO_ADDRESS (@i{universal_integer})
26428 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
26429 an extension to Ada 83 not strictly compatible with the reference manual.
26430 In GNAT, we are constrained to be exactly compatible with the standard,
26431 and this means we cannot provide this capability. In HP Ada 83, the
26432 point of this definition is to deal with a call like:
26434 @smallexample @c ada
26435 TO_ADDRESS (16#12777#);
26439 Normally, according to the Ada 83 standard, one would expect this to be
26440 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
26441 of TO_ADDRESS@. However, in HP Ada 83, there is no ambiguity, since the
26442 definition using @i{universal_integer} takes precedence.
26444 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
26445 is not possible to be 100% compatible. Since there are many programs using
26446 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
26447 to change the name of the function in the UNSIGNED_LONGWORD case, so the
26448 declarations provided in the GNAT version of AUX_Dec are:
26450 @smallexample @c ada
26451 function To_Address (X : Integer) return Address;
26452 pragma Pure_Function (To_Address);
26454 function To_Address_Long (X : Unsigned_Longword)
26456 pragma Pure_Function (To_Address_Long);
26460 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
26461 change the name to TO_ADDRESS_LONG@.
26463 @item Task_Id values
26464 The Task_Id values assigned will be different in the two systems, and GNAT
26465 does not provide a specified value for the Task_Id of the environment task,
26466 which in GNAT is treated like any other declared task.
26470 For full details on these and other less significant compatibility issues,
26471 see appendix E of the HP publication entitled @cite{HP Ada, Technical
26472 Overview and Comparison on HP Platforms}.
26474 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
26475 attributes are recognized, although only a subset of them can sensibly
26476 be implemented. The description of pragmas in @ref{Implementation
26477 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
26478 indicates whether or not they are applicable to non-VMS systems.
26482 @node Transitioning to 64-Bit GNAT for OpenVMS
26483 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
26486 This section is meant to assist users of pre-2006 @value{EDITION}
26487 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
26488 the version of the GNAT technology supplied in 2006 and later for
26489 OpenVMS on both Alpha and I64.
26492 * Introduction to transitioning::
26493 * Migration of 32 bit code::
26494 * Taking advantage of 64 bit addressing::
26495 * Technical details::
26498 @node Introduction to transitioning
26499 @subsection Introduction
26502 64-bit @value{EDITION} for Open VMS has been designed to meet
26507 Providing a full conforming implementation of Ada 95 and Ada 2005
26510 Allowing maximum backward compatibility, thus easing migration of existing
26514 Supplying a path for exploiting the full 64-bit address range
26518 Ada's strong typing semantics has made it
26519 impractical to have different 32-bit and 64-bit modes. As soon as
26520 one object could possibly be outside the 32-bit address space, this
26521 would make it necessary for the @code{System.Address} type to be 64 bits.
26522 In particular, this would cause inconsistencies if 32-bit code is
26523 called from 64-bit code that raises an exception.
26525 This issue has been resolved by always using 64-bit addressing
26526 at the system level, but allowing for automatic conversions between
26527 32-bit and 64-bit addresses where required. Thus users who
26528 do not currently require 64-bit addressing capabilities, can
26529 recompile their code with only minimal changes (and indeed
26530 if the code is written in portable Ada, with no assumptions about
26531 the size of the @code{Address} type, then no changes at all are necessary).
26533 this approach provides a simple, gradual upgrade path to future
26534 use of larger memories than available for 32-bit systems.
26535 Also, newly written applications or libraries will by default
26536 be fully compatible with future systems exploiting 64-bit
26537 addressing capabilities.
26539 @ref{Migration of 32 bit code}, will focus on porting applications
26540 that do not require more than 2 GB of
26541 addressable memory. This code will be referred to as
26542 @emph{32-bit code}.
26543 For applications intending to exploit the full 64-bit address space,
26544 @ref{Taking advantage of 64 bit addressing},
26545 will consider further changes that may be required.
26546 Such code will be referred to below as @emph{64-bit code}.
26548 @node Migration of 32 bit code
26549 @subsection Migration of 32-bit code
26553 * Access types and 32/64-bit allocation::
26554 * Unchecked conversions::
26555 * Predefined constants::
26556 * Interfacing with C::
26557 * 32/64-bit descriptors::
26558 * Experience with source compatibility::
26561 @node Address types
26562 @subsubsection Address types
26565 To solve the problem of mixing 64-bit and 32-bit addressing,
26566 while maintaining maximum backward compatibility, the following
26567 approach has been taken:
26571 @code{System.Address} always has a size of 64 bits
26572 @cindex @code{System.Address} size
26573 @cindex @code{Address} size
26576 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
26577 @cindex @code{System.Short_Address} size
26578 @cindex @code{Short_Address} size
26582 Since @code{System.Short_Address} is a subtype of @code{System.Address},
26583 a @code{Short_Address}
26584 may be used where an @code{Address} is required, and vice versa, without
26585 needing explicit type conversions.
26586 By virtue of the Open VMS parameter passing conventions,
26588 and exported subprograms that have 32-bit address parameters are
26589 compatible with those that have 64-bit address parameters.
26590 (See @ref{Making code 64 bit clean} for details.)
26592 The areas that may need attention are those where record types have
26593 been defined that contain components of the type @code{System.Address}, and
26594 where objects of this type are passed to code expecting a record layout with
26597 Different compilers on different platforms cannot be
26598 expected to represent the same type in the same way,
26599 since alignment constraints
26600 and other system-dependent properties affect the compiler's decision.
26601 For that reason, Ada code
26602 generally uses representation clauses to specify the expected
26603 layout where required.
26605 If such a representation clause uses 32 bits for a component having
26606 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
26607 will detect that error and produce a specific diagnostic message.
26608 The developer should then determine whether the representation
26609 should be 64 bits or not and make either of two changes:
26610 change the size to 64 bits and leave the type as @code{System.Address}, or
26611 leave the size as 32 bits and change the type to @code{System.Short_Address}.
26612 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
26613 required in any code setting or accessing the field; the compiler will
26614 automatically perform any needed conversions between address
26617 @node Access types and 32/64-bit allocation
26618 @subsubsection Access types and 32/64-bit allocation
26619 @cindex 32-bit allocation
26620 @cindex 64-bit allocation
26623 By default, objects designated by access values are always allocated in
26624 the 64-bit address space, and access values themselves are represented
26625 in 64 bits. If these defaults are not appropriate, and 32-bit allocation
26626 is required (for example if the address of an allocated object is assigned
26627 to a @code{Short_Address} variable), then several alternatives are available:
26631 A pool-specific access type (ie, an @w{Ada 83} access type, whose
26632 definition is @code{access T} versus @code{access all T} or
26633 @code{access constant T}), may be declared with a @code{'Size} representation
26634 clause that establishes the size as 32 bits.
26635 In such circumstances allocations for that type will
26636 be from the 32-bit heap. Such a clause is not permitted
26637 for a general access type (declared with @code{access all} or
26638 @code{access constant}) as values of such types must be able to refer
26639 to any object of the designated type, including objects residing outside
26640 the 32-bit address range. Existing @w{Ada 83} code will not contain such
26641 type definitions, however, since general access types were introduced
26645 Switches for @command{GNAT BIND} control whether the internal GNAT
26646 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
26647 @cindex @code{__gnat_malloc}
26648 The switches are respectively @option{-H64} (the default) and
26650 @cindex @option{-H32} (@command{gnatbind})
26651 @cindex @option{-H64} (@command{gnatbind})
26654 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
26655 @cindex @code{GNAT$NO_MALLOC_64} environment variable
26656 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
26657 If this variable is left
26658 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
26659 then the default (64-bit) allocation is used.
26660 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
26661 then 32-bit allocation is used. The gnatbind qualifiers described above
26662 override this logical name.
26665 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
26666 @cindex @option{-mno-malloc64} (^gcc^gcc^)
26667 at a low level to convert explicit calls to @code{malloc} and related
26668 functions from the C run-time library so that they perform allocations
26669 in the 32-bit heap.
26670 Since all internal allocations from GNAT use @code{__gnat_malloc},
26671 this switch is not required unless the program makes explicit calls on
26672 @code{malloc} (or related functions) from interfaced C code.
26676 @node Unchecked conversions
26677 @subsubsection Unchecked conversions
26680 In the case of an @code{Unchecked_Conversion} where the source type is a
26681 64-bit access type or the type @code{System.Address}, and the target
26682 type is a 32-bit type, the compiler will generate a warning.
26683 Even though the generated code will still perform the required
26684 conversions, it is highly recommended in these cases to use
26685 respectively a 32-bit access type or @code{System.Short_Address}
26686 as the source type.
26688 @node Predefined constants
26689 @subsubsection Predefined constants
26692 The following table shows the correspondence between pre-2006 versions of
26693 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
26696 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
26697 @item @b{Constant} @tab @b{Old} @tab @b{New}
26698 @item @code{System.Word_Size} @tab 32 @tab 64
26699 @item @code{System.Memory_Size} @tab 2**32 @tab 2**64
26700 @item @code{System.Short_Memory_Size} @tab 2**32 @tab 2**32
26701 @item @code{System.Address_Size} @tab 32 @tab 64
26705 If you need to refer to the specific
26706 memory size of a 32-bit implementation, instead of the
26707 actual memory size, use @code{System.Short_Memory_Size}
26708 rather than @code{System.Memory_Size}.
26709 Similarly, references to @code{System.Address_Size} may need
26710 to be replaced by @code{System.Short_Address'Size}.
26711 The program @command{gnatfind} may be useful for locating
26712 references to the above constants, so that you can verify that they
26715 @node Interfacing with C
26716 @subsubsection Interfacing with C
26719 In order to minimize the impact of the transition to 64-bit addresses on
26720 legacy programs, some fundamental types in the @code{Interfaces.C}
26721 package hierarchy continue to be represented in 32 bits.
26722 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
26723 This eases integration with the default HP C layout choices, for example
26724 as found in the system routines in @code{DECC$SHR.EXE}.
26725 Because of this implementation choice, the type fully compatible with
26726 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
26727 Depending on the context the compiler will issue a
26728 warning or an error when type @code{Address} is used, alerting the user to a
26729 potential problem. Otherwise 32-bit programs that use
26730 @code{Interfaces.C} should normally not require code modifications
26732 The other issue arising with C interfacing concerns pragma @code{Convention}.
26733 For VMS 64-bit systems, there is an issue of the appropriate default size
26734 of C convention pointers in the absence of an explicit size clause. The HP
26735 C compiler can choose either 32 or 64 bits depending on compiler options.
26736 GNAT chooses 32-bits rather than 64-bits in the default case where no size
26737 clause is given. This proves a better choice for porting 32-bit legacy
26738 applications. In order to have a 64-bit representation, it is necessary to
26739 specify a size representation clause. For example:
26741 @smallexample @c ada
26742 type int_star is access Interfaces.C.int;
26743 pragma Convention(C, int_star);
26744 for int_star'Size use 64; -- Necessary to get 64 and not 32 bits
26747 @node 32/64-bit descriptors
26748 @subsubsection 32/64-bit descriptors
26751 By default, GNAT uses a 64-bit descriptor mechanism. For an imported
26752 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
26753 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
26754 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
26755 @cindex @code{Short_Descriptor} mechanism for imported subprograms
26757 If the configuration pragma @code{Short_Descriptors} is supplied, then
26758 all descriptors will be 32 bits.
26759 @cindex pragma @code{Short_Descriptors}
26761 @node Experience with source compatibility
26762 @subsubsection Experience with source compatibility
26765 The Security Server and STARLET on I64 provide an interesting ``test case''
26766 for source compatibility issues, since it is in such system code
26767 where assumptions about @code{Address} size might be expected to occur.
26768 Indeed, there were a small number of occasions in the Security Server
26769 file @file{jibdef.ads}
26770 where a representation clause for a record type specified
26771 32 bits for a component of type @code{Address}.
26772 All of these errors were detected by the compiler.
26773 The repair was obvious and immediate; to simply replace @code{Address} by
26774 @code{Short_Address}.
26776 In the case of STARLET, there were several record types that should
26777 have had representation clauses but did not. In these record types
26778 there was an implicit assumption that an @code{Address} value occupied
26780 These compiled without error, but their usage resulted in run-time error
26781 returns from STARLET system calls.
26782 Future GNAT technology enhancements may include a tool that detects and flags
26783 these sorts of potential source code porting problems.
26785 @c ****************************************
26786 @node Taking advantage of 64 bit addressing
26787 @subsection Taking advantage of 64-bit addressing
26790 * Making code 64 bit clean::
26791 * Allocating memory from the 64 bit storage pool::
26792 * Restrictions on use of 64 bit objects::
26793 * STARLET and other predefined libraries::
26796 @node Making code 64 bit clean
26797 @subsubsection Making code 64-bit clean
26800 In order to prevent problems that may occur when (parts of) a
26801 system start using memory outside the 32-bit address range,
26802 we recommend some additional guidelines:
26806 For imported subprograms that take parameters of the
26807 type @code{System.Address}, ensure that these subprograms can
26808 indeed handle 64-bit addresses. If not, or when in doubt,
26809 change the subprogram declaration to specify
26810 @code{System.Short_Address} instead.
26813 Resolve all warnings related to size mismatches in
26814 unchecked conversions. Failing to do so causes
26815 erroneous execution if the source object is outside
26816 the 32-bit address space.
26819 (optional) Explicitly use the 32-bit storage pool
26820 for access types used in a 32-bit context, or use
26821 generic access types where possible
26822 (@pxref{Restrictions on use of 64 bit objects}).
26826 If these rules are followed, the compiler will automatically insert
26827 any necessary checks to ensure that no addresses or access values
26828 passed to 32-bit code ever refer to objects outside the 32-bit
26830 Any attempt to do this will raise @code{Constraint_Error}.
26832 @node Allocating memory from the 64 bit storage pool
26833 @subsubsection Allocating memory from the 64-bit storage pool
26836 By default, all allocations -- for both pool-specific and general
26837 access types -- use the 64-bit storage pool. To override
26838 this default, for an individual access type or globally, see
26839 @ref{Access types and 32/64-bit allocation}.
26841 @node Restrictions on use of 64 bit objects
26842 @subsubsection Restrictions on use of 64-bit objects
26845 Taking the address of an object allocated from a 64-bit storage pool,
26846 and then passing this address to a subprogram expecting
26847 @code{System.Short_Address},
26848 or assigning it to a variable of type @code{Short_Address}, will cause
26849 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
26850 (@pxref{Making code 64 bit clean}), or checks are suppressed,
26851 no exception is raised and execution
26852 will become erroneous.
26854 @node STARLET and other predefined libraries
26855 @subsubsection STARLET and other predefined libraries
26858 All code that comes as part of GNAT is 64-bit clean, but the
26859 restrictions given in @ref{Restrictions on use of 64 bit objects},
26860 still apply. Look at the package
26861 specs to see in which contexts objects allocated
26862 in 64-bit address space are acceptable.
26864 @node Technical details
26865 @subsection Technical details
26868 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
26869 Ada standard with respect to the type of @code{System.Address}. Previous
26870 versions of GNAT Pro have defined this type as private and implemented it as a
26873 In order to allow defining @code{System.Short_Address} as a proper subtype,
26874 and to match the implicit sign extension in parameter passing,
26875 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
26876 visible (i.e., non-private) integer type.
26877 Standard operations on the type, such as the binary operators ``+'', ``-'',
26878 etc., that take @code{Address} operands and return an @code{Address} result,
26879 have been hidden by declaring these
26880 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
26881 ambiguities that would otherwise result from overloading.
26882 (Note that, although @code{Address} is a visible integer type,
26883 good programming practice dictates against exploiting the type's
26884 integer properties such as literals, since this will compromise
26887 Defining @code{Address} as a visible integer type helps achieve
26888 maximum compatibility for existing Ada code,
26889 without sacrificing the capabilities of the 64-bit architecture.
26892 @c ************************************************
26894 @node Microsoft Windows Topics
26895 @appendix Microsoft Windows Topics
26901 This chapter describes topics that are specific to the Microsoft Windows
26902 platforms (NT, 2000, and XP Professional).
26905 * Using GNAT on Windows::
26906 * Using a network installation of GNAT::
26907 * CONSOLE and WINDOWS subsystems::
26908 * Temporary Files::
26909 * Mixed-Language Programming on Windows::
26910 * Windows Calling Conventions::
26911 * Introduction to Dynamic Link Libraries (DLLs)::
26912 * Using DLLs with GNAT::
26913 * Building DLLs with GNAT Project files::
26914 * Building DLLs with GNAT::
26915 * Building DLLs with gnatdll::
26916 * GNAT and Windows Resources::
26917 * Debugging a DLL::
26918 * Setting Stack Size from gnatlink::
26919 * Setting Heap Size from gnatlink::
26922 @node Using GNAT on Windows
26923 @section Using GNAT on Windows
26926 One of the strengths of the GNAT technology is that its tool set
26927 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
26928 @code{gdb} debugger, etc.) is used in the same way regardless of the
26931 On Windows this tool set is complemented by a number of Microsoft-specific
26932 tools that have been provided to facilitate interoperability with Windows
26933 when this is required. With these tools:
26938 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
26942 You can use any Dynamically Linked Library (DLL) in your Ada code (both
26943 relocatable and non-relocatable DLLs are supported).
26946 You can build Ada DLLs for use in other applications. These applications
26947 can be written in a language other than Ada (e.g., C, C++, etc). Again both
26948 relocatable and non-relocatable Ada DLLs are supported.
26951 You can include Windows resources in your Ada application.
26954 You can use or create COM/DCOM objects.
26958 Immediately below are listed all known general GNAT-for-Windows restrictions.
26959 Other restrictions about specific features like Windows Resources and DLLs
26960 are listed in separate sections below.
26965 It is not possible to use @code{GetLastError} and @code{SetLastError}
26966 when tasking, protected records, or exceptions are used. In these
26967 cases, in order to implement Ada semantics, the GNAT run-time system
26968 calls certain Win32 routines that set the last error variable to 0 upon
26969 success. It should be possible to use @code{GetLastError} and
26970 @code{SetLastError} when tasking, protected record, and exception
26971 features are not used, but it is not guaranteed to work.
26974 It is not possible to link against Microsoft libraries except for
26975 import libraries. Interfacing must be done by the mean of DLLs.
26978 When the compilation environment is located on FAT32 drives, users may
26979 experience recompilations of the source files that have not changed if
26980 Daylight Saving Time (DST) state has changed since the last time files
26981 were compiled. NTFS drives do not have this problem.
26984 No components of the GNAT toolset use any entries in the Windows
26985 registry. The only entries that can be created are file associations and
26986 PATH settings, provided the user has chosen to create them at installation
26987 time, as well as some minimal book-keeping information needed to correctly
26988 uninstall or integrate different GNAT products.
26991 @node Using a network installation of GNAT
26992 @section Using a network installation of GNAT
26995 Make sure the system on which GNAT is installed is accessible from the
26996 current machine, i.e., the install location is shared over the network.
26997 Shared resources are accessed on Windows by means of UNC paths, which
26998 have the format @code{\\server\sharename\path}
27000 In order to use such a network installation, simply add the UNC path of the
27001 @file{bin} directory of your GNAT installation in front of your PATH. For
27002 example, if GNAT is installed in @file{\GNAT} directory of a share location
27003 called @file{c-drive} on a machine @file{LOKI}, the following command will
27006 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
27008 Be aware that every compilation using the network installation results in the
27009 transfer of large amounts of data across the network and will likely cause
27010 serious performance penalty.
27012 @node CONSOLE and WINDOWS subsystems
27013 @section CONSOLE and WINDOWS subsystems
27014 @cindex CONSOLE Subsystem
27015 @cindex WINDOWS Subsystem
27019 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
27020 (which is the default subsystem) will always create a console when
27021 launching the application. This is not something desirable when the
27022 application has a Windows GUI. To get rid of this console the
27023 application must be using the @code{WINDOWS} subsystem. To do so
27024 the @option{-mwindows} linker option must be specified.
27027 $ gnatmake winprog -largs -mwindows
27030 @node Temporary Files
27031 @section Temporary Files
27032 @cindex Temporary files
27035 It is possible to control where temporary files gets created by setting
27036 the @env{TMP} environment variable. The file will be created:
27039 @item Under the directory pointed to by the @env{TMP} environment variable if
27040 this directory exists.
27042 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
27043 set (or not pointing to a directory) and if this directory exists.
27045 @item Under the current working directory otherwise.
27049 This allows you to determine exactly where the temporary
27050 file will be created. This is particularly useful in networked
27051 environments where you may not have write access to some
27054 @node Mixed-Language Programming on Windows
27055 @section Mixed-Language Programming on Windows
27058 Developing pure Ada applications on Windows is no different than on
27059 other GNAT-supported platforms. However, when developing or porting an
27060 application that contains a mix of Ada and C/C++, the choice of your
27061 Windows C/C++ development environment conditions your overall
27062 interoperability strategy.
27064 If you use @command{gcc} to compile the non-Ada part of your application,
27065 there are no Windows-specific restrictions that affect the overall
27066 interoperability with your Ada code. If you do want to use the
27067 Microsoft tools for your non-Ada code, you have two choices:
27071 Encapsulate your non-Ada code in a DLL to be linked with your Ada
27072 application. In this case, use the Microsoft or whatever environment to
27073 build the DLL and use GNAT to build your executable
27074 (@pxref{Using DLLs with GNAT}).
27077 Or you can encapsulate your Ada code in a DLL to be linked with the
27078 other part of your application. In this case, use GNAT to build the DLL
27079 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
27080 or whatever environment to build your executable.
27083 @node Windows Calling Conventions
27084 @section Windows Calling Conventions
27088 This section pertain only to Win32. On Win64 there is a single native
27089 calling convention. All convention specifiers are ignored on this
27093 * C Calling Convention::
27094 * Stdcall Calling Convention::
27095 * Win32 Calling Convention::
27096 * DLL Calling Convention::
27100 When a subprogram @code{F} (caller) calls a subprogram @code{G}
27101 (callee), there are several ways to push @code{G}'s parameters on the
27102 stack and there are several possible scenarios to clean up the stack
27103 upon @code{G}'s return. A calling convention is an agreed upon software
27104 protocol whereby the responsibilities between the caller (@code{F}) and
27105 the callee (@code{G}) are clearly defined. Several calling conventions
27106 are available for Windows:
27110 @code{C} (Microsoft defined)
27113 @code{Stdcall} (Microsoft defined)
27116 @code{Win32} (GNAT specific)
27119 @code{DLL} (GNAT specific)
27122 @node C Calling Convention
27123 @subsection @code{C} Calling Convention
27126 This is the default calling convention used when interfacing to C/C++
27127 routines compiled with either @command{gcc} or Microsoft Visual C++.
27129 In the @code{C} calling convention subprogram parameters are pushed on the
27130 stack by the caller from right to left. The caller itself is in charge of
27131 cleaning up the stack after the call. In addition, the name of a routine
27132 with @code{C} calling convention is mangled by adding a leading underscore.
27134 The name to use on the Ada side when importing (or exporting) a routine
27135 with @code{C} calling convention is the name of the routine. For
27136 instance the C function:
27139 int get_val (long);
27143 should be imported from Ada as follows:
27145 @smallexample @c ada
27147 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27148 pragma Import (C, Get_Val, External_Name => "get_val");
27153 Note that in this particular case the @code{External_Name} parameter could
27154 have been omitted since, when missing, this parameter is taken to be the
27155 name of the Ada entity in lower case. When the @code{Link_Name} parameter
27156 is missing, as in the above example, this parameter is set to be the
27157 @code{External_Name} with a leading underscore.
27159 When importing a variable defined in C, you should always use the @code{C}
27160 calling convention unless the object containing the variable is part of a
27161 DLL (in which case you should use the @code{Stdcall} calling
27162 convention, @pxref{Stdcall Calling Convention}).
27164 @node Stdcall Calling Convention
27165 @subsection @code{Stdcall} Calling Convention
27168 This convention, which was the calling convention used for Pascal
27169 programs, is used by Microsoft for all the routines in the Win32 API for
27170 efficiency reasons. It must be used to import any routine for which this
27171 convention was specified.
27173 In the @code{Stdcall} calling convention subprogram parameters are pushed
27174 on the stack by the caller from right to left. The callee (and not the
27175 caller) is in charge of cleaning the stack on routine exit. In addition,
27176 the name of a routine with @code{Stdcall} calling convention is mangled by
27177 adding a leading underscore (as for the @code{C} calling convention) and a
27178 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
27179 bytes) of the parameters passed to the routine.
27181 The name to use on the Ada side when importing a C routine with a
27182 @code{Stdcall} calling convention is the name of the C routine. The leading
27183 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
27184 the compiler. For instance the Win32 function:
27187 @b{APIENTRY} int get_val (long);
27191 should be imported from Ada as follows:
27193 @smallexample @c ada
27195 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27196 pragma Import (Stdcall, Get_Val);
27197 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
27202 As for the @code{C} calling convention, when the @code{External_Name}
27203 parameter is missing, it is taken to be the name of the Ada entity in lower
27204 case. If instead of writing the above import pragma you write:
27206 @smallexample @c ada
27208 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27209 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
27214 then the imported routine is @code{_retrieve_val@@4}. However, if instead
27215 of specifying the @code{External_Name} parameter you specify the
27216 @code{Link_Name} as in the following example:
27218 @smallexample @c ada
27220 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27221 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
27226 then the imported routine is @code{retrieve_val}, that is, there is no
27227 decoration at all. No leading underscore and no Stdcall suffix
27228 @code{@@}@code{@var{nn}}.
27231 This is especially important as in some special cases a DLL's entry
27232 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
27233 name generated for a call has it.
27236 It is also possible to import variables defined in a DLL by using an
27237 import pragma for a variable. As an example, if a DLL contains a
27238 variable defined as:
27245 then, to access this variable from Ada you should write:
27247 @smallexample @c ada
27249 My_Var : Interfaces.C.int;
27250 pragma Import (Stdcall, My_Var);
27255 Note that to ease building cross-platform bindings this convention
27256 will be handled as a @code{C} calling convention on non-Windows platforms.
27258 @node Win32 Calling Convention
27259 @subsection @code{Win32} Calling Convention
27262 This convention, which is GNAT-specific is fully equivalent to the
27263 @code{Stdcall} calling convention described above.
27265 @node DLL Calling Convention
27266 @subsection @code{DLL} Calling Convention
27269 This convention, which is GNAT-specific is fully equivalent to the
27270 @code{Stdcall} calling convention described above.
27272 @node Introduction to Dynamic Link Libraries (DLLs)
27273 @section Introduction to Dynamic Link Libraries (DLLs)
27277 A Dynamically Linked Library (DLL) is a library that can be shared by
27278 several applications running under Windows. A DLL can contain any number of
27279 routines and variables.
27281 One advantage of DLLs is that you can change and enhance them without
27282 forcing all the applications that depend on them to be relinked or
27283 recompiled. However, you should be aware than all calls to DLL routines are
27284 slower since, as you will understand below, such calls are indirect.
27286 To illustrate the remainder of this section, suppose that an application
27287 wants to use the services of a DLL @file{API.dll}. To use the services
27288 provided by @file{API.dll} you must statically link against the DLL or
27289 an import library which contains a jump table with an entry for each
27290 routine and variable exported by the DLL. In the Microsoft world this
27291 import library is called @file{API.lib}. When using GNAT this import
27292 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
27293 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
27295 After you have linked your application with the DLL or the import library
27296 and you run your application, here is what happens:
27300 Your application is loaded into memory.
27303 The DLL @file{API.dll} is mapped into the address space of your
27304 application. This means that:
27308 The DLL will use the stack of the calling thread.
27311 The DLL will use the virtual address space of the calling process.
27314 The DLL will allocate memory from the virtual address space of the calling
27318 Handles (pointers) can be safely exchanged between routines in the DLL
27319 routines and routines in the application using the DLL.
27323 The entries in the jump table (from the import library @file{libAPI.dll.a}
27324 or @file{API.lib} or automatically created when linking against a DLL)
27325 which is part of your application are initialized with the addresses
27326 of the routines and variables in @file{API.dll}.
27329 If present in @file{API.dll}, routines @code{DllMain} or
27330 @code{DllMainCRTStartup} are invoked. These routines typically contain
27331 the initialization code needed for the well-being of the routines and
27332 variables exported by the DLL.
27336 There is an additional point which is worth mentioning. In the Windows
27337 world there are two kind of DLLs: relocatable and non-relocatable
27338 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
27339 in the target application address space. If the addresses of two
27340 non-relocatable DLLs overlap and these happen to be used by the same
27341 application, a conflict will occur and the application will run
27342 incorrectly. Hence, when possible, it is always preferable to use and
27343 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
27344 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
27345 User's Guide) removes the debugging symbols from the DLL but the DLL can
27346 still be relocated.
27348 As a side note, an interesting difference between Microsoft DLLs and
27349 Unix shared libraries, is the fact that on most Unix systems all public
27350 routines are exported by default in a Unix shared library, while under
27351 Windows it is possible (but not required) to list exported routines in
27352 a definition file (@pxref{The Definition File}).
27354 @node Using DLLs with GNAT
27355 @section Using DLLs with GNAT
27358 * Creating an Ada Spec for the DLL Services::
27359 * Creating an Import Library::
27363 To use the services of a DLL, say @file{API.dll}, in your Ada application
27368 The Ada spec for the routines and/or variables you want to access in
27369 @file{API.dll}. If not available this Ada spec must be built from the C/C++
27370 header files provided with the DLL.
27373 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
27374 mentioned an import library is a statically linked library containing the
27375 import table which will be filled at load time to point to the actual
27376 @file{API.dll} routines. Sometimes you don't have an import library for the
27377 DLL you want to use. The following sections will explain how to build
27378 one. Note that this is optional.
27381 The actual DLL, @file{API.dll}.
27385 Once you have all the above, to compile an Ada application that uses the
27386 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
27387 you simply issue the command
27390 $ gnatmake my_ada_app -largs -lAPI
27394 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
27395 tells the GNAT linker to look for an import library. The linker will
27396 look for a library name in this specific order:
27399 @item @file{libAPI.dll.a}
27400 @item @file{API.dll.a}
27401 @item @file{libAPI.a}
27402 @item @file{API.lib}
27403 @item @file{libAPI.dll}
27404 @item @file{API.dll}
27407 The first three are the GNU style import libraries. The third is the
27408 Microsoft style import libraries. The last two are the DLL themself.
27410 Note that if the Ada package spec for @file{API.dll} contains the
27413 @smallexample @c ada
27414 pragma Linker_Options ("-lAPI");
27418 you do not have to add @option{-largs -lAPI} at the end of the
27419 @command{gnatmake} command.
27421 If any one of the items above is missing you will have to create it
27422 yourself. The following sections explain how to do so using as an
27423 example a fictitious DLL called @file{API.dll}.
27425 @node Creating an Ada Spec for the DLL Services
27426 @subsection Creating an Ada Spec for the DLL Services
27429 A DLL typically comes with a C/C++ header file which provides the
27430 definitions of the routines and variables exported by the DLL. The Ada
27431 equivalent of this header file is a package spec that contains definitions
27432 for the imported entities. If the DLL you intend to use does not come with
27433 an Ada spec you have to generate one such spec yourself. For example if
27434 the header file of @file{API.dll} is a file @file{api.h} containing the
27435 following two definitions:
27447 then the equivalent Ada spec could be:
27449 @smallexample @c ada
27452 with Interfaces.C.Strings;
27457 function Get (Str : C.Strings.Chars_Ptr) return C.int;
27460 pragma Import (C, Get);
27461 pragma Import (DLL, Some_Var);
27468 Note that a variable is
27469 @strong{always imported with a DLL convention}. A function
27470 can have @code{C} or @code{Stdcall} convention.
27471 (@pxref{Windows Calling Conventions}).
27473 @node Creating an Import Library
27474 @subsection Creating an Import Library
27475 @cindex Import library
27478 * The Definition File::
27479 * GNAT-Style Import Library::
27480 * Microsoft-Style Import Library::
27484 If a Microsoft-style import library @file{API.lib} or a GNAT-style
27485 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
27486 with @file{API.dll} you can skip this section. You can also skip this
27487 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
27488 as in this case it is possible to link directly against the
27489 DLL. Otherwise read on.
27491 @node The Definition File
27492 @subsubsection The Definition File
27493 @cindex Definition file
27497 As previously mentioned, and unlike Unix systems, the list of symbols
27498 that are exported from a DLL must be provided explicitly in Windows.
27499 The main goal of a definition file is precisely that: list the symbols
27500 exported by a DLL. A definition file (usually a file with a @code{.def}
27501 suffix) has the following structure:
27506 @r{[}LIBRARY @var{name}@r{]}
27507 @r{[}DESCRIPTION @var{string}@r{]}
27517 @item LIBRARY @var{name}
27518 This section, which is optional, gives the name of the DLL.
27520 @item DESCRIPTION @var{string}
27521 This section, which is optional, gives a description string that will be
27522 embedded in the import library.
27525 This section gives the list of exported symbols (procedures, functions or
27526 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
27527 section of @file{API.def} looks like:
27541 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
27542 (@pxref{Windows Calling Conventions}) for a Stdcall
27543 calling convention function in the exported symbols list.
27546 There can actually be other sections in a definition file, but these
27547 sections are not relevant to the discussion at hand.
27549 @node GNAT-Style Import Library
27550 @subsubsection GNAT-Style Import Library
27553 To create a static import library from @file{API.dll} with the GNAT tools
27554 you should proceed as follows:
27558 Create the definition file @file{API.def} (@pxref{The Definition File}).
27559 For that use the @code{dll2def} tool as follows:
27562 $ dll2def API.dll > API.def
27566 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
27567 to standard output the list of entry points in the DLL. Note that if
27568 some routines in the DLL have the @code{Stdcall} convention
27569 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
27570 suffix then you'll have to edit @file{api.def} to add it, and specify
27571 @option{-k} to @command{gnatdll} when creating the import library.
27574 Here are some hints to find the right @code{@@}@var{nn} suffix.
27578 If you have the Microsoft import library (.lib), it is possible to get
27579 the right symbols by using Microsoft @code{dumpbin} tool (see the
27580 corresponding Microsoft documentation for further details).
27583 $ dumpbin /exports api.lib
27587 If you have a message about a missing symbol at link time the compiler
27588 tells you what symbol is expected. You just have to go back to the
27589 definition file and add the right suffix.
27593 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
27594 (@pxref{Using gnatdll}) as follows:
27597 $ gnatdll -e API.def -d API.dll
27601 @code{gnatdll} takes as input a definition file @file{API.def} and the
27602 name of the DLL containing the services listed in the definition file
27603 @file{API.dll}. The name of the static import library generated is
27604 computed from the name of the definition file as follows: if the
27605 definition file name is @var{xyz}@code{.def}, the import library name will
27606 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
27607 @option{-e} could have been removed because the name of the definition
27608 file (before the ``@code{.def}'' suffix) is the same as the name of the
27609 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
27612 @node Microsoft-Style Import Library
27613 @subsubsection Microsoft-Style Import Library
27616 With GNAT you can either use a GNAT-style or Microsoft-style import
27617 library. A Microsoft import library is needed only if you plan to make an
27618 Ada DLL available to applications developed with Microsoft
27619 tools (@pxref{Mixed-Language Programming on Windows}).
27621 To create a Microsoft-style import library for @file{API.dll} you
27622 should proceed as follows:
27626 Create the definition file @file{API.def} from the DLL. For this use either
27627 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
27628 tool (see the corresponding Microsoft documentation for further details).
27631 Build the actual import library using Microsoft's @code{lib} utility:
27634 $ lib -machine:IX86 -def:API.def -out:API.lib
27638 If you use the above command the definition file @file{API.def} must
27639 contain a line giving the name of the DLL:
27646 See the Microsoft documentation for further details about the usage of
27650 @node Building DLLs with GNAT Project files
27651 @section Building DLLs with GNAT Project files
27652 @cindex DLLs, building
27655 There is nothing specific to Windows in the build process.
27656 @pxref{Library Projects}.
27659 Due to a system limitation, it is not possible under Windows to create threads
27660 when inside the @code{DllMain} routine which is used for auto-initialization
27661 of shared libraries, so it is not possible to have library level tasks in SALs.
27663 @node Building DLLs with GNAT
27664 @section Building DLLs with GNAT
27665 @cindex DLLs, building
27668 This section explain how to build DLLs using the GNAT built-in DLL
27669 support. With the following procedure it is straight forward to build
27670 and use DLLs with GNAT.
27674 @item building object files
27676 The first step is to build all objects files that are to be included
27677 into the DLL. This is done by using the standard @command{gnatmake} tool.
27679 @item building the DLL
27681 To build the DLL you must use @command{gcc}'s @option{-shared}
27682 option. It is quite simple to use this method:
27685 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
27688 It is important to note that in this case all symbols found in the
27689 object files are automatically exported. It is possible to restrict
27690 the set of symbols to export by passing to @command{gcc} a definition
27691 file, @pxref{The Definition File}. For example:
27694 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
27697 If you use a definition file you must export the elaboration procedures
27698 for every package that required one. Elaboration procedures are named
27699 using the package name followed by "_E".
27701 @item preparing DLL to be used
27703 For the DLL to be used by client programs the bodies must be hidden
27704 from it and the .ali set with read-only attribute. This is very important
27705 otherwise GNAT will recompile all packages and will not actually use
27706 the code in the DLL. For example:
27710 $ copy *.ads *.ali api.dll apilib
27711 $ attrib +R apilib\*.ali
27716 At this point it is possible to use the DLL by directly linking
27717 against it. Note that you must use the GNAT shared runtime when using
27718 GNAT shared libraries. This is achieved by using @option{-shared} binder's
27722 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
27725 @node Building DLLs with gnatdll
27726 @section Building DLLs with gnatdll
27727 @cindex DLLs, building
27730 * Limitations When Using Ada DLLs from Ada::
27731 * Exporting Ada Entities::
27732 * Ada DLLs and Elaboration::
27733 * Ada DLLs and Finalization::
27734 * Creating a Spec for Ada DLLs::
27735 * Creating the Definition File::
27740 Note that it is preferred to use GNAT Project files
27741 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
27742 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
27744 This section explains how to build DLLs containing Ada code using
27745 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
27746 remainder of this section.
27748 The steps required to build an Ada DLL that is to be used by Ada as well as
27749 non-Ada applications are as follows:
27753 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
27754 @code{Stdcall} calling convention to avoid any Ada name mangling for the
27755 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
27756 skip this step if you plan to use the Ada DLL only from Ada applications.
27759 Your Ada code must export an initialization routine which calls the routine
27760 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
27761 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
27762 routine exported by the Ada DLL must be invoked by the clients of the DLL
27763 to initialize the DLL.
27766 When useful, the DLL should also export a finalization routine which calls
27767 routine @code{adafinal} generated by @command{gnatbind} to perform the
27768 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
27769 The finalization routine exported by the Ada DLL must be invoked by the
27770 clients of the DLL when the DLL services are no further needed.
27773 You must provide a spec for the services exported by the Ada DLL in each
27774 of the programming languages to which you plan to make the DLL available.
27777 You must provide a definition file listing the exported entities
27778 (@pxref{The Definition File}).
27781 Finally you must use @code{gnatdll} to produce the DLL and the import
27782 library (@pxref{Using gnatdll}).
27786 Note that a relocatable DLL stripped using the @code{strip}
27787 binutils tool will not be relocatable anymore. To build a DLL without
27788 debug information pass @code{-largs -s} to @code{gnatdll}. This
27789 restriction does not apply to a DLL built using a Library Project.
27790 @pxref{Library Projects}.
27792 @node Limitations When Using Ada DLLs from Ada
27793 @subsection Limitations When Using Ada DLLs from Ada
27796 When using Ada DLLs from Ada applications there is a limitation users
27797 should be aware of. Because on Windows the GNAT run time is not in a DLL of
27798 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
27799 each Ada DLL includes the services of the GNAT run time that are necessary
27800 to the Ada code inside the DLL. As a result, when an Ada program uses an
27801 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
27802 one in the main program.
27804 It is therefore not possible to exchange GNAT run-time objects between the
27805 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
27806 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
27809 It is completely safe to exchange plain elementary, array or record types,
27810 Windows object handles, etc.
27812 @node Exporting Ada Entities
27813 @subsection Exporting Ada Entities
27814 @cindex Export table
27817 Building a DLL is a way to encapsulate a set of services usable from any
27818 application. As a result, the Ada entities exported by a DLL should be
27819 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
27820 any Ada name mangling. As an example here is an Ada package
27821 @code{API}, spec and body, exporting two procedures, a function, and a
27824 @smallexample @c ada
27827 with Interfaces.C; use Interfaces;
27829 Count : C.int := 0;
27830 function Factorial (Val : C.int) return C.int;
27832 procedure Initialize_API;
27833 procedure Finalize_API;
27834 -- Initialization & Finalization routines. More in the next section.
27836 pragma Export (C, Initialize_API);
27837 pragma Export (C, Finalize_API);
27838 pragma Export (C, Count);
27839 pragma Export (C, Factorial);
27845 @smallexample @c ada
27848 package body API is
27849 function Factorial (Val : C.int) return C.int is
27852 Count := Count + 1;
27853 for K in 1 .. Val loop
27859 procedure Initialize_API is
27861 pragma Import (C, Adainit);
27864 end Initialize_API;
27866 procedure Finalize_API is
27867 procedure Adafinal;
27868 pragma Import (C, Adafinal);
27878 If the Ada DLL you are building will only be used by Ada applications
27879 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
27880 convention. As an example, the previous package could be written as
27883 @smallexample @c ada
27887 Count : Integer := 0;
27888 function Factorial (Val : Integer) return Integer;
27890 procedure Initialize_API;
27891 procedure Finalize_API;
27892 -- Initialization and Finalization routines.
27898 @smallexample @c ada
27901 package body API is
27902 function Factorial (Val : Integer) return Integer is
27903 Fact : Integer := 1;
27905 Count := Count + 1;
27906 for K in 1 .. Val loop
27913 -- The remainder of this package body is unchanged.
27920 Note that if you do not export the Ada entities with a @code{C} or
27921 @code{Stdcall} convention you will have to provide the mangled Ada names
27922 in the definition file of the Ada DLL
27923 (@pxref{Creating the Definition File}).
27925 @node Ada DLLs and Elaboration
27926 @subsection Ada DLLs and Elaboration
27927 @cindex DLLs and elaboration
27930 The DLL that you are building contains your Ada code as well as all the
27931 routines in the Ada library that are needed by it. The first thing a
27932 user of your DLL must do is elaborate the Ada code
27933 (@pxref{Elaboration Order Handling in GNAT}).
27935 To achieve this you must export an initialization routine
27936 (@code{Initialize_API} in the previous example), which must be invoked
27937 before using any of the DLL services. This elaboration routine must call
27938 the Ada elaboration routine @code{adainit} generated by the GNAT binder
27939 (@pxref{Binding with Non-Ada Main Programs}). See the body of
27940 @code{Initialize_Api} for an example. Note that the GNAT binder is
27941 automatically invoked during the DLL build process by the @code{gnatdll}
27942 tool (@pxref{Using gnatdll}).
27944 When a DLL is loaded, Windows systematically invokes a routine called
27945 @code{DllMain}. It would therefore be possible to call @code{adainit}
27946 directly from @code{DllMain} without having to provide an explicit
27947 initialization routine. Unfortunately, it is not possible to call
27948 @code{adainit} from the @code{DllMain} if your program has library level
27949 tasks because access to the @code{DllMain} entry point is serialized by
27950 the system (that is, only a single thread can execute ``through'' it at a
27951 time), which means that the GNAT run time will deadlock waiting for the
27952 newly created task to complete its initialization.
27954 @node Ada DLLs and Finalization
27955 @subsection Ada DLLs and Finalization
27956 @cindex DLLs and finalization
27959 When the services of an Ada DLL are no longer needed, the client code should
27960 invoke the DLL finalization routine, if available. The DLL finalization
27961 routine is in charge of releasing all resources acquired by the DLL. In the
27962 case of the Ada code contained in the DLL, this is achieved by calling
27963 routine @code{adafinal} generated by the GNAT binder
27964 (@pxref{Binding with Non-Ada Main Programs}).
27965 See the body of @code{Finalize_Api} for an
27966 example. As already pointed out the GNAT binder is automatically invoked
27967 during the DLL build process by the @code{gnatdll} tool
27968 (@pxref{Using gnatdll}).
27970 @node Creating a Spec for Ada DLLs
27971 @subsection Creating a Spec for Ada DLLs
27974 To use the services exported by the Ada DLL from another programming
27975 language (e.g.@: C), you have to translate the specs of the exported Ada
27976 entities in that language. For instance in the case of @code{API.dll},
27977 the corresponding C header file could look like:
27982 extern int *_imp__count;
27983 #define count (*_imp__count)
27984 int factorial (int);
27990 It is important to understand that when building an Ada DLL to be used by
27991 other Ada applications, you need two different specs for the packages
27992 contained in the DLL: one for building the DLL and the other for using
27993 the DLL. This is because the @code{DLL} calling convention is needed to
27994 use a variable defined in a DLL, but when building the DLL, the variable
27995 must have either the @code{Ada} or @code{C} calling convention. As an
27996 example consider a DLL comprising the following package @code{API}:
27998 @smallexample @c ada
28002 Count : Integer := 0;
28004 -- Remainder of the package omitted.
28011 After producing a DLL containing package @code{API}, the spec that
28012 must be used to import @code{API.Count} from Ada code outside of the
28015 @smallexample @c ada
28020 pragma Import (DLL, Count);
28026 @node Creating the Definition File
28027 @subsection Creating the Definition File
28030 The definition file is the last file needed to build the DLL. It lists
28031 the exported symbols. As an example, the definition file for a DLL
28032 containing only package @code{API} (where all the entities are exported
28033 with a @code{C} calling convention) is:
28048 If the @code{C} calling convention is missing from package @code{API},
28049 then the definition file contains the mangled Ada names of the above
28050 entities, which in this case are:
28059 api__initialize_api
28064 @node Using gnatdll
28065 @subsection Using @code{gnatdll}
28069 * gnatdll Example::
28070 * gnatdll behind the Scenes::
28075 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
28076 and non-Ada sources that make up your DLL have been compiled.
28077 @code{gnatdll} is actually in charge of two distinct tasks: build the
28078 static import library for the DLL and the actual DLL. The form of the
28079 @code{gnatdll} command is
28083 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28084 @c Expanding @ovar macro inline (explanation in macro def comments)
28085 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28090 where @var{list-of-files} is a list of ALI and object files. The object
28091 file list must be the exact list of objects corresponding to the non-Ada
28092 sources whose services are to be included in the DLL. The ALI file list
28093 must be the exact list of ALI files for the corresponding Ada sources
28094 whose services are to be included in the DLL. If @var{list-of-files} is
28095 missing, only the static import library is generated.
28098 You may specify any of the following switches to @code{gnatdll}:
28101 @c @item -a@ovar{address}
28102 @c Expanding @ovar macro inline (explanation in macro def comments)
28103 @item -a@r{[}@var{address}@r{]}
28104 @cindex @option{-a} (@code{gnatdll})
28105 Build a non-relocatable DLL at @var{address}. If @var{address} is not
28106 specified the default address @var{0x11000000} will be used. By default,
28107 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
28108 advise the reader to build relocatable DLL.
28110 @item -b @var{address}
28111 @cindex @option{-b} (@code{gnatdll})
28112 Set the relocatable DLL base address. By default the address is
28115 @item -bargs @var{opts}
28116 @cindex @option{-bargs} (@code{gnatdll})
28117 Binder options. Pass @var{opts} to the binder.
28119 @item -d @var{dllfile}
28120 @cindex @option{-d} (@code{gnatdll})
28121 @var{dllfile} is the name of the DLL. This switch must be present for
28122 @code{gnatdll} to do anything. The name of the generated import library is
28123 obtained algorithmically from @var{dllfile} as shown in the following
28124 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
28125 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
28126 by option @option{-e}) is obtained algorithmically from @var{dllfile}
28127 as shown in the following example:
28128 if @var{dllfile} is @code{xyz.dll}, the definition
28129 file used is @code{xyz.def}.
28131 @item -e @var{deffile}
28132 @cindex @option{-e} (@code{gnatdll})
28133 @var{deffile} is the name of the definition file.
28136 @cindex @option{-g} (@code{gnatdll})
28137 Generate debugging information. This information is stored in the object
28138 file and copied from there to the final DLL file by the linker,
28139 where it can be read by the debugger. You must use the
28140 @option{-g} switch if you plan on using the debugger or the symbolic
28144 @cindex @option{-h} (@code{gnatdll})
28145 Help mode. Displays @code{gnatdll} switch usage information.
28148 @cindex @option{-I} (@code{gnatdll})
28149 Direct @code{gnatdll} to search the @var{dir} directory for source and
28150 object files needed to build the DLL.
28151 (@pxref{Search Paths and the Run-Time Library (RTL)}).
28154 @cindex @option{-k} (@code{gnatdll})
28155 Removes the @code{@@}@var{nn} suffix from the import library's exported
28156 names, but keeps them for the link names. You must specify this
28157 option if you want to use a @code{Stdcall} function in a DLL for which
28158 the @code{@@}@var{nn} suffix has been removed. This is the case for most
28159 of the Windows NT DLL for example. This option has no effect when
28160 @option{-n} option is specified.
28162 @item -l @var{file}
28163 @cindex @option{-l} (@code{gnatdll})
28164 The list of ALI and object files used to build the DLL are listed in
28165 @var{file}, instead of being given in the command line. Each line in
28166 @var{file} contains the name of an ALI or object file.
28169 @cindex @option{-n} (@code{gnatdll})
28170 No Import. Do not create the import library.
28173 @cindex @option{-q} (@code{gnatdll})
28174 Quiet mode. Do not display unnecessary messages.
28177 @cindex @option{-v} (@code{gnatdll})
28178 Verbose mode. Display extra information.
28180 @item -largs @var{opts}
28181 @cindex @option{-largs} (@code{gnatdll})
28182 Linker options. Pass @var{opts} to the linker.
28185 @node gnatdll Example
28186 @subsubsection @code{gnatdll} Example
28189 As an example the command to build a relocatable DLL from @file{api.adb}
28190 once @file{api.adb} has been compiled and @file{api.def} created is
28193 $ gnatdll -d api.dll api.ali
28197 The above command creates two files: @file{libapi.dll.a} (the import
28198 library) and @file{api.dll} (the actual DLL). If you want to create
28199 only the DLL, just type:
28202 $ gnatdll -d api.dll -n api.ali
28206 Alternatively if you want to create just the import library, type:
28209 $ gnatdll -d api.dll
28212 @node gnatdll behind the Scenes
28213 @subsubsection @code{gnatdll} behind the Scenes
28216 This section details the steps involved in creating a DLL. @code{gnatdll}
28217 does these steps for you. Unless you are interested in understanding what
28218 goes on behind the scenes, you should skip this section.
28220 We use the previous example of a DLL containing the Ada package @code{API},
28221 to illustrate the steps necessary to build a DLL. The starting point is a
28222 set of objects that will make up the DLL and the corresponding ALI
28223 files. In the case of this example this means that @file{api.o} and
28224 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
28229 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
28230 the information necessary to generate relocation information for the
28236 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
28241 In addition to the base file, the @command{gnatlink} command generates an
28242 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
28243 asks @command{gnatlink} to generate the routines @code{DllMain} and
28244 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
28245 is loaded into memory.
28248 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
28249 export table (@file{api.exp}). The export table contains the relocation
28250 information in a form which can be used during the final link to ensure
28251 that the Windows loader is able to place the DLL anywhere in memory.
28255 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28256 --output-exp api.exp
28261 @code{gnatdll} builds the base file using the new export table. Note that
28262 @command{gnatbind} must be called once again since the binder generated file
28263 has been deleted during the previous call to @command{gnatlink}.
28268 $ gnatlink api -o api.jnk api.exp -mdll
28269 -Wl,--base-file,api.base
28274 @code{gnatdll} builds the new export table using the new base file and
28275 generates the DLL import library @file{libAPI.dll.a}.
28279 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28280 --output-exp api.exp --output-lib libAPI.a
28285 Finally @code{gnatdll} builds the relocatable DLL using the final export
28291 $ gnatlink api api.exp -o api.dll -mdll
28296 @node Using dlltool
28297 @subsubsection Using @code{dlltool}
28300 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
28301 DLLs and static import libraries. This section summarizes the most
28302 common @code{dlltool} switches. The form of the @code{dlltool} command
28306 @c $ dlltool @ovar{switches}
28307 @c Expanding @ovar macro inline (explanation in macro def comments)
28308 $ dlltool @r{[}@var{switches}@r{]}
28312 @code{dlltool} switches include:
28315 @item --base-file @var{basefile}
28316 @cindex @option{--base-file} (@command{dlltool})
28317 Read the base file @var{basefile} generated by the linker. This switch
28318 is used to create a relocatable DLL.
28320 @item --def @var{deffile}
28321 @cindex @option{--def} (@command{dlltool})
28322 Read the definition file.
28324 @item --dllname @var{name}
28325 @cindex @option{--dllname} (@command{dlltool})
28326 Gives the name of the DLL. This switch is used to embed the name of the
28327 DLL in the static import library generated by @code{dlltool} with switch
28328 @option{--output-lib}.
28331 @cindex @option{-k} (@command{dlltool})
28332 Kill @code{@@}@var{nn} from exported names
28333 (@pxref{Windows Calling Conventions}
28334 for a discussion about @code{Stdcall}-style symbols.
28337 @cindex @option{--help} (@command{dlltool})
28338 Prints the @code{dlltool} switches with a concise description.
28340 @item --output-exp @var{exportfile}
28341 @cindex @option{--output-exp} (@command{dlltool})
28342 Generate an export file @var{exportfile}. The export file contains the
28343 export table (list of symbols in the DLL) and is used to create the DLL.
28345 @item --output-lib @var{libfile}
28346 @cindex @option{--output-lib} (@command{dlltool})
28347 Generate a static import library @var{libfile}.
28350 @cindex @option{-v} (@command{dlltool})
28353 @item --as @var{assembler-name}
28354 @cindex @option{--as} (@command{dlltool})
28355 Use @var{assembler-name} as the assembler. The default is @code{as}.
28358 @node GNAT and Windows Resources
28359 @section GNAT and Windows Resources
28360 @cindex Resources, windows
28363 * Building Resources::
28364 * Compiling Resources::
28365 * Using Resources::
28369 Resources are an easy way to add Windows specific objects to your
28370 application. The objects that can be added as resources include:
28399 This section explains how to build, compile and use resources.
28401 @node Building Resources
28402 @subsection Building Resources
28403 @cindex Resources, building
28406 A resource file is an ASCII file. By convention resource files have an
28407 @file{.rc} extension.
28408 The easiest way to build a resource file is to use Microsoft tools
28409 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
28410 @code{dlgedit.exe} to build dialogs.
28411 It is always possible to build an @file{.rc} file yourself by writing a
28414 It is not our objective to explain how to write a resource file. A
28415 complete description of the resource script language can be found in the
28416 Microsoft documentation.
28418 @node Compiling Resources
28419 @subsection Compiling Resources
28422 @cindex Resources, compiling
28425 This section describes how to build a GNAT-compatible (COFF) object file
28426 containing the resources. This is done using the Resource Compiler
28427 @code{windres} as follows:
28430 $ windres -i myres.rc -o myres.o
28434 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
28435 file. You can specify an alternate preprocessor (usually named
28436 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
28437 parameter. A list of all possible options may be obtained by entering
28438 the command @code{windres} @option{--help}.
28440 It is also possible to use the Microsoft resource compiler @code{rc.exe}
28441 to produce a @file{.res} file (binary resource file). See the
28442 corresponding Microsoft documentation for further details. In this case
28443 you need to use @code{windres} to translate the @file{.res} file to a
28444 GNAT-compatible object file as follows:
28447 $ windres -i myres.res -o myres.o
28450 @node Using Resources
28451 @subsection Using Resources
28452 @cindex Resources, using
28455 To include the resource file in your program just add the
28456 GNAT-compatible object file for the resource(s) to the linker
28457 arguments. With @command{gnatmake} this is done by using the @option{-largs}
28461 $ gnatmake myprog -largs myres.o
28464 @node Debugging a DLL
28465 @section Debugging a DLL
28466 @cindex DLL debugging
28469 * Program and DLL Both Built with GCC/GNAT::
28470 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
28474 Debugging a DLL is similar to debugging a standard program. But
28475 we have to deal with two different executable parts: the DLL and the
28476 program that uses it. We have the following four possibilities:
28480 The program and the DLL are built with @code{GCC/GNAT}.
28482 The program is built with foreign tools and the DLL is built with
28485 The program is built with @code{GCC/GNAT} and the DLL is built with
28490 In this section we address only cases one and two above.
28491 There is no point in trying to debug
28492 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
28493 information in it. To do so you must use a debugger compatible with the
28494 tools suite used to build the DLL.
28496 @node Program and DLL Both Built with GCC/GNAT
28497 @subsection Program and DLL Both Built with GCC/GNAT
28500 This is the simplest case. Both the DLL and the program have @code{GDB}
28501 compatible debugging information. It is then possible to break anywhere in
28502 the process. Let's suppose here that the main procedure is named
28503 @code{ada_main} and that in the DLL there is an entry point named
28507 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
28508 program must have been built with the debugging information (see GNAT -g
28509 switch). Here are the step-by-step instructions for debugging it:
28512 @item Launch @code{GDB} on the main program.
28518 @item Start the program and stop at the beginning of the main procedure
28525 This step is required to be able to set a breakpoint inside the DLL. As long
28526 as the program is not run, the DLL is not loaded. This has the
28527 consequence that the DLL debugging information is also not loaded, so it is not
28528 possible to set a breakpoint in the DLL.
28530 @item Set a breakpoint inside the DLL
28533 (gdb) break ada_dll
28540 At this stage a breakpoint is set inside the DLL. From there on
28541 you can use the standard approach to debug the whole program
28542 (@pxref{Running and Debugging Ada Programs}).
28545 @c This used to work, probably because the DLLs were non-relocatable
28546 @c keep this section around until the problem is sorted out.
28548 To break on the @code{DllMain} routine it is not possible to follow
28549 the procedure above. At the time the program stop on @code{ada_main}
28550 the @code{DllMain} routine as already been called. Either you can use
28551 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
28554 @item Launch @code{GDB} on the main program.
28560 @item Load DLL symbols
28563 (gdb) add-sym api.dll
28566 @item Set a breakpoint inside the DLL
28569 (gdb) break ada_dll.adb:45
28572 Note that at this point it is not possible to break using the routine symbol
28573 directly as the program is not yet running. The solution is to break
28574 on the proper line (break in @file{ada_dll.adb} line 45).
28576 @item Start the program
28585 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
28586 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
28589 * Debugging the DLL Directly::
28590 * Attaching to a Running Process::
28594 In this case things are slightly more complex because it is not possible to
28595 start the main program and then break at the beginning to load the DLL and the
28596 associated DLL debugging information. It is not possible to break at the
28597 beginning of the program because there is no @code{GDB} debugging information,
28598 and therefore there is no direct way of getting initial control. This
28599 section addresses this issue by describing some methods that can be used
28600 to break somewhere in the DLL to debug it.
28603 First suppose that the main procedure is named @code{main} (this is for
28604 example some C code built with Microsoft Visual C) and that there is a
28605 DLL named @code{test.dll} containing an Ada entry point named
28609 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
28610 been built with debugging information (see GNAT -g option).
28612 @node Debugging the DLL Directly
28613 @subsubsection Debugging the DLL Directly
28617 Find out the executable starting address
28620 $ objdump --file-header main.exe
28623 The starting address is reported on the last line. For example:
28626 main.exe: file format pei-i386
28627 architecture: i386, flags 0x0000010a:
28628 EXEC_P, HAS_DEBUG, D_PAGED
28629 start address 0x00401010
28633 Launch the debugger on the executable.
28640 Set a breakpoint at the starting address, and launch the program.
28643 $ (gdb) break *0x00401010
28647 The program will stop at the given address.
28650 Set a breakpoint on a DLL subroutine.
28653 (gdb) break ada_dll.adb:45
28656 Or if you want to break using a symbol on the DLL, you need first to
28657 select the Ada language (language used by the DLL).
28660 (gdb) set language ada
28661 (gdb) break ada_dll
28665 Continue the program.
28672 This will run the program until it reaches the breakpoint that has been
28673 set. From that point you can use the standard way to debug a program
28674 as described in (@pxref{Running and Debugging Ada Programs}).
28679 It is also possible to debug the DLL by attaching to a running process.
28681 @node Attaching to a Running Process
28682 @subsubsection Attaching to a Running Process
28683 @cindex DLL debugging, attach to process
28686 With @code{GDB} it is always possible to debug a running process by
28687 attaching to it. It is possible to debug a DLL this way. The limitation
28688 of this approach is that the DLL must run long enough to perform the
28689 attach operation. It may be useful for instance to insert a time wasting
28690 loop in the code of the DLL to meet this criterion.
28694 @item Launch the main program @file{main.exe}.
28700 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
28701 that the process PID for @file{main.exe} is 208.
28709 @item Attach to the running process to be debugged.
28715 @item Load the process debugging information.
28718 (gdb) symbol-file main.exe
28721 @item Break somewhere in the DLL.
28724 (gdb) break ada_dll
28727 @item Continue process execution.
28736 This last step will resume the process execution, and stop at
28737 the breakpoint we have set. From there you can use the standard
28738 approach to debug a program as described in
28739 (@pxref{Running and Debugging Ada Programs}).
28741 @node Setting Stack Size from gnatlink
28742 @section Setting Stack Size from @command{gnatlink}
28745 It is possible to specify the program stack size at link time. On modern
28746 versions of Windows, starting with XP, this is mostly useful to set the size of
28747 the main stack (environment task). The other task stacks are set with pragma
28748 Storage_Size or with the @command{gnatbind -d} command.
28750 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
28751 reserve size of individual tasks, the link-time stack size applies to all
28752 tasks, and pragma Storage_Size has no effect.
28753 In particular, Stack Overflow checks are made against this
28754 link-time specified size.
28756 This setting can be done with
28757 @command{gnatlink} using either:
28761 @item using @option{-Xlinker} linker option
28764 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
28767 This sets the stack reserve size to 0x10000 bytes and the stack commit
28768 size to 0x1000 bytes.
28770 @item using @option{-Wl} linker option
28773 $ gnatlink hello -Wl,--stack=0x1000000
28776 This sets the stack reserve size to 0x1000000 bytes. Note that with
28777 @option{-Wl} option it is not possible to set the stack commit size
28778 because the coma is a separator for this option.
28782 @node Setting Heap Size from gnatlink
28783 @section Setting Heap Size from @command{gnatlink}
28786 Under Windows systems, it is possible to specify the program heap size from
28787 @command{gnatlink} using either:
28791 @item using @option{-Xlinker} linker option
28794 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
28797 This sets the heap reserve size to 0x10000 bytes and the heap commit
28798 size to 0x1000 bytes.
28800 @item using @option{-Wl} linker option
28803 $ gnatlink hello -Wl,--heap=0x1000000
28806 This sets the heap reserve size to 0x1000000 bytes. Note that with
28807 @option{-Wl} option it is not possible to set the heap commit size
28808 because the coma is a separator for this option.
28814 @c **********************************
28815 @c * GNU Free Documentation License *
28816 @c **********************************
28818 @c GNU Free Documentation License
28820 @node Index,,GNU Free Documentation License, Top
28826 @c Put table of contents at end, otherwise it precedes the "title page" in
28827 @c the .txt version
28828 @c Edit the pdf file to move the contents to the beginning, after the title