1 \input texinfo @c -*-texinfo-*-
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
6 @c GNAT DOCUMENTATION o
10 @c GNAT is maintained by Ada Core Technologies Inc (http://www.gnat.com). 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 half
1782 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 compiled):
3829 cannot generate code for file @var{fff} (package spec)
3830 to check package spec, use -gnatc
3832 cannot generate code for file @var{fff} (missing subunits)
3833 to check parent unit, use -gnatc
3835 cannot generate code for file @var{fff} (subprogram spec)
3836 to check subprogram spec, use -gnatc
3838 cannot generate code for file @var{fff} (subunit)
3839 to check subunit, use -gnatc
3843 As indicated by the above error messages, if you want to submit
3844 one of these files to the compiler to check for correct semantics
3845 without generating code, then use the @option{-gnatc} switch.
3847 The basic command for compiling a file containing an Ada unit is
3850 @c $ gcc -c @ovar{switches} @file{file name}
3851 @c Expanding @ovar macro inline (explanation in macro def comments)
3852 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3856 where @var{file name} is the name of the Ada file (usually
3858 @file{.ads} for a spec or @file{.adb} for a body).
3861 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3863 The result of a successful compilation is an object file, which has the
3864 same name as the source file but an extension of @file{.o} and an Ada
3865 Library Information (ALI) file, which also has the same name as the
3866 source file, but with @file{.ali} as the extension. GNAT creates these
3867 two output files in the current directory, but you may specify a source
3868 file in any directory using an absolute or relative path specification
3869 containing the directory information.
3872 @command{gcc} is actually a driver program that looks at the extensions of
3873 the file arguments and loads the appropriate compiler. For example, the
3874 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3875 These programs are in directories known to the driver program (in some
3876 configurations via environment variables you set), but need not be in
3877 your path. The @command{gcc} driver also calls the assembler and any other
3878 utilities needed to complete the generation of the required object
3881 It is possible to supply several file names on the same @command{gcc}
3882 command. This causes @command{gcc} to call the appropriate compiler for
3883 each file. For example, the following command lists three separate
3884 files to be compiled:
3887 $ gcc -c x.adb y.adb z.c
3891 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3892 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3893 The compiler generates three object files @file{x.o}, @file{y.o} and
3894 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3895 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3898 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3901 @node Switches for gcc
3902 @section Switches for @command{gcc}
3905 The @command{gcc} command accepts switches that control the
3906 compilation process. These switches are fully described in this section.
3907 First we briefly list all the switches, in alphabetical order, then we
3908 describe the switches in more detail in functionally grouped sections.
3910 More switches exist for GCC than those documented here, especially
3911 for specific targets. However, their use is not recommended as
3912 they may change code generation in ways that are incompatible with
3913 the Ada run-time library, or can cause inconsistencies between
3917 * Output and Error Message Control::
3918 * Warning Message Control::
3919 * Debugging and Assertion Control::
3920 * Validity Checking::
3923 * Using gcc for Syntax Checking::
3924 * Using gcc for Semantic Checking::
3925 * Compiling Different Versions of Ada::
3926 * Character Set Control::
3927 * File Naming Control::
3928 * Subprogram Inlining Control::
3929 * Auxiliary Output Control::
3930 * Debugging Control::
3931 * Exception Handling Control::
3932 * Units to Sources Mapping Files::
3933 * Integrated Preprocessing::
3934 * Code Generation Control::
3943 @cindex @option{-b} (@command{gcc})
3944 @item -b @var{target}
3945 Compile your program to run on @var{target}, which is the name of a
3946 system configuration. You must have a GNAT cross-compiler built if
3947 @var{target} is not the same as your host system.
3950 @cindex @option{-B} (@command{gcc})
3951 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3952 from @var{dir} instead of the default location. Only use this switch
3953 when multiple versions of the GNAT compiler are available.
3954 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3955 GNU Compiler Collection (GCC)}, for further details. You would normally
3956 use the @option{-b} or @option{-V} switch instead.
3959 @cindex @option{-c} (@command{gcc})
3960 Compile. Always use this switch when compiling Ada programs.
3962 Note: for some other languages when using @command{gcc}, notably in
3963 the case of C and C++, it is possible to use
3964 use @command{gcc} without a @option{-c} switch to
3965 compile and link in one step. In the case of GNAT, you
3966 cannot use this approach, because the binder must be run
3967 and @command{gcc} cannot be used to run the GNAT binder.
3971 @cindex @option{-fno-inline} (@command{gcc})
3972 Suppresses all back-end inlining, even if other optimization or inlining
3974 This includes suppression of inlining that results
3975 from the use of the pragma @code{Inline_Always}.
3976 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3977 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3978 effect if this switch is present.
3980 @item -fno-inline-functions
3981 @cindex @option{-fno-inline-functions} (@command{gcc})
3982 Suppresses automatic inlining of simple subprograms, which is enabled
3983 if @option{-O3} is used.
3985 @item -fno-inline-small-functions
3986 @cindex @option{-fno-inline-small-functions} (@command{gcc})
3987 Suppresses automatic inlining of small subprograms, which is enabled
3988 if @option{-O2} is used.
3990 @item -fno-inline-functions-called-once
3991 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
3992 Suppresses inlining of subprograms local to the unit and called once
3993 from within it, which is enabled if @option{-O1} is used.
3996 @cindex @option{-fno-ivopts} (@command{gcc})
3997 Suppresses high-level loop induction variable optimizations, which are
3998 enabled if @option{-O1} is used. These optimizations are generally
3999 profitable but, for some specific cases of loops with numerous uses
4000 of the iteration variable that follow a common pattern, they may end
4001 up destroying the regularity that could be exploited at a lower level
4002 and thus producing inferior code.
4004 @item -fno-strict-aliasing
4005 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4006 Causes the compiler to avoid assumptions regarding non-aliasing
4007 of objects of different types. See
4008 @ref{Optimization and Strict Aliasing} for details.
4011 @cindex @option{-fstack-check} (@command{gcc})
4012 Activates stack checking.
4013 See @ref{Stack Overflow Checking} for details.
4016 @cindex @option{-fstack-usage} (@command{gcc})
4017 Makes the compiler output stack usage information for the program, on a
4018 per-function basis. See @ref{Static Stack Usage Analysis} for details.
4020 @item -fcallgraph-info@r{[}=su@r{]}
4021 @cindex @option{-fcallgraph-info} (@command{gcc})
4022 Makes the compiler output callgraph information for the program, on a
4023 per-file basis. The information is generated in the VCG format. It can
4024 be decorated with stack-usage per-node information.
4027 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4028 Generate debugging information. This information is stored in the object
4029 file and copied from there to the final executable file by the linker,
4030 where it can be read by the debugger. You must use the
4031 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4034 @cindex @option{-gnat83} (@command{gcc})
4035 Enforce Ada 83 restrictions.
4038 @cindex @option{-gnat95} (@command{gcc})
4039 Enforce Ada 95 restrictions.
4042 @cindex @option{-gnat05} (@command{gcc})
4043 Allow full Ada 2005 features.
4046 @cindex @option{-gnat2005} (@command{gcc})
4047 Allow full Ada 2005 features (same as @option{-gnat05}
4050 @cindex @option{-gnat12} (@command{gcc})
4053 @cindex @option{-gnat2012} (@command{gcc})
4054 Allow full Ada 2012 features (same as @option{-gnat12}
4057 @cindex @option{-gnata} (@command{gcc})
4058 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4059 activated. Note that these pragmas can also be controlled using the
4060 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4061 It also activates pragmas @code{Check}, @code{Precondition}, and
4062 @code{Postcondition}. Note that these pragmas can also be controlled
4063 using the configuration pragma @code{Check_Policy}.
4066 @cindex @option{-gnatA} (@command{gcc})
4067 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4071 @cindex @option{-gnatb} (@command{gcc})
4072 Generate brief messages to @file{stderr} even if verbose mode set.
4075 @cindex @option{-gnatB} (@command{gcc})
4076 Assume no invalid (bad) values except for 'Valid attribute use
4077 (@pxref{Validity Checking}).
4080 @cindex @option{-gnatc} (@command{gcc})
4081 Check syntax and semantics only (no code generation attempted).
4084 @cindex @option{-gnatC} (@command{gcc})
4085 Generate CodePeer information (no code generation attempted).
4086 This switch will generate an intermediate representation suitable for
4087 use by CodePeer (@file{.scil} files). This switch is not compatible with
4088 code generation (it will, among other things, disable some switches such
4089 as -gnatn, and enable others such as -gnata).
4092 @cindex @option{-gnatd} (@command{gcc})
4093 Specify debug options for the compiler. The string of characters after
4094 the @option{-gnatd} specify the specific debug options. The possible
4095 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4096 compiler source file @file{debug.adb} for details of the implemented
4097 debug options. Certain debug options are relevant to applications
4098 programmers, and these are documented at appropriate points in this
4103 @cindex @option{-gnatD[nn]} (@command{gcc})
4106 @item /XDEBUG /LXDEBUG=nnn
4108 Create expanded source files for source level debugging. This switch
4109 also suppress generation of cross-reference information
4110 (see @option{-gnatx}).
4112 @item -gnatec=@var{path}
4113 @cindex @option{-gnatec} (@command{gcc})
4114 Specify a configuration pragma file
4116 (the equal sign is optional)
4118 (@pxref{The Configuration Pragmas Files}).
4120 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4121 @cindex @option{-gnateD} (@command{gcc})
4122 Defines a symbol, associated with @var{value}, for preprocessing.
4123 (@pxref{Integrated Preprocessing}).
4126 @cindex @option{-gnatef} (@command{gcc})
4127 Display full source path name in brief error messages.
4130 @cindex @option{-gnateG} (@command{gcc})
4131 Save result of preprocessing in a text file.
4133 @item -gnatem=@var{path}
4134 @cindex @option{-gnatem} (@command{gcc})
4135 Specify a mapping file
4137 (the equal sign is optional)
4139 (@pxref{Units to Sources Mapping Files}).
4141 @item -gnatep=@var{file}
4142 @cindex @option{-gnatep} (@command{gcc})
4143 Specify a preprocessing data file
4145 (the equal sign is optional)
4147 (@pxref{Integrated Preprocessing}).
4150 @cindex @option{-gnateS} (@command{gcc})
4151 Generate SCO (Source Coverage Obligation) information in the ALI
4152 file. This information is used by advanced coverage tools. See
4153 unit @file{SCOs} in the compiler sources for details in files
4154 @file{scos.ads} and @file{scos.adb}.
4157 @cindex @option{-gnatE} (@command{gcc})
4158 Full dynamic elaboration checks.
4161 @cindex @option{-gnatf} (@command{gcc})
4162 Full errors. Multiple errors per line, all undefined references, do not
4163 attempt to suppress cascaded errors.
4166 @cindex @option{-gnatF} (@command{gcc})
4167 Externals names are folded to all uppercase.
4169 @item ^-gnatg^/GNAT_INTERNAL^
4170 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4171 Internal GNAT implementation mode. This should not be used for
4172 applications programs, it is intended only for use by the compiler
4173 and its run-time library. For documentation, see the GNAT sources.
4174 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4175 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4176 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4177 so that all standard warnings and all standard style options are turned on.
4178 All warnings and style messages are treated as errors.
4182 @cindex @option{-gnatG[nn]} (@command{gcc})
4185 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4187 List generated expanded code in source form.
4189 @item ^-gnath^/HELP^
4190 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4191 Output usage information. The output is written to @file{stdout}.
4193 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4194 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4195 Identifier character set
4197 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4199 For details of the possible selections for @var{c},
4200 see @ref{Character Set Control}.
4202 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4203 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4204 Ignore representation clauses. When this switch is used,
4205 representation clauses are treated as comments. This is useful
4206 when initially porting code where you want to ignore rep clause
4207 problems, and also for compiling foreign code (particularly
4208 for use with ASIS). The representation clauses that are ignored
4209 are: enumeration_representation_clause, record_representation_clause,
4210 and attribute_definition_clause for the following attributes:
4211 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4212 Object_Size, Size, Small, Stream_Size, and Value_Size.
4213 Note that this option should be used only for compiling -- the
4214 code is likely to malfunction at run time.
4217 @cindex @option{-gnatjnn} (@command{gcc})
4218 Reformat error messages to fit on nn character lines
4220 @item -gnatk=@var{n}
4221 @cindex @option{-gnatk} (@command{gcc})
4222 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4225 @cindex @option{-gnatl} (@command{gcc})
4226 Output full source listing with embedded error messages.
4229 @cindex @option{-gnatL} (@command{gcc})
4230 Used in conjunction with -gnatG or -gnatD to intersperse original
4231 source lines (as comment lines with line numbers) in the expanded
4234 @item -gnatm=@var{n}
4235 @cindex @option{-gnatm} (@command{gcc})
4236 Limit number of detected error or warning messages to @var{n}
4237 where @var{n} is in the range 1..999999. The default setting if
4238 no switch is given is 9999. If the number of warnings reaches this
4239 limit, then a message is output and further warnings are suppressed,
4240 but the compilation is continued. If the number of error messages
4241 reaches this limit, then a message is output and the compilation
4242 is abandoned. The equal sign here is optional. A value of zero
4243 means that no limit applies.
4246 @cindex @option{-gnatn} (@command{gcc})
4247 Activate inlining for subprograms for which
4248 pragma @code{inline} is specified. This inlining is performed
4249 by the GCC back-end.
4252 @cindex @option{-gnatN} (@command{gcc})
4253 Activate front end inlining for subprograms for which
4254 pragma @code{Inline} is specified. This inlining is performed
4255 by the front end and will be visible in the
4256 @option{-gnatG} output.
4258 When using a gcc-based back end (in practice this means using any version
4259 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4260 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4261 Historically front end inlining was more extensive than the gcc back end
4262 inlining, but that is no longer the case.
4265 @cindex @option{-gnato} (@command{gcc})
4266 Enable numeric overflow checking (which is not normally enabled by
4267 default). Note that division by zero is a separate check that is not
4268 controlled by this switch (division by zero checking is on by default).
4271 @cindex @option{-gnatp} (@command{gcc})
4272 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4273 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4276 @cindex @option{-gnat-p} (@command{gcc})
4277 Cancel effect of previous @option{-gnatp} switch.
4280 @cindex @option{-gnatP} (@command{gcc})
4281 Enable polling. This is required on some systems (notably Windows NT) to
4282 obtain asynchronous abort and asynchronous transfer of control capability.
4283 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4287 @cindex @option{-gnatq} (@command{gcc})
4288 Don't quit. Try semantics, even if parse errors.
4291 @cindex @option{-gnatQ} (@command{gcc})
4292 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4295 @cindex @option{-gnatr} (@command{gcc})
4296 Treat pragma Restrictions as Restriction_Warnings.
4298 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4299 @cindex @option{-gnatR} (@command{gcc})
4300 Output representation information for declared types and objects.
4303 @cindex @option{-gnats} (@command{gcc})
4307 @cindex @option{-gnatS} (@command{gcc})
4308 Print package Standard.
4311 @cindex @option{-gnatt} (@command{gcc})
4312 Generate tree output file.
4314 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4315 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4316 All compiler tables start at @var{nnn} times usual starting size.
4319 @cindex @option{-gnatu} (@command{gcc})
4320 List units for this compilation.
4323 @cindex @option{-gnatU} (@command{gcc})
4324 Tag all error messages with the unique string ``error:''
4327 @cindex @option{-gnatv} (@command{gcc})
4328 Verbose mode. Full error output with source lines to @file{stdout}.
4331 @cindex @option{-gnatV} (@command{gcc})
4332 Control level of validity checking (@pxref{Validity Checking}).
4334 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4335 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4337 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4338 the exact warnings that
4339 are enabled or disabled (@pxref{Warning Message Control}).
4341 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4342 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4343 Wide character encoding method
4345 (@var{e}=n/h/u/s/e/8).
4348 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4352 @cindex @option{-gnatx} (@command{gcc})
4353 Suppress generation of cross-reference information.
4356 @cindex @option{-gnatX} (@command{gcc})
4357 Enable GNAT implementation extensions and latest Ada version.
4359 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4360 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4361 Enable built-in style checks (@pxref{Style Checking}).
4363 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4364 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4365 Distribution stub generation and compilation
4367 (@var{m}=r/c for receiver/caller stubs).
4370 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4371 to be generated and compiled).
4374 @item ^-I^/SEARCH=^@var{dir}
4375 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4377 Direct GNAT to search the @var{dir} directory for source files needed by
4378 the current compilation
4379 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4381 @item ^-I-^/NOCURRENT_DIRECTORY^
4382 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4384 Except for the source file named in the command line, do not look for source
4385 files in the directory containing the source file named in the command line
4386 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4390 @cindex @option{-mbig-switch} (@command{gcc})
4391 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4392 This standard gcc switch causes the compiler to use larger offsets in its
4393 jump table representation for @code{case} statements.
4394 This may result in less efficient code, but is sometimes necessary
4395 (for example on HP-UX targets)
4396 @cindex HP-UX and @option{-mbig-switch} option
4397 in order to compile large and/or nested @code{case} statements.
4400 @cindex @option{-o} (@command{gcc})
4401 This switch is used in @command{gcc} to redirect the generated object file
4402 and its associated ALI file. Beware of this switch with GNAT, because it may
4403 cause the object file and ALI file to have different names which in turn
4404 may confuse the binder and the linker.
4408 @cindex @option{-nostdinc} (@command{gcc})
4409 Inhibit the search of the default location for the GNAT Run Time
4410 Library (RTL) source files.
4413 @cindex @option{-nostdlib} (@command{gcc})
4414 Inhibit the search of the default location for the GNAT Run Time
4415 Library (RTL) ALI files.
4419 @c Expanding @ovar macro inline (explanation in macro def comments)
4420 @item -O@r{[}@var{n}@r{]}
4421 @cindex @option{-O} (@command{gcc})
4422 @var{n} controls the optimization level.
4426 No optimization, the default setting if no @option{-O} appears
4429 Normal optimization, the default if you specify @option{-O} without
4430 an operand. A good compromise between code quality and compilation
4434 Extensive optimization, may improve execution time, possibly at the cost of
4435 substantially increased compilation time.
4438 Same as @option{-O2}, and also includes inline expansion for small subprograms
4442 Optimize space usage
4446 See also @ref{Optimization Levels}.
4451 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4452 Equivalent to @option{/OPTIMIZE=NONE}.
4453 This is the default behavior in the absence of an @option{/OPTIMIZE}
4456 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4457 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4458 Selects the level of optimization for your program. The supported
4459 keywords are as follows:
4462 Perform most optimizations, including those that
4464 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4465 without keyword options.
4468 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4471 Perform some optimizations, but omit ones that are costly.
4474 Same as @code{SOME}.
4477 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4478 automatic inlining of small subprograms within a unit
4481 Try to unroll loops. This keyword may be specified together with
4482 any keyword above other than @code{NONE}. Loop unrolling
4483 usually, but not always, improves the performance of programs.
4486 Optimize space usage
4490 See also @ref{Optimization Levels}.
4494 @item -pass-exit-codes
4495 @cindex @option{-pass-exit-codes} (@command{gcc})
4496 Catch exit codes from the compiler and use the most meaningful as
4500 @item --RTS=@var{rts-path}
4501 @cindex @option{--RTS} (@command{gcc})
4502 Specifies the default location of the runtime library. Same meaning as the
4503 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4506 @cindex @option{^-S^/ASM^} (@command{gcc})
4507 ^Used in place of @option{-c} to^Used to^
4508 cause the assembler source file to be
4509 generated, using @file{^.s^.S^} as the extension,
4510 instead of the object file.
4511 This may be useful if you need to examine the generated assembly code.
4513 @item ^-fverbose-asm^/VERBOSE_ASM^
4514 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4515 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4516 to cause the generated assembly code file to be annotated with variable
4517 names, making it significantly easier to follow.
4520 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4521 Show commands generated by the @command{gcc} driver. Normally used only for
4522 debugging purposes or if you need to be sure what version of the
4523 compiler you are executing.
4527 @cindex @option{-V} (@command{gcc})
4528 Execute @var{ver} version of the compiler. This is the @command{gcc}
4529 version, not the GNAT version.
4532 @item ^-w^/NO_BACK_END_WARNINGS^
4533 @cindex @option{-w} (@command{gcc})
4534 Turn off warnings generated by the back end of the compiler. Use of
4535 this switch also causes the default for front end warnings to be set
4536 to suppress (as though @option{-gnatws} had appeared at the start of
4542 @c Combining qualifiers does not work on VMS
4543 You may combine a sequence of GNAT switches into a single switch. For
4544 example, the combined switch
4546 @cindex Combining GNAT switches
4552 is equivalent to specifying the following sequence of switches:
4555 -gnato -gnatf -gnati3
4560 The following restrictions apply to the combination of switches
4565 The switch @option{-gnatc} if combined with other switches must come
4566 first in the string.
4569 The switch @option{-gnats} if combined with other switches must come
4570 first in the string.
4574 ^^@option{/DISTRIBUTION_STUBS=},^
4575 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4576 switches, and only one of them may appear in the command line.
4579 The switch @option{-gnat-p} may not be combined with any other switch.
4583 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4584 switch), then all further characters in the switch are interpreted
4585 as style modifiers (see description of @option{-gnaty}).
4588 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4589 switch), then all further characters in the switch are interpreted
4590 as debug flags (see description of @option{-gnatd}).
4593 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4594 switch), then all further characters in the switch are interpreted
4595 as warning mode modifiers (see description of @option{-gnatw}).
4598 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4599 switch), then all further characters in the switch are interpreted
4600 as validity checking options (@pxref{Validity Checking}).
4603 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4604 a combined list of options.
4608 @node Output and Error Message Control
4609 @subsection Output and Error Message Control
4613 The standard default format for error messages is called ``brief format''.
4614 Brief format messages are written to @file{stderr} (the standard error
4615 file) and have the following form:
4618 e.adb:3:04: Incorrect spelling of keyword "function"
4619 e.adb:4:20: ";" should be "is"
4623 The first integer after the file name is the line number in the file,
4624 and the second integer is the column number within the line.
4626 @code{GPS} can parse the error messages
4627 and point to the referenced character.
4629 The following switches provide control over the error message
4635 @cindex @option{-gnatv} (@command{gcc})
4638 The v stands for verbose.
4640 The effect of this setting is to write long-format error
4641 messages to @file{stdout} (the standard output file.
4642 The same program compiled with the
4643 @option{-gnatv} switch would generate:
4647 3. funcion X (Q : Integer)
4649 >>> Incorrect spelling of keyword "function"
4652 >>> ";" should be "is"
4657 The vertical bar indicates the location of the error, and the @samp{>>>}
4658 prefix can be used to search for error messages. When this switch is
4659 used the only source lines output are those with errors.
4662 @cindex @option{-gnatl} (@command{gcc})
4664 The @code{l} stands for list.
4666 This switch causes a full listing of
4667 the file to be generated. In the case where a body is
4668 compiled, the corresponding spec is also listed, along
4669 with any subunits. Typical output from compiling a package
4670 body @file{p.adb} might look like:
4672 @smallexample @c ada
4676 1. package body p is
4678 3. procedure a is separate;
4689 2. pragma Elaborate_Body
4713 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4714 standard output is redirected, a brief summary is written to
4715 @file{stderr} (standard error) giving the number of error messages and
4716 warning messages generated.
4718 @item -^gnatl^OUTPUT_FILE^=file
4719 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4720 This has the same effect as @option{-gnatl} except that the output is
4721 written to a file instead of to standard output. If the given name
4722 @file{fname} does not start with a period, then it is the full name
4723 of the file to be written. If @file{fname} is an extension, it is
4724 appended to the name of the file being compiled. For example, if
4725 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4726 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4729 @cindex @option{-gnatU} (@command{gcc})
4730 This switch forces all error messages to be preceded by the unique
4731 string ``error:''. This means that error messages take a few more
4732 characters in space, but allows easy searching for and identification
4736 @cindex @option{-gnatb} (@command{gcc})
4738 The @code{b} stands for brief.
4740 This switch causes GNAT to generate the
4741 brief format error messages to @file{stderr} (the standard error
4742 file) as well as the verbose
4743 format message or full listing (which as usual is written to
4744 @file{stdout} (the standard output file).
4746 @item -gnatm=@var{n}
4747 @cindex @option{-gnatm} (@command{gcc})
4749 The @code{m} stands for maximum.
4751 @var{n} is a decimal integer in the
4752 range of 1 to 999999 and limits the number of error or warning
4753 messages to be generated. For example, using
4754 @option{-gnatm2} might yield
4757 e.adb:3:04: Incorrect spelling of keyword "function"
4758 e.adb:5:35: missing ".."
4759 fatal error: maximum number of errors detected
4760 compilation abandoned
4764 The default setting if
4765 no switch is given is 9999. If the number of warnings reaches this
4766 limit, then a message is output and further warnings are suppressed,
4767 but the compilation is continued. If the number of error messages
4768 reaches this limit, then a message is output and the compilation
4769 is abandoned. A value of zero means that no limit applies.
4772 Note that the equal sign is optional, so the switches
4773 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4776 @cindex @option{-gnatf} (@command{gcc})
4777 @cindex Error messages, suppressing
4779 The @code{f} stands for full.
4781 Normally, the compiler suppresses error messages that are likely to be
4782 redundant. This switch causes all error
4783 messages to be generated. In particular, in the case of
4784 references to undefined variables. If a given variable is referenced
4785 several times, the normal format of messages is
4787 e.adb:7:07: "V" is undefined (more references follow)
4791 where the parenthetical comment warns that there are additional
4792 references to the variable @code{V}. Compiling the same program with the
4793 @option{-gnatf} switch yields
4796 e.adb:7:07: "V" is undefined
4797 e.adb:8:07: "V" is undefined
4798 e.adb:8:12: "V" is undefined
4799 e.adb:8:16: "V" is undefined
4800 e.adb:9:07: "V" is undefined
4801 e.adb:9:12: "V" is undefined
4805 The @option{-gnatf} switch also generates additional information for
4806 some error messages. Some examples are:
4810 Details on possibly non-portable unchecked conversion
4812 List possible interpretations for ambiguous calls
4814 Additional details on incorrect parameters
4818 @cindex @option{-gnatjnn} (@command{gcc})
4819 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4820 with continuation lines are treated as though the continuation lines were
4821 separate messages (and so a warning with two continuation lines counts as
4822 three warnings, and is listed as three separate messages).
4824 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4825 messages are output in a different manner. A message and all its continuation
4826 lines are treated as a unit, and count as only one warning or message in the
4827 statistics totals. Furthermore, the message is reformatted so that no line
4828 is longer than nn characters.
4831 @cindex @option{-gnatq} (@command{gcc})
4833 The @code{q} stands for quit (really ``don't quit'').
4835 In normal operation mode, the compiler first parses the program and
4836 determines if there are any syntax errors. If there are, appropriate
4837 error messages are generated and compilation is immediately terminated.
4839 GNAT to continue with semantic analysis even if syntax errors have been
4840 found. This may enable the detection of more errors in a single run. On
4841 the other hand, the semantic analyzer is more likely to encounter some
4842 internal fatal error when given a syntactically invalid tree.
4845 @cindex @option{-gnatQ} (@command{gcc})
4846 In normal operation mode, the @file{ALI} file is not generated if any
4847 illegalities are detected in the program. The use of @option{-gnatQ} forces
4848 generation of the @file{ALI} file. This file is marked as being in
4849 error, so it cannot be used for binding purposes, but it does contain
4850 reasonably complete cross-reference information, and thus may be useful
4851 for use by tools (e.g., semantic browsing tools or integrated development
4852 environments) that are driven from the @file{ALI} file. This switch
4853 implies @option{-gnatq}, since the semantic phase must be run to get a
4854 meaningful ALI file.
4856 In addition, if @option{-gnatt} is also specified, then the tree file is
4857 generated even if there are illegalities. It may be useful in this case
4858 to also specify @option{-gnatq} to ensure that full semantic processing
4859 occurs. The resulting tree file can be processed by ASIS, for the purpose
4860 of providing partial information about illegal units, but if the error
4861 causes the tree to be badly malformed, then ASIS may crash during the
4864 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4865 being in error, @command{gnatmake} will attempt to recompile the source when it
4866 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4868 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4869 since ALI files are never generated if @option{-gnats} is set.
4873 @node Warning Message Control
4874 @subsection Warning Message Control
4875 @cindex Warning messages
4877 In addition to error messages, which correspond to illegalities as defined
4878 in the Ada Reference Manual, the compiler detects two kinds of warning
4881 First, the compiler considers some constructs suspicious and generates a
4882 warning message to alert you to a possible error. Second, if the
4883 compiler detects a situation that is sure to raise an exception at
4884 run time, it generates a warning message. The following shows an example
4885 of warning messages:
4887 e.adb:4:24: warning: creation of object may raise Storage_Error
4888 e.adb:10:17: warning: static value out of range
4889 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4893 GNAT considers a large number of situations as appropriate
4894 for the generation of warning messages. As always, warnings are not
4895 definite indications of errors. For example, if you do an out-of-range
4896 assignment with the deliberate intention of raising a
4897 @code{Constraint_Error} exception, then the warning that may be
4898 issued does not indicate an error. Some of the situations for which GNAT
4899 issues warnings (at least some of the time) are given in the following
4900 list. This list is not complete, and new warnings are often added to
4901 subsequent versions of GNAT. The list is intended to give a general idea
4902 of the kinds of warnings that are generated.
4906 Possible infinitely recursive calls
4909 Out-of-range values being assigned
4912 Possible order of elaboration problems
4915 Assertions (pragma Assert) that are sure to fail
4921 Address clauses with possibly unaligned values, or where an attempt is
4922 made to overlay a smaller variable with a larger one.
4925 Fixed-point type declarations with a null range
4928 Direct_IO or Sequential_IO instantiated with a type that has access values
4931 Variables that are never assigned a value
4934 Variables that are referenced before being initialized
4937 Task entries with no corresponding @code{accept} statement
4940 Duplicate accepts for the same task entry in a @code{select}
4943 Objects that take too much storage
4946 Unchecked conversion between types of differing sizes
4949 Missing @code{return} statement along some execution path in a function
4952 Incorrect (unrecognized) pragmas
4955 Incorrect external names
4958 Allocation from empty storage pool
4961 Potentially blocking operation in protected type
4964 Suspicious parenthesization of expressions
4967 Mismatching bounds in an aggregate
4970 Attempt to return local value by reference
4973 Premature instantiation of a generic body
4976 Attempt to pack aliased components
4979 Out of bounds array subscripts
4982 Wrong length on string assignment
4985 Violations of style rules if style checking is enabled
4988 Unused @code{with} clauses
4991 @code{Bit_Order} usage that does not have any effect
4994 @code{Standard.Duration} used to resolve universal fixed expression
4997 Dereference of possibly null value
5000 Declaration that is likely to cause storage error
5003 Internal GNAT unit @code{with}'ed by application unit
5006 Values known to be out of range at compile time
5009 Unreferenced labels and variables
5012 Address overlays that could clobber memory
5015 Unexpected initialization when address clause present
5018 Bad alignment for address clause
5021 Useless type conversions
5024 Redundant assignment statements and other redundant constructs
5027 Useless exception handlers
5030 Accidental hiding of name by child unit
5033 Access before elaboration detected at compile time
5036 A range in a @code{for} loop that is known to be null or might be null
5041 The following section lists compiler switches that are available
5042 to control the handling of warning messages. It is also possible
5043 to exercise much finer control over what warnings are issued and
5044 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5045 gnat_rm, GNAT Reference manual}.
5050 @emph{Activate all optional errors.}
5051 @cindex @option{-gnatwa} (@command{gcc})
5052 This switch activates most optional warning messages, see remaining list
5053 in this section for details on optional warning messages that can be
5054 individually controlled. The warnings that are not turned on by this
5056 @option{-gnatwd} (implicit dereferencing),
5057 @option{-gnatwh} (hiding),
5058 @option{-gnatwl} (elaboration warnings),
5059 @option{-gnatw.o} (warn on values set by out parameters ignored)
5060 and @option{-gnatwt} (tracking of deleted conditional code).
5061 All other optional warnings are turned on.
5064 @emph{Suppress all optional errors.}
5065 @cindex @option{-gnatwA} (@command{gcc})
5066 This switch suppresses all optional warning messages, see remaining list
5067 in this section for details on optional warning messages that can be
5068 individually controlled.
5071 @emph{Activate warnings on failing assertions.}
5072 @cindex @option{-gnatw.a} (@command{gcc})
5073 @cindex Assert failures
5074 This switch activates warnings for assertions where the compiler can tell at
5075 compile time that the assertion will fail. Note that this warning is given
5076 even if assertions are disabled. The default is that such warnings are
5080 @emph{Suppress warnings on failing assertions.}
5081 @cindex @option{-gnatw.A} (@command{gcc})
5082 @cindex Assert failures
5083 This switch suppresses warnings for assertions where the compiler can tell at
5084 compile time that the assertion will fail.
5087 @emph{Activate warnings on bad fixed values.}
5088 @cindex @option{-gnatwb} (@command{gcc})
5089 @cindex Bad fixed values
5090 @cindex Fixed-point Small value
5092 This switch activates warnings for static fixed-point expressions whose
5093 value is not an exact multiple of Small. Such values are implementation
5094 dependent, since an implementation is free to choose either of the multiples
5095 that surround the value. GNAT always chooses the closer one, but this is not
5096 required behavior, and it is better to specify a value that is an exact
5097 multiple, ensuring predictable execution. The default is that such warnings
5101 @emph{Suppress warnings on bad fixed values.}
5102 @cindex @option{-gnatwB} (@command{gcc})
5103 This switch suppresses warnings for static fixed-point expressions whose
5104 value is not an exact multiple of Small.
5107 @emph{Activate warnings on biased representation.}
5108 @cindex @option{-gnatw.b} (@command{gcc})
5109 @cindex Biased representation
5110 This switch activates warnings when a size clause, value size clause, component
5111 clause, or component size clause forces the use of biased representation for an
5112 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5113 to represent 10/11). The default is that such warnings are generated.
5116 @emph{Suppress warnings on biased representation.}
5117 @cindex @option{-gnatwB} (@command{gcc})
5118 This switch suppresses warnings for representation clauses that force the use
5119 of biased representation.
5122 @emph{Activate warnings on conditionals.}
5123 @cindex @option{-gnatwc} (@command{gcc})
5124 @cindex Conditionals, constant
5125 This switch activates warnings for conditional expressions used in
5126 tests that are known to be True or False at compile time. The default
5127 is that such warnings are not generated.
5128 Note that this warning does
5129 not get issued for the use of boolean variables or constants whose
5130 values are known at compile time, since this is a standard technique
5131 for conditional compilation in Ada, and this would generate too many
5132 false positive warnings.
5134 This warning option also activates a special test for comparisons using
5135 the operators ``>='' and`` <=''.
5136 If the compiler can tell that only the equality condition is possible,
5137 then it will warn that the ``>'' or ``<'' part of the test
5138 is useless and that the operator could be replaced by ``=''.
5139 An example would be comparing a @code{Natural} variable <= 0.
5141 This warning option also generates warnings if
5142 one or both tests is optimized away in a membership test for integer
5143 values if the result can be determined at compile time. Range tests on
5144 enumeration types are not included, since it is common for such tests
5145 to include an end point.
5147 This warning can also be turned on using @option{-gnatwa}.
5150 @emph{Suppress warnings on conditionals.}
5151 @cindex @option{-gnatwC} (@command{gcc})
5152 This switch suppresses warnings for conditional expressions used in
5153 tests that are known to be True or False at compile time.
5156 @emph{Activate warnings on missing component clauses.}
5157 @cindex @option{-gnatw.c} (@command{gcc})
5158 @cindex Component clause, missing
5159 This switch activates warnings for record components where a record
5160 representation clause is present and has component clauses for the
5161 majority, but not all, of the components. A warning is given for each
5162 component for which no component clause is present.
5164 This warning can also be turned on using @option{-gnatwa}.
5167 @emph{Suppress warnings on missing component clauses.}
5168 @cindex @option{-gnatwC} (@command{gcc})
5169 This switch suppresses warnings for record components that are
5170 missing a component clause in the situation described above.
5173 @emph{Activate warnings on implicit dereferencing.}
5174 @cindex @option{-gnatwd} (@command{gcc})
5175 If this switch is set, then the use of a prefix of an access type
5176 in an indexed component, slice, or selected component without an
5177 explicit @code{.all} will generate a warning. With this warning
5178 enabled, access checks occur only at points where an explicit
5179 @code{.all} appears in the source code (assuming no warnings are
5180 generated as a result of this switch). The default is that such
5181 warnings are not generated.
5182 Note that @option{-gnatwa} does not affect the setting of
5183 this warning option.
5186 @emph{Suppress warnings on implicit dereferencing.}
5187 @cindex @option{-gnatwD} (@command{gcc})
5188 @cindex Implicit dereferencing
5189 @cindex Dereferencing, implicit
5190 This switch suppresses warnings for implicit dereferences in
5191 indexed components, slices, and selected components.
5194 @emph{Treat warnings and style checks as errors.}
5195 @cindex @option{-gnatwe} (@command{gcc})
5196 @cindex Warnings, treat as error
5197 This switch causes warning messages and style check messages to be
5199 The warning string still appears, but the warning messages are counted
5200 as errors, and prevent the generation of an object file. Note that this
5201 is the only -gnatw switch that affects the handling of style check messages.
5204 @emph{Activate every optional warning}
5205 @cindex @option{-gnatw.e} (@command{gcc})
5206 @cindex Warnings, activate every optional warning
5207 This switch activates all optional warnings, including those which
5208 are not activated by @code{-gnatwa}.
5211 @emph{Activate warnings on unreferenced formals.}
5212 @cindex @option{-gnatwf} (@command{gcc})
5213 @cindex Formals, unreferenced
5214 This switch causes a warning to be generated if a formal parameter
5215 is not referenced in the body of the subprogram. This warning can
5216 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5217 default is that these warnings are not generated.
5220 @emph{Suppress warnings on unreferenced formals.}
5221 @cindex @option{-gnatwF} (@command{gcc})
5222 This switch suppresses warnings for unreferenced formal
5223 parameters. Note that the
5224 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5225 effect of warning on unreferenced entities other than subprogram
5229 @emph{Activate warnings on unrecognized pragmas.}
5230 @cindex @option{-gnatwg} (@command{gcc})
5231 @cindex Pragmas, unrecognized
5232 This switch causes a warning to be generated if an unrecognized
5233 pragma is encountered. Apart from issuing this warning, the
5234 pragma is ignored and has no effect. This warning can
5235 also be turned on using @option{-gnatwa}. The default
5236 is that such warnings are issued (satisfying the Ada Reference
5237 Manual requirement that such warnings appear).
5240 @emph{Suppress warnings on unrecognized pragmas.}
5241 @cindex @option{-gnatwG} (@command{gcc})
5242 This switch suppresses warnings for unrecognized pragmas.
5245 @emph{Activate warnings on hiding.}
5246 @cindex @option{-gnatwh} (@command{gcc})
5247 @cindex Hiding of Declarations
5248 This switch activates warnings on hiding declarations.
5249 A declaration is considered hiding
5250 if it is for a non-overloadable entity, and it declares an entity with the
5251 same name as some other entity that is directly or use-visible. The default
5252 is that such warnings are not generated.
5253 Note that @option{-gnatwa} does not affect the setting of this warning option.
5256 @emph{Suppress warnings on hiding.}
5257 @cindex @option{-gnatwH} (@command{gcc})
5258 This switch suppresses warnings on hiding declarations.
5261 @emph{Activate warnings on implementation units.}
5262 @cindex @option{-gnatwi} (@command{gcc})
5263 This switch activates warnings for a @code{with} of an internal GNAT
5264 implementation unit, defined as any unit from the @code{Ada},
5265 @code{Interfaces}, @code{GNAT},
5266 ^^@code{DEC},^ or @code{System}
5267 hierarchies that is not
5268 documented in either the Ada Reference Manual or the GNAT
5269 Programmer's Reference Manual. Such units are intended only
5270 for internal implementation purposes and should not be @code{with}'ed
5271 by user programs. The default is that such warnings are generated
5272 This warning can also be turned on using @option{-gnatwa}.
5275 @emph{Disable warnings on implementation units.}
5276 @cindex @option{-gnatwI} (@command{gcc})
5277 This switch disables warnings for a @code{with} of an internal GNAT
5278 implementation unit.
5281 @emph{Activate warnings on overlapping actuals.}
5282 @cindex @option{-gnatw.i} (@command{gcc})
5283 This switch enables a warning on statically detectable overlapping actuals in
5284 a subprogram call, when one of the actuals is an in-out parameter, and the
5285 types of the actuals are not by-copy types. The warning is off by default,
5286 and is not included under -gnatwa.
5289 @emph{Disable warnings on overlapping actuals.}
5290 @cindex @option{-gnatw.I} (@command{gcc})
5291 This switch disables warnings on overlapping actuals in a call..
5294 @emph{Activate warnings on obsolescent features (Annex J).}
5295 @cindex @option{-gnatwj} (@command{gcc})
5296 @cindex Features, obsolescent
5297 @cindex Obsolescent features
5298 If this warning option is activated, then warnings are generated for
5299 calls to subprograms marked with @code{pragma Obsolescent} and
5300 for use of features in Annex J of the Ada Reference Manual. In the
5301 case of Annex J, not all features are flagged. In particular use
5302 of the renamed packages (like @code{Text_IO}) and use of package
5303 @code{ASCII} are not flagged, since these are very common and
5304 would generate many annoying positive warnings. The default is that
5305 such warnings are not generated. This warning is also turned on by
5306 the use of @option{-gnatwa}.
5308 In addition to the above cases, warnings are also generated for
5309 GNAT features that have been provided in past versions but which
5310 have been superseded (typically by features in the new Ada standard).
5311 For example, @code{pragma Ravenscar} will be flagged since its
5312 function is replaced by @code{pragma Profile(Ravenscar)}.
5314 Note that this warning option functions differently from the
5315 restriction @code{No_Obsolescent_Features} in two respects.
5316 First, the restriction applies only to annex J features.
5317 Second, the restriction does flag uses of package @code{ASCII}.
5320 @emph{Suppress warnings on obsolescent features (Annex J).}
5321 @cindex @option{-gnatwJ} (@command{gcc})
5322 This switch disables warnings on use of obsolescent features.
5325 @emph{Activate warnings on variables that could be constants.}
5326 @cindex @option{-gnatwk} (@command{gcc})
5327 This switch activates warnings for variables that are initialized but
5328 never modified, and then could be declared constants. The default is that
5329 such warnings are not given.
5330 This warning can also be turned on using @option{-gnatwa}.
5333 @emph{Suppress warnings on variables that could be constants.}
5334 @cindex @option{-gnatwK} (@command{gcc})
5335 This switch disables warnings on variables that could be declared constants.
5338 @emph{Activate warnings for elaboration pragmas.}
5339 @cindex @option{-gnatwl} (@command{gcc})
5340 @cindex Elaboration, warnings
5341 This switch activates warnings on missing
5342 @code{Elaborate_All} and @code{Elaborate} pragmas.
5343 See the section in this guide on elaboration checking for details on
5344 when such pragmas should be used. In dynamic elaboration mode, this switch
5345 generations warnings about the need to add elaboration pragmas. Note however,
5346 that if you blindly follow these warnings, and add @code{Elaborate_All}
5347 warnings wherever they are recommended, you basically end up with the
5348 equivalent of the static elaboration model, which may not be what you want for
5349 legacy code for which the static model does not work.
5351 For the static model, the messages generated are labeled "info:" (for
5352 information messages). They are not warnings to add elaboration pragmas,
5353 merely informational messages showing what implicit elaboration pragmas
5354 have been added, for use in analyzing elaboration circularity problems.
5356 Warnings are also generated if you
5357 are using the static mode of elaboration, and a @code{pragma Elaborate}
5358 is encountered. The default is that such warnings
5360 This warning is not automatically turned on by the use of @option{-gnatwa}.
5363 @emph{Suppress warnings for elaboration pragmas.}
5364 @cindex @option{-gnatwL} (@command{gcc})
5365 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5366 See the section in this guide on elaboration checking for details on
5367 when such pragmas should be used.
5370 @emph{Activate warnings on modified but unreferenced variables.}
5371 @cindex @option{-gnatwm} (@command{gcc})
5372 This switch activates warnings for variables that are assigned (using
5373 an initialization value or with one or more assignment statements) but
5374 whose value is never read. The warning is suppressed for volatile
5375 variables and also for variables that are renamings of other variables
5376 or for which an address clause is given.
5377 This warning can also be turned on using @option{-gnatwa}.
5378 The default is that these warnings are not given.
5381 @emph{Disable warnings on modified but unreferenced variables.}
5382 @cindex @option{-gnatwM} (@command{gcc})
5383 This switch disables warnings for variables that are assigned or
5384 initialized, but never read.
5387 @emph{Activate warnings on suspicious modulus values.}
5388 @cindex @option{-gnatw.m} (@command{gcc})
5389 This switch activates warnings for modulus values that seem suspicious.
5390 The cases caught are where the size is the same as the modulus (e.g.
5391 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5392 with no size clause. The guess in both cases is that 2**x was intended
5393 rather than x. The default is that these warnings are given.
5396 @emph{Disable warnings on suspicious modulus values.}
5397 @cindex @option{-gnatw.M} (@command{gcc})
5398 This switch disables warnings for suspicious modulus values.
5401 @emph{Set normal warnings mode.}
5402 @cindex @option{-gnatwn} (@command{gcc})
5403 This switch sets normal warning mode, in which enabled warnings are
5404 issued and treated as warnings rather than errors. This is the default
5405 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5406 an explicit @option{-gnatws} or
5407 @option{-gnatwe}. It also cancels the effect of the
5408 implicit @option{-gnatwe} that is activated by the
5409 use of @option{-gnatg}.
5412 @emph{Activate warnings on address clause overlays.}
5413 @cindex @option{-gnatwo} (@command{gcc})
5414 @cindex Address Clauses, warnings
5415 This switch activates warnings for possibly unintended initialization
5416 effects of defining address clauses that cause one variable to overlap
5417 another. The default is that such warnings are generated.
5418 This warning can also be turned on using @option{-gnatwa}.
5421 @emph{Suppress warnings on address clause overlays.}
5422 @cindex @option{-gnatwO} (@command{gcc})
5423 This switch suppresses warnings on possibly unintended initialization
5424 effects of defining address clauses that cause one variable to overlap
5428 @emph{Activate warnings on modified but unreferenced out parameters.}
5429 @cindex @option{-gnatw.o} (@command{gcc})
5430 This switch activates warnings for variables that are modified by using
5431 them as actuals for a call to a procedure with an out mode formal, where
5432 the resulting assigned value is never read. It is applicable in the case
5433 where there is more than one out mode formal. If there is only one out
5434 mode formal, the warning is issued by default (controlled by -gnatwu).
5435 The warning is suppressed for volatile
5436 variables and also for variables that are renamings of other variables
5437 or for which an address clause is given.
5438 The default is that these warnings are not given. Note that this warning
5439 is not included in -gnatwa, it must be activated explicitly.
5442 @emph{Disable warnings on modified but unreferenced out parameters.}
5443 @cindex @option{-gnatw.O} (@command{gcc})
5444 This switch suppresses warnings for variables that are modified by using
5445 them as actuals for a call to a procedure with an out mode formal, where
5446 the resulting assigned value is never read.
5449 @emph{Activate warnings on ineffective pragma Inlines.}
5450 @cindex @option{-gnatwp} (@command{gcc})
5451 @cindex Inlining, warnings
5452 This switch activates warnings for failure of front end inlining
5453 (activated by @option{-gnatN}) to inline a particular call. There are
5454 many reasons for not being able to inline a call, including most
5455 commonly that the call is too complex to inline. The default is
5456 that such warnings are not given.
5457 This warning can also be turned on using @option{-gnatwa}.
5458 Warnings on ineffective inlining by the gcc back-end can be activated
5459 separately, using the gcc switch -Winline.
5462 @emph{Suppress warnings on ineffective pragma Inlines.}
5463 @cindex @option{-gnatwP} (@command{gcc})
5464 This switch suppresses warnings on ineffective pragma Inlines. If the
5465 inlining mechanism cannot inline a call, it will simply ignore the
5469 @emph{Activate warnings on parameter ordering.}
5470 @cindex @option{-gnatw.p} (@command{gcc})
5471 @cindex Parameter order, warnings
5472 This switch activates warnings for cases of suspicious parameter
5473 ordering when the list of arguments are all simple identifiers that
5474 match the names of the formals, but are in a different order. The
5475 warning is suppressed if any use of named parameter notation is used,
5476 so this is the appropriate way to suppress a false positive (and
5477 serves to emphasize that the "misordering" is deliberate). The
5479 that such warnings are not given.
5480 This warning can also be turned on using @option{-gnatwa}.
5483 @emph{Suppress warnings on parameter ordering.}
5484 @cindex @option{-gnatw.P} (@command{gcc})
5485 This switch suppresses warnings on cases of suspicious parameter
5489 @emph{Activate warnings on questionable missing parentheses.}
5490 @cindex @option{-gnatwq} (@command{gcc})
5491 @cindex Parentheses, warnings
5492 This switch activates warnings for cases where parentheses are not used and
5493 the result is potential ambiguity from a readers point of view. For example
5494 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5495 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5496 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5497 follow the rule of always parenthesizing to make the association clear, and
5498 this warning switch warns if such parentheses are not present. The default
5499 is that these warnings are given.
5500 This warning can also be turned on using @option{-gnatwa}.
5503 @emph{Suppress warnings on questionable missing parentheses.}
5504 @cindex @option{-gnatwQ} (@command{gcc})
5505 This switch suppresses warnings for cases where the association is not
5506 clear and the use of parentheses is preferred.
5509 @emph{Activate warnings on redundant constructs.}
5510 @cindex @option{-gnatwr} (@command{gcc})
5511 This switch activates warnings for redundant constructs. The following
5512 is the current list of constructs regarded as redundant:
5516 Assignment of an item to itself.
5518 Type conversion that converts an expression to its own type.
5520 Use of the attribute @code{Base} where @code{typ'Base} is the same
5523 Use of pragma @code{Pack} when all components are placed by a record
5524 representation clause.
5526 Exception handler containing only a reraise statement (raise with no
5527 operand) which has no effect.
5529 Use of the operator abs on an operand that is known at compile time
5532 Comparison of boolean expressions to an explicit True value.
5535 This warning can also be turned on using @option{-gnatwa}.
5536 The default is that warnings for redundant constructs are not given.
5539 @emph{Suppress warnings on redundant constructs.}
5540 @cindex @option{-gnatwR} (@command{gcc})
5541 This switch suppresses warnings for redundant constructs.
5544 @emph{Activate warnings for object renaming function.}
5545 @cindex @option{-gnatw.r} (@command{gcc})
5546 This switch activates warnings for an object renaming that renames a
5547 function call, which is equivalent to a constant declaration (as
5548 opposed to renaming the function itself). The default is that these
5549 warnings are given. This warning can also be turned on using
5553 @emph{Suppress warnings for object renaming function.}
5554 @cindex @option{-gnatwT} (@command{gcc})
5555 This switch suppresses warnings for object renaming function.
5558 @emph{Suppress all warnings.}
5559 @cindex @option{-gnatws} (@command{gcc})
5560 This switch completely suppresses the
5561 output of all warning messages from the GNAT front end.
5562 Note that it does not suppress warnings from the @command{gcc} back end.
5563 To suppress these back end warnings as well, use the switch @option{-w}
5564 in addition to @option{-gnatws}. Also this switch has no effect on the
5565 handling of style check messages.
5568 @emph{Activate warnings for tracking of deleted conditional code.}
5569 @cindex @option{-gnatwt} (@command{gcc})
5570 @cindex Deactivated code, warnings
5571 @cindex Deleted code, warnings
5572 This switch activates warnings for tracking of code in conditionals (IF and
5573 CASE statements) that is detected to be dead code which cannot be executed, and
5574 which is removed by the front end. This warning is off by default, and is not
5575 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5576 useful for detecting deactivated code in certified applications.
5579 @emph{Suppress warnings for tracking of deleted conditional code.}
5580 @cindex @option{-gnatwT} (@command{gcc})
5581 This switch suppresses warnings for tracking of deleted conditional code.
5584 @emph{Activate warnings on unused entities.}
5585 @cindex @option{-gnatwu} (@command{gcc})
5586 This switch activates warnings to be generated for entities that
5587 are declared but not referenced, and for units that are @code{with}'ed
5589 referenced. In the case of packages, a warning is also generated if
5590 no entities in the package are referenced. This means that if the package
5591 is referenced but the only references are in @code{use}
5592 clauses or @code{renames}
5593 declarations, a warning is still generated. A warning is also generated
5594 for a generic package that is @code{with}'ed but never instantiated.
5595 In the case where a package or subprogram body is compiled, and there
5596 is a @code{with} on the corresponding spec
5597 that is only referenced in the body,
5598 a warning is also generated, noting that the
5599 @code{with} can be moved to the body. The default is that
5600 such warnings are not generated.
5601 This switch also activates warnings on unreferenced formals
5602 (it includes the effect of @option{-gnatwf}).
5603 This warning can also be turned on using @option{-gnatwa}.
5606 @emph{Suppress warnings on unused entities.}
5607 @cindex @option{-gnatwU} (@command{gcc})
5608 This switch suppresses warnings for unused entities and packages.
5609 It also turns off warnings on unreferenced formals (and thus includes
5610 the effect of @option{-gnatwF}).
5613 @emph{Activate warnings on unordered enumeration types.}
5614 @cindex @option{-gnatw.u} (@command{gcc})
5615 This switch causes enumeration types to be considered as conceptually
5616 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5617 The effect is to generate warnings in clients that use explicit comparisons
5618 or subranges, since these constructs both treat objects of the type as
5619 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5620 which the type is declared, or its body or subunits.) Please refer to
5621 the description of pragma @code{Ordered} in the
5622 @cite{@value{EDITION} Reference Manual} for further details.
5625 @emph{Deactivate warnings on unordered enumeration types.}
5626 @cindex @option{-gnatw.U} (@command{gcc})
5627 This switch causes all enumeration types to be considered as ordered, so
5628 that no warnings are given for comparisons or subranges for any type.
5631 @emph{Activate warnings on unassigned variables.}
5632 @cindex @option{-gnatwv} (@command{gcc})
5633 @cindex Unassigned variable warnings
5634 This switch activates warnings for access to variables which
5635 may not be properly initialized. The default is that
5636 such warnings are generated.
5637 This warning can also be turned on using @option{-gnatwa}.
5640 @emph{Suppress warnings on unassigned variables.}
5641 @cindex @option{-gnatwV} (@command{gcc})
5642 This switch suppresses warnings for access to variables which
5643 may not be properly initialized.
5644 For variables of a composite type, the warning can also be suppressed in
5645 Ada 2005 by using a default initialization with a box. For example, if
5646 Table is an array of records whose components are only partially uninitialized,
5647 then the following code:
5649 @smallexample @c ada
5650 Tab : Table := (others => <>);
5653 will suppress warnings on subsequent statements that access components
5657 @emph{Activate warnings on wrong low bound assumption.}
5658 @cindex @option{-gnatww} (@command{gcc})
5659 @cindex String indexing warnings
5660 This switch activates warnings for indexing an unconstrained string parameter
5661 with a literal or S'Length. This is a case where the code is assuming that the
5662 low bound is one, which is in general not true (for example when a slice is
5663 passed). The default is that such warnings are generated.
5664 This warning can also be turned on using @option{-gnatwa}.
5667 @emph{Suppress warnings on wrong low bound assumption.}
5668 @cindex @option{-gnatwW} (@command{gcc})
5669 This switch suppresses warnings for indexing an unconstrained string parameter
5670 with a literal or S'Length. Note that this warning can also be suppressed
5671 in a particular case by adding an
5672 assertion that the lower bound is 1,
5673 as shown in the following example.
5675 @smallexample @c ada
5676 procedure K (S : String) is
5677 pragma Assert (S'First = 1);
5682 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5683 @cindex @option{-gnatw.w} (@command{gcc})
5684 @cindex Warnings Off control
5685 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5686 where either the pragma is entirely useless (because it suppresses no
5687 warnings), or it could be replaced by @code{pragma Unreferenced} or
5688 @code{pragma Unmodified}.The default is that these warnings are not given.
5689 Note that this warning is not included in -gnatwa, it must be
5690 activated explicitly.
5693 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5694 @cindex @option{-gnatw.W} (@command{gcc})
5695 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5698 @emph{Activate warnings on Export/Import pragmas.}
5699 @cindex @option{-gnatwx} (@command{gcc})
5700 @cindex Export/Import pragma warnings
5701 This switch activates warnings on Export/Import pragmas when
5702 the compiler detects a possible conflict between the Ada and
5703 foreign language calling sequences. For example, the use of
5704 default parameters in a convention C procedure is dubious
5705 because the C compiler cannot supply the proper default, so
5706 a warning is issued. The default is that such warnings are
5708 This warning can also be turned on using @option{-gnatwa}.
5711 @emph{Suppress warnings on Export/Import pragmas.}
5712 @cindex @option{-gnatwX} (@command{gcc})
5713 This switch suppresses warnings on Export/Import pragmas.
5714 The sense of this is that you are telling the compiler that
5715 you know what you are doing in writing the pragma, and it
5716 should not complain at you.
5719 @emph{Activate warnings for No_Exception_Propagation mode.}
5720 @cindex @option{-gnatwm} (@command{gcc})
5721 This switch activates warnings for exception usage when pragma Restrictions
5722 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5723 explicit exception raises which are not covered by a local handler, and for
5724 exception handlers which do not cover a local raise. The default is that these
5725 warnings are not given.
5728 @emph{Disable warnings for No_Exception_Propagation mode.}
5729 This switch disables warnings for exception usage when pragma Restrictions
5730 (No_Exception_Propagation) is in effect.
5733 @emph{Activate warnings for Ada 2005 compatibility issues.}
5734 @cindex @option{-gnatwy} (@command{gcc})
5735 @cindex Ada 2005 compatibility issues warnings
5736 For the most part Ada 2005 is upwards compatible with Ada 95,
5737 but there are some exceptions (for example the fact that
5738 @code{interface} is now a reserved word in Ada 2005). This
5739 switch activates several warnings to help in identifying
5740 and correcting such incompatibilities. The default is that
5741 these warnings are generated. Note that at one point Ada 2005
5742 was called Ada 0Y, hence the choice of character.
5743 This warning can also be turned on using @option{-gnatwa}.
5746 @emph{Disable warnings for Ada 2005 compatibility issues.}
5747 @cindex @option{-gnatwY} (@command{gcc})
5748 @cindex Ada 2005 compatibility issues warnings
5749 This switch suppresses several warnings intended to help in identifying
5750 incompatibilities between Ada 95 and Ada 2005.
5753 @emph{Activate warnings on unchecked conversions.}
5754 @cindex @option{-gnatwz} (@command{gcc})
5755 @cindex Unchecked_Conversion warnings
5756 This switch activates warnings for unchecked conversions
5757 where the types are known at compile time to have different
5759 is that such warnings are generated. Warnings are also
5760 generated for subprogram pointers with different conventions,
5761 and, on VMS only, for data pointers with different conventions.
5762 This warning can also be turned on using @option{-gnatwa}.
5765 @emph{Suppress warnings on unchecked conversions.}
5766 @cindex @option{-gnatwZ} (@command{gcc})
5767 This switch suppresses warnings for unchecked conversions
5768 where the types are known at compile time to have different
5769 sizes or conventions.
5771 @item ^-Wunused^WARNINGS=UNUSED^
5772 @cindex @option{-Wunused}
5773 The warnings controlled by the @option{-gnatw} switch are generated by
5774 the front end of the compiler. The @option{GCC} back end can provide
5775 additional warnings and they are controlled by the @option{-W} switch.
5776 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5777 warnings for entities that are declared but not referenced.
5779 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5780 @cindex @option{-Wuninitialized}
5781 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5782 the back end warning for uninitialized variables. This switch must be
5783 used in conjunction with an optimization level greater than zero.
5785 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5786 @cindex @option{-Wall}
5787 This switch enables all the above warnings from the @option{GCC} back end.
5788 The code generator detects a number of warning situations that are missed
5789 by the @option{GNAT} front end, and this switch can be used to activate them.
5790 The use of this switch also sets the default front end warning mode to
5791 @option{-gnatwa}, that is, most front end warnings activated as well.
5793 @item ^-w^/NO_BACK_END_WARNINGS^
5795 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5796 The use of this switch also sets the default front end warning mode to
5797 @option{-gnatws}, that is, front end warnings suppressed as well.
5803 A string of warning parameters can be used in the same parameter. For example:
5810 will turn on all optional warnings except for elaboration pragma warnings,
5811 and also specify that warnings should be treated as errors.
5813 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5838 @node Debugging and Assertion Control
5839 @subsection Debugging and Assertion Control
5843 @cindex @option{-gnata} (@command{gcc})
5849 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5850 are ignored. This switch, where @samp{a} stands for assert, causes
5851 @code{Assert} and @code{Debug} pragmas to be activated.
5853 The pragmas have the form:
5857 @b{pragma} Assert (@var{Boolean-expression} @r{[},
5858 @var{static-string-expression}@r{]})
5859 @b{pragma} Debug (@var{procedure call})
5864 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5865 If the result is @code{True}, the pragma has no effect (other than
5866 possible side effects from evaluating the expression). If the result is
5867 @code{False}, the exception @code{Assert_Failure} declared in the package
5868 @code{System.Assertions} is
5869 raised (passing @var{static-string-expression}, if present, as the
5870 message associated with the exception). If no string expression is
5871 given the default is a string giving the file name and line number
5874 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5875 @code{pragma Debug} may appear within a declaration sequence, allowing
5876 debugging procedures to be called between declarations.
5879 @item /DEBUG@r{[}=debug-level@r{]}
5881 Specifies how much debugging information is to be included in
5882 the resulting object file where 'debug-level' is one of the following:
5885 Include both debugger symbol records and traceback
5887 This is the default setting.
5889 Include both debugger symbol records and traceback in
5892 Excludes both debugger symbol records and traceback
5893 the object file. Same as /NODEBUG.
5895 Includes only debugger symbol records in the object
5896 file. Note that this doesn't include traceback information.
5901 @node Validity Checking
5902 @subsection Validity Checking
5903 @findex Validity Checking
5906 The Ada Reference Manual defines the concept of invalid values (see
5907 RM 13.9.1). The primary source of invalid values is uninitialized
5908 variables. A scalar variable that is left uninitialized may contain
5909 an invalid value; the concept of invalid does not apply to access or
5912 It is an error to read an invalid value, but the RM does not require
5913 run-time checks to detect such errors, except for some minimal
5914 checking to prevent erroneous execution (i.e. unpredictable
5915 behavior). This corresponds to the @option{-gnatVd} switch below,
5916 which is the default. For example, by default, if the expression of a
5917 case statement is invalid, it will raise Constraint_Error rather than
5918 causing a wild jump, and if an array index on the left-hand side of an
5919 assignment is invalid, it will raise Constraint_Error rather than
5920 overwriting an arbitrary memory location.
5922 The @option{-gnatVa} may be used to enable additional validity checks,
5923 which are not required by the RM. These checks are often very
5924 expensive (which is why the RM does not require them). These checks
5925 are useful in tracking down uninitialized variables, but they are
5926 not usually recommended for production builds.
5928 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
5929 control; you can enable whichever validity checks you desire. However,
5930 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5931 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5932 sufficient for non-debugging use.
5934 The @option{-gnatB} switch tells the compiler to assume that all
5935 values are valid (that is, within their declared subtype range)
5936 except in the context of a use of the Valid attribute. This means
5937 the compiler can generate more efficient code, since the range
5938 of values is better known at compile time. However, an uninitialized
5939 variable can cause wild jumps and memory corruption in this mode.
5941 The @option{-gnatV^@var{x}^^} switch allows control over the validity
5942 checking mode as described below.
5944 The @code{x} argument is a string of letters that
5945 indicate validity checks that are performed or not performed in addition
5946 to the default checks required by Ada as described above.
5949 The options allowed for this qualifier
5950 indicate validity checks that are performed or not performed in addition
5951 to the default checks required by Ada as described above.
5957 @emph{All validity checks.}
5958 @cindex @option{-gnatVa} (@command{gcc})
5959 All validity checks are turned on.
5961 That is, @option{-gnatVa} is
5962 equivalent to @option{gnatVcdfimorst}.
5966 @emph{Validity checks for copies.}
5967 @cindex @option{-gnatVc} (@command{gcc})
5968 The right hand side of assignments, and the initializing values of
5969 object declarations are validity checked.
5972 @emph{Default (RM) validity checks.}
5973 @cindex @option{-gnatVd} (@command{gcc})
5974 Some validity checks are done by default following normal Ada semantics
5976 A check is done in case statements that the expression is within the range
5977 of the subtype. If it is not, Constraint_Error is raised.
5978 For assignments to array components, a check is done that the expression used
5979 as index is within the range. If it is not, Constraint_Error is raised.
5980 Both these validity checks may be turned off using switch @option{-gnatVD}.
5981 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5982 switch @option{-gnatVd} will leave the checks turned on.
5983 Switch @option{-gnatVD} should be used only if you are sure that all such
5984 expressions have valid values. If you use this switch and invalid values
5985 are present, then the program is erroneous, and wild jumps or memory
5986 overwriting may occur.
5989 @emph{Validity checks for elementary components.}
5990 @cindex @option{-gnatVe} (@command{gcc})
5991 In the absence of this switch, assignments to record or array components are
5992 not validity checked, even if validity checks for assignments generally
5993 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5994 require valid data, but assignment of individual components does. So for
5995 example, there is a difference between copying the elements of an array with a
5996 slice assignment, compared to assigning element by element in a loop. This
5997 switch allows you to turn off validity checking for components, even when they
5998 are assigned component by component.
6001 @emph{Validity checks for floating-point values.}
6002 @cindex @option{-gnatVf} (@command{gcc})
6003 In the absence of this switch, validity checking occurs only for discrete
6004 values. If @option{-gnatVf} is specified, then validity checking also applies
6005 for floating-point values, and NaNs and infinities are considered invalid,
6006 as well as out of range values for constrained types. Note that this means
6007 that standard IEEE infinity mode is not allowed. The exact contexts
6008 in which floating-point values are checked depends on the setting of other
6009 options. For example,
6010 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6011 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6012 (the order does not matter) specifies that floating-point parameters of mode
6013 @code{in} should be validity checked.
6016 @emph{Validity checks for @code{in} mode parameters}
6017 @cindex @option{-gnatVi} (@command{gcc})
6018 Arguments for parameters of mode @code{in} are validity checked in function
6019 and procedure calls at the point of call.
6022 @emph{Validity checks for @code{in out} mode parameters.}
6023 @cindex @option{-gnatVm} (@command{gcc})
6024 Arguments for parameters of mode @code{in out} are validity checked in
6025 procedure calls at the point of call. The @code{'m'} here stands for
6026 modify, since this concerns parameters that can be modified by the call.
6027 Note that there is no specific option to test @code{out} parameters,
6028 but any reference within the subprogram will be tested in the usual
6029 manner, and if an invalid value is copied back, any reference to it
6030 will be subject to validity checking.
6033 @emph{No validity checks.}
6034 @cindex @option{-gnatVn} (@command{gcc})
6035 This switch turns off all validity checking, including the default checking
6036 for case statements and left hand side subscripts. Note that the use of
6037 the switch @option{-gnatp} suppresses all run-time checks, including
6038 validity checks, and thus implies @option{-gnatVn}. When this switch
6039 is used, it cancels any other @option{-gnatV} previously issued.
6042 @emph{Validity checks for operator and attribute operands.}
6043 @cindex @option{-gnatVo} (@command{gcc})
6044 Arguments for predefined operators and attributes are validity checked.
6045 This includes all operators in package @code{Standard},
6046 the shift operators defined as intrinsic in package @code{Interfaces}
6047 and operands for attributes such as @code{Pos}. Checks are also made
6048 on individual component values for composite comparisons, and on the
6049 expressions in type conversions and qualified expressions. Checks are
6050 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6053 @emph{Validity checks for parameters.}
6054 @cindex @option{-gnatVp} (@command{gcc})
6055 This controls the treatment of parameters within a subprogram (as opposed
6056 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6057 of parameters on a call. If either of these call options is used, then
6058 normally an assumption is made within a subprogram that the input arguments
6059 have been validity checking at the point of call, and do not need checking
6060 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6061 is not made, and parameters are not assumed to be valid, so their validity
6062 will be checked (or rechecked) within the subprogram.
6065 @emph{Validity checks for function returns.}
6066 @cindex @option{-gnatVr} (@command{gcc})
6067 The expression in @code{return} statements in functions is validity
6071 @emph{Validity checks for subscripts.}
6072 @cindex @option{-gnatVs} (@command{gcc})
6073 All subscripts expressions are checked for validity, whether they appear
6074 on the right side or left side (in default mode only left side subscripts
6075 are validity checked).
6078 @emph{Validity checks for tests.}
6079 @cindex @option{-gnatVt} (@command{gcc})
6080 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6081 statements are checked, as well as guard expressions in entry calls.
6086 The @option{-gnatV} switch may be followed by
6087 ^a string of letters^a list of options^
6088 to turn on a series of validity checking options.
6090 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6091 specifies that in addition to the default validity checking, copies and
6092 function return expressions are to be validity checked.
6093 In order to make it easier
6094 to specify the desired combination of effects,
6096 the upper case letters @code{CDFIMORST} may
6097 be used to turn off the corresponding lower case option.
6100 the prefix @code{NO} on an option turns off the corresponding validity
6103 @item @code{NOCOPIES}
6104 @item @code{NODEFAULT}
6105 @item @code{NOFLOATS}
6106 @item @code{NOIN_PARAMS}
6107 @item @code{NOMOD_PARAMS}
6108 @item @code{NOOPERANDS}
6109 @item @code{NORETURNS}
6110 @item @code{NOSUBSCRIPTS}
6111 @item @code{NOTESTS}
6115 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6116 turns on all validity checking options except for
6117 checking of @code{@b{in out}} procedure arguments.
6119 The specification of additional validity checking generates extra code (and
6120 in the case of @option{-gnatVa} the code expansion can be substantial).
6121 However, these additional checks can be very useful in detecting
6122 uninitialized variables, incorrect use of unchecked conversion, and other
6123 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6124 is useful in conjunction with the extra validity checking, since this
6125 ensures that wherever possible uninitialized variables have invalid values.
6127 See also the pragma @code{Validity_Checks} which allows modification of
6128 the validity checking mode at the program source level, and also allows for
6129 temporary disabling of validity checks.
6131 @node Style Checking
6132 @subsection Style Checking
6133 @findex Style checking
6136 The @option{-gnaty^x^(option,option,@dots{})^} switch
6137 @cindex @option{-gnaty} (@command{gcc})
6138 causes the compiler to
6139 enforce specified style rules. A limited set of style rules has been used
6140 in writing the GNAT sources themselves. This switch allows user programs
6141 to activate all or some of these checks. If the source program fails a
6142 specified style check, an appropriate message is given, preceded by
6143 the character sequence ``(style)''. This message does not prevent
6144 successful compilation (unless the @option{-gnatwe} switch is used).
6147 @code{(option,option,@dots{})} is a sequence of keywords
6150 The string @var{x} is a sequence of letters or digits
6152 indicating the particular style
6153 checks to be performed. The following checks are defined:
6158 @emph{Specify indentation level.}
6159 If a digit from 1-9 appears
6160 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6161 then proper indentation is checked, with the digit indicating the
6162 indentation level required. A value of zero turns off this style check.
6163 The general style of required indentation is as specified by
6164 the examples in the Ada Reference Manual. Full line comments must be
6165 aligned with the @code{--} starting on a column that is a multiple of
6166 the alignment level, or they may be aligned the same way as the following
6167 non-blank line (this is useful when full line comments appear in the middle
6171 @emph{Check attribute casing.}
6172 Attribute names, including the case of keywords such as @code{digits}
6173 used as attributes names, must be written in mixed case, that is, the
6174 initial letter and any letter following an underscore must be uppercase.
6175 All other letters must be lowercase.
6177 @item ^A^ARRAY_INDEXES^
6178 @emph{Use of array index numbers in array attributes.}
6179 When using the array attributes First, Last, Range,
6180 or Length, the index number must be omitted for one-dimensional arrays
6181 and is required for multi-dimensional arrays.
6184 @emph{Blanks not allowed at statement end.}
6185 Trailing blanks are not allowed at the end of statements. The purpose of this
6186 rule, together with h (no horizontal tabs), is to enforce a canonical format
6187 for the use of blanks to separate source tokens.
6189 @item ^B^BOOLEAN_OPERATORS^
6190 @emph{Check Boolean operators.}
6191 The use of AND/OR operators is not permitted except in the cases of modular
6192 operands, array operands, and simple stand-alone boolean variables or
6193 boolean constants. In all other cases AND THEN/OR ELSE are required.
6196 @emph{Check comments.}
6197 Comments must meet the following set of rules:
6202 The ``@code{--}'' that starts the column must either start in column one,
6203 or else at least one blank must precede this sequence.
6206 Comments that follow other tokens on a line must have at least one blank
6207 following the ``@code{--}'' at the start of the comment.
6210 Full line comments must have two blanks following the ``@code{--}'' that
6211 starts the comment, with the following exceptions.
6214 A line consisting only of the ``@code{--}'' characters, possibly preceded
6215 by blanks is permitted.
6218 A comment starting with ``@code{--x}'' where @code{x} is a special character
6220 This allows proper processing of the output generated by specialized tools
6221 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6223 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6224 special character is defined as being in one of the ASCII ranges
6225 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6226 Note that this usage is not permitted
6227 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6230 A line consisting entirely of minus signs, possibly preceded by blanks, is
6231 permitted. This allows the construction of box comments where lines of minus
6232 signs are used to form the top and bottom of the box.
6235 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6236 least one blank follows the initial ``@code{--}''. Together with the preceding
6237 rule, this allows the construction of box comments, as shown in the following
6240 ---------------------------
6241 -- This is a box comment --
6242 -- with two text lines. --
6243 ---------------------------
6247 @item ^d^DOS_LINE_ENDINGS^
6248 @emph{Check no DOS line terminators present.}
6249 All lines must be terminated by a single ASCII.LF
6250 character (in particular the DOS line terminator sequence CR/LF is not
6254 @emph{Check end/exit labels.}
6255 Optional labels on @code{end} statements ending subprograms and on
6256 @code{exit} statements exiting named loops, are required to be present.
6259 @emph{No form feeds or vertical tabs.}
6260 Neither form feeds nor vertical tab characters are permitted
6264 @emph{GNAT style mode}
6265 The set of style check switches is set to match that used by the GNAT sources.
6266 This may be useful when developing code that is eventually intended to be
6267 incorporated into GNAT. For further details, see GNAT sources.
6270 @emph{No horizontal tabs.}
6271 Horizontal tab characters are not permitted in the source text.
6272 Together with the b (no blanks at end of line) check, this
6273 enforces a canonical form for the use of blanks to separate
6277 @emph{Check if-then layout.}
6278 The keyword @code{then} must appear either on the same
6279 line as corresponding @code{if}, or on a line on its own, lined
6280 up under the @code{if} with at least one non-blank line in between
6281 containing all or part of the condition to be tested.
6284 @emph{check mode IN keywords}
6285 Mode @code{in} (the default mode) is not
6286 allowed to be given explicitly. @code{in out} is fine,
6287 but not @code{in} on its own.
6290 @emph{Check keyword casing.}
6291 All keywords must be in lower case (with the exception of keywords
6292 such as @code{digits} used as attribute names to which this check
6296 @emph{Check layout.}
6297 Layout of statement and declaration constructs must follow the
6298 recommendations in the Ada Reference Manual, as indicated by the
6299 form of the syntax rules. For example an @code{else} keyword must
6300 be lined up with the corresponding @code{if} keyword.
6302 There are two respects in which the style rule enforced by this check
6303 option are more liberal than those in the Ada Reference Manual. First
6304 in the case of record declarations, it is permissible to put the
6305 @code{record} keyword on the same line as the @code{type} keyword, and
6306 then the @code{end} in @code{end record} must line up under @code{type}.
6307 This is also permitted when the type declaration is split on two lines.
6308 For example, any of the following three layouts is acceptable:
6310 @smallexample @c ada
6333 Second, in the case of a block statement, a permitted alternative
6334 is to put the block label on the same line as the @code{declare} or
6335 @code{begin} keyword, and then line the @code{end} keyword up under
6336 the block label. For example both the following are permitted:
6338 @smallexample @c ada
6356 The same alternative format is allowed for loops. For example, both of
6357 the following are permitted:
6359 @smallexample @c ada
6361 Clear : while J < 10 loop
6372 @item ^Lnnn^MAX_NESTING=nnn^
6373 @emph{Set maximum nesting level}
6374 The maximum level of nesting of constructs (including subprograms, loops,
6375 blocks, packages, and conditionals) may not exceed the given value
6376 @option{nnn}. A value of zero disconnects this style check.
6378 @item ^m^LINE_LENGTH^
6379 @emph{Check maximum line length.}
6380 The length of source lines must not exceed 79 characters, including
6381 any trailing blanks. The value of 79 allows convenient display on an
6382 80 character wide device or window, allowing for possible special
6383 treatment of 80 character lines. Note that this count is of
6384 characters in the source text. This means that a tab character counts
6385 as one character in this count but a wide character sequence counts as
6386 a single character (however many bytes are needed in the encoding).
6388 @item ^Mnnn^MAX_LENGTH=nnn^
6389 @emph{Set maximum line length.}
6390 The length of lines must not exceed the
6391 given value @option{nnn}. The maximum value that can be specified is 32767.
6393 @item ^n^STANDARD_CASING^
6394 @emph{Check casing of entities in Standard.}
6395 Any identifier from Standard must be cased
6396 to match the presentation in the Ada Reference Manual (for example,
6397 @code{Integer} and @code{ASCII.NUL}).
6400 @emph{Turn off all style checks}
6401 All style check options are turned off.
6403 @item ^o^ORDERED_SUBPROGRAMS^
6404 @emph{Check order of subprogram bodies.}
6405 All subprogram bodies in a given scope
6406 (e.g.@: a package body) must be in alphabetical order. The ordering
6407 rule uses normal Ada rules for comparing strings, ignoring casing
6408 of letters, except that if there is a trailing numeric suffix, then
6409 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6412 @item ^O^OVERRIDING_INDICATORS^
6413 @emph{Check that overriding subprograms are explicitly marked as such.}
6414 The declaration of a primitive operation of a type extension that overrides
6415 an inherited operation must carry an overriding indicator.
6418 @emph{Check pragma casing.}
6419 Pragma names must be written in mixed case, that is, the
6420 initial letter and any letter following an underscore must be uppercase.
6421 All other letters must be lowercase.
6423 @item ^r^REFERENCES^
6424 @emph{Check references.}
6425 All identifier references must be cased in the same way as the
6426 corresponding declaration. No specific casing style is imposed on
6427 identifiers. The only requirement is for consistency of references
6430 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6431 @emph{Check no statements after THEN/ELSE.}
6432 No statements are allowed
6433 on the same line as a THEN or ELSE keyword following the
6434 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6435 and a special exception allows a pragma to appear after ELSE.
6438 @emph{Check separate specs.}
6439 Separate declarations (``specs'') are required for subprograms (a
6440 body is not allowed to serve as its own declaration). The only
6441 exception is that parameterless library level procedures are
6442 not required to have a separate declaration. This exception covers
6443 the most frequent form of main program procedures.
6446 @emph{Check token spacing.}
6447 The following token spacing rules are enforced:
6452 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6455 The token @code{=>} must be surrounded by spaces.
6458 The token @code{<>} must be preceded by a space or a left parenthesis.
6461 Binary operators other than @code{**} must be surrounded by spaces.
6462 There is no restriction on the layout of the @code{**} binary operator.
6465 Colon must be surrounded by spaces.
6468 Colon-equal (assignment, initialization) must be surrounded by spaces.
6471 Comma must be the first non-blank character on the line, or be
6472 immediately preceded by a non-blank character, and must be followed
6476 If the token preceding a left parenthesis ends with a letter or digit, then
6477 a space must separate the two tokens.
6480 if the token following a right parenthesis starts with a letter or digit, then
6481 a space must separate the two tokens.
6484 A right parenthesis must either be the first non-blank character on
6485 a line, or it must be preceded by a non-blank character.
6488 A semicolon must not be preceded by a space, and must not be followed by
6489 a non-blank character.
6492 A unary plus or minus may not be followed by a space.
6495 A vertical bar must be surrounded by spaces.
6498 @item ^u^UNNECESSARY_BLANK_LINES^
6499 @emph{Check unnecessary blank lines.}
6500 Unnecessary blank lines are not allowed. A blank line is considered
6501 unnecessary if it appears at the end of the file, or if more than
6502 one blank line occurs in sequence.
6504 @item ^x^XTRA_PARENS^
6505 @emph{Check extra parentheses.}
6506 Unnecessary extra level of parentheses (C-style) are not allowed
6507 around conditions in @code{if} statements, @code{while} statements and
6508 @code{exit} statements.
6510 @item ^y^ALL_BUILTIN^
6511 @emph{Set all standard style check options}
6512 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6513 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6514 @option{-gnatyS}, @option{-gnatyLnnn},
6515 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6519 @emph{Remove style check options}
6520 This causes any subsequent options in the string to act as canceling the
6521 corresponding style check option. To cancel maximum nesting level control,
6522 use @option{L} parameter witout any integer value after that, because any
6523 digit following @option{-} in the parameter string of the @option{-gnaty}
6524 option will be threated as canceling indentation check. The same is true
6525 for @option{M} parameter. @option{y} and @option{N} parameters are not
6526 allowed after @option{-}.
6529 This causes any subsequent options in the string to enable the corresponding
6530 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6536 @emph{Removing style check options}
6537 If the name of a style check is preceded by @option{NO} then the corresponding
6538 style check is turned off. For example @option{NOCOMMENTS} turns off style
6539 checking for comments.
6544 In the above rules, appearing in column one is always permitted, that is,
6545 counts as meeting either a requirement for a required preceding space,
6546 or as meeting a requirement for no preceding space.
6548 Appearing at the end of a line is also always permitted, that is, counts
6549 as meeting either a requirement for a following space, or as meeting
6550 a requirement for no following space.
6553 If any of these style rules is violated, a message is generated giving
6554 details on the violation. The initial characters of such messages are
6555 always ``@code{(style)}''. Note that these messages are treated as warning
6556 messages, so they normally do not prevent the generation of an object
6557 file. The @option{-gnatwe} switch can be used to treat warning messages,
6558 including style messages, as fatal errors.
6562 @option{-gnaty} on its own (that is not
6563 followed by any letters or digits), then the effect is equivalent
6564 to the use of @option{-gnatyy}, as described above, that is all
6565 built-in standard style check options are enabled.
6569 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6570 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6571 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6581 clears any previously set style checks.
6583 @node Run-Time Checks
6584 @subsection Run-Time Checks
6585 @cindex Division by zero
6586 @cindex Access before elaboration
6587 @cindex Checks, division by zero
6588 @cindex Checks, access before elaboration
6589 @cindex Checks, stack overflow checking
6592 By default, the following checks are suppressed: integer overflow
6593 checks, stack overflow checks, and checks for access before
6594 elaboration on subprogram calls. All other checks, including range
6595 checks and array bounds checks, are turned on by default. The
6596 following @command{gcc} switches refine this default behavior.
6601 @cindex @option{-gnatp} (@command{gcc})
6602 @cindex Suppressing checks
6603 @cindex Checks, suppressing
6605 This switch causes the unit to be compiled
6606 as though @code{pragma Suppress (All_checks)}
6607 had been present in the source. Validity checks are also eliminated (in
6608 other words @option{-gnatp} also implies @option{-gnatVn}.
6609 Use this switch to improve the performance
6610 of the code at the expense of safety in the presence of invalid data or
6613 Note that when checks are suppressed, the compiler is allowed, but not
6614 required, to omit the checking code. If the run-time cost of the
6615 checking code is zero or near-zero, the compiler will generate it even
6616 if checks are suppressed. In particular, if the compiler can prove
6617 that a certain check will necessarily fail, it will generate code to
6618 do an unconditional ``raise'', even if checks are suppressed. The
6619 compiler warns in this case. Another case in which checks may not be
6620 eliminated is when they are embedded in certain run time routines such
6621 as math library routines.
6623 Of course, run-time checks are omitted whenever the compiler can prove
6624 that they will not fail, whether or not checks are suppressed.
6626 Note that if you suppress a check that would have failed, program
6627 execution is erroneous, which means the behavior is totally
6628 unpredictable. The program might crash, or print wrong answers, or
6629 do anything else. It might even do exactly what you wanted it to do
6630 (and then it might start failing mysteriously next week or next
6631 year). The compiler will generate code based on the assumption that
6632 the condition being checked is true, which can result in disaster if
6633 that assumption is wrong.
6635 The @option{-gnatp} switch has no effect if a subsequent
6636 @option{-gnat-p} switch appears.
6639 @cindex @option{-gnat-p} (@command{gcc})
6640 @cindex Suppressing checks
6641 @cindex Checks, suppressing
6643 This switch cancels the effect of a previous @option{gnatp} switch.
6646 @cindex @option{-gnato} (@command{gcc})
6647 @cindex Overflow checks
6648 @cindex Check, overflow
6649 Enables overflow checking for integer operations.
6650 This causes GNAT to generate slower and larger executable
6651 programs by adding code to check for overflow (resulting in raising
6652 @code{Constraint_Error} as required by standard Ada
6653 semantics). These overflow checks correspond to situations in which
6654 the true value of the result of an operation may be outside the base
6655 range of the result type. The following example shows the distinction:
6657 @smallexample @c ada
6658 X1 : Integer := "Integer'Last";
6659 X2 : Integer range 1 .. 5 := "5";
6660 X3 : Integer := "Integer'Last";
6661 X4 : Integer range 1 .. 5 := "5";
6662 F : Float := "2.0E+20";
6671 Note that if explicit values are assigned at compile time, the
6672 compiler may be able to detect overflow at compile time, in which case
6673 no actual run-time checking code is required, and Constraint_Error
6674 will be raised unconditionally, with or without
6675 @option{-gnato}. That's why the assigned values in the above fragment
6676 are in quotes, the meaning is "assign a value not known to the
6677 compiler that happens to be equal to ...". The remaining discussion
6678 assumes that the compiler cannot detect the values at compile time.
6680 Here the first addition results in a value that is outside the base range
6681 of Integer, and hence requires an overflow check for detection of the
6682 constraint error. Thus the first assignment to @code{X1} raises a
6683 @code{Constraint_Error} exception only if @option{-gnato} is set.
6685 The second increment operation results in a violation of the explicit
6686 range constraint; such range checks are performed by default, and are
6687 unaffected by @option{-gnato}.
6689 The two conversions of @code{F} both result in values that are outside
6690 the base range of type @code{Integer} and thus will raise
6691 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6692 The fact that the result of the second conversion is assigned to
6693 variable @code{X4} with a restricted range is irrelevant, since the problem
6694 is in the conversion, not the assignment.
6696 Basically the rule is that in the default mode (@option{-gnato} not
6697 used), the generated code assures that all integer variables stay
6698 within their declared ranges, or within the base range if there is
6699 no declared range. This prevents any serious problems like indexes
6700 out of range for array operations.
6702 What is not checked in default mode is an overflow that results in
6703 an in-range, but incorrect value. In the above example, the assignments
6704 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6705 range of the target variable, but the result is wrong in the sense that
6706 it is too large to be represented correctly. Typically the assignment
6707 to @code{X1} will result in wrap around to the largest negative number.
6708 The conversions of @code{F} will result in some @code{Integer} value
6709 and if that integer value is out of the @code{X4} range then the
6710 subsequent assignment would generate an exception.
6712 @findex Machine_Overflows
6713 Note that the @option{-gnato} switch does not affect the code generated
6714 for any floating-point operations; it applies only to integer
6716 For floating-point, GNAT has the @code{Machine_Overflows}
6717 attribute set to @code{False} and the normal mode of operation is to
6718 generate IEEE NaN and infinite values on overflow or invalid operations
6719 (such as dividing 0.0 by 0.0).
6721 The reason that we distinguish overflow checking from other kinds of
6722 range constraint checking is that a failure of an overflow check, unlike
6723 for example the failure of a range check, can result in an incorrect
6724 value, but cannot cause random memory destruction (like an out of range
6725 subscript), or a wild jump (from an out of range case value). Overflow
6726 checking is also quite expensive in time and space, since in general it
6727 requires the use of double length arithmetic.
6729 Note again that @option{-gnato} is off by default, so overflow checking is
6730 not performed in default mode. This means that out of the box, with the
6731 default settings, GNAT does not do all the checks expected from the
6732 language description in the Ada Reference Manual. If you want all constraint
6733 checks to be performed, as described in this Manual, then you must
6734 explicitly use the -gnato switch either on the @command{gnatmake} or
6735 @command{gcc} command.
6738 @cindex @option{-gnatE} (@command{gcc})
6739 @cindex Elaboration checks
6740 @cindex Check, elaboration
6741 Enables dynamic checks for access-before-elaboration
6742 on subprogram calls and generic instantiations.
6743 Note that @option{-gnatE} is not necessary for safety, because in the
6744 default mode, GNAT ensures statically that the checks would not fail.
6745 For full details of the effect and use of this switch,
6746 @xref{Compiling Using gcc}.
6749 @cindex @option{-fstack-check} (@command{gcc})
6750 @cindex Stack Overflow Checking
6751 @cindex Checks, stack overflow checking
6752 Activates stack overflow checking. For full details of the effect and use of
6753 this switch see @ref{Stack Overflow Checking}.
6758 The setting of these switches only controls the default setting of the
6759 checks. You may modify them using either @code{Suppress} (to remove
6760 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6763 @node Using gcc for Syntax Checking
6764 @subsection Using @command{gcc} for Syntax Checking
6767 @cindex @option{-gnats} (@command{gcc})
6771 The @code{s} stands for ``syntax''.
6774 Run GNAT in syntax checking only mode. For
6775 example, the command
6778 $ gcc -c -gnats x.adb
6782 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6783 series of files in a single command
6785 , and can use wild cards to specify such a group of files.
6786 Note that you must specify the @option{-c} (compile
6787 only) flag in addition to the @option{-gnats} flag.
6790 You may use other switches in conjunction with @option{-gnats}. In
6791 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6792 format of any generated error messages.
6794 When the source file is empty or contains only empty lines and/or comments,
6795 the output is a warning:
6798 $ gcc -c -gnats -x ada toto.txt
6799 toto.txt:1:01: warning: empty file, contains no compilation units
6803 Otherwise, the output is simply the error messages, if any. No object file or
6804 ALI file is generated by a syntax-only compilation. Also, no units other
6805 than the one specified are accessed. For example, if a unit @code{X}
6806 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6807 check only mode does not access the source file containing unit
6810 @cindex Multiple units, syntax checking
6811 Normally, GNAT allows only a single unit in a source file. However, this
6812 restriction does not apply in syntax-check-only mode, and it is possible
6813 to check a file containing multiple compilation units concatenated
6814 together. This is primarily used by the @code{gnatchop} utility
6815 (@pxref{Renaming Files Using gnatchop}).
6818 @node Using gcc for Semantic Checking
6819 @subsection Using @command{gcc} for Semantic Checking
6822 @cindex @option{-gnatc} (@command{gcc})
6826 The @code{c} stands for ``check''.
6828 Causes the compiler to operate in semantic check mode,
6829 with full checking for all illegalities specified in the
6830 Ada Reference Manual, but without generation of any object code
6831 (no object file is generated).
6833 Because dependent files must be accessed, you must follow the GNAT
6834 semantic restrictions on file structuring to operate in this mode:
6838 The needed source files must be accessible
6839 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6842 Each file must contain only one compilation unit.
6845 The file name and unit name must match (@pxref{File Naming Rules}).
6848 The output consists of error messages as appropriate. No object file is
6849 generated. An @file{ALI} file is generated for use in the context of
6850 cross-reference tools, but this file is marked as not being suitable
6851 for binding (since no object file is generated).
6852 The checking corresponds exactly to the notion of
6853 legality in the Ada Reference Manual.
6855 Any unit can be compiled in semantics-checking-only mode, including
6856 units that would not normally be compiled (subunits,
6857 and specifications where a separate body is present).
6860 @node Compiling Different Versions of Ada
6861 @subsection Compiling Different Versions of Ada
6864 The switches described in this section allow you to explicitly specify
6865 the version of the Ada language that your programs are written in.
6866 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6867 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6868 indicate Ada 83 compatibility mode.
6871 @cindex Compatibility with Ada 83
6873 @item -gnat83 (Ada 83 Compatibility Mode)
6874 @cindex @option{-gnat83} (@command{gcc})
6875 @cindex ACVC, Ada 83 tests
6879 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6880 specifies that the program is to be compiled in Ada 83 mode. With
6881 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6882 semantics where this can be done easily.
6883 It is not possible to guarantee this switch does a perfect
6884 job; some subtle tests, such as are
6885 found in earlier ACVC tests (and that have been removed from the ACATS suite
6886 for Ada 95), might not compile correctly.
6887 Nevertheless, this switch may be useful in some circumstances, for example
6888 where, due to contractual reasons, existing code needs to be maintained
6889 using only Ada 83 features.
6891 With few exceptions (most notably the need to use @code{<>} on
6892 @cindex Generic formal parameters
6893 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6894 reserved words, and the use of packages
6895 with optional bodies), it is not necessary to specify the
6896 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6897 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6898 a correct Ada 83 program is usually also a correct program
6899 in these later versions of the language standard.
6900 For further information, please refer to @ref{Compatibility and Porting Guide}.
6902 @item -gnat95 (Ada 95 mode)
6903 @cindex @option{-gnat95} (@command{gcc})
6907 This switch directs the compiler to implement the Ada 95 version of the
6909 Since Ada 95 is almost completely upwards
6910 compatible with Ada 83, Ada 83 programs may generally be compiled using
6911 this switch (see the description of the @option{-gnat83} switch for further
6912 information about Ada 83 mode).
6913 If an Ada 2005 program is compiled in Ada 95 mode,
6914 uses of the new Ada 2005 features will cause error
6915 messages or warnings.
6917 This switch also can be used to cancel the effect of a previous
6918 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
6919 switch earlier in the command line.
6921 @item -gnat05 or -gnat2005 (Ada 2005 mode)
6922 @cindex @option{-gnat05} (@command{gcc})
6923 @cindex @option{-gnat2005} (@command{gcc})
6924 @cindex Ada 2005 mode
6927 This switch directs the compiler to implement the Ada 2005 version of the
6928 language, as documented in the official Ada standards document.
6929 Since Ada 2005 is almost completely upwards
6930 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6931 may generally be compiled using this switch (see the description of the
6932 @option{-gnat83} and @option{-gnat95} switches for further
6935 Note that even though Ada 2005 is the current official version of the
6936 language, GNAT still compiles in Ada 95 mode by default, so if you are
6937 using Ada 2005 features in your program, you must use this switch (or
6938 the equivalent Ada_05 or Ada_2005 configuration pragmas).
6940 @item -gnat12 or -gnat2012 (Ada 2012 mode)
6941 @cindex @option{-gnat12} (@command{gcc})
6942 @cindex @option{-gnat2012} (@command{gcc})
6943 @cindex Ada 2012 mode
6946 This switch directs the compiler to implement the Ada 2012 version of the
6948 Since Ada 2012 is almost completely upwards
6949 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
6950 Ada 83 and Ada 95 programs
6951 may generally be compiled using this switch (see the description of the
6952 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
6953 for further information).
6955 For information about the approved ``Ada Issues'' that have been incorporated
6956 into Ada 2012, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6957 Included with GNAT releases is a file @file{features-ada12} that describes
6958 the set of implemented Ada 2012 features.
6960 @item -gnatX (Enable GNAT Extensions)
6961 @cindex @option{-gnatX} (@command{gcc})
6962 @cindex Ada language extensions
6963 @cindex GNAT extensions
6966 This switch directs the compiler to implement the latest version of the
6967 language (currently Ada 2012) and also to enable certain GNAT implementation
6968 extensions that are not part of any Ada standard. For a full list of these
6969 extensions, see the GNAT reference manual.
6973 @node Character Set Control
6974 @subsection Character Set Control
6976 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6977 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6980 Normally GNAT recognizes the Latin-1 character set in source program
6981 identifiers, as described in the Ada Reference Manual.
6983 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6984 single character ^^or word^ indicating the character set, as follows:
6988 ISO 8859-1 (Latin-1) identifiers
6991 ISO 8859-2 (Latin-2) letters allowed in identifiers
6994 ISO 8859-3 (Latin-3) letters allowed in identifiers
6997 ISO 8859-4 (Latin-4) letters allowed in identifiers
7000 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7003 ISO 8859-15 (Latin-9) letters allowed in identifiers
7006 IBM PC letters (code page 437) allowed in identifiers
7009 IBM PC letters (code page 850) allowed in identifiers
7011 @item ^f^FULL_UPPER^
7012 Full upper-half codes allowed in identifiers
7015 No upper-half codes allowed in identifiers
7018 Wide-character codes (that is, codes greater than 255)
7019 allowed in identifiers
7022 @xref{Foreign Language Representation}, for full details on the
7023 implementation of these character sets.
7025 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7026 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7027 Specify the method of encoding for wide characters.
7028 @var{e} is one of the following:
7033 Hex encoding (brackets coding also recognized)
7036 Upper half encoding (brackets encoding also recognized)
7039 Shift/JIS encoding (brackets encoding also recognized)
7042 EUC encoding (brackets encoding also recognized)
7045 UTF-8 encoding (brackets encoding also recognized)
7048 Brackets encoding only (default value)
7050 For full details on these encoding
7051 methods see @ref{Wide Character Encodings}.
7052 Note that brackets coding is always accepted, even if one of the other
7053 options is specified, so for example @option{-gnatW8} specifies that both
7054 brackets and UTF-8 encodings will be recognized. The units that are
7055 with'ed directly or indirectly will be scanned using the specified
7056 representation scheme, and so if one of the non-brackets scheme is
7057 used, it must be used consistently throughout the program. However,
7058 since brackets encoding is always recognized, it may be conveniently
7059 used in standard libraries, allowing these libraries to be used with
7060 any of the available coding schemes.
7063 If no @option{-gnatW?} parameter is present, then the default
7064 representation is normally Brackets encoding only. However, if the
7065 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7066 byte order mark or BOM for UTF-8), then these three characters are
7067 skipped and the default representation for the file is set to UTF-8.
7069 Note that the wide character representation that is specified (explicitly
7070 or by default) for the main program also acts as the default encoding used
7071 for Wide_Text_IO files if not specifically overridden by a WCEM form
7075 @node File Naming Control
7076 @subsection File Naming Control
7079 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7080 @cindex @option{-gnatk} (@command{gcc})
7081 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7082 1-999, indicates the maximum allowable length of a file name (not
7083 including the @file{.ads} or @file{.adb} extension). The default is not
7084 to enable file name krunching.
7086 For the source file naming rules, @xref{File Naming Rules}.
7089 @node Subprogram Inlining Control
7090 @subsection Subprogram Inlining Control
7095 @cindex @option{-gnatn} (@command{gcc})
7097 The @code{n} here is intended to suggest the first syllable of the
7100 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7101 inlining to actually occur, optimization must be enabled. To enable
7102 inlining of subprograms specified by pragma @code{Inline},
7103 you must also specify this switch.
7104 In the absence of this switch, GNAT does not attempt
7105 inlining and does not need to access the bodies of
7106 subprograms for which @code{pragma Inline} is specified if they are not
7107 in the current unit.
7109 If you specify this switch the compiler will access these bodies,
7110 creating an extra source dependency for the resulting object file, and
7111 where possible, the call will be inlined.
7112 For further details on when inlining is possible
7113 see @ref{Inlining of Subprograms}.
7116 @cindex @option{-gnatN} (@command{gcc})
7117 This switch activates front-end inlining which also
7118 generates additional dependencies.
7120 When using a gcc-based back end (in practice this means using any version
7121 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7122 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7123 Historically front end inlining was more extensive than the gcc back end
7124 inlining, but that is no longer the case.
7127 @node Auxiliary Output Control
7128 @subsection Auxiliary Output Control
7132 @cindex @option{-gnatt} (@command{gcc})
7133 @cindex Writing internal trees
7134 @cindex Internal trees, writing to file
7135 Causes GNAT to write the internal tree for a unit to a file (with the
7136 extension @file{.adt}.
7137 This not normally required, but is used by separate analysis tools.
7139 these tools do the necessary compilations automatically, so you should
7140 not have to specify this switch in normal operation.
7141 Note that the combination of switches @option{-gnatct}
7142 generates a tree in the form required by ASIS applications.
7145 @cindex @option{-gnatu} (@command{gcc})
7146 Print a list of units required by this compilation on @file{stdout}.
7147 The listing includes all units on which the unit being compiled depends
7148 either directly or indirectly.
7151 @item -pass-exit-codes
7152 @cindex @option{-pass-exit-codes} (@command{gcc})
7153 If this switch is not used, the exit code returned by @command{gcc} when
7154 compiling multiple files indicates whether all source files have
7155 been successfully used to generate object files or not.
7157 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7158 exit status and allows an integrated development environment to better
7159 react to a compilation failure. Those exit status are:
7163 There was an error in at least one source file.
7165 At least one source file did not generate an object file.
7167 The compiler died unexpectedly (internal error for example).
7169 An object file has been generated for every source file.
7174 @node Debugging Control
7175 @subsection Debugging Control
7179 @cindex Debugging options
7182 @cindex @option{-gnatd} (@command{gcc})
7183 Activate internal debugging switches. @var{x} is a letter or digit, or
7184 string of letters or digits, which specifies the type of debugging
7185 outputs desired. Normally these are used only for internal development
7186 or system debugging purposes. You can find full documentation for these
7187 switches in the body of the @code{Debug} unit in the compiler source
7188 file @file{debug.adb}.
7192 @cindex @option{-gnatG} (@command{gcc})
7193 This switch causes the compiler to generate auxiliary output containing
7194 a pseudo-source listing of the generated expanded code. Like most Ada
7195 compilers, GNAT works by first transforming the high level Ada code into
7196 lower level constructs. For example, tasking operations are transformed
7197 into calls to the tasking run-time routines. A unique capability of GNAT
7198 is to list this expanded code in a form very close to normal Ada source.
7199 This is very useful in understanding the implications of various Ada
7200 usage on the efficiency of the generated code. There are many cases in
7201 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7202 generate a lot of run-time code. By using @option{-gnatG} you can identify
7203 these cases, and consider whether it may be desirable to modify the coding
7204 approach to improve efficiency.
7206 The optional parameter @code{nn} if present after -gnatG specifies an
7207 alternative maximum line length that overrides the normal default of 72.
7208 This value is in the range 40-999999, values less than 40 being silently
7209 reset to 40. The equal sign is optional.
7211 The format of the output is very similar to standard Ada source, and is
7212 easily understood by an Ada programmer. The following special syntactic
7213 additions correspond to low level features used in the generated code that
7214 do not have any exact analogies in pure Ada source form. The following
7215 is a partial list of these special constructions. See the spec
7216 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7218 If the switch @option{-gnatL} is used in conjunction with
7219 @cindex @option{-gnatL} (@command{gcc})
7220 @option{-gnatG}, then the original source lines are interspersed
7221 in the expanded source (as comment lines with the original line number).
7224 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7225 Shows the storage pool being used for an allocator.
7227 @item at end @var{procedure-name};
7228 Shows the finalization (cleanup) procedure for a scope.
7230 @item (if @var{expr} then @var{expr} else @var{expr})
7231 Conditional expression equivalent to the @code{x?y:z} construction in C.
7233 @item @var{target}^^^(@var{source})
7234 A conversion with floating-point truncation instead of rounding.
7236 @item @var{target}?(@var{source})
7237 A conversion that bypasses normal Ada semantic checking. In particular
7238 enumeration types and fixed-point types are treated simply as integers.
7240 @item @var{target}?^^^(@var{source})
7241 Combines the above two cases.
7243 @item @var{x} #/ @var{y}
7244 @itemx @var{x} #mod @var{y}
7245 @itemx @var{x} #* @var{y}
7246 @itemx @var{x} #rem @var{y}
7247 A division or multiplication of fixed-point values which are treated as
7248 integers without any kind of scaling.
7250 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7251 Shows the storage pool associated with a @code{free} statement.
7253 @item [subtype or type declaration]
7254 Used to list an equivalent declaration for an internally generated
7255 type that is referenced elsewhere in the listing.
7257 @c @item freeze @var{type-name} @ovar{actions}
7258 @c Expanding @ovar macro inline (explanation in macro def comments)
7259 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7260 Shows the point at which @var{type-name} is frozen, with possible
7261 associated actions to be performed at the freeze point.
7263 @item reference @var{itype}
7264 Reference (and hence definition) to internal type @var{itype}.
7266 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7267 Intrinsic function call.
7269 @item @var{label-name} : label
7270 Declaration of label @var{labelname}.
7272 @item #$ @var{subprogram-name}
7273 An implicit call to a run-time support routine
7274 (to meet the requirement of H.3.1(9) in a
7277 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7278 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7279 @var{expr}, but handled more efficiently).
7281 @item [constraint_error]
7282 Raise the @code{Constraint_Error} exception.
7284 @item @var{expression}'reference
7285 A pointer to the result of evaluating @var{expression}.
7287 @item @var{target-type}!(@var{source-expression})
7288 An unchecked conversion of @var{source-expression} to @var{target-type}.
7290 @item [@var{numerator}/@var{denominator}]
7291 Used to represent internal real literals (that) have no exact
7292 representation in base 2-16 (for example, the result of compile time
7293 evaluation of the expression 1.0/27.0).
7297 @cindex @option{-gnatD} (@command{gcc})
7298 When used in conjunction with @option{-gnatG}, this switch causes
7299 the expanded source, as described above for
7300 @option{-gnatG} to be written to files with names
7301 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7302 instead of to the standard output file. For
7303 example, if the source file name is @file{hello.adb}, then a file
7304 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written. The debugging
7305 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7306 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7307 you to do source level debugging using the generated code which is
7308 sometimes useful for complex code, for example to find out exactly
7309 which part of a complex construction raised an exception. This switch
7310 also suppress generation of cross-reference information (see
7311 @option{-gnatx}) since otherwise the cross-reference information
7312 would refer to the @file{^.dg^.DG^} file, which would cause
7313 confusion since this is not the original source file.
7315 Note that @option{-gnatD} actually implies @option{-gnatG}
7316 automatically, so it is not necessary to give both options.
7317 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7319 If the switch @option{-gnatL} is used in conjunction with
7320 @cindex @option{-gnatL} (@command{gcc})
7321 @option{-gnatDG}, then the original source lines are interspersed
7322 in the expanded source (as comment lines with the original line number).
7324 The optional parameter @code{nn} if present after -gnatD specifies an
7325 alternative maximum line length that overrides the normal default of 72.
7326 This value is in the range 40-999999, values less than 40 being silently
7327 reset to 40. The equal sign is optional.
7330 @cindex @option{-gnatr} (@command{gcc})
7331 @cindex pragma Restrictions
7332 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7333 so that violation of restrictions causes warnings rather than illegalities.
7334 This is useful during the development process when new restrictions are added
7335 or investigated. The switch also causes pragma Profile to be treated as
7336 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7337 restriction warnings rather than restrictions.
7340 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7341 @cindex @option{-gnatR} (@command{gcc})
7342 This switch controls output from the compiler of a listing showing
7343 representation information for declared types and objects. For
7344 @option{-gnatR0}, no information is output (equivalent to omitting
7345 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7346 so @option{-gnatR} with no parameter has the same effect), size and alignment
7347 information is listed for declared array and record types. For
7348 @option{-gnatR2}, size and alignment information is listed for all
7349 declared types and objects. Finally @option{-gnatR3} includes symbolic
7350 expressions for values that are computed at run time for
7351 variant records. These symbolic expressions have a mostly obvious
7352 format with #n being used to represent the value of the n'th
7353 discriminant. See source files @file{repinfo.ads/adb} in the
7354 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7355 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7356 the output is to a file with the name @file{^file.rep^file_REP^} where
7357 file is the name of the corresponding source file.
7360 @item /REPRESENTATION_INFO
7361 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7362 This qualifier controls output from the compiler of a listing showing
7363 representation information for declared types and objects. For
7364 @option{/REPRESENTATION_INFO=NONE}, no information is output
7365 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7366 @option{/REPRESENTATION_INFO} without option is equivalent to
7367 @option{/REPRESENTATION_INFO=ARRAYS}.
7368 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7369 information is listed for declared array and record types. For
7370 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7371 is listed for all expression information for values that are computed
7372 at run time for variant records. These symbolic expressions have a mostly
7373 obvious format with #n being used to represent the value of the n'th
7374 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7375 @code{GNAT} sources for full details on the format of
7376 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7377 If _FILE is added at the end of an option
7378 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7379 then the output is to a file with the name @file{file_REP} where
7380 file is the name of the corresponding source file.
7382 Note that it is possible for record components to have zero size. In
7383 this case, the component clause uses an obvious extension of permitted
7384 Ada syntax, for example @code{at 0 range 0 .. -1}.
7386 Representation information requires that code be generated (since it is the
7387 code generator that lays out complex data structures). If an attempt is made
7388 to output representation information when no code is generated, for example
7389 when a subunit is compiled on its own, then no information can be generated
7390 and the compiler outputs a message to this effect.
7393 @cindex @option{-gnatS} (@command{gcc})
7394 The use of the switch @option{-gnatS} for an
7395 Ada compilation will cause the compiler to output a
7396 representation of package Standard in a form very
7397 close to standard Ada. It is not quite possible to
7398 do this entirely in standard Ada (since new
7399 numeric base types cannot be created in standard
7400 Ada), but the output is easily
7401 readable to any Ada programmer, and is useful to
7402 determine the characteristics of target dependent
7403 types in package Standard.
7406 @cindex @option{-gnatx} (@command{gcc})
7407 Normally the compiler generates full cross-referencing information in
7408 the @file{ALI} file. This information is used by a number of tools,
7409 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7410 suppresses this information. This saves some space and may slightly
7411 speed up compilation, but means that these tools cannot be used.
7414 @node Exception Handling Control
7415 @subsection Exception Handling Control
7418 GNAT uses two methods for handling exceptions at run-time. The
7419 @code{setjmp/longjmp} method saves the context when entering
7420 a frame with an exception handler. Then when an exception is
7421 raised, the context can be restored immediately, without the
7422 need for tracing stack frames. This method provides very fast
7423 exception propagation, but introduces significant overhead for
7424 the use of exception handlers, even if no exception is raised.
7426 The other approach is called ``zero cost'' exception handling.
7427 With this method, the compiler builds static tables to describe
7428 the exception ranges. No dynamic code is required when entering
7429 a frame containing an exception handler. When an exception is
7430 raised, the tables are used to control a back trace of the
7431 subprogram invocation stack to locate the required exception
7432 handler. This method has considerably poorer performance for
7433 the propagation of exceptions, but there is no overhead for
7434 exception handlers if no exception is raised. Note that in this
7435 mode and in the context of mixed Ada and C/C++ programming,
7436 to propagate an exception through a C/C++ code, the C/C++ code
7437 must be compiled with the @option{-funwind-tables} GCC's
7440 The following switches may be used to control which of the
7441 two exception handling methods is used.
7447 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7448 This switch causes the setjmp/longjmp run-time (when available) to be used
7449 for exception handling. If the default
7450 mechanism for the target is zero cost exceptions, then
7451 this switch can be used to modify this default, and must be
7452 used for all units in the partition.
7453 This option is rarely used. One case in which it may be
7454 advantageous is if you have an application where exception
7455 raising is common and the overall performance of the
7456 application is improved by favoring exception propagation.
7459 @cindex @option{--RTS=zcx} (@command{gnatmake})
7460 @cindex Zero Cost Exceptions
7461 This switch causes the zero cost approach to be used
7462 for exception handling. If this is the default mechanism for the
7463 target (see below), then this switch is unneeded. If the default
7464 mechanism for the target is setjmp/longjmp exceptions, then
7465 this switch can be used to modify this default, and must be
7466 used for all units in the partition.
7467 This option can only be used if the zero cost approach
7468 is available for the target in use, otherwise it will generate an error.
7472 The same option @option{--RTS} must be used both for @command{gcc}
7473 and @command{gnatbind}. Passing this option to @command{gnatmake}
7474 (@pxref{Switches for gnatmake}) will ensure the required consistency
7475 through the compilation and binding steps.
7477 @node Units to Sources Mapping Files
7478 @subsection Units to Sources Mapping Files
7482 @item -gnatem=@var{path}
7483 @cindex @option{-gnatem} (@command{gcc})
7484 A mapping file is a way to communicate to the compiler two mappings:
7485 from unit names to file names (without any directory information) and from
7486 file names to path names (with full directory information). These mappings
7487 are used by the compiler to short-circuit the path search.
7489 The use of mapping files is not required for correct operation of the
7490 compiler, but mapping files can improve efficiency, particularly when
7491 sources are read over a slow network connection. In normal operation,
7492 you need not be concerned with the format or use of mapping files,
7493 and the @option{-gnatem} switch is not a switch that you would use
7494 explicitly. It is intended primarily for use by automatic tools such as
7495 @command{gnatmake} running under the project file facility. The
7496 description here of the format of mapping files is provided
7497 for completeness and for possible use by other tools.
7499 A mapping file is a sequence of sets of three lines. In each set, the
7500 first line is the unit name, in lower case, with @code{%s} appended
7501 for specs and @code{%b} appended for bodies; the second line is the
7502 file name; and the third line is the path name.
7508 /gnat/project1/sources/main.2.ada
7511 When the switch @option{-gnatem} is specified, the compiler will
7512 create in memory the two mappings from the specified file. If there is
7513 any problem (nonexistent file, truncated file or duplicate entries),
7514 no mapping will be created.
7516 Several @option{-gnatem} switches may be specified; however, only the
7517 last one on the command line will be taken into account.
7519 When using a project file, @command{gnatmake} creates a temporary
7520 mapping file and communicates it to the compiler using this switch.
7524 @node Integrated Preprocessing
7525 @subsection Integrated Preprocessing
7528 GNAT sources may be preprocessed immediately before compilation.
7529 In this case, the actual
7530 text of the source is not the text of the source file, but is derived from it
7531 through a process called preprocessing. Integrated preprocessing is specified
7532 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7533 indicates, through a text file, the preprocessing data to be used.
7534 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7537 Note that when integrated preprocessing is used, the output from the
7538 preprocessor is not written to any external file. Instead it is passed
7539 internally to the compiler. If you need to preserve the result of
7540 preprocessing in a file, then you should use @command{gnatprep}
7541 to perform the desired preprocessing in stand-alone mode.
7544 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7545 used when Integrated Preprocessing is used. The reason is that preprocessing
7546 with another Preprocessing Data file without changing the sources will
7547 not trigger recompilation without this switch.
7550 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7551 always trigger recompilation for sources that are preprocessed,
7552 because @command{gnatmake} cannot compute the checksum of the source after
7556 The actual preprocessing function is described in details in section
7557 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7558 preprocessing is triggered and parameterized.
7562 @item -gnatep=@var{file}
7563 @cindex @option{-gnatep} (@command{gcc})
7564 This switch indicates to the compiler the file name (without directory
7565 information) of the preprocessor data file to use. The preprocessor data file
7566 should be found in the source directories.
7569 A preprocessing data file is a text file with significant lines indicating
7570 how should be preprocessed either a specific source or all sources not
7571 mentioned in other lines. A significant line is a nonempty, non-comment line.
7572 Comments are similar to Ada comments.
7575 Each significant line starts with either a literal string or the character '*'.
7576 A literal string is the file name (without directory information) of the source
7577 to preprocess. A character '*' indicates the preprocessing for all the sources
7578 that are not specified explicitly on other lines (order of the lines is not
7579 significant). It is an error to have two lines with the same file name or two
7580 lines starting with the character '*'.
7583 After the file name or the character '*', another optional literal string
7584 indicating the file name of the definition file to be used for preprocessing
7585 (@pxref{Form of Definitions File}). The definition files are found by the
7586 compiler in one of the source directories. In some cases, when compiling
7587 a source in a directory other than the current directory, if the definition
7588 file is in the current directory, it may be necessary to add the current
7589 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7590 the compiler would not find the definition file.
7593 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7594 be found. Those ^switches^switches^ are:
7599 Causes both preprocessor lines and the lines deleted by
7600 preprocessing to be replaced by blank lines, preserving the line number.
7601 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7602 it cancels the effect of @option{-c}.
7605 Causes both preprocessor lines and the lines deleted
7606 by preprocessing to be retained as comments marked
7607 with the special string ``@code{--! }''.
7609 @item -Dsymbol=value
7610 Define or redefine a symbol, associated with value. A symbol is an Ada
7611 identifier, or an Ada reserved word, with the exception of @code{if},
7612 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7613 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7614 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7615 same name defined in a definition file.
7618 Causes a sorted list of symbol names and values to be
7619 listed on the standard output file.
7622 Causes undefined symbols to be treated as having the value @code{FALSE}
7624 of a preprocessor test. In the absence of this option, an undefined symbol in
7625 a @code{#if} or @code{#elsif} test will be treated as an error.
7630 Examples of valid lines in a preprocessor data file:
7633 "toto.adb" "prep.def" -u
7634 -- preprocess "toto.adb", using definition file "prep.def",
7635 -- undefined symbol are False.
7638 -- preprocess all other sources without a definition file;
7639 -- suppressed lined are commented; symbol VERSION has the value V101.
7641 "titi.adb" "prep2.def" -s
7642 -- preprocess "titi.adb", using definition file "prep2.def";
7643 -- list all symbols with their values.
7646 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7647 @cindex @option{-gnateD} (@command{gcc})
7648 Define or redefine a preprocessing symbol, associated with value. If no value
7649 is given on the command line, then the value of the symbol is @code{True}.
7650 A symbol is an identifier, following normal Ada (case-insensitive)
7651 rules for its syntax, and value is any sequence (including an empty sequence)
7652 of characters from the set (letters, digits, period, underline).
7653 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7654 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7657 A symbol declared with this ^switch^switch^ on the command line replaces a
7658 symbol with the same name either in a definition file or specified with a
7659 ^switch^switch^ -D in the preprocessor data file.
7662 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7665 When integrated preprocessing is performed and the preprocessor modifies
7666 the source text, write the result of this preprocessing into a file
7667 <source>^.prep^_prep^.
7671 @node Code Generation Control
7672 @subsection Code Generation Control
7676 The GCC technology provides a wide range of target dependent
7677 @option{-m} switches for controlling
7678 details of code generation with respect to different versions of
7679 architectures. This includes variations in instruction sets (e.g.@:
7680 different members of the power pc family), and different requirements
7681 for optimal arrangement of instructions (e.g.@: different members of
7682 the x86 family). The list of available @option{-m} switches may be
7683 found in the GCC documentation.
7685 Use of these @option{-m} switches may in some cases result in improved
7688 The GNAT Pro technology is tested and qualified without any
7689 @option{-m} switches,
7690 so generally the most reliable approach is to avoid the use of these
7691 switches. However, we generally expect most of these switches to work
7692 successfully with GNAT Pro, and many customers have reported successful
7693 use of these options.
7695 Our general advice is to avoid the use of @option{-m} switches unless
7696 special needs lead to requirements in this area. In particular,
7697 there is no point in using @option{-m} switches to improve performance
7698 unless you actually see a performance improvement.
7702 @subsection Return Codes
7703 @cindex Return Codes
7704 @cindex @option{/RETURN_CODES=VMS}
7707 On VMS, GNAT compiled programs return POSIX-style codes by default,
7708 e.g.@: @option{/RETURN_CODES=POSIX}.
7710 To enable VMS style return codes, use GNAT BIND and LINK with the option
7711 @option{/RETURN_CODES=VMS}. For example:
7714 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7715 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7719 Programs built with /RETURN_CODES=VMS are suitable to be called in
7720 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7721 are suitable for spawning with appropriate GNAT RTL routines.
7725 @node Search Paths and the Run-Time Library (RTL)
7726 @section Search Paths and the Run-Time Library (RTL)
7729 With the GNAT source-based library system, the compiler must be able to
7730 find source files for units that are needed by the unit being compiled.
7731 Search paths are used to guide this process.
7733 The compiler compiles one source file whose name must be given
7734 explicitly on the command line. In other words, no searching is done
7735 for this file. To find all other source files that are needed (the most
7736 common being the specs of units), the compiler examines the following
7737 directories, in the following order:
7741 The directory containing the source file of the main unit being compiled
7742 (the file name on the command line).
7745 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7746 @command{gcc} command line, in the order given.
7749 @findex ADA_PRJ_INCLUDE_FILE
7750 Each of the directories listed in the text file whose name is given
7751 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7754 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7755 driver when project files are used. It should not normally be set
7759 @findex ADA_INCLUDE_PATH
7760 Each of the directories listed in the value of the
7761 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7763 Construct this value
7764 exactly as the @env{PATH} environment variable: a list of directory
7765 names separated by colons (semicolons when working with the NT version).
7768 Normally, define this value as a logical name containing a comma separated
7769 list of directory names.
7771 This variable can also be defined by means of an environment string
7772 (an argument to the HP C exec* set of functions).
7776 DEFINE ANOTHER_PATH FOO:[BAG]
7777 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7780 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7781 first, followed by the standard Ada
7782 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7783 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7784 (Text_IO, Sequential_IO, etc)
7785 instead of the standard Ada packages. Thus, in order to get the standard Ada
7786 packages by default, ADA_INCLUDE_PATH must be redefined.
7790 The content of the @file{ada_source_path} file which is part of the GNAT
7791 installation tree and is used to store standard libraries such as the
7792 GNAT Run Time Library (RTL) source files.
7794 @ref{Installing a library}
7799 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7800 inhibits the use of the directory
7801 containing the source file named in the command line. You can still
7802 have this directory on your search path, but in this case it must be
7803 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7805 Specifying the switch @option{-nostdinc}
7806 inhibits the search of the default location for the GNAT Run Time
7807 Library (RTL) source files.
7809 The compiler outputs its object files and ALI files in the current
7812 Caution: The object file can be redirected with the @option{-o} switch;
7813 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7814 so the @file{ALI} file will not go to the right place. Therefore, you should
7815 avoid using the @option{-o} switch.
7819 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7820 children make up the GNAT RTL, together with the simple @code{System.IO}
7821 package used in the @code{"Hello World"} example. The sources for these units
7822 are needed by the compiler and are kept together in one directory. Not
7823 all of the bodies are needed, but all of the sources are kept together
7824 anyway. In a normal installation, you need not specify these directory
7825 names when compiling or binding. Either the environment variables or
7826 the built-in defaults cause these files to be found.
7828 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7829 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7830 consisting of child units of @code{GNAT}. This is a collection of generally
7831 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7832 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7834 Besides simplifying access to the RTL, a major use of search paths is
7835 in compiling sources from multiple directories. This can make
7836 development environments much more flexible.
7838 @node Order of Compilation Issues
7839 @section Order of Compilation Issues
7842 If, in our earlier example, there was a spec for the @code{hello}
7843 procedure, it would be contained in the file @file{hello.ads}; yet this
7844 file would not have to be explicitly compiled. This is the result of the
7845 model we chose to implement library management. Some of the consequences
7846 of this model are as follows:
7850 There is no point in compiling specs (except for package
7851 specs with no bodies) because these are compiled as needed by clients. If
7852 you attempt a useless compilation, you will receive an error message.
7853 It is also useless to compile subunits because they are compiled as needed
7857 There are no order of compilation requirements: performing a
7858 compilation never obsoletes anything. The only way you can obsolete
7859 something and require recompilations is to modify one of the
7860 source files on which it depends.
7863 There is no library as such, apart from the ALI files
7864 (@pxref{The Ada Library Information Files}, for information on the format
7865 of these files). For now we find it convenient to create separate ALI files,
7866 but eventually the information therein may be incorporated into the object
7870 When you compile a unit, the source files for the specs of all units
7871 that it @code{with}'s, all its subunits, and the bodies of any generics it
7872 instantiates must be available (reachable by the search-paths mechanism
7873 described above), or you will receive a fatal error message.
7880 The following are some typical Ada compilation command line examples:
7883 @item $ gcc -c xyz.adb
7884 Compile body in file @file{xyz.adb} with all default options.
7887 @item $ gcc -c -O2 -gnata xyz-def.adb
7890 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7893 Compile the child unit package in file @file{xyz-def.adb} with extensive
7894 optimizations, and pragma @code{Assert}/@code{Debug} statements
7897 @item $ gcc -c -gnatc abc-def.adb
7898 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7902 @node Binding Using gnatbind
7903 @chapter Binding Using @code{gnatbind}
7907 * Running gnatbind::
7908 * Switches for gnatbind::
7909 * Command-Line Access::
7910 * Search Paths for gnatbind::
7911 * Examples of gnatbind Usage::
7915 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7916 to bind compiled GNAT objects.
7918 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7919 driver (see @ref{The GNAT Driver and Project Files}).
7921 The @code{gnatbind} program performs four separate functions:
7925 Checks that a program is consistent, in accordance with the rules in
7926 Chapter 10 of the Ada Reference Manual. In particular, error
7927 messages are generated if a program uses inconsistent versions of a
7931 Checks that an acceptable order of elaboration exists for the program
7932 and issues an error message if it cannot find an order of elaboration
7933 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7936 Generates a main program incorporating the given elaboration order.
7937 This program is a small Ada package (body and spec) that
7938 must be subsequently compiled
7939 using the GNAT compiler. The necessary compilation step is usually
7940 performed automatically by @command{gnatlink}. The two most important
7941 functions of this program
7942 are to call the elaboration routines of units in an appropriate order
7943 and to call the main program.
7946 Determines the set of object files required by the given main program.
7947 This information is output in the forms of comments in the generated program,
7948 to be read by the @command{gnatlink} utility used to link the Ada application.
7951 @node Running gnatbind
7952 @section Running @code{gnatbind}
7955 The form of the @code{gnatbind} command is
7958 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7959 @c Expanding @ovar macro inline (explanation in macro def comments)
7960 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
7964 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7965 unit body. @code{gnatbind} constructs an Ada
7966 package in two files whose names are
7967 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7968 For example, if given the
7969 parameter @file{hello.ali}, for a main program contained in file
7970 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7971 and @file{b~hello.adb}.
7973 When doing consistency checking, the binder takes into consideration
7974 any source files it can locate. For example, if the binder determines
7975 that the given main program requires the package @code{Pack}, whose
7977 file is @file{pack.ali} and whose corresponding source spec file is
7978 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7979 (using the same search path conventions as previously described for the
7980 @command{gcc} command). If it can locate this source file, it checks that
7982 or source checksums of the source and its references to in @file{ALI} files
7983 match. In other words, any @file{ALI} files that mentions this spec must have
7984 resulted from compiling this version of the source file (or in the case
7985 where the source checksums match, a version close enough that the
7986 difference does not matter).
7988 @cindex Source files, use by binder
7989 The effect of this consistency checking, which includes source files, is
7990 that the binder ensures that the program is consistent with the latest
7991 version of the source files that can be located at bind time. Editing a
7992 source file without compiling files that depend on the source file cause
7993 error messages to be generated by the binder.
7995 For example, suppose you have a main program @file{hello.adb} and a
7996 package @code{P}, from file @file{p.ads} and you perform the following
8001 Enter @code{gcc -c hello.adb} to compile the main program.
8004 Enter @code{gcc -c p.ads} to compile package @code{P}.
8007 Edit file @file{p.ads}.
8010 Enter @code{gnatbind hello}.
8014 At this point, the file @file{p.ali} contains an out-of-date time stamp
8015 because the file @file{p.ads} has been edited. The attempt at binding
8016 fails, and the binder generates the following error messages:
8019 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8020 error: "p.ads" has been modified and must be recompiled
8024 Now both files must be recompiled as indicated, and then the bind can
8025 succeed, generating a main program. You need not normally be concerned
8026 with the contents of this file, but for reference purposes a sample
8027 binder output file is given in @ref{Example of Binder Output File}.
8029 In most normal usage, the default mode of @command{gnatbind} which is to
8030 generate the main package in Ada, as described in the previous section.
8031 In particular, this means that any Ada programmer can read and understand
8032 the generated main program. It can also be debugged just like any other
8033 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8034 @command{gnatbind} and @command{gnatlink}.
8036 @node Switches for gnatbind
8037 @section Switches for @command{gnatbind}
8040 The following switches are available with @code{gnatbind}; details will
8041 be presented in subsequent sections.
8044 * Consistency-Checking Modes::
8045 * Binder Error Message Control::
8046 * Elaboration Control::
8048 * Binding with Non-Ada Main Programs::
8049 * Binding Programs with No Main Subprogram::
8056 @cindex @option{--version} @command{gnatbind}
8057 Display Copyright and version, then exit disregarding all other options.
8060 @cindex @option{--help} @command{gnatbind}
8061 If @option{--version} was not used, display usage, then exit disregarding
8065 @cindex @option{-a} @command{gnatbind}
8066 Indicates that, if supported by the platform, the adainit procedure should
8067 be treated as an initialisation routine by the linker (a constructor). This
8068 is intended to be used by the Project Manager to automatically initialize
8069 shared Stand-Alone Libraries.
8071 @item ^-aO^/OBJECT_SEARCH^
8072 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8073 Specify directory to be searched for ALI files.
8075 @item ^-aI^/SOURCE_SEARCH^
8076 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8077 Specify directory to be searched for source file.
8079 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8080 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8081 Output ALI list (to standard output or to the named file).
8083 @item ^-b^/REPORT_ERRORS=BRIEF^
8084 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8085 Generate brief messages to @file{stderr} even if verbose mode set.
8087 @item ^-c^/NOOUTPUT^
8088 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8089 Check only, no generation of binder output file.
8091 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8092 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8093 This switch can be used to change the default task stack size value
8094 to a specified size @var{nn}, which is expressed in bytes by default, or
8095 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8097 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8098 in effect, to completing all task specs with
8099 @smallexample @c ada
8100 pragma Storage_Size (nn);
8102 When they do not already have such a pragma.
8104 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8105 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8106 This switch can be used to change the default secondary 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
8111 The secondary stack is used to deal with functions that return a variable
8112 sized result, for example a function returning an unconstrained
8113 String. There are two ways in which this secondary stack is allocated.
8115 For most targets, the secondary stack is growing on demand and is allocated
8116 as a chain of blocks in the heap. The -D option is not very
8117 relevant. It only give some control over the size of the allocated
8118 blocks (whose size is the minimum of the default secondary stack size value,
8119 and the actual size needed for the current allocation request).
8121 For certain targets, notably VxWorks 653,
8122 the secondary stack is allocated by carving off a fixed ratio chunk of the
8123 primary task stack. The -D option is used to define the
8124 size of the environment task's secondary stack.
8126 @item ^-e^/ELABORATION_DEPENDENCIES^
8127 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8128 Output complete list of elaboration-order dependencies.
8130 @item ^-E^/STORE_TRACEBACKS^
8131 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8132 Store tracebacks in exception occurrences when the target supports it.
8134 @c The following may get moved to an appendix
8135 This option is currently supported on the following targets:
8136 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8138 See also the packages @code{GNAT.Traceback} and
8139 @code{GNAT.Traceback.Symbolic} for more information.
8141 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8142 @command{gcc} option.
8145 @item ^-F^/FORCE_ELABS_FLAGS^
8146 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8147 Force the checks of elaboration flags. @command{gnatbind} does not normally
8148 generate checks of elaboration flags for the main executable, except when
8149 a Stand-Alone Library is used. However, there are cases when this cannot be
8150 detected by gnatbind. An example is importing an interface of a Stand-Alone
8151 Library through a pragma Import and only specifying through a linker switch
8152 this Stand-Alone Library. This switch is used to guarantee that elaboration
8153 flag checks are generated.
8156 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8157 Output usage (help) information
8160 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8161 Specify directory to be searched for source and ALI files.
8163 @item ^-I-^/NOCURRENT_DIRECTORY^
8164 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8165 Do not look for sources in the current directory where @code{gnatbind} was
8166 invoked, and do not look for ALI files in the directory containing the
8167 ALI file named in the @code{gnatbind} command line.
8169 @item ^-l^/ORDER_OF_ELABORATION^
8170 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8171 Output chosen elaboration order.
8173 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8174 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8175 Bind the units for library building. In this case the adainit and
8176 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8177 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8178 ^@var{xxx}final^@var{XXX}FINAL^.
8179 Implies ^-n^/NOCOMPILE^.
8181 (@xref{GNAT and Libraries}, for more details.)
8184 On OpenVMS, these init and final procedures are exported in uppercase
8185 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8186 the init procedure will be "TOTOINIT" and the exported name of the final
8187 procedure will be "TOTOFINAL".
8190 @item ^-Mxyz^/RENAME_MAIN=xyz^
8191 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8192 Rename generated main program from main to xyz. This option is
8193 supported on cross environments only.
8195 @item ^-m^/ERROR_LIMIT=^@var{n}
8196 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8197 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8198 in the range 1..999999. The default value if no switch is
8199 given is 9999. If the number of warnings reaches this limit, then a
8200 message is output and further warnings are suppressed, the bind
8201 continues in this case. If the number of errors reaches this
8202 limit, then a message is output and the bind is abandoned.
8203 A value of zero means that no limit is enforced. The equal
8207 Furthermore, under Windows, the sources pointed to by the libraries path
8208 set in the registry are not searched for.
8212 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8216 @cindex @option{-nostdinc} (@command{gnatbind})
8217 Do not look for sources in the system default directory.
8220 @cindex @option{-nostdlib} (@command{gnatbind})
8221 Do not look for library files in the system default directory.
8223 @item --RTS=@var{rts-path}
8224 @cindex @option{--RTS} (@code{gnatbind})
8225 Specifies the default location of the runtime library. Same meaning as the
8226 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8228 @item ^-o ^/OUTPUT=^@var{file}
8229 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8230 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8231 Note that if this option is used, then linking must be done manually,
8232 gnatlink cannot be used.
8234 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8235 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8236 Output object list (to standard output or to the named file).
8238 @item ^-p^/PESSIMISTIC_ELABORATION^
8239 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8240 Pessimistic (worst-case) elaboration order
8243 @cindex @option{^-R^-R^} (@command{gnatbind})
8244 Output closure source list.
8246 @item ^-s^/READ_SOURCES=ALL^
8247 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8248 Require all source files to be present.
8250 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8251 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8252 Specifies the value to be used when detecting uninitialized scalar
8253 objects with pragma Initialize_Scalars.
8254 The @var{xxx} ^string specified with the switch^option^ may be either
8256 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8257 @item ``@option{^lo^LOW^}'' for the lowest possible value
8258 @item ``@option{^hi^HIGH^}'' for the highest possible value
8259 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8260 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8263 In addition, you can specify @option{-Sev} to indicate that the value is
8264 to be set at run time. In this case, the program will look for an environment
8265 @cindex GNAT_INIT_SCALARS
8266 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8267 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8268 If no environment variable is found, or if it does not have a valid value,
8269 then the default is @option{in} (invalid values).
8273 @cindex @option{-static} (@code{gnatbind})
8274 Link against a static GNAT run time.
8277 @cindex @option{-shared} (@code{gnatbind})
8278 Link against a shared GNAT run time when available.
8281 @item ^-t^/NOTIME_STAMP_CHECK^
8282 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8283 Tolerate time stamp and other consistency errors
8285 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8286 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8287 Set the time slice value to @var{n} milliseconds. If the system supports
8288 the specification of a specific time slice value, then the indicated value
8289 is used. If the system does not support specific time slice values, but
8290 does support some general notion of round-robin scheduling, then any
8291 nonzero value will activate round-robin scheduling.
8293 A value of zero is treated specially. It turns off time
8294 slicing, and in addition, indicates to the tasking run time that the
8295 semantics should match as closely as possible the Annex D
8296 requirements of the Ada RM, and in particular sets the default
8297 scheduling policy to @code{FIFO_Within_Priorities}.
8299 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8300 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8301 Enable dynamic stack usage, with @var{n} results stored and displayed
8302 at program termination. A result is generated when a task
8303 terminates. Results that can't be stored are displayed on the fly, at
8304 task termination. This option is currently not supported on Itanium
8305 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8307 @item ^-v^/REPORT_ERRORS=VERBOSE^
8308 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8309 Verbose mode. Write error messages, header, summary output to
8314 @cindex @option{-w} (@code{gnatbind})
8315 Warning mode (@var{x}=s/e for suppress/treat as error)
8319 @item /WARNINGS=NORMAL
8320 @cindex @option{/WARNINGS} (@code{gnatbind})
8321 Normal warnings mode. Warnings are issued but ignored
8323 @item /WARNINGS=SUPPRESS
8324 @cindex @option{/WARNINGS} (@code{gnatbind})
8325 All warning messages are suppressed
8327 @item /WARNINGS=ERROR
8328 @cindex @option{/WARNINGS} (@code{gnatbind})
8329 Warning messages are treated as fatal errors
8332 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8333 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8334 Override default wide character encoding for standard Text_IO files.
8336 @item ^-x^/READ_SOURCES=NONE^
8337 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8338 Exclude source files (check object consistency only).
8341 @item /READ_SOURCES=AVAILABLE
8342 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8343 Default mode, in which sources are checked for consistency only if
8347 @item ^-y^/ENABLE_LEAP_SECONDS^
8348 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8349 Enable leap seconds support in @code{Ada.Calendar} and its children.
8351 @item ^-z^/ZERO_MAIN^
8352 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8358 You may obtain this listing of switches by running @code{gnatbind} with
8362 @node Consistency-Checking Modes
8363 @subsection Consistency-Checking Modes
8366 As described earlier, by default @code{gnatbind} checks
8367 that object files are consistent with one another and are consistent
8368 with any source files it can locate. The following switches control binder
8373 @item ^-s^/READ_SOURCES=ALL^
8374 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8375 Require source files to be present. In this mode, the binder must be
8376 able to locate all source files that are referenced, in order to check
8377 their consistency. In normal mode, if a source file cannot be located it
8378 is simply ignored. If you specify this switch, a missing source
8381 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8382 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8383 Override default wide character encoding for standard Text_IO files.
8384 Normally the default wide character encoding method used for standard
8385 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8386 the main source input (see description of switch
8387 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8388 use of this switch for the binder (which has the same set of
8389 possible arguments) overrides this default as specified.
8391 @item ^-x^/READ_SOURCES=NONE^
8392 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8393 Exclude source files. In this mode, the binder only checks that ALI
8394 files are consistent with one another. Source files are not accessed.
8395 The binder runs faster in this mode, and there is still a guarantee that
8396 the resulting program is self-consistent.
8397 If a source file has been edited since it was last compiled, and you
8398 specify this switch, the binder will not detect that the object
8399 file is out of date with respect to the source file. Note that this is the
8400 mode that is automatically used by @command{gnatmake} because in this
8401 case the checking against sources has already been performed by
8402 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8405 @item /READ_SOURCES=AVAILABLE
8406 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8407 This is the default mode in which source files are checked if they are
8408 available, and ignored if they are not available.
8412 @node Binder Error Message Control
8413 @subsection Binder Error Message Control
8416 The following switches provide control over the generation of error
8417 messages from the binder:
8421 @item ^-v^/REPORT_ERRORS=VERBOSE^
8422 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8423 Verbose mode. In the normal mode, brief error messages are generated to
8424 @file{stderr}. If this switch is present, a header is written
8425 to @file{stdout} and any error messages are directed to @file{stdout}.
8426 All that is written to @file{stderr} is a brief summary message.
8428 @item ^-b^/REPORT_ERRORS=BRIEF^
8429 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8430 Generate brief error messages to @file{stderr} even if verbose mode is
8431 specified. This is relevant only when used with the
8432 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8436 @cindex @option{-m} (@code{gnatbind})
8437 Limits the number of error messages to @var{n}, a decimal integer in the
8438 range 1-999. The binder terminates immediately if this limit is reached.
8441 @cindex @option{-M} (@code{gnatbind})
8442 Renames the generated main program from @code{main} to @code{xxx}.
8443 This is useful in the case of some cross-building environments, where
8444 the actual main program is separate from the one generated
8448 @item ^-ws^/WARNINGS=SUPPRESS^
8449 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8451 Suppress all warning messages.
8453 @item ^-we^/WARNINGS=ERROR^
8454 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8455 Treat any warning messages as fatal errors.
8458 @item /WARNINGS=NORMAL
8459 Standard mode with warnings generated, but warnings do not get treated
8463 @item ^-t^/NOTIME_STAMP_CHECK^
8464 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8465 @cindex Time stamp checks, in binder
8466 @cindex Binder consistency checks
8467 @cindex Consistency checks, in binder
8468 The binder performs a number of consistency checks including:
8472 Check that time stamps of a given source unit are consistent
8474 Check that checksums of a given source unit are consistent
8476 Check that consistent versions of @code{GNAT} were used for compilation
8478 Check consistency of configuration pragmas as required
8482 Normally failure of such checks, in accordance with the consistency
8483 requirements of the Ada Reference Manual, causes error messages to be
8484 generated which abort the binder and prevent the output of a binder
8485 file and subsequent link to obtain an executable.
8487 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8488 into warnings, so that
8489 binding and linking can continue to completion even in the presence of such
8490 errors. The result may be a failed link (due to missing symbols), or a
8491 non-functional executable which has undefined semantics.
8492 @emph{This means that
8493 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8497 @node Elaboration Control
8498 @subsection Elaboration Control
8501 The following switches provide additional control over the elaboration
8502 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8505 @item ^-p^/PESSIMISTIC_ELABORATION^
8506 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8507 Normally the binder attempts to choose an elaboration order that is
8508 likely to minimize the likelihood of an elaboration order error resulting
8509 in raising a @code{Program_Error} exception. This switch reverses the
8510 action of the binder, and requests that it deliberately choose an order
8511 that is likely to maximize the likelihood of an elaboration error.
8512 This is useful in ensuring portability and avoiding dependence on
8513 accidental fortuitous elaboration ordering.
8515 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8517 elaboration checking is used (@option{-gnatE} switch used for compilation).
8518 This is because in the default static elaboration mode, all necessary
8519 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8520 These implicit pragmas are still respected by the binder in
8521 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8522 safe elaboration order is assured.
8525 @node Output Control
8526 @subsection Output Control
8529 The following switches allow additional control over the output
8530 generated by the binder.
8535 @item ^-c^/NOOUTPUT^
8536 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8537 Check only. Do not generate the binder output file. In this mode the
8538 binder performs all error checks but does not generate an output file.
8540 @item ^-e^/ELABORATION_DEPENDENCIES^
8541 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8542 Output complete list of elaboration-order dependencies, showing the
8543 reason for each dependency. This output can be rather extensive but may
8544 be useful in diagnosing problems with elaboration order. The output is
8545 written to @file{stdout}.
8548 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8549 Output usage information. The output is written to @file{stdout}.
8551 @item ^-K^/LINKER_OPTION_LIST^
8552 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8553 Output linker options to @file{stdout}. Includes library search paths,
8554 contents of pragmas Ident and Linker_Options, and libraries added
8557 @item ^-l^/ORDER_OF_ELABORATION^
8558 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8559 Output chosen elaboration order. The output is written to @file{stdout}.
8561 @item ^-O^/OBJECT_LIST^
8562 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8563 Output full names of all the object files that must be linked to provide
8564 the Ada component of the program. The output is written to @file{stdout}.
8565 This list includes the files explicitly supplied and referenced by the user
8566 as well as implicitly referenced run-time unit files. The latter are
8567 omitted if the corresponding units reside in shared libraries. The
8568 directory names for the run-time units depend on the system configuration.
8570 @item ^-o ^/OUTPUT=^@var{file}
8571 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8572 Set name of output file to @var{file} instead of the normal
8573 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8574 binder generated body filename.
8575 Note that if this option is used, then linking must be done manually.
8576 It is not possible to use gnatlink in this case, since it cannot locate
8579 @item ^-r^/RESTRICTION_LIST^
8580 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8581 Generate list of @code{pragma Restrictions} that could be applied to
8582 the current unit. This is useful for code audit purposes, and also may
8583 be used to improve code generation in some cases.
8587 @node Binding with Non-Ada Main Programs
8588 @subsection Binding with Non-Ada Main Programs
8591 In our description so far we have assumed that the main
8592 program is in Ada, and that the task of the binder is to generate a
8593 corresponding function @code{main} that invokes this Ada main
8594 program. GNAT also supports the building of executable programs where
8595 the main program is not in Ada, but some of the called routines are
8596 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8597 The following switch is used in this situation:
8601 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8602 No main program. The main program is not in Ada.
8606 In this case, most of the functions of the binder are still required,
8607 but instead of generating a main program, the binder generates a file
8608 containing the following callable routines:
8613 You must call this routine to initialize the Ada part of the program by
8614 calling the necessary elaboration routines. A call to @code{adainit} is
8615 required before the first call to an Ada subprogram.
8617 Note that it is assumed that the basic execution environment must be setup
8618 to be appropriate for Ada execution at the point where the first Ada
8619 subprogram is called. In particular, if the Ada code will do any
8620 floating-point operations, then the FPU must be setup in an appropriate
8621 manner. For the case of the x86, for example, full precision mode is
8622 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8623 that the FPU is in the right state.
8627 You must call this routine to perform any library-level finalization
8628 required by the Ada subprograms. A call to @code{adafinal} is required
8629 after the last call to an Ada subprogram, and before the program
8634 If the @option{^-n^/NOMAIN^} switch
8635 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8636 @cindex Binder, multiple input files
8637 is given, more than one ALI file may appear on
8638 the command line for @code{gnatbind}. The normal @dfn{closure}
8639 calculation is performed for each of the specified units. Calculating
8640 the closure means finding out the set of units involved by tracing
8641 @code{with} references. The reason it is necessary to be able to
8642 specify more than one ALI file is that a given program may invoke two or
8643 more quite separate groups of Ada units.
8645 The binder takes the name of its output file from the last specified ALI
8646 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8647 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8648 The output is an Ada unit in source form that can be compiled with GNAT.
8649 This compilation occurs automatically as part of the @command{gnatlink}
8652 Currently the GNAT run time requires a FPU using 80 bits mode
8653 precision. Under targets where this is not the default it is required to
8654 call GNAT.Float_Control.Reset before using floating point numbers (this
8655 include float computation, float input and output) in the Ada code. A
8656 side effect is that this could be the wrong mode for the foreign code
8657 where floating point computation could be broken after this call.
8659 @node Binding Programs with No Main Subprogram
8660 @subsection Binding Programs with No Main Subprogram
8663 It is possible to have an Ada program which does not have a main
8664 subprogram. This program will call the elaboration routines of all the
8665 packages, then the finalization routines.
8667 The following switch is used to bind programs organized in this manner:
8670 @item ^-z^/ZERO_MAIN^
8671 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8672 Normally the binder checks that the unit name given on the command line
8673 corresponds to a suitable main subprogram. When this switch is used,
8674 a list of ALI files can be given, and the execution of the program
8675 consists of elaboration of these units in an appropriate order. Note
8676 that the default wide character encoding method for standard Text_IO
8677 files is always set to Brackets if this switch is set (you can use
8679 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8682 @node Command-Line Access
8683 @section Command-Line Access
8686 The package @code{Ada.Command_Line} provides access to the command-line
8687 arguments and program name. In order for this interface to operate
8688 correctly, the two variables
8700 are declared in one of the GNAT library routines. These variables must
8701 be set from the actual @code{argc} and @code{argv} values passed to the
8702 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8703 generates the C main program to automatically set these variables.
8704 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8705 set these variables. If they are not set, the procedures in
8706 @code{Ada.Command_Line} will not be available, and any attempt to use
8707 them will raise @code{Constraint_Error}. If command line access is
8708 required, your main program must set @code{gnat_argc} and
8709 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8712 @node Search Paths for gnatbind
8713 @section Search Paths for @code{gnatbind}
8716 The binder takes the name of an ALI file as its argument and needs to
8717 locate source files as well as other ALI files to verify object consistency.
8719 For source files, it follows exactly the same search rules as @command{gcc}
8720 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8721 directories searched are:
8725 The directory containing the ALI file named in the command line, unless
8726 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8729 All directories specified by @option{^-I^/SEARCH^}
8730 switches on the @code{gnatbind}
8731 command line, in the order given.
8734 @findex ADA_PRJ_OBJECTS_FILE
8735 Each of the directories listed in the text file whose name is given
8736 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8739 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8740 driver when project files are used. It should not normally be set
8744 @findex ADA_OBJECTS_PATH
8745 Each of the directories listed in the value of the
8746 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8748 Construct this value
8749 exactly as the @env{PATH} environment variable: a list of directory
8750 names separated by colons (semicolons when working with the NT version
8754 Normally, define this value as a logical name containing a comma separated
8755 list of directory names.
8757 This variable can also be defined by means of an environment string
8758 (an argument to the HP C exec* set of functions).
8762 DEFINE ANOTHER_PATH FOO:[BAG]
8763 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8766 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8767 first, followed by the standard Ada
8768 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8769 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8770 (Text_IO, Sequential_IO, etc)
8771 instead of the standard Ada packages. Thus, in order to get the standard Ada
8772 packages by default, ADA_OBJECTS_PATH must be redefined.
8776 The content of the @file{ada_object_path} file which is part of the GNAT
8777 installation tree and is used to store standard libraries such as the
8778 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8781 @ref{Installing a library}
8786 In the binder the switch @option{^-I^/SEARCH^}
8787 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8788 is used to specify both source and
8789 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8790 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8791 instead if you want to specify
8792 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8793 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8794 if you want to specify library paths
8795 only. This means that for the binder
8796 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8797 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8798 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8799 The binder generates the bind file (a C language source file) in the
8800 current working directory.
8806 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8807 children make up the GNAT Run-Time Library, together with the package
8808 GNAT and its children, which contain a set of useful additional
8809 library functions provided by GNAT. The sources for these units are
8810 needed by the compiler and are kept together in one directory. The ALI
8811 files and object files generated by compiling the RTL are needed by the
8812 binder and the linker and are kept together in one directory, typically
8813 different from the directory containing the sources. In a normal
8814 installation, you need not specify these directory names when compiling
8815 or binding. Either the environment variables or the built-in defaults
8816 cause these files to be found.
8818 Besides simplifying access to the RTL, a major use of search paths is
8819 in compiling sources from multiple directories. This can make
8820 development environments much more flexible.
8822 @node Examples of gnatbind Usage
8823 @section Examples of @code{gnatbind} Usage
8826 This section contains a number of examples of using the GNAT binding
8827 utility @code{gnatbind}.
8830 @item gnatbind hello
8831 The main program @code{Hello} (source program in @file{hello.adb}) is
8832 bound using the standard switch settings. The generated main program is
8833 @file{b~hello.adb}. This is the normal, default use of the binder.
8836 @item gnatbind hello -o mainprog.adb
8839 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8841 The main program @code{Hello} (source program in @file{hello.adb}) is
8842 bound using the standard switch settings. The generated main program is
8843 @file{mainprog.adb} with the associated spec in
8844 @file{mainprog.ads}. Note that you must specify the body here not the
8845 spec. Note that if this option is used, then linking must be done manually,
8846 since gnatlink will not be able to find the generated file.
8849 @c ------------------------------------
8850 @node Linking Using gnatlink
8851 @chapter Linking Using @command{gnatlink}
8852 @c ------------------------------------
8856 This chapter discusses @command{gnatlink}, a tool that links
8857 an Ada program and builds an executable file. This utility
8858 invokes the system linker ^(via the @command{gcc} command)^^
8859 with a correct list of object files and library references.
8860 @command{gnatlink} automatically determines the list of files and
8861 references for the Ada part of a program. It uses the binder file
8862 generated by the @command{gnatbind} to determine this list.
8864 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8865 driver (see @ref{The GNAT Driver and Project Files}).
8868 * Running gnatlink::
8869 * Switches for gnatlink::
8872 @node Running gnatlink
8873 @section Running @command{gnatlink}
8876 The form of the @command{gnatlink} command is
8879 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8880 @c @ovar{non-Ada objects} @ovar{linker options}
8881 @c Expanding @ovar macro inline (explanation in macro def comments)
8882 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
8883 @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
8888 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8890 or linker options) may be in any order, provided that no non-Ada object may
8891 be mistaken for a main @file{ALI} file.
8892 Any file name @file{F} without the @file{.ali}
8893 extension will be taken as the main @file{ALI} file if a file exists
8894 whose name is the concatenation of @file{F} and @file{.ali}.
8897 @file{@var{mainprog}.ali} references the ALI file of the main program.
8898 The @file{.ali} extension of this file can be omitted. From this
8899 reference, @command{gnatlink} locates the corresponding binder file
8900 @file{b~@var{mainprog}.adb} and, using the information in this file along
8901 with the list of non-Ada objects and linker options, constructs a
8902 linker command file to create the executable.
8904 The arguments other than the @command{gnatlink} switches and the main
8905 @file{ALI} file are passed to the linker uninterpreted.
8906 They typically include the names of
8907 object files for units written in other languages than Ada and any library
8908 references required to resolve references in any of these foreign language
8909 units, or in @code{Import} pragmas in any Ada units.
8911 @var{linker options} is an optional list of linker specific
8913 The default linker called by gnatlink is @command{gcc} which in
8914 turn calls the appropriate system linker.
8915 Standard options for the linker such as @option{-lmy_lib} or
8916 @option{-Ldir} can be added as is.
8917 For options that are not recognized by
8918 @command{gcc} as linker options, use the @command{gcc} switches
8919 @option{-Xlinker} or @option{-Wl,}.
8920 Refer to the GCC documentation for
8921 details. Here is an example showing how to generate a linker map:
8924 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8927 Using @var{linker options} it is possible to set the program stack and
8930 See @ref{Setting Stack Size from gnatlink} and
8931 @ref{Setting Heap Size from gnatlink}.
8934 @command{gnatlink} determines the list of objects required by the Ada
8935 program and prepends them to the list of objects passed to the linker.
8936 @command{gnatlink} also gathers any arguments set by the use of
8937 @code{pragma Linker_Options} and adds them to the list of arguments
8938 presented to the linker.
8941 @command{gnatlink} accepts the following types of extra files on the command
8942 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8943 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8944 handled according to their extension.
8947 @node Switches for gnatlink
8948 @section Switches for @command{gnatlink}
8951 The following switches are available with the @command{gnatlink} utility:
8957 @cindex @option{--version} @command{gnatlink}
8958 Display Copyright and version, then exit disregarding all other options.
8961 @cindex @option{--help} @command{gnatlink}
8962 If @option{--version} was not used, display usage, then exit disregarding
8965 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8966 @cindex Command line length
8967 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8968 On some targets, the command line length is limited, and @command{gnatlink}
8969 will generate a separate file for the linker if the list of object files
8971 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8972 to be generated even if
8973 the limit is not exceeded. This is useful in some cases to deal with
8974 special situations where the command line length is exceeded.
8977 @cindex Debugging information, including
8978 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8979 The option to include debugging information causes the Ada bind file (in
8980 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8981 @option{^-g^/DEBUG^}.
8982 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8983 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8984 Without @option{^-g^/DEBUG^}, the binder removes these files by
8985 default. The same procedure apply if a C bind file was generated using
8986 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8987 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8989 @item ^-n^/NOCOMPILE^
8990 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8991 Do not compile the file generated by the binder. This may be used when
8992 a link is rerun with different options, but there is no need to recompile
8996 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8997 Causes additional information to be output, including a full list of the
8998 included object files. This switch option is most useful when you want
8999 to see what set of object files are being used in the link step.
9001 @item ^-v -v^/VERBOSE/VERBOSE^
9002 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9003 Very verbose mode. Requests that the compiler operate in verbose mode when
9004 it compiles the binder file, and that the system linker run in verbose mode.
9006 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9007 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9008 @var{exec-name} specifies an alternate name for the generated
9009 executable program. If this switch is omitted, the executable has the same
9010 name as the main unit. For example, @code{gnatlink try.ali} creates
9011 an executable called @file{^try^TRY.EXE^}.
9014 @item -b @var{target}
9015 @cindex @option{-b} (@command{gnatlink})
9016 Compile your program to run on @var{target}, which is the name of a
9017 system configuration. You must have a GNAT cross-compiler built if
9018 @var{target} is not the same as your host system.
9021 @cindex @option{-B} (@command{gnatlink})
9022 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9023 from @var{dir} instead of the default location. Only use this switch
9024 when multiple versions of the GNAT compiler are available.
9025 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9026 for further details. You would normally use the @option{-b} or
9027 @option{-V} switch instead.
9029 @item --GCC=@var{compiler_name}
9030 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9031 Program used for compiling the binder file. The default is
9032 @command{gcc}. You need to use quotes around @var{compiler_name} if
9033 @code{compiler_name} contains spaces or other separator characters.
9034 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9035 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9036 inserted after your command name. Thus in the above example the compiler
9037 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9038 A limitation of this syntax is that the name and path name of the executable
9039 itself must not include any embedded spaces. If the compiler executable is
9040 different from the default one (gcc or <prefix>-gcc), then the back-end
9041 switches in the ALI file are not used to compile the binder generated source.
9042 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9043 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9044 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9045 is taken into account. However, all the additional switches are also taken
9047 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9048 @option{--GCC="bar -x -y -z -t"}.
9050 @item --LINK=@var{name}
9051 @cindex @option{--LINK=} (@command{gnatlink})
9052 @var{name} is the name of the linker to be invoked. This is especially
9053 useful in mixed language programs since languages such as C++ require
9054 their own linker to be used. When this switch is omitted, the default
9055 name for the linker is @command{gcc}. When this switch is used, the
9056 specified linker is called instead of @command{gcc} with exactly the same
9057 parameters that would have been passed to @command{gcc} so if the desired
9058 linker requires different parameters it is necessary to use a wrapper
9059 script that massages the parameters before invoking the real linker. It
9060 may be useful to control the exact invocation by using the verbose
9066 @item /DEBUG=TRACEBACK
9067 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9068 This qualifier causes sufficient information to be included in the
9069 executable file to allow a traceback, but does not include the full
9070 symbol information needed by the debugger.
9072 @item /IDENTIFICATION="<string>"
9073 @code{"<string>"} specifies the string to be stored in the image file
9074 identification field in the image header.
9075 It overrides any pragma @code{Ident} specified string.
9077 @item /NOINHIBIT-EXEC
9078 Generate the executable file even if there are linker warnings.
9080 @item /NOSTART_FILES
9081 Don't link in the object file containing the ``main'' transfer address.
9082 Used when linking with a foreign language main program compiled with an
9086 Prefer linking with object libraries over sharable images, even without
9092 @node The GNAT Make Program gnatmake
9093 @chapter The GNAT Make Program @command{gnatmake}
9097 * Running gnatmake::
9098 * Switches for gnatmake::
9099 * Mode Switches for gnatmake::
9100 * Notes on the Command Line::
9101 * How gnatmake Works::
9102 * Examples of gnatmake Usage::
9105 A typical development cycle when working on an Ada program consists of
9106 the following steps:
9110 Edit some sources to fix bugs.
9116 Compile all sources affected.
9126 The third step can be tricky, because not only do the modified files
9127 @cindex Dependency rules
9128 have to be compiled, but any files depending on these files must also be
9129 recompiled. The dependency rules in Ada can be quite complex, especially
9130 in the presence of overloading, @code{use} clauses, generics and inlined
9133 @command{gnatmake} automatically takes care of the third and fourth steps
9134 of this process. It determines which sources need to be compiled,
9135 compiles them, and binds and links the resulting object files.
9137 Unlike some other Ada make programs, the dependencies are always
9138 accurately recomputed from the new sources. The source based approach of
9139 the GNAT compilation model makes this possible. This means that if
9140 changes to the source program cause corresponding changes in
9141 dependencies, they will always be tracked exactly correctly by
9144 @node Running gnatmake
9145 @section Running @command{gnatmake}
9148 The usual form of the @command{gnatmake} command is
9151 @c $ gnatmake @ovar{switches} @var{file_name}
9152 @c @ovar{file_names} @ovar{mode_switches}
9153 @c Expanding @ovar macro inline (explanation in macro def comments)
9154 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9155 @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9159 The only required argument is one @var{file_name}, which specifies
9160 a compilation unit that is a main program. Several @var{file_names} can be
9161 specified: this will result in several executables being built.
9162 If @code{switches} are present, they can be placed before the first
9163 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9164 If @var{mode_switches} are present, they must always be placed after
9165 the last @var{file_name} and all @code{switches}.
9167 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9168 extension may be omitted from the @var{file_name} arguments. However, if
9169 you are using non-standard extensions, then it is required that the
9170 extension be given. A relative or absolute directory path can be
9171 specified in a @var{file_name}, in which case, the input source file will
9172 be searched for in the specified directory only. Otherwise, the input
9173 source file will first be searched in the directory where
9174 @command{gnatmake} was invoked and if it is not found, it will be search on
9175 the source path of the compiler as described in
9176 @ref{Search Paths and the Run-Time Library (RTL)}.
9178 All @command{gnatmake} output (except when you specify
9179 @option{^-M^/DEPENDENCIES_LIST^}) is to
9180 @file{stderr}. The output produced by the
9181 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9184 @node Switches for gnatmake
9185 @section Switches for @command{gnatmake}
9188 You may specify any of the following switches to @command{gnatmake}:
9194 @cindex @option{--version} @command{gnatmake}
9195 Display Copyright and version, then exit disregarding all other options.
9198 @cindex @option{--help} @command{gnatmake}
9199 If @option{--version} was not used, display usage, then exit disregarding
9203 @item --GCC=@var{compiler_name}
9204 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9205 Program used for compiling. The default is `@command{gcc}'. You need to use
9206 quotes around @var{compiler_name} if @code{compiler_name} contains
9207 spaces or other separator characters. As an example @option{--GCC="foo -x
9208 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9209 compiler. A limitation of this syntax is that the name and path name of
9210 the executable itself must not include any embedded spaces. Note that
9211 switch @option{-c} is always inserted after your command name. Thus in the
9212 above example the compiler command that will be used by @command{gnatmake}
9213 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9214 used, only the last @var{compiler_name} is taken into account. However,
9215 all the additional switches are also taken into account. Thus,
9216 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9217 @option{--GCC="bar -x -y -z -t"}.
9219 @item --GNATBIND=@var{binder_name}
9220 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9221 Program used for binding. The default is `@code{gnatbind}'. You need to
9222 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9223 or other separator characters. As an example @option{--GNATBIND="bar -x
9224 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9225 binder. Binder switches that are normally appended by @command{gnatmake}
9226 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9227 A limitation of this syntax is that the name and path name of the executable
9228 itself must not include any embedded spaces.
9230 @item --GNATLINK=@var{linker_name}
9231 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9232 Program used for linking. The default is `@command{gnatlink}'. You need to
9233 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9234 or other separator characters. As an example @option{--GNATLINK="lan -x
9235 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9236 linker. Linker switches that are normally appended by @command{gnatmake} to
9237 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9238 A limitation of this syntax is that the name and path name of the executable
9239 itself must not include any embedded spaces.
9243 @item ^--subdirs^/SUBDIRS^=subdir
9244 Actual object directory of each project file is the subdirectory subdir of the
9245 object directory specified or defaulted in the project file.
9247 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9248 Disallow simultaneous compilations in the same object directory when
9249 project files are used.
9251 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9252 By default, shared library projects are not allowed to import static library
9253 projects. When this switch is used on the command line, this restriction is
9256 @item ^-a^/ALL_FILES^
9257 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9258 Consider all files in the make process, even the GNAT internal system
9259 files (for example, the predefined Ada library files), as well as any
9260 locked files. Locked files are files whose ALI file is write-protected.
9262 @command{gnatmake} does not check these files,
9263 because the assumption is that the GNAT internal files are properly up
9264 to date, and also that any write protected ALI files have been properly
9265 installed. Note that if there is an installation problem, such that one
9266 of these files is not up to date, it will be properly caught by the
9268 You may have to specify this switch if you are working on GNAT
9269 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9270 in conjunction with @option{^-f^/FORCE_COMPILE^}
9271 if you need to recompile an entire application,
9272 including run-time files, using special configuration pragmas,
9273 such as a @code{Normalize_Scalars} pragma.
9276 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9279 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9282 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9285 @item ^-b^/ACTIONS=BIND^
9286 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9287 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9288 compilation and binding, but no link.
9289 Can be combined with @option{^-l^/ACTIONS=LINK^}
9290 to do binding and linking. When not combined with
9291 @option{^-c^/ACTIONS=COMPILE^}
9292 all the units in the closure of the main program must have been previously
9293 compiled and must be up to date. The root unit specified by @var{file_name}
9294 may be given without extension, with the source extension or, if no GNAT
9295 Project File is specified, with the ALI file extension.
9297 @item ^-c^/ACTIONS=COMPILE^
9298 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9299 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9300 is also specified. Do not perform linking, except if both
9301 @option{^-b^/ACTIONS=BIND^} and
9302 @option{^-l^/ACTIONS=LINK^} are also specified.
9303 If the root unit specified by @var{file_name} is not a main unit, this is the
9304 default. Otherwise @command{gnatmake} will attempt binding and linking
9305 unless all objects are up to date and the executable is more recent than
9309 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9310 Use a temporary mapping file. A mapping file is a way to communicate
9311 to the compiler two mappings: from unit names to file names (without
9312 any directory information) and from file names to path names (with
9313 full directory information). A mapping file can make the compiler's
9314 file searches faster, especially if there are many source directories,
9315 or the sources are read over a slow network connection. If
9316 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9317 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9318 is initially populated based on the project file. If
9319 @option{^-C^/MAPPING^} is used without
9320 @option{^-P^/PROJECT_FILE^},
9321 the mapping file is initially empty. Each invocation of the compiler
9322 will add any newly accessed sources to the mapping file.
9324 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9325 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9326 Use a specific mapping file. The file, specified as a path name (absolute or
9327 relative) by this switch, should already exist, otherwise the switch is
9328 ineffective. The specified mapping file will be communicated to the compiler.
9329 This switch is not compatible with a project file
9330 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9331 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9333 @item ^-d^/DISPLAY_PROGRESS^
9334 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9335 Display progress for each source, up to date or not, as a single line
9338 completed x out of y (zz%)
9341 If the file needs to be compiled this is displayed after the invocation of
9342 the compiler. These lines are displayed even in quiet output mode.
9344 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9345 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9346 Put all object files and ALI file in directory @var{dir}.
9347 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9348 and ALI files go in the current working directory.
9350 This switch cannot be used when using a project file.
9354 @cindex @option{-eL} (@command{gnatmake})
9355 @cindex symbolic links
9356 Follow all symbolic links when processing project files.
9357 This should be used if your project uses symbolic links for files or
9358 directories, but is not needed in other cases.
9360 @cindex naming scheme
9361 This also assumes that no directory matches the naming scheme for files (for
9362 instance that you do not have a directory called "sources.ads" when using the
9363 default GNAT naming scheme).
9365 When you do not have to use this switch (ie by default), gnatmake is able to
9366 save a lot of system calls (several per source file and object file), which
9367 can result in a significant speed up to load and manipulate a project file,
9368 especially when using source files from a remote system.
9372 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9373 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9374 Output the commands for the compiler, the binder and the linker
9375 on ^standard output^SYS$OUTPUT^,
9376 instead of ^standard error^SYS$ERROR^.
9378 @item ^-f^/FORCE_COMPILE^
9379 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9380 Force recompilations. Recompile all sources, even though some object
9381 files may be up to date, but don't recompile predefined or GNAT internal
9382 files or locked files (files with a write-protected ALI file),
9383 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9385 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9386 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9387 When using project files, if some errors or warnings are detected during
9388 parsing and verbose mode is not in effect (no use of switch
9389 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9390 file, rather than its simple file name.
9393 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9394 Enable debugging. This switch is simply passed to the compiler and to the
9397 @item ^-i^/IN_PLACE^
9398 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9399 In normal mode, @command{gnatmake} compiles all object files and ALI files
9400 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9401 then instead object files and ALI files that already exist are overwritten
9402 in place. This means that once a large project is organized into separate
9403 directories in the desired manner, then @command{gnatmake} will automatically
9404 maintain and update this organization. If no ALI files are found on the
9405 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9406 the new object and ALI files are created in the
9407 directory containing the source being compiled. If another organization
9408 is desired, where objects and sources are kept in different directories,
9409 a useful technique is to create dummy ALI files in the desired directories.
9410 When detecting such a dummy file, @command{gnatmake} will be forced to
9411 recompile the corresponding source file, and it will be put the resulting
9412 object and ALI files in the directory where it found the dummy file.
9414 @item ^-j^/PROCESSES=^@var{n}
9415 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9416 @cindex Parallel make
9417 Use @var{n} processes to carry out the (re)compilations. On a
9418 multiprocessor machine compilations will occur in parallel. In the
9419 event of compilation errors, messages from various compilations might
9420 get interspersed (but @command{gnatmake} will give you the full ordered
9421 list of failing compiles at the end). If this is problematic, rerun
9422 the make process with n set to 1 to get a clean list of messages.
9424 @item ^-k^/CONTINUE_ON_ERROR^
9425 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9426 Keep going. Continue as much as possible after a compilation error. To
9427 ease the programmer's task in case of compilation errors, the list of
9428 sources for which the compile fails is given when @command{gnatmake}
9431 If @command{gnatmake} is invoked with several @file{file_names} and with this
9432 switch, if there are compilation errors when building an executable,
9433 @command{gnatmake} will not attempt to build the following executables.
9435 @item ^-l^/ACTIONS=LINK^
9436 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9437 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9438 and linking. Linking will not be performed if combined with
9439 @option{^-c^/ACTIONS=COMPILE^}
9440 but not with @option{^-b^/ACTIONS=BIND^}.
9441 When not combined with @option{^-b^/ACTIONS=BIND^}
9442 all the units in the closure of the main program must have been previously
9443 compiled and must be up to date, and the main program needs to have been bound.
9444 The root unit specified by @var{file_name}
9445 may be given without extension, with the source extension or, if no GNAT
9446 Project File is specified, with the ALI file extension.
9448 @item ^-m^/MINIMAL_RECOMPILATION^
9449 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9450 Specify that the minimum necessary amount of recompilations
9451 be performed. In this mode @command{gnatmake} ignores time
9452 stamp differences when the only
9453 modifications to a source file consist in adding/removing comments,
9454 empty lines, spaces or tabs. This means that if you have changed the
9455 comments in a source file or have simply reformatted it, using this
9456 switch will tell @command{gnatmake} not to recompile files that depend on it
9457 (provided other sources on which these files depend have undergone no
9458 semantic modifications). Note that the debugging information may be
9459 out of date with respect to the sources if the @option{-m} switch causes
9460 a compilation to be switched, so the use of this switch represents a
9461 trade-off between compilation time and accurate debugging information.
9463 @item ^-M^/DEPENDENCIES_LIST^
9464 @cindex Dependencies, producing list
9465 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9466 Check if all objects are up to date. If they are, output the object
9467 dependences to @file{stdout} in a form that can be directly exploited in
9468 a @file{Makefile}. By default, each source file is prefixed with its
9469 (relative or absolute) directory name. This name is whatever you
9470 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9471 and @option{^-I^/SEARCH^} switches. If you use
9472 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9473 @option{^-q^/QUIET^}
9474 (see below), only the source file names,
9475 without relative paths, are output. If you just specify the
9476 @option{^-M^/DEPENDENCIES_LIST^}
9477 switch, dependencies of the GNAT internal system files are omitted. This
9478 is typically what you want. If you also specify
9479 the @option{^-a^/ALL_FILES^} switch,
9480 dependencies of the GNAT internal files are also listed. Note that
9481 dependencies of the objects in external Ada libraries (see switch
9482 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9485 @item ^-n^/DO_OBJECT_CHECK^
9486 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9487 Don't compile, bind, or link. Checks if all objects are up to date.
9488 If they are not, the full name of the first file that needs to be
9489 recompiled is printed.
9490 Repeated use of this option, followed by compiling the indicated source
9491 file, will eventually result in recompiling all required units.
9493 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9494 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9495 Output executable name. The name of the final executable program will be
9496 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9497 name for the executable will be the name of the input file in appropriate form
9498 for an executable file on the host system.
9500 This switch cannot be used when invoking @command{gnatmake} with several
9503 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9504 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9505 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9506 automatically missing object directories, library directories and exec
9509 @item ^-P^/PROJECT_FILE=^@var{project}
9510 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9511 Use project file @var{project}. Only one such switch can be used.
9512 @xref{gnatmake and Project Files}.
9515 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9516 Quiet. When this flag is not set, the commands carried out by
9517 @command{gnatmake} are displayed.
9519 @item ^-s^/SWITCH_CHECK/^
9520 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9521 Recompile if compiler switches have changed since last compilation.
9522 All compiler switches but -I and -o are taken into account in the
9524 orders between different ``first letter'' switches are ignored, but
9525 orders between same switches are taken into account. For example,
9526 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9527 is equivalent to @option{-O -g}.
9529 This switch is recommended when Integrated Preprocessing is used.
9532 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9533 Unique. Recompile at most the main files. It implies -c. Combined with
9534 -f, it is equivalent to calling the compiler directly. Note that using
9535 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9536 (@pxref{Project Files and Main Subprograms}).
9538 @item ^-U^/ALL_PROJECTS^
9539 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9540 When used without a project file or with one or several mains on the command
9541 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9542 on the command line, all sources of all project files are checked and compiled
9543 if not up to date, and libraries are rebuilt, if necessary.
9546 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9547 Verbose. Display the reason for all recompilations @command{gnatmake}
9548 decides are necessary, with the highest verbosity level.
9550 @item ^-vl^/LOW_VERBOSITY^
9551 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9552 Verbosity level Low. Display fewer lines than in verbosity Medium.
9554 @item ^-vm^/MEDIUM_VERBOSITY^
9555 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9556 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9558 @item ^-vh^/HIGH_VERBOSITY^
9559 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9560 Verbosity level High. Equivalent to ^-v^/REASONS^.
9562 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9563 Indicate the verbosity of the parsing of GNAT project files.
9564 @xref{Switches Related to Project Files}.
9566 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9567 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9568 Indicate that sources that are not part of any Project File may be compiled.
9569 Normally, when using Project Files, only sources that are part of a Project
9570 File may be compile. When this switch is used, a source outside of all Project
9571 Files may be compiled. The ALI file and the object file will be put in the
9572 object directory of the main Project. The compilation switches used will only
9573 be those specified on the command line. Even when
9574 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9575 command line need to be sources of a project file.
9577 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9578 Indicate that external variable @var{name} has the value @var{value}.
9579 The Project Manager will use this value for occurrences of
9580 @code{external(name)} when parsing the project file.
9581 @xref{Switches Related to Project Files}.
9584 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9585 No main subprogram. Bind and link the program even if the unit name
9586 given on the command line is a package name. The resulting executable
9587 will execute the elaboration routines of the package and its closure,
9588 then the finalization routines.
9593 @item @command{gcc} @asis{switches}
9595 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9596 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9599 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9600 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9601 automatically treated as a compiler switch, and passed on to all
9602 compilations that are carried out.
9607 Source and library search path switches:
9611 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9612 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9613 When looking for source files also look in directory @var{dir}.
9614 The order in which source files search is undertaken is
9615 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9617 @item ^-aL^/SKIP_MISSING=^@var{dir}
9618 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9619 Consider @var{dir} as being an externally provided Ada library.
9620 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9621 files have been located in directory @var{dir}. This allows you to have
9622 missing bodies for the units in @var{dir} and to ignore out of date bodies
9623 for the same units. You still need to specify
9624 the location of the specs for these units by using the switches
9625 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9626 or @option{^-I^/SEARCH=^@var{dir}}.
9627 Note: this switch is provided for compatibility with previous versions
9628 of @command{gnatmake}. The easier method of causing standard libraries
9629 to be excluded from consideration is to write-protect the corresponding
9632 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9633 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9634 When searching for library and object files, look in directory
9635 @var{dir}. The order in which library files are searched is described in
9636 @ref{Search Paths for gnatbind}.
9638 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9639 @cindex Search paths, for @command{gnatmake}
9640 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9641 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9642 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9644 @item ^-I^/SEARCH=^@var{dir}
9645 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9646 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9647 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9649 @item ^-I-^/NOCURRENT_DIRECTORY^
9650 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9651 @cindex Source files, suppressing search
9652 Do not look for source files in the directory containing the source
9653 file named in the command line.
9654 Do not look for ALI or object files in the directory
9655 where @command{gnatmake} was invoked.
9657 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9658 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9659 @cindex Linker libraries
9660 Add directory @var{dir} to the list of directories in which the linker
9661 will search for libraries. This is equivalent to
9662 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9664 Furthermore, under Windows, the sources pointed to by the libraries path
9665 set in the registry are not searched for.
9669 @cindex @option{-nostdinc} (@command{gnatmake})
9670 Do not look for source files in the system default directory.
9673 @cindex @option{-nostdlib} (@command{gnatmake})
9674 Do not look for library files in the system default directory.
9676 @item --RTS=@var{rts-path}
9677 @cindex @option{--RTS} (@command{gnatmake})
9678 Specifies the default location of the runtime library. GNAT looks for the
9680 in the following directories, and stops as soon as a valid runtime is found
9681 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9682 @file{ada_object_path} present):
9685 @item <current directory>/$rts_path
9687 @item <default-search-dir>/$rts_path
9689 @item <default-search-dir>/rts-$rts_path
9693 The selected path is handled like a normal RTS path.
9697 @node Mode Switches for gnatmake
9698 @section Mode Switches for @command{gnatmake}
9701 The mode switches (referred to as @code{mode_switches}) allow the
9702 inclusion of switches that are to be passed to the compiler itself, the
9703 binder or the linker. The effect of a mode switch is to cause all
9704 subsequent switches up to the end of the switch list, or up to the next
9705 mode switch, to be interpreted as switches to be passed on to the
9706 designated component of GNAT.
9710 @item -cargs @var{switches}
9711 @cindex @option{-cargs} (@command{gnatmake})
9712 Compiler switches. Here @var{switches} is a list of switches
9713 that are valid switches for @command{gcc}. They will be passed on to
9714 all compile steps performed by @command{gnatmake}.
9716 @item -bargs @var{switches}
9717 @cindex @option{-bargs} (@command{gnatmake})
9718 Binder switches. Here @var{switches} is a list of switches
9719 that are valid switches for @code{gnatbind}. They will be passed on to
9720 all bind steps performed by @command{gnatmake}.
9722 @item -largs @var{switches}
9723 @cindex @option{-largs} (@command{gnatmake})
9724 Linker switches. Here @var{switches} is a list of switches
9725 that are valid switches for @command{gnatlink}. They will be passed on to
9726 all link steps performed by @command{gnatmake}.
9728 @item -margs @var{switches}
9729 @cindex @option{-margs} (@command{gnatmake})
9730 Make switches. The switches are directly interpreted by @command{gnatmake},
9731 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9735 @node Notes on the Command Line
9736 @section Notes on the Command Line
9739 This section contains some additional useful notes on the operation
9740 of the @command{gnatmake} command.
9744 @cindex Recompilation, by @command{gnatmake}
9745 If @command{gnatmake} finds no ALI files, it recompiles the main program
9746 and all other units required by the main program.
9747 This means that @command{gnatmake}
9748 can be used for the initial compile, as well as during subsequent steps of
9749 the development cycle.
9752 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9753 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9754 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9758 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9759 is used to specify both source and
9760 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9761 instead if you just want to specify
9762 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9763 if you want to specify library paths
9767 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9768 This may conveniently be used to exclude standard libraries from
9769 consideration and in particular it means that the use of the
9770 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9771 unless @option{^-a^/ALL_FILES^} is also specified.
9774 @command{gnatmake} has been designed to make the use of Ada libraries
9775 particularly convenient. Assume you have an Ada library organized
9776 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9777 of your Ada compilation units,
9778 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9779 specs of these units, but no bodies. Then to compile a unit
9780 stored in @code{main.adb}, which uses this Ada library you would just type
9784 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
9787 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9788 /SKIP_MISSING=@i{[OBJ_DIR]} main
9793 Using @command{gnatmake} along with the
9794 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9795 switch provides a mechanism for avoiding unnecessary recompilations. Using
9797 you can update the comments/format of your
9798 source files without having to recompile everything. Note, however, that
9799 adding or deleting lines in a source files may render its debugging
9800 info obsolete. If the file in question is a spec, the impact is rather
9801 limited, as that debugging info will only be useful during the
9802 elaboration phase of your program. For bodies the impact can be more
9803 significant. In all events, your debugger will warn you if a source file
9804 is more recent than the corresponding object, and alert you to the fact
9805 that the debugging information may be out of date.
9808 @node How gnatmake Works
9809 @section How @command{gnatmake} Works
9812 Generally @command{gnatmake} automatically performs all necessary
9813 recompilations and you don't need to worry about how it works. However,
9814 it may be useful to have some basic understanding of the @command{gnatmake}
9815 approach and in particular to understand how it uses the results of
9816 previous compilations without incorrectly depending on them.
9818 First a definition: an object file is considered @dfn{up to date} if the
9819 corresponding ALI file exists and if all the source files listed in the
9820 dependency section of this ALI file have time stamps matching those in
9821 the ALI file. This means that neither the source file itself nor any
9822 files that it depends on have been modified, and hence there is no need
9823 to recompile this file.
9825 @command{gnatmake} works by first checking if the specified main unit is up
9826 to date. If so, no compilations are required for the main unit. If not,
9827 @command{gnatmake} compiles the main program to build a new ALI file that
9828 reflects the latest sources. Then the ALI file of the main unit is
9829 examined to find all the source files on which the main program depends,
9830 and @command{gnatmake} recursively applies the above procedure on all these
9833 This process ensures that @command{gnatmake} only trusts the dependencies
9834 in an existing ALI file if they are known to be correct. Otherwise it
9835 always recompiles to determine a new, guaranteed accurate set of
9836 dependencies. As a result the program is compiled ``upside down'' from what may
9837 be more familiar as the required order of compilation in some other Ada
9838 systems. In particular, clients are compiled before the units on which
9839 they depend. The ability of GNAT to compile in any order is critical in
9840 allowing an order of compilation to be chosen that guarantees that
9841 @command{gnatmake} will recompute a correct set of new dependencies if
9844 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9845 imported by several of the executables, it will be recompiled at most once.
9847 Note: when using non-standard naming conventions
9848 (@pxref{Using Other File Names}), changing through a configuration pragmas
9849 file the version of a source and invoking @command{gnatmake} to recompile may
9850 have no effect, if the previous version of the source is still accessible
9851 by @command{gnatmake}. It may be necessary to use the switch
9852 ^-f^/FORCE_COMPILE^.
9854 @node Examples of gnatmake Usage
9855 @section Examples of @command{gnatmake} Usage
9858 @item gnatmake hello.adb
9859 Compile all files necessary to bind and link the main program
9860 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9861 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9863 @item gnatmake main1 main2 main3
9864 Compile all files necessary to bind and link the main programs
9865 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9866 (containing unit @code{Main2}) and @file{main3.adb}
9867 (containing unit @code{Main3}) and bind and link the resulting object files
9868 to generate three executable files @file{^main1^MAIN1.EXE^},
9869 @file{^main2^MAIN2.EXE^}
9870 and @file{^main3^MAIN3.EXE^}.
9873 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9877 @item gnatmake Main_Unit /QUIET
9878 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9879 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9881 Compile all files necessary to bind and link the main program unit
9882 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9883 be done with optimization level 2 and the order of elaboration will be
9884 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9885 displaying commands it is executing.
9888 @c *************************
9889 @node Improving Performance
9890 @chapter Improving Performance
9891 @cindex Improving performance
9894 This chapter presents several topics related to program performance.
9895 It first describes some of the tradeoffs that need to be considered
9896 and some of the techniques for making your program run faster.
9897 It then documents the @command{gnatelim} tool and unused subprogram/data
9898 elimination feature, which can reduce the size of program executables.
9900 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9901 driver (see @ref{The GNAT Driver and Project Files}).
9905 * Performance Considerations::
9906 * Text_IO Suggestions::
9907 * Reducing Size of Ada Executables with gnatelim::
9908 * Reducing Size of Executables with unused subprogram/data elimination::
9912 @c *****************************
9913 @node Performance Considerations
9914 @section Performance Considerations
9917 The GNAT system provides a number of options that allow a trade-off
9922 performance of the generated code
9925 speed of compilation
9928 minimization of dependences and recompilation
9931 the degree of run-time checking.
9935 The defaults (if no options are selected) aim at improving the speed
9936 of compilation and minimizing dependences, at the expense of performance
9937 of the generated code:
9944 no inlining of subprogram calls
9947 all run-time checks enabled except overflow and elaboration checks
9951 These options are suitable for most program development purposes. This
9952 chapter describes how you can modify these choices, and also provides
9953 some guidelines on debugging optimized code.
9956 * Controlling Run-Time Checks::
9957 * Use of Restrictions::
9958 * Optimization Levels::
9959 * Debugging Optimized Code::
9960 * Inlining of Subprograms::
9961 * Other Optimization Switches::
9962 * Optimization and Strict Aliasing::
9965 * Coverage Analysis::
9969 @node Controlling Run-Time Checks
9970 @subsection Controlling Run-Time Checks
9973 By default, GNAT generates all run-time checks, except integer overflow
9974 checks, stack overflow checks, and checks for access before elaboration on
9975 subprogram calls. The latter are not required in default mode, because all
9976 necessary checking is done at compile time.
9977 @cindex @option{-gnatp} (@command{gcc})
9978 @cindex @option{-gnato} (@command{gcc})
9979 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9980 be modified. @xref{Run-Time Checks}.
9982 Our experience is that the default is suitable for most development
9985 We treat integer overflow specially because these
9986 are quite expensive and in our experience are not as important as other
9987 run-time checks in the development process. Note that division by zero
9988 is not considered an overflow check, and divide by zero checks are
9989 generated where required by default.
9991 Elaboration checks are off by default, and also not needed by default, since
9992 GNAT uses a static elaboration analysis approach that avoids the need for
9993 run-time checking. This manual contains a full chapter discussing the issue
9994 of elaboration checks, and if the default is not satisfactory for your use,
9995 you should read this chapter.
9997 For validity checks, the minimal checks required by the Ada Reference
9998 Manual (for case statements and assignments to array elements) are on
9999 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10000 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10001 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10002 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10003 are also suppressed entirely if @option{-gnatp} is used.
10005 @cindex Overflow checks
10006 @cindex Checks, overflow
10009 @cindex pragma Suppress
10010 @cindex pragma Unsuppress
10011 Note that the setting of the switches controls the default setting of
10012 the checks. They may be modified using either @code{pragma Suppress} (to
10013 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10014 checks) in the program source.
10016 @node Use of Restrictions
10017 @subsection Use of Restrictions
10020 The use of pragma Restrictions allows you to control which features are
10021 permitted in your program. Apart from the obvious point that if you avoid
10022 relatively expensive features like finalization (enforceable by the use
10023 of pragma Restrictions (No_Finalization), the use of this pragma does not
10024 affect the generated code in most cases.
10026 One notable exception to this rule is that the possibility of task abort
10027 results in some distributed overhead, particularly if finalization or
10028 exception handlers are used. The reason is that certain sections of code
10029 have to be marked as non-abortable.
10031 If you use neither the @code{abort} statement, nor asynchronous transfer
10032 of control (@code{select @dots{} then abort}), then this distributed overhead
10033 is removed, which may have a general positive effect in improving
10034 overall performance. Especially code involving frequent use of tasking
10035 constructs and controlled types will show much improved performance.
10036 The relevant restrictions pragmas are
10038 @smallexample @c ada
10039 pragma Restrictions (No_Abort_Statements);
10040 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10044 It is recommended that these restriction pragmas be used if possible. Note
10045 that this also means that you can write code without worrying about the
10046 possibility of an immediate abort at any point.
10048 @node Optimization Levels
10049 @subsection Optimization Levels
10050 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10053 Without any optimization ^option,^qualifier,^
10054 the compiler's goal is to reduce the cost of
10055 compilation and to make debugging produce the expected results.
10056 Statements are independent: if you stop the program with a breakpoint between
10057 statements, you can then assign a new value to any variable or change
10058 the program counter to any other statement in the subprogram and get exactly
10059 the results you would expect from the source code.
10061 Turning on optimization makes the compiler attempt to improve the
10062 performance and/or code size at the expense of compilation time and
10063 possibly the ability to debug the program.
10065 If you use multiple
10066 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10067 the last such option is the one that is effective.
10070 The default is optimization off. This results in the fastest compile
10071 times, but GNAT makes absolutely no attempt to optimize, and the
10072 generated programs are considerably larger and slower than when
10073 optimization is enabled. You can use the
10075 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10076 @option{-O2}, @option{-O3}, and @option{-Os})
10079 @code{OPTIMIZE} qualifier
10081 to @command{gcc} to control the optimization level:
10084 @item ^-O0^/OPTIMIZE=NONE^
10085 No optimization (the default);
10086 generates unoptimized code but has
10087 the fastest compilation time.
10089 Note that many other compilers do fairly extensive optimization
10090 even if ``no optimization'' is specified. With gcc, it is
10091 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10092 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10093 really does mean no optimization at all. This difference between
10094 gcc and other compilers should be kept in mind when doing
10095 performance comparisons.
10097 @item ^-O1^/OPTIMIZE=SOME^
10098 Moderate optimization;
10099 optimizes reasonably well but does not
10100 degrade compilation time significantly.
10102 @item ^-O2^/OPTIMIZE=ALL^
10104 @itemx /OPTIMIZE=DEVELOPMENT
10107 generates highly optimized code and has
10108 the slowest compilation time.
10110 @item ^-O3^/OPTIMIZE=INLINING^
10111 Full optimization as in @option{-O2},
10112 and also attempts automatic inlining of small
10113 subprograms within a unit (@pxref{Inlining of Subprograms}).
10115 @item ^-Os^/OPTIMIZE=SPACE^
10116 Optimize space usage of resulting program.
10120 Higher optimization levels perform more global transformations on the
10121 program and apply more expensive analysis algorithms in order to generate
10122 faster and more compact code. The price in compilation time, and the
10123 resulting improvement in execution time,
10124 both depend on the particular application and the hardware environment.
10125 You should experiment to find the best level for your application.
10127 Since the precise set of optimizations done at each level will vary from
10128 release to release (and sometime from target to target), it is best to think
10129 of the optimization settings in general terms.
10130 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10131 the GNU Compiler Collection (GCC)}, for details about
10132 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10133 individually enable or disable specific optimizations.
10135 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10136 been tested extensively at all optimization levels. There are some bugs
10137 which appear only with optimization turned on, but there have also been
10138 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10139 level of optimization does not improve the reliability of the code
10140 generator, which in practice is highly reliable at all optimization
10143 Note regarding the use of @option{-O3}: The use of this optimization level
10144 is generally discouraged with GNAT, since it often results in larger
10145 executables which run more slowly. See further discussion of this point
10146 in @ref{Inlining of Subprograms}.
10148 @node Debugging Optimized Code
10149 @subsection Debugging Optimized Code
10150 @cindex Debugging optimized code
10151 @cindex Optimization and debugging
10154 Although it is possible to do a reasonable amount of debugging at
10156 nonzero optimization levels,
10157 the higher the level the more likely that
10160 @option{/OPTIMIZE} settings other than @code{NONE},
10161 such settings will make it more likely that
10163 source-level constructs will have been eliminated by optimization.
10164 For example, if a loop is strength-reduced, the loop
10165 control variable may be completely eliminated and thus cannot be
10166 displayed in the debugger.
10167 This can only happen at @option{-O2} or @option{-O3}.
10168 Explicit temporary variables that you code might be eliminated at
10169 ^level^setting^ @option{-O1} or higher.
10171 The use of the @option{^-g^/DEBUG^} switch,
10172 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10173 which is needed for source-level debugging,
10174 affects the size of the program executable on disk,
10175 and indeed the debugging information can be quite large.
10176 However, it has no effect on the generated code (and thus does not
10177 degrade performance)
10179 Since the compiler generates debugging tables for a compilation unit before
10180 it performs optimizations, the optimizing transformations may invalidate some
10181 of the debugging data. You therefore need to anticipate certain
10182 anomalous situations that may arise while debugging optimized code.
10183 These are the most common cases:
10187 @i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next}
10189 the PC bouncing back and forth in the code. This may result from any of
10190 the following optimizations:
10194 @i{Common subexpression elimination:} using a single instance of code for a
10195 quantity that the source computes several times. As a result you
10196 may not be able to stop on what looks like a statement.
10199 @i{Invariant code motion:} moving an expression that does not change within a
10200 loop, to the beginning of the loop.
10203 @i{Instruction scheduling:} moving instructions so as to
10204 overlap loads and stores (typically) with other code, or in
10205 general to move computations of values closer to their uses. Often
10206 this causes you to pass an assignment statement without the assignment
10207 happening and then later bounce back to the statement when the
10208 value is actually needed. Placing a breakpoint on a line of code
10209 and then stepping over it may, therefore, not always cause all the
10210 expected side-effects.
10214 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10215 two identical pieces of code are merged and the program counter suddenly
10216 jumps to a statement that is not supposed to be executed, simply because
10217 it (and the code following) translates to the same thing as the code
10218 that @emph{was} supposed to be executed. This effect is typically seen in
10219 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10220 a @code{break} in a C @code{^switch^switch^} statement.
10223 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10224 There are various reasons for this effect:
10228 In a subprogram prologue, a parameter may not yet have been moved to its
10232 A variable may be dead, and its register re-used. This is
10233 probably the most common cause.
10236 As mentioned above, the assignment of a value to a variable may
10240 A variable may be eliminated entirely by value propagation or
10241 other means. In this case, GCC may incorrectly generate debugging
10242 information for the variable
10246 In general, when an unexpected value appears for a local variable or parameter
10247 you should first ascertain if that value was actually computed by
10248 your program, as opposed to being incorrectly reported by the debugger.
10250 array elements in an object designated by an access value
10251 are generally less of a problem, once you have ascertained that the access
10253 Typically, this means checking variables in the preceding code and in the
10254 calling subprogram to verify that the value observed is explainable from other
10255 values (one must apply the procedure recursively to those
10256 other values); or re-running the code and stopping a little earlier
10257 (perhaps before the call) and stepping to better see how the variable obtained
10258 the value in question; or continuing to step @emph{from} the point of the
10259 strange value to see if code motion had simply moved the variable's
10264 In light of such anomalies, a recommended technique is to use @option{-O0}
10265 early in the software development cycle, when extensive debugging capabilities
10266 are most needed, and then move to @option{-O1} and later @option{-O2} as
10267 the debugger becomes less critical.
10268 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10269 a release management issue.
10271 Note that if you use @option{-g} you can then use the @command{strip} program
10272 on the resulting executable,
10273 which removes both debugging information and global symbols.
10276 @node Inlining of Subprograms
10277 @subsection Inlining of Subprograms
10280 A call to a subprogram in the current unit is inlined if all the
10281 following conditions are met:
10285 The optimization level is at least @option{-O1}.
10288 The called subprogram is suitable for inlining: It must be small enough
10289 and not contain something that @command{gcc} cannot support in inlined
10293 @cindex pragma Inline
10295 Either @code{pragma Inline} applies to the subprogram, or it is local
10296 to the unit and called once from within it, or it is small and automatic
10297 inlining (optimization level @option{-O3}) is specified.
10301 Calls to subprograms in @code{with}'ed units are normally not inlined.
10302 To achieve actual inlining (that is, replacement of the call by the code
10303 in the body of the subprogram), the following conditions must all be true.
10307 The optimization level is at least @option{-O1}.
10310 The called subprogram is suitable for inlining: It must be small enough
10311 and not contain something that @command{gcc} cannot support in inlined
10315 The call appears in a body (not in a package spec).
10318 There is a @code{pragma Inline} for the subprogram.
10321 @cindex @option{-gnatn} (@command{gcc})
10322 The @option{^-gnatn^/INLINE^} switch
10323 is used in the @command{gcc} command line
10326 Even if all these conditions are met, it may not be possible for
10327 the compiler to inline the call, due to the length of the body,
10328 or features in the body that make it impossible for the compiler
10329 to do the inlining.
10331 Note that specifying the @option{-gnatn} switch causes additional
10332 compilation dependencies. Consider the following:
10334 @smallexample @c ada
10354 With the default behavior (no @option{-gnatn} switch specified), the
10355 compilation of the @code{Main} procedure depends only on its own source,
10356 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10357 means that editing the body of @code{R} does not require recompiling
10360 On the other hand, the call @code{R.Q} is not inlined under these
10361 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10362 is compiled, the call will be inlined if the body of @code{Q} is small
10363 enough, but now @code{Main} depends on the body of @code{R} in
10364 @file{r.adb} as well as on the spec. This means that if this body is edited,
10365 the main program must be recompiled. Note that this extra dependency
10366 occurs whether or not the call is in fact inlined by @command{gcc}.
10368 The use of front end inlining with @option{-gnatN} generates similar
10369 additional dependencies.
10371 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10372 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10373 can be used to prevent
10374 all inlining. This switch overrides all other conditions and ensures
10375 that no inlining occurs. The extra dependences resulting from
10376 @option{-gnatn} will still be active, even if
10377 this switch is used to suppress the resulting inlining actions.
10379 @cindex @option{-fno-inline-functions} (@command{gcc})
10380 Note: The @option{-fno-inline-functions} switch can be used to prevent
10381 automatic inlining of small subprograms if @option{-O3} is used.
10383 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10384 Note: The @option{-fno-inline-functions-called-once} switch
10385 can be used to prevent inlining of subprograms local to the unit
10386 and called once from within it if @option{-O1} is used.
10388 Note regarding the use of @option{-O3}: There is no difference in inlining
10389 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10390 pragma @code{Inline} assuming the use of @option{-gnatn}
10391 or @option{-gnatN} (the switches that activate inlining). If you have used
10392 pragma @code{Inline} in appropriate cases, then it is usually much better
10393 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10394 in this case only has the effect of inlining subprograms you did not
10395 think should be inlined. We often find that the use of @option{-O3} slows
10396 down code by performing excessive inlining, leading to increased instruction
10397 cache pressure from the increased code size. So the bottom line here is
10398 that you should not automatically assume that @option{-O3} is better than
10399 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10400 it actually improves performance.
10402 @node Other Optimization Switches
10403 @subsection Other Optimization Switches
10404 @cindex Optimization Switches
10406 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10407 @command{gcc} optimization switches are potentially usable. These switches
10408 have not been extensively tested with GNAT but can generally be expected
10409 to work. Examples of switches in this category are
10410 @option{-funroll-loops} and
10411 the various target-specific @option{-m} options (in particular, it has been
10412 observed that @option{-march=pentium4} can significantly improve performance
10413 on appropriate machines). For full details of these switches, see
10414 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10415 the GNU Compiler Collection (GCC)}.
10417 @node Optimization and Strict Aliasing
10418 @subsection Optimization and Strict Aliasing
10420 @cindex Strict Aliasing
10421 @cindex No_Strict_Aliasing
10424 The strong typing capabilities of Ada allow an optimizer to generate
10425 efficient code in situations where other languages would be forced to
10426 make worst case assumptions preventing such optimizations. Consider
10427 the following example:
10429 @smallexample @c ada
10432 type Int1 is new Integer;
10433 type Int2 is new Integer;
10434 type Int1A is access Int1;
10435 type Int2A is access Int2;
10442 for J in Data'Range loop
10443 if Data (J) = Int1V.all then
10444 Int2V.all := Int2V.all + 1;
10453 In this example, since the variable @code{Int1V} can only access objects
10454 of type @code{Int1}, and @code{Int2V} can only access objects of type
10455 @code{Int2}, there is no possibility that the assignment to
10456 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10457 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10458 for all iterations of the loop and avoid the extra memory reference
10459 required to dereference it each time through the loop.
10461 This kind of optimization, called strict aliasing analysis, is
10462 triggered by specifying an optimization level of @option{-O2} or
10463 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10464 when access values are involved.
10466 However, although this optimization is always correct in terms of
10467 the formal semantics of the Ada Reference Manual, difficulties can
10468 arise if features like @code{Unchecked_Conversion} are used to break
10469 the typing system. Consider the following complete program example:
10471 @smallexample @c ada
10474 type int1 is new integer;
10475 type int2 is new integer;
10476 type a1 is access int1;
10477 type a2 is access int2;
10482 function to_a2 (Input : a1) return a2;
10485 with Unchecked_Conversion;
10487 function to_a2 (Input : a1) return a2 is
10489 new Unchecked_Conversion (a1, a2);
10491 return to_a2u (Input);
10497 with Text_IO; use Text_IO;
10499 v1 : a1 := new int1;
10500 v2 : a2 := to_a2 (v1);
10504 put_line (int1'image (v1.all));
10510 This program prints out 0 in @option{-O0} or @option{-O1}
10511 mode, but it prints out 1 in @option{-O2} mode. That's
10512 because in strict aliasing mode, the compiler can and
10513 does assume that the assignment to @code{v2.all} could not
10514 affect the value of @code{v1.all}, since different types
10517 This behavior is not a case of non-conformance with the standard, since
10518 the Ada RM specifies that an unchecked conversion where the resulting
10519 bit pattern is not a correct value of the target type can result in an
10520 abnormal value and attempting to reference an abnormal value makes the
10521 execution of a program erroneous. That's the case here since the result
10522 does not point to an object of type @code{int2}. This means that the
10523 effect is entirely unpredictable.
10525 However, although that explanation may satisfy a language
10526 lawyer, in practice an applications programmer expects an
10527 unchecked conversion involving pointers to create true
10528 aliases and the behavior of printing 1 seems plain wrong.
10529 In this case, the strict aliasing optimization is unwelcome.
10531 Indeed the compiler recognizes this possibility, and the
10532 unchecked conversion generates a warning:
10535 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10536 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10537 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
10541 Unfortunately the problem is recognized when compiling the body of
10542 package @code{p2}, but the actual "bad" code is generated while
10543 compiling the body of @code{m} and this latter compilation does not see
10544 the suspicious @code{Unchecked_Conversion}.
10546 As implied by the warning message, there are approaches you can use to
10547 avoid the unwanted strict aliasing optimization in a case like this.
10549 One possibility is to simply avoid the use of @option{-O2}, but
10550 that is a bit drastic, since it throws away a number of useful
10551 optimizations that do not involve strict aliasing assumptions.
10553 A less drastic approach is to compile the program using the
10554 option @option{-fno-strict-aliasing}. Actually it is only the
10555 unit containing the dereferencing of the suspicious pointer
10556 that needs to be compiled. So in this case, if we compile
10557 unit @code{m} with this switch, then we get the expected
10558 value of zero printed. Analyzing which units might need
10559 the switch can be painful, so a more reasonable approach
10560 is to compile the entire program with options @option{-O2}
10561 and @option{-fno-strict-aliasing}. If the performance is
10562 satisfactory with this combination of options, then the
10563 advantage is that the entire issue of possible "wrong"
10564 optimization due to strict aliasing is avoided.
10566 To avoid the use of compiler switches, the configuration
10567 pragma @code{No_Strict_Aliasing} with no parameters may be
10568 used to specify that for all access types, the strict
10569 aliasing optimization should be suppressed.
10571 However, these approaches are still overkill, in that they causes
10572 all manipulations of all access values to be deoptimized. A more
10573 refined approach is to concentrate attention on the specific
10574 access type identified as problematic.
10576 First, if a careful analysis of uses of the pointer shows
10577 that there are no possible problematic references, then
10578 the warning can be suppressed by bracketing the
10579 instantiation of @code{Unchecked_Conversion} to turn
10582 @smallexample @c ada
10583 pragma Warnings (Off);
10585 new Unchecked_Conversion (a1, a2);
10586 pragma Warnings (On);
10590 Of course that approach is not appropriate for this particular
10591 example, since indeed there is a problematic reference. In this
10592 case we can take one of two other approaches.
10594 The first possibility is to move the instantiation of unchecked
10595 conversion to the unit in which the type is declared. In
10596 this example, we would move the instantiation of
10597 @code{Unchecked_Conversion} from the body of package
10598 @code{p2} to the spec of package @code{p1}. Now the
10599 warning disappears. That's because any use of the
10600 access type knows there is a suspicious unchecked
10601 conversion, and the strict aliasing optimization
10602 is automatically suppressed for the type.
10604 If it is not practical to move the unchecked conversion to the same unit
10605 in which the destination access type is declared (perhaps because the
10606 source type is not visible in that unit), you may use pragma
10607 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10608 same declarative sequence as the declaration of the access type:
10610 @smallexample @c ada
10611 type a2 is access int2;
10612 pragma No_Strict_Aliasing (a2);
10616 Here again, the compiler now knows that the strict aliasing optimization
10617 should be suppressed for any reference to type @code{a2} and the
10618 expected behavior is obtained.
10620 Finally, note that although the compiler can generate warnings for
10621 simple cases of unchecked conversions, there are tricker and more
10622 indirect ways of creating type incorrect aliases which the compiler
10623 cannot detect. Examples are the use of address overlays and unchecked
10624 conversions involving composite types containing access types as
10625 components. In such cases, no warnings are generated, but there can
10626 still be aliasing problems. One safe coding practice is to forbid the
10627 use of address clauses for type overlaying, and to allow unchecked
10628 conversion only for primitive types. This is not really a significant
10629 restriction since any possible desired effect can be achieved by
10630 unchecked conversion of access values.
10632 The aliasing analysis done in strict aliasing mode can certainly
10633 have significant benefits. We have seen cases of large scale
10634 application code where the time is increased by up to 5% by turning
10635 this optimization off. If you have code that includes significant
10636 usage of unchecked conversion, you might want to just stick with
10637 @option{-O1} and avoid the entire issue. If you get adequate
10638 performance at this level of optimization level, that's probably
10639 the safest approach. If tests show that you really need higher
10640 levels of optimization, then you can experiment with @option{-O2}
10641 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10642 has on size and speed of the code. If you really need to use
10643 @option{-O2} with strict aliasing in effect, then you should
10644 review any uses of unchecked conversion of access types,
10645 particularly if you are getting the warnings described above.
10648 @node Coverage Analysis
10649 @subsection Coverage Analysis
10652 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10653 the user to determine the distribution of execution time across a program,
10654 @pxref{Profiling} for details of usage.
10658 @node Text_IO Suggestions
10659 @section @code{Text_IO} Suggestions
10660 @cindex @code{Text_IO} and performance
10663 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10664 the requirement of maintaining page and line counts. If performance
10665 is critical, a recommendation is to use @code{Stream_IO} instead of
10666 @code{Text_IO} for volume output, since this package has less overhead.
10668 If @code{Text_IO} must be used, note that by default output to the standard
10669 output and standard error files is unbuffered (this provides better
10670 behavior when output statements are used for debugging, or if the
10671 progress of a program is observed by tracking the output, e.g. by
10672 using the Unix @command{tail -f} command to watch redirected output.
10674 If you are generating large volumes of output with @code{Text_IO} and
10675 performance is an important factor, use a designated file instead
10676 of the standard output file, or change the standard output file to
10677 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10681 @node Reducing Size of Ada Executables with gnatelim
10682 @section Reducing Size of Ada Executables with @code{gnatelim}
10686 This section describes @command{gnatelim}, a tool which detects unused
10687 subprograms and helps the compiler to create a smaller executable for your
10692 * Running gnatelim::
10693 * Processing Precompiled Libraries::
10694 * Correcting the List of Eliminate Pragmas::
10695 * Making Your Executables Smaller::
10696 * Summary of the gnatelim Usage Cycle::
10699 @node About gnatelim
10700 @subsection About @code{gnatelim}
10703 When a program shares a set of Ada
10704 packages with other programs, it may happen that this program uses
10705 only a fraction of the subprograms defined in these packages. The code
10706 created for these unused subprograms increases the size of the executable.
10708 @code{gnatelim} tracks unused subprograms in an Ada program and
10709 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10710 subprograms that are declared but never called. By placing the list of
10711 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10712 recompiling your program, you may decrease the size of its executable,
10713 because the compiler will not generate the code for 'eliminated' subprograms.
10714 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10715 information about this pragma.
10717 @code{gnatelim} needs as its input data the name of the main subprogram.
10719 If a set of source files is specified as @code{gnatelim} arguments, it
10720 treats these files as a complete set of sources making up a program to
10721 analyse, and analyses only these sources.
10723 After a full successful build of the main subprogram @code{gnatelim} can be
10724 called without specifying sources to analyse, in this case it computes
10725 the source closure of the main unit from the @file{ALI} files.
10727 The following command will create the set of @file{ALI} files needed for
10731 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10734 Note that @code{gnatelim} does not need object files.
10736 @node Running gnatelim
10737 @subsection Running @code{gnatelim}
10740 @code{gnatelim} has the following command-line interface:
10743 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
10747 @var{main_unit_name} should be a name of a source file that contains the main
10748 subprogram of a program (partition).
10750 Each @var{filename} is the name (including the extension) of a source
10751 file to process. ``Wildcards'' are allowed, and
10752 the file name may contain path information.
10754 @samp{@var{gcc_switches}} is a list of switches for
10755 @command{gcc}. They will be passed on to all compiler invocations made by
10756 @command{gnatelim} to generate the ASIS trees. Here you can provide
10757 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
10758 use the @option{-gnatec} switch to set the configuration file,
10759 use the @option{-gnat05} switch if sources should be compiled in
10762 @code{gnatelim} has the following switches:
10766 @item ^-files^/FILES^=@var{filename}
10767 @cindex @option{^-files^/FILES^} (@code{gnatelim})
10768 Take the argument source files from the specified file. This file should be an
10769 ordinary text file containing file names separated by spaces or
10770 line breaks. You can use this switch more than once in the same call to
10771 @command{gnatelim}. You also can combine this switch with
10772 an explicit list of files.
10775 @cindex @option{^-log^/LOG^} (@command{gnatelim})
10776 Duplicate all the output sent to @file{stderr} into a log file. The log file
10777 is named @file{gnatelim.log} and is located in the current directory.
10779 @item ^-log^/LOGFILE^=@var{filename}
10780 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
10781 Duplicate all the output sent to @file{stderr} into a specified log file.
10783 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
10784 @item ^--no-elim-dispatch^/NO_DISPATCH^
10785 Do not generate pragmas for dispatching operations.
10787 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
10788 @item ^-o^/OUTPUT^=@var{report_file}
10789 Put @command{gnatelim} output into a specified file. If this file already exists,
10790 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
10794 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10795 Quiet mode: by default @code{gnatelim} outputs to the standard error
10796 stream the number of program units left to be processed. This option turns
10799 @cindex @option{^-t^/TIME^} (@command{gnatelim})
10801 Print out execution time.
10803 @item ^-v^/VERBOSE^
10804 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10805 Verbose mode: @code{gnatelim} version information is printed as Ada
10806 comments to the standard output stream. Also, in addition to the number of
10807 program units left @code{gnatelim} will output the name of the current unit
10810 @item ^-wq^/WARNINGS=QUIET^
10811 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
10812 Quet warning mode - some warnings are suppressed. In particular warnings that
10813 indicate that the analysed set of sources is incomplete to make up a
10814 partition and that some subprogram bodies are missing are not generated.
10817 @node Processing Precompiled Libraries
10818 @subsection Processing Precompiled Libraries
10821 If some program uses a precompiled Ada library, it can be processed by
10822 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
10823 Eliminate pragma for a subprogram if the body of this subprogram has not
10824 been analysed, this is a typical case for subprograms from precompiled
10825 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
10826 warnings about missing source files and non-analyzed subprogram bodies
10827 that can be generated when processing precompiled Ada libraries.
10829 @node Correcting the List of Eliminate Pragmas
10830 @subsection Correcting the List of Eliminate Pragmas
10833 In some rare cases @code{gnatelim} may try to eliminate
10834 subprograms that are actually called in the program. In this case, the
10835 compiler will generate an error message of the form:
10838 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
10842 You will need to manually remove the wrong @code{Eliminate} pragmas from
10843 the configuration file indicated in the error message. You should recompile
10844 your program from scratch after that, because you need a consistent
10845 configuration file(s) during the entire compilation.
10847 @node Making Your Executables Smaller
10848 @subsection Making Your Executables Smaller
10851 In order to get a smaller executable for your program you now have to
10852 recompile the program completely with the configuration file containing
10853 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
10854 @file{gnat.adc} file located in your current directory, just do:
10857 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10861 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10862 recompile everything
10863 with the set of pragmas @code{Eliminate} that you have obtained with
10864 @command{gnatelim}).
10866 Be aware that the set of @code{Eliminate} pragmas is specific to each
10867 program. It is not recommended to merge sets of @code{Eliminate}
10868 pragmas created for different programs in one configuration file.
10870 @node Summary of the gnatelim Usage Cycle
10871 @subsection Summary of the @code{gnatelim} Usage Cycle
10874 Here is a quick summary of the steps to be taken in order to reduce
10875 the size of your executables with @code{gnatelim}. You may use
10876 other GNAT options to control the optimization level,
10877 to produce the debugging information, to set search path, etc.
10881 Create a complete set of @file{ALI} files (if the program has not been
10885 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10889 Generate a list of @code{Eliminate} pragmas in default configuration file
10890 @file{gnat.adc} in the current directory
10893 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10896 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
10901 Recompile the application
10904 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10909 @node Reducing Size of Executables with unused subprogram/data elimination
10910 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10911 @findex unused subprogram/data elimination
10914 This section describes how you can eliminate unused subprograms and data from
10915 your executable just by setting options at compilation time.
10918 * About unused subprogram/data elimination::
10919 * Compilation options::
10920 * Example of unused subprogram/data elimination::
10923 @node About unused subprogram/data elimination
10924 @subsection About unused subprogram/data elimination
10927 By default, an executable contains all code and data of its composing objects
10928 (directly linked or coming from statically linked libraries), even data or code
10929 never used by this executable.
10931 This feature will allow you to eliminate such unused code from your
10932 executable, making it smaller (in disk and in memory).
10934 This functionality is available on all Linux platforms except for the IA-64
10935 architecture and on all cross platforms using the ELF binary file format.
10936 In both cases GNU binutils version 2.16 or later are required to enable it.
10938 @node Compilation options
10939 @subsection Compilation options
10942 The operation of eliminating the unused code and data from the final executable
10943 is directly performed by the linker.
10945 In order to do this, it has to work with objects compiled with the
10947 @option{-ffunction-sections} @option{-fdata-sections}.
10948 @cindex @option{-ffunction-sections} (@command{gcc})
10949 @cindex @option{-fdata-sections} (@command{gcc})
10950 These options are usable with C and Ada files.
10951 They will place respectively each
10952 function or data in a separate section in the resulting object file.
10954 Once the objects and static libraries are created with these options, the
10955 linker can perform the dead code elimination. You can do this by setting
10956 the @option{-Wl,--gc-sections} option to gcc command or in the
10957 @option{-largs} section of @command{gnatmake}. This will perform a
10958 garbage collection of code and data never referenced.
10960 If the linker performs a partial link (@option{-r} ld linker option), then you
10961 will need to provide one or several entry point using the
10962 @option{-e} / @option{--entry} ld option.
10964 Note that objects compiled without the @option{-ffunction-sections} and
10965 @option{-fdata-sections} options can still be linked with the executable.
10966 However, no dead code elimination will be performed on those objects (they will
10969 The GNAT static library is now compiled with -ffunction-sections and
10970 -fdata-sections on some platforms. This allows you to eliminate the unused code
10971 and data of the GNAT library from your executable.
10973 @node Example of unused subprogram/data elimination
10974 @subsection Example of unused subprogram/data elimination
10977 Here is a simple example:
10979 @smallexample @c ada
10988 Used_Data : Integer;
10989 Unused_Data : Integer;
10991 procedure Used (Data : Integer);
10992 procedure Unused (Data : Integer);
10995 package body Aux is
10996 procedure Used (Data : Integer) is
11001 procedure Unused (Data : Integer) is
11003 Unused_Data := Data;
11009 @code{Unused} and @code{Unused_Data} are never referenced in this code
11010 excerpt, and hence they may be safely removed from the final executable.
11015 $ nm test | grep used
11016 020015f0 T aux__unused
11017 02005d88 B aux__unused_data
11018 020015cc T aux__used
11019 02005d84 B aux__used_data
11021 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11022 -largs -Wl,--gc-sections
11024 $ nm test | grep used
11025 02005350 T aux__used
11026 0201ffe0 B aux__used_data
11030 It can be observed that the procedure @code{Unused} and the object
11031 @code{Unused_Data} are removed by the linker when using the
11032 appropriate options.
11034 @c ********************************
11035 @node Renaming Files Using gnatchop
11036 @chapter Renaming Files Using @code{gnatchop}
11040 This chapter discusses how to handle files with multiple units by using
11041 the @code{gnatchop} utility. This utility is also useful in renaming
11042 files to meet the standard GNAT default file naming conventions.
11045 * Handling Files with Multiple Units::
11046 * Operating gnatchop in Compilation Mode::
11047 * Command Line for gnatchop::
11048 * Switches for gnatchop::
11049 * Examples of gnatchop Usage::
11052 @node Handling Files with Multiple Units
11053 @section Handling Files with Multiple Units
11056 The basic compilation model of GNAT requires that a file submitted to the
11057 compiler have only one unit and there be a strict correspondence
11058 between the file name and the unit name.
11060 The @code{gnatchop} utility allows both of these rules to be relaxed,
11061 allowing GNAT to process files which contain multiple compilation units
11062 and files with arbitrary file names. @code{gnatchop}
11063 reads the specified file and generates one or more output files,
11064 containing one unit per file. The unit and the file name correspond,
11065 as required by GNAT.
11067 If you want to permanently restructure a set of ``foreign'' files so that
11068 they match the GNAT rules, and do the remaining development using the
11069 GNAT structure, you can simply use @command{gnatchop} once, generate the
11070 new set of files and work with them from that point on.
11072 Alternatively, if you want to keep your files in the ``foreign'' format,
11073 perhaps to maintain compatibility with some other Ada compilation
11074 system, you can set up a procedure where you use @command{gnatchop} each
11075 time you compile, regarding the source files that it writes as temporary
11076 files that you throw away.
11078 Note that if your file containing multiple units starts with a byte order
11079 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11080 will each start with a copy of this BOM, meaning that they can be compiled
11081 automatically in UTF-8 mode without needing to specify an explicit encoding.
11083 @node Operating gnatchop in Compilation Mode
11084 @section Operating gnatchop in Compilation Mode
11087 The basic function of @code{gnatchop} is to take a file with multiple units
11088 and split it into separate files. The boundary between files is reasonably
11089 clear, except for the issue of comments and pragmas. In default mode, the
11090 rule is that any pragmas between units belong to the previous unit, except
11091 that configuration pragmas always belong to the following unit. Any comments
11092 belong to the following unit. These rules
11093 almost always result in the right choice of
11094 the split point without needing to mark it explicitly and most users will
11095 find this default to be what they want. In this default mode it is incorrect to
11096 submit a file containing only configuration pragmas, or one that ends in
11097 configuration pragmas, to @code{gnatchop}.
11099 However, using a special option to activate ``compilation mode'',
11101 can perform another function, which is to provide exactly the semantics
11102 required by the RM for handling of configuration pragmas in a compilation.
11103 In the absence of configuration pragmas (at the main file level), this
11104 option has no effect, but it causes such configuration pragmas to be handled
11105 in a quite different manner.
11107 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11108 only configuration pragmas, then this file is appended to the
11109 @file{gnat.adc} file in the current directory. This behavior provides
11110 the required behavior described in the RM for the actions to be taken
11111 on submitting such a file to the compiler, namely that these pragmas
11112 should apply to all subsequent compilations in the same compilation
11113 environment. Using GNAT, the current directory, possibly containing a
11114 @file{gnat.adc} file is the representation
11115 of a compilation environment. For more information on the
11116 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11118 Second, in compilation mode, if @code{gnatchop}
11119 is given a file that starts with
11120 configuration pragmas, and contains one or more units, then these
11121 configuration pragmas are prepended to each of the chopped files. This
11122 behavior provides the required behavior described in the RM for the
11123 actions to be taken on compiling such a file, namely that the pragmas
11124 apply to all units in the compilation, but not to subsequently compiled
11127 Finally, if configuration pragmas appear between units, they are appended
11128 to the previous unit. This results in the previous unit being illegal,
11129 since the compiler does not accept configuration pragmas that follow
11130 a unit. This provides the required RM behavior that forbids configuration
11131 pragmas other than those preceding the first compilation unit of a
11134 For most purposes, @code{gnatchop} will be used in default mode. The
11135 compilation mode described above is used only if you need exactly
11136 accurate behavior with respect to compilations, and you have files
11137 that contain multiple units and configuration pragmas. In this
11138 circumstance the use of @code{gnatchop} with the compilation mode
11139 switch provides the required behavior, and is for example the mode
11140 in which GNAT processes the ACVC tests.
11142 @node Command Line for gnatchop
11143 @section Command Line for @code{gnatchop}
11146 The @code{gnatchop} command has the form:
11149 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11150 @c @ovar{directory}
11151 @c Expanding @ovar macro inline (explanation in macro def comments)
11152 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11153 @r{[}@var{directory}@r{]}
11157 The only required argument is the file name of the file to be chopped.
11158 There are no restrictions on the form of this file name. The file itself
11159 contains one or more Ada units, in normal GNAT format, concatenated
11160 together. As shown, more than one file may be presented to be chopped.
11162 When run in default mode, @code{gnatchop} generates one output file in
11163 the current directory for each unit in each of the files.
11165 @var{directory}, if specified, gives the name of the directory to which
11166 the output files will be written. If it is not specified, all files are
11167 written to the current directory.
11169 For example, given a
11170 file called @file{hellofiles} containing
11172 @smallexample @c ada
11177 with Text_IO; use Text_IO;
11180 Put_Line ("Hello");
11190 $ gnatchop ^hellofiles^HELLOFILES.^
11194 generates two files in the current directory, one called
11195 @file{hello.ads} containing the single line that is the procedure spec,
11196 and the other called @file{hello.adb} containing the remaining text. The
11197 original file is not affected. The generated files can be compiled in
11201 When gnatchop is invoked on a file that is empty or that contains only empty
11202 lines and/or comments, gnatchop will not fail, but will not produce any
11205 For example, given a
11206 file called @file{toto.txt} containing
11208 @smallexample @c ada
11220 $ gnatchop ^toto.txt^TOT.TXT^
11224 will not produce any new file and will result in the following warnings:
11227 toto.txt:1:01: warning: empty file, contains no compilation units
11228 no compilation units found
11229 no source files written
11232 @node Switches for gnatchop
11233 @section Switches for @code{gnatchop}
11236 @command{gnatchop} recognizes the following switches:
11242 @cindex @option{--version} @command{gnatchop}
11243 Display Copyright and version, then exit disregarding all other options.
11246 @cindex @option{--help} @command{gnatchop}
11247 If @option{--version} was not used, display usage, then exit disregarding
11250 @item ^-c^/COMPILATION^
11251 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11252 Causes @code{gnatchop} to operate in compilation mode, in which
11253 configuration pragmas are handled according to strict RM rules. See
11254 previous section for a full description of this mode.
11257 @item -gnat@var{xxx}
11258 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11259 used to parse the given file. Not all @var{xxx} options make sense,
11260 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11261 process a source file that uses Latin-2 coding for identifiers.
11265 Causes @code{gnatchop} to generate a brief help summary to the standard
11266 output file showing usage information.
11268 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11269 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11270 Limit generated file names to the specified number @code{mm}
11272 This is useful if the
11273 resulting set of files is required to be interoperable with systems
11274 which limit the length of file names.
11276 If no value is given, or
11277 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11278 a default of 39, suitable for OpenVMS Alpha
11279 Systems, is assumed
11282 No space is allowed between the @option{-k} and the numeric value. The numeric
11283 value may be omitted in which case a default of @option{-k8},
11285 with DOS-like file systems, is used. If no @option{-k} switch
11287 there is no limit on the length of file names.
11290 @item ^-p^/PRESERVE^
11291 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11292 Causes the file ^modification^creation^ time stamp of the input file to be
11293 preserved and used for the time stamp of the output file(s). This may be
11294 useful for preserving coherency of time stamps in an environment where
11295 @code{gnatchop} is used as part of a standard build process.
11298 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11299 Causes output of informational messages indicating the set of generated
11300 files to be suppressed. Warnings and error messages are unaffected.
11302 @item ^-r^/REFERENCE^
11303 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11304 @findex Source_Reference
11305 Generate @code{Source_Reference} pragmas. Use this switch if the output
11306 files are regarded as temporary and development is to be done in terms
11307 of the original unchopped file. This switch causes
11308 @code{Source_Reference} pragmas to be inserted into each of the
11309 generated files to refers back to the original file name and line number.
11310 The result is that all error messages refer back to the original
11312 In addition, the debugging information placed into the object file (when
11313 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11315 also refers back to this original file so that tools like profilers and
11316 debuggers will give information in terms of the original unchopped file.
11318 If the original file to be chopped itself contains
11319 a @code{Source_Reference}
11320 pragma referencing a third file, then gnatchop respects
11321 this pragma, and the generated @code{Source_Reference} pragmas
11322 in the chopped file refer to the original file, with appropriate
11323 line numbers. This is particularly useful when @code{gnatchop}
11324 is used in conjunction with @code{gnatprep} to compile files that
11325 contain preprocessing statements and multiple units.
11327 @item ^-v^/VERBOSE^
11328 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11329 Causes @code{gnatchop} to operate in verbose mode. The version
11330 number and copyright notice are output, as well as exact copies of
11331 the gnat1 commands spawned to obtain the chop control information.
11333 @item ^-w^/OVERWRITE^
11334 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11335 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11336 fatal error if there is already a file with the same name as a
11337 file it would otherwise output, in other words if the files to be
11338 chopped contain duplicated units. This switch bypasses this
11339 check, and causes all but the last instance of such duplicated
11340 units to be skipped.
11343 @item --GCC=@var{xxxx}
11344 @cindex @option{--GCC=} (@code{gnatchop})
11345 Specify the path of the GNAT parser to be used. When this switch is used,
11346 no attempt is made to add the prefix to the GNAT parser executable.
11350 @node Examples of gnatchop Usage
11351 @section Examples of @code{gnatchop} Usage
11355 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11358 @item gnatchop -w hello_s.ada prerelease/files
11361 Chops the source file @file{hello_s.ada}. The output files will be
11362 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11364 files with matching names in that directory (no files in the current
11365 directory are modified).
11367 @item gnatchop ^archive^ARCHIVE.^
11368 Chops the source file @file{^archive^ARCHIVE.^}
11369 into the current directory. One
11370 useful application of @code{gnatchop} is in sending sets of sources
11371 around, for example in email messages. The required sources are simply
11372 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11374 @command{gnatchop} is used at the other end to reconstitute the original
11377 @item gnatchop file1 file2 file3 direc
11378 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11379 the resulting files in the directory @file{direc}. Note that if any units
11380 occur more than once anywhere within this set of files, an error message
11381 is generated, and no files are written. To override this check, use the
11382 @option{^-w^/OVERWRITE^} switch,
11383 in which case the last occurrence in the last file will
11384 be the one that is output, and earlier duplicate occurrences for a given
11385 unit will be skipped.
11388 @node Configuration Pragmas
11389 @chapter Configuration Pragmas
11390 @cindex Configuration pragmas
11391 @cindex Pragmas, configuration
11394 Configuration pragmas include those pragmas described as
11395 such in the Ada Reference Manual, as well as
11396 implementation-dependent pragmas that are configuration pragmas.
11397 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11398 for details on these additional GNAT-specific configuration pragmas.
11399 Most notably, the pragma @code{Source_File_Name}, which allows
11400 specifying non-default names for source files, is a configuration
11401 pragma. The following is a complete list of configuration pragmas
11402 recognized by GNAT:
11412 Assume_No_Invalid_Values
11417 Compile_Time_Warning
11419 Component_Alignment
11420 Convention_Identifier
11428 External_Name_Casing
11431 Float_Representation
11444 Priority_Specific_Dispatching
11447 Propagate_Exceptions
11450 Restricted_Run_Time
11452 Restrictions_Warnings
11454 Short_Circuit_And_Or
11456 Source_File_Name_Project
11459 Suppress_Exception_Locations
11460 Task_Dispatching_Policy
11466 Wide_Character_Encoding
11471 * Handling of Configuration Pragmas::
11472 * The Configuration Pragmas Files::
11475 @node Handling of Configuration Pragmas
11476 @section Handling of Configuration Pragmas
11478 Configuration pragmas may either appear at the start of a compilation
11479 unit, in which case they apply only to that unit, or they may apply to
11480 all compilations performed in a given compilation environment.
11482 GNAT also provides the @code{gnatchop} utility to provide an automatic
11483 way to handle configuration pragmas following the semantics for
11484 compilations (that is, files with multiple units), described in the RM.
11485 See @ref{Operating gnatchop in Compilation Mode} for details.
11486 However, for most purposes, it will be more convenient to edit the
11487 @file{gnat.adc} file that contains configuration pragmas directly,
11488 as described in the following section.
11490 @node The Configuration Pragmas Files
11491 @section The Configuration Pragmas Files
11492 @cindex @file{gnat.adc}
11495 In GNAT a compilation environment is defined by the current
11496 directory at the time that a compile command is given. This current
11497 directory is searched for a file whose name is @file{gnat.adc}. If
11498 this file is present, it is expected to contain one or more
11499 configuration pragmas that will be applied to the current compilation.
11500 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11503 Configuration pragmas may be entered into the @file{gnat.adc} file
11504 either by running @code{gnatchop} on a source file that consists only of
11505 configuration pragmas, or more conveniently by
11506 direct editing of the @file{gnat.adc} file, which is a standard format
11509 In addition to @file{gnat.adc}, additional files containing configuration
11510 pragmas may be applied to the current compilation using the switch
11511 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11512 contains only configuration pragmas. These configuration pragmas are
11513 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11514 is present and switch @option{-gnatA} is not used).
11516 It is allowed to specify several switches @option{-gnatec}, all of which
11517 will be taken into account.
11519 If you are using project file, a separate mechanism is provided using
11520 project attributes, see @ref{Specifying Configuration Pragmas} for more
11524 Of special interest to GNAT OpenVMS Alpha is the following
11525 configuration pragma:
11527 @smallexample @c ada
11529 pragma Extend_System (Aux_DEC);
11534 In the presence of this pragma, GNAT adds to the definition of the
11535 predefined package SYSTEM all the additional types and subprograms that are
11536 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11539 @node Handling Arbitrary File Naming Conventions Using gnatname
11540 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11541 @cindex Arbitrary File Naming Conventions
11544 * Arbitrary File Naming Conventions::
11545 * Running gnatname::
11546 * Switches for gnatname::
11547 * Examples of gnatname Usage::
11550 @node Arbitrary File Naming Conventions
11551 @section Arbitrary File Naming Conventions
11554 The GNAT compiler must be able to know the source file name of a compilation
11555 unit. When using the standard GNAT default file naming conventions
11556 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11557 does not need additional information.
11560 When the source file names do not follow the standard GNAT default file naming
11561 conventions, the GNAT compiler must be given additional information through
11562 a configuration pragmas file (@pxref{Configuration Pragmas})
11564 When the non-standard file naming conventions are well-defined,
11565 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11566 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11567 if the file naming conventions are irregular or arbitrary, a number
11568 of pragma @code{Source_File_Name} for individual compilation units
11570 To help maintain the correspondence between compilation unit names and
11571 source file names within the compiler,
11572 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11575 @node Running gnatname
11576 @section Running @code{gnatname}
11579 The usual form of the @code{gnatname} command is
11582 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11583 @c @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11584 @c Expanding @ovar macro inline (explanation in macro def comments)
11585 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11586 @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11590 All of the arguments are optional. If invoked without any argument,
11591 @code{gnatname} will display its usage.
11594 When used with at least one naming pattern, @code{gnatname} will attempt to
11595 find all the compilation units in files that follow at least one of the
11596 naming patterns. To find these compilation units,
11597 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11601 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11602 Each Naming Pattern is enclosed between double quotes (or single
11603 quotes on Windows).
11604 A Naming Pattern is a regular expression similar to the wildcard patterns
11605 used in file names by the Unix shells or the DOS prompt.
11608 @code{gnatname} may be called with several sections of directories/patterns.
11609 Sections are separated by switch @code{--and}. In each section, there must be
11610 at least one pattern. If no directory is specified in a section, the current
11611 directory (or the project directory is @code{-P} is used) is implied.
11612 The options other that the directory switches and the patterns apply globally
11613 even if they are in different sections.
11616 Examples of Naming Patterns are
11625 For a more complete description of the syntax of Naming Patterns,
11626 see the second kind of regular expressions described in @file{g-regexp.ads}
11627 (the ``Glob'' regular expressions).
11630 When invoked with no switch @code{-P}, @code{gnatname} will create a
11631 configuration pragmas file @file{gnat.adc} in the current working directory,
11632 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11635 @node Switches for gnatname
11636 @section Switches for @code{gnatname}
11639 Switches for @code{gnatname} must precede any specified Naming Pattern.
11642 You may specify any of the following switches to @code{gnatname}:
11648 @cindex @option{--version} @command{gnatname}
11649 Display Copyright and version, then exit disregarding all other options.
11652 @cindex @option{--help} @command{gnatname}
11653 If @option{--version} was not used, display usage, then exit disregarding
11657 Start another section of directories/patterns.
11659 @item ^-c^/CONFIG_FILE=^@file{file}
11660 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11661 Create a configuration pragmas file @file{file} (instead of the default
11664 There may be zero, one or more space between @option{-c} and
11667 @file{file} may include directory information. @file{file} must be
11668 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11669 When a switch @option{^-c^/CONFIG_FILE^} is
11670 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11672 @item ^-d^/SOURCE_DIRS=^@file{dir}
11673 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11674 Look for source files in directory @file{dir}. There may be zero, one or more
11675 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11676 When a switch @option{^-d^/SOURCE_DIRS^}
11677 is specified, the current working directory will not be searched for source
11678 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11679 or @option{^-D^/DIR_FILES^} switch.
11680 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11681 If @file{dir} is a relative path, it is relative to the directory of
11682 the configuration pragmas file specified with switch
11683 @option{^-c^/CONFIG_FILE^},
11684 or to the directory of the project file specified with switch
11685 @option{^-P^/PROJECT_FILE^} or,
11686 if neither switch @option{^-c^/CONFIG_FILE^}
11687 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11688 current working directory. The directory
11689 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11691 @item ^-D^/DIRS_FILE=^@file{file}
11692 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11693 Look for source files in all directories listed in text file @file{file}.
11694 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11696 @file{file} must be an existing, readable text file.
11697 Each nonempty line in @file{file} must be a directory.
11698 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11699 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11702 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11703 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11704 Foreign patterns. Using this switch, it is possible to add sources of languages
11705 other than Ada to the list of sources of a project file.
11706 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11709 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11712 will look for Ada units in all files with the @file{.ada} extension,
11713 and will add to the list of file for project @file{prj.gpr} the C files
11714 with extension @file{.^c^C^}.
11717 @cindex @option{^-h^/HELP^} (@code{gnatname})
11718 Output usage (help) information. The output is written to @file{stdout}.
11720 @item ^-P^/PROJECT_FILE=^@file{proj}
11721 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11722 Create or update project file @file{proj}. There may be zero, one or more space
11723 between @option{-P} and @file{proj}. @file{proj} may include directory
11724 information. @file{proj} must be writable.
11725 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11726 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11727 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11729 @item ^-v^/VERBOSE^
11730 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11731 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11732 This includes name of the file written, the name of the directories to search
11733 and, for each file in those directories whose name matches at least one of
11734 the Naming Patterns, an indication of whether the file contains a unit,
11735 and if so the name of the unit.
11737 @item ^-v -v^/VERBOSE /VERBOSE^
11738 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11739 Very Verbose mode. In addition to the output produced in verbose mode,
11740 for each file in the searched directories whose name matches none of
11741 the Naming Patterns, an indication is given that there is no match.
11743 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11744 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11745 Excluded patterns. Using this switch, it is possible to exclude some files
11746 that would match the name patterns. For example,
11748 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11751 will look for Ada units in all files with the @file{.ada} extension,
11752 except those whose names end with @file{_nt.ada}.
11756 @node Examples of gnatname Usage
11757 @section Examples of @code{gnatname} Usage
11761 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11767 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11772 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11773 and be writable. In addition, the directory
11774 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11775 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11778 Note the optional spaces after @option{-c} and @option{-d}.
11783 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11784 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11787 $ gnatname /PROJECT_FILE=[HOME.ME]PROJ
11788 /EXCLUDED_PATTERN=*_nt_body.ada
11789 /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11790 /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11794 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11795 even in conjunction with one or several switches
11796 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11797 are used in this example.
11799 @c *****************************************
11800 @c * G N A T P r o j e c t M a n a g e r *
11801 @c *****************************************
11803 @c ------ macros for projects.texi
11804 @c These macros are needed when building the gprbuild documentation, but
11805 @c should have no effect in the gnat user's guide
11807 @macro CODESAMPLE{TXT}
11815 @macro PROJECTFILE{TXT}
11819 @c simulates a newline when in a @CODESAMPLE
11830 @macro TIPHTML{TXT}
11834 @macro IMPORTANT{TXT}
11849 @include projects.texi
11851 @c *****************************************
11852 @c * Cross-referencing tools
11853 @c *****************************************
11855 @node The Cross-Referencing Tools gnatxref and gnatfind
11856 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
11861 The compiler generates cross-referencing information (unless
11862 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
11863 This information indicates where in the source each entity is declared and
11864 referenced. Note that entities in package Standard are not included, but
11865 entities in all other predefined units are included in the output.
11867 Before using any of these two tools, you need to compile successfully your
11868 application, so that GNAT gets a chance to generate the cross-referencing
11871 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
11872 information to provide the user with the capability to easily locate the
11873 declaration and references to an entity. These tools are quite similar,
11874 the difference being that @code{gnatfind} is intended for locating
11875 definitions and/or references to a specified entity or entities, whereas
11876 @code{gnatxref} is oriented to generating a full report of all
11879 To use these tools, you must not compile your application using the
11880 @option{-gnatx} switch on the @command{gnatmake} command line
11881 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
11882 information will not be generated.
11884 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
11885 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
11888 * Switches for gnatxref::
11889 * Switches for gnatfind::
11890 * Project Files for gnatxref and gnatfind::
11891 * Regular Expressions in gnatfind and gnatxref::
11892 * Examples of gnatxref Usage::
11893 * Examples of gnatfind Usage::
11896 @node Switches for gnatxref
11897 @section @code{gnatxref} Switches
11900 The command invocation for @code{gnatxref} is:
11902 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
11903 @c Expanding @ovar macro inline (explanation in macro def comments)
11904 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
11913 identifies the source files for which a report is to be generated. The
11914 ``with''ed units will be processed too. You must provide at least one file.
11916 These file names are considered to be regular expressions, so for instance
11917 specifying @file{source*.adb} is the same as giving every file in the current
11918 directory whose name starts with @file{source} and whose extension is
11921 You shouldn't specify any directory name, just base names. @command{gnatxref}
11922 and @command{gnatfind} will be able to locate these files by themselves using
11923 the source path. If you specify directories, no result is produced.
11928 The switches can be:
11932 @cindex @option{--version} @command{gnatxref}
11933 Display Copyright and version, then exit disregarding all other options.
11936 @cindex @option{--help} @command{gnatxref}
11937 If @option{--version} was not used, display usage, then exit disregarding
11940 @item ^-a^/ALL_FILES^
11941 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
11942 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
11943 the read-only files found in the library search path. Otherwise, these files
11944 will be ignored. This option can be used to protect Gnat sources or your own
11945 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
11946 much faster, and their output much smaller. Read-only here refers to access
11947 or permissions status in the file system for the current user.
11950 @cindex @option{-aIDIR} (@command{gnatxref})
11951 When looking for source files also look in directory DIR. The order in which
11952 source file search is undertaken is the same as for @command{gnatmake}.
11955 @cindex @option{-aODIR} (@command{gnatxref})
11956 When searching for library and object files, look in directory
11957 DIR. The order in which library files are searched is the same as for
11958 @command{gnatmake}.
11961 @cindex @option{-nostdinc} (@command{gnatxref})
11962 Do not look for sources in the system default directory.
11965 @cindex @option{-nostdlib} (@command{gnatxref})
11966 Do not look for library files in the system default directory.
11968 @item --ext=@var{extension}
11969 @cindex @option{--ext} (@command{gnatxref})
11970 Specify an alternate ali file extension. The default is @code{ali} and other
11971 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
11972 switch. Note that if this switch overrides the default, which means that only
11973 the new extension will be considered.
11975 @item --RTS=@var{rts-path}
11976 @cindex @option{--RTS} (@command{gnatxref})
11977 Specifies the default location of the runtime library. Same meaning as the
11978 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
11980 @item ^-d^/DERIVED_TYPES^
11981 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
11982 If this switch is set @code{gnatxref} will output the parent type
11983 reference for each matching derived types.
11985 @item ^-f^/FULL_PATHNAME^
11986 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
11987 If this switch is set, the output file names will be preceded by their
11988 directory (if the file was found in the search path). If this switch is
11989 not set, the directory will not be printed.
11991 @item ^-g^/IGNORE_LOCALS^
11992 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
11993 If this switch is set, information is output only for library-level
11994 entities, ignoring local entities. The use of this switch may accelerate
11995 @code{gnatfind} and @code{gnatxref}.
11998 @cindex @option{-IDIR} (@command{gnatxref})
11999 Equivalent to @samp{-aODIR -aIDIR}.
12002 @cindex @option{-pFILE} (@command{gnatxref})
12003 Specify a project file to use @xref{GNAT Project Manager}.
12004 If you need to use the @file{.gpr}
12005 project files, you should use gnatxref through the GNAT driver
12006 (@command{gnat xref -Pproject}).
12008 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12009 project file in the current directory.
12011 If a project file is either specified or found by the tools, then the content
12012 of the source directory and object directory lines are added as if they
12013 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
12014 and @samp{^-aO^OBJECT_SEARCH^}.
12016 Output only unused symbols. This may be really useful if you give your
12017 main compilation unit on the command line, as @code{gnatxref} will then
12018 display every unused entity and 'with'ed package.
12022 Instead of producing the default output, @code{gnatxref} will generate a
12023 @file{tags} file that can be used by vi. For examples how to use this
12024 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
12025 to the standard output, thus you will have to redirect it to a file.
12031 All these switches may be in any order on the command line, and may even
12032 appear after the file names. They need not be separated by spaces, thus
12033 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12034 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12036 @node Switches for gnatfind
12037 @section @code{gnatfind} Switches
12040 The command line for @code{gnatfind} is:
12043 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12044 @c @r{[}@var{file1} @var{file2} @dots{}]
12045 @c Expanding @ovar macro inline (explanation in macro def comments)
12046 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12047 @r{[}@var{file1} @var{file2} @dots{}@r{]}
12055 An entity will be output only if it matches the regular expression found
12056 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
12058 Omitting the pattern is equivalent to specifying @samp{*}, which
12059 will match any entity. Note that if you do not provide a pattern, you
12060 have to provide both a sourcefile and a line.
12062 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12063 for matching purposes. At the current time there is no support for
12064 8-bit codes other than Latin-1, or for wide characters in identifiers.
12067 @code{gnatfind} will look for references, bodies or declarations
12068 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
12069 and column @var{column}. See @ref{Examples of gnatfind Usage}
12070 for syntax examples.
12073 is a decimal integer identifying the line number containing
12074 the reference to the entity (or entities) to be located.
12077 is a decimal integer identifying the exact location on the
12078 line of the first character of the identifier for the
12079 entity reference. Columns are numbered from 1.
12081 @item file1 file2 @dots{}
12082 The search will be restricted to these source files. If none are given, then
12083 the search will be done for every library file in the search path.
12084 These file must appear only after the pattern or sourcefile.
12086 These file names are considered to be regular expressions, so for instance
12087 specifying @file{source*.adb} is the same as giving every file in the current
12088 directory whose name starts with @file{source} and whose extension is
12091 The location of the spec of the entity will always be displayed, even if it
12092 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{} The
12093 occurrences of the entity in the separate units of the ones given on the
12094 command line will also be displayed.
12096 Note that if you specify at least one file in this part, @code{gnatfind} may
12097 sometimes not be able to find the body of the subprograms.
12102 At least one of 'sourcefile' or 'pattern' has to be present on
12105 The following switches are available:
12109 @cindex @option{--version} @command{gnatfind}
12110 Display Copyright and version, then exit disregarding all other options.
12113 @cindex @option{--help} @command{gnatfind}
12114 If @option{--version} was not used, display usage, then exit disregarding
12117 @item ^-a^/ALL_FILES^
12118 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
12119 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12120 the read-only files found in the library search path. Otherwise, these files
12121 will be ignored. This option can be used to protect Gnat sources or your own
12122 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12123 much faster, and their output much smaller. Read-only here refers to access
12124 or permission status in the file system for the current user.
12127 @cindex @option{-aIDIR} (@command{gnatfind})
12128 When looking for source files also look in directory DIR. The order in which
12129 source file search is undertaken is the same as for @command{gnatmake}.
12132 @cindex @option{-aODIR} (@command{gnatfind})
12133 When searching for library and object files, look in directory
12134 DIR. The order in which library files are searched is the same as for
12135 @command{gnatmake}.
12138 @cindex @option{-nostdinc} (@command{gnatfind})
12139 Do not look for sources in the system default directory.
12142 @cindex @option{-nostdlib} (@command{gnatfind})
12143 Do not look for library files in the system default directory.
12145 @item --ext=@var{extension}
12146 @cindex @option{--ext} (@command{gnatfind})
12147 Specify an alternate ali file extension. The default is @code{ali} and other
12148 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12149 switch. Note that if this switch overrides the default, which means that only
12150 the new extension will be considered.
12152 @item --RTS=@var{rts-path}
12153 @cindex @option{--RTS} (@command{gnatfind})
12154 Specifies the default location of the runtime library. Same meaning as the
12155 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12157 @item ^-d^/DERIVED_TYPE_INFORMATION^
12158 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
12159 If this switch is set, then @code{gnatfind} will output the parent type
12160 reference for each matching derived types.
12162 @item ^-e^/EXPRESSIONS^
12163 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
12164 By default, @code{gnatfind} accept the simple regular expression set for
12165 @samp{pattern}. If this switch is set, then the pattern will be
12166 considered as full Unix-style regular expression.
12168 @item ^-f^/FULL_PATHNAME^
12169 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
12170 If this switch is set, the output file names will be preceded by their
12171 directory (if the file was found in the search path). If this switch is
12172 not set, the directory will not be printed.
12174 @item ^-g^/IGNORE_LOCALS^
12175 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
12176 If this switch is set, information is output only for library-level
12177 entities, ignoring local entities. The use of this switch may accelerate
12178 @code{gnatfind} and @code{gnatxref}.
12181 @cindex @option{-IDIR} (@command{gnatfind})
12182 Equivalent to @samp{-aODIR -aIDIR}.
12185 @cindex @option{-pFILE} (@command{gnatfind})
12186 Specify a project file (@pxref{GNAT Project Manager}) to use.
12187 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12188 project file in the current directory.
12190 If a project file is either specified or found by the tools, then the content
12191 of the source directory and object directory lines are added as if they
12192 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
12193 @samp{^-aO^/OBJECT_SEARCH^}.
12195 @item ^-r^/REFERENCES^
12196 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
12197 By default, @code{gnatfind} will output only the information about the
12198 declaration, body or type completion of the entities. If this switch is
12199 set, the @code{gnatfind} will locate every reference to the entities in
12200 the files specified on the command line (or in every file in the search
12201 path if no file is given on the command line).
12203 @item ^-s^/PRINT_LINES^
12204 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
12205 If this switch is set, then @code{gnatfind} will output the content
12206 of the Ada source file lines were the entity was found.
12208 @item ^-t^/TYPE_HIERARCHY^
12209 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
12210 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12211 the specified type. It act like -d option but recursively from parent
12212 type to parent type. When this switch is set it is not possible to
12213 specify more than one file.
12218 All these switches may be in any order on the command line, and may even
12219 appear after the file names. They need not be separated by spaces, thus
12220 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12221 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12223 As stated previously, gnatfind will search in every directory in the
12224 search path. You can force it to look only in the current directory if
12225 you specify @code{*} at the end of the command line.
12227 @node Project Files for gnatxref and gnatfind
12228 @section Project Files for @command{gnatxref} and @command{gnatfind}
12231 Project files allow a programmer to specify how to compile its
12232 application, where to find sources, etc. These files are used
12234 primarily by GPS, but they can also be used
12237 @code{gnatxref} and @code{gnatfind}.
12239 A project file name must end with @file{.gpr}. If a single one is
12240 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
12241 extract the information from it. If multiple project files are found, none of
12242 them is read, and you have to use the @samp{-p} switch to specify the one
12245 The following lines can be included, even though most of them have default
12246 values which can be used in most cases.
12247 The lines can be entered in any order in the file.
12248 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
12249 each line. If you have multiple instances, only the last one is taken into
12254 [default: @code{"^./^[]^"}]
12255 specifies a directory where to look for source files. Multiple @code{src_dir}
12256 lines can be specified and they will be searched in the order they
12260 [default: @code{"^./^[]^"}]
12261 specifies a directory where to look for object and library files. Multiple
12262 @code{obj_dir} lines can be specified, and they will be searched in the order
12265 @item comp_opt=SWITCHES
12266 [default: @code{""}]
12267 creates a variable which can be referred to subsequently by using
12268 the @code{$@{comp_opt@}} notation. This is intended to store the default
12269 switches given to @command{gnatmake} and @command{gcc}.
12271 @item bind_opt=SWITCHES
12272 [default: @code{""}]
12273 creates a variable which can be referred to subsequently by using
12274 the @samp{$@{bind_opt@}} notation. This is intended to store the default
12275 switches given to @command{gnatbind}.
12277 @item link_opt=SWITCHES
12278 [default: @code{""}]
12279 creates a variable which can be referred to subsequently by using
12280 the @samp{$@{link_opt@}} notation. This is intended to store the default
12281 switches given to @command{gnatlink}.
12283 @item main=EXECUTABLE
12284 [default: @code{""}]
12285 specifies the name of the executable for the application. This variable can
12286 be referred to in the following lines by using the @samp{$@{main@}} notation.
12289 @item comp_cmd=COMMAND
12290 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
12293 @item comp_cmd=COMMAND
12294 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
12296 specifies the command used to compile a single file in the application.
12299 @item make_cmd=COMMAND
12300 [default: @code{"GNAT MAKE $@{main@}
12301 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
12302 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
12303 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
12306 @item make_cmd=COMMAND
12307 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
12308 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
12309 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
12311 specifies the command used to recompile the whole application.
12313 @item run_cmd=COMMAND
12314 [default: @code{"$@{main@}"}]
12315 specifies the command used to run the application.
12317 @item debug_cmd=COMMAND
12318 [default: @code{"gdb $@{main@}"}]
12319 specifies the command used to debug the application
12324 @command{gnatxref} and @command{gnatfind} only take into account the
12325 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
12327 @node Regular Expressions in gnatfind and gnatxref
12328 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
12331 As specified in the section about @command{gnatfind}, the pattern can be a
12332 regular expression. Actually, there are to set of regular expressions
12333 which are recognized by the program:
12336 @item globbing patterns
12337 These are the most usual regular expression. They are the same that you
12338 generally used in a Unix shell command line, or in a DOS session.
12340 Here is a more formal grammar:
12347 term ::= elmt -- matches elmt
12348 term ::= elmt elmt -- concatenation (elmt then elmt)
12349 term ::= * -- any string of 0 or more characters
12350 term ::= ? -- matches any character
12351 term ::= [char @{char@}] -- matches any character listed
12352 term ::= [char - char] -- matches any character in range
12356 @item full regular expression
12357 The second set of regular expressions is much more powerful. This is the
12358 type of regular expressions recognized by utilities such a @file{grep}.
12360 The following is the form of a regular expression, expressed in Ada
12361 reference manual style BNF is as follows
12368 regexp ::= term @{| term@} -- alternation (term or term @dots{})
12370 term ::= item @{item@} -- concatenation (item then item)
12372 item ::= elmt -- match elmt
12373 item ::= elmt * -- zero or more elmt's
12374 item ::= elmt + -- one or more elmt's
12375 item ::= elmt ? -- matches elmt or nothing
12378 elmt ::= nschar -- matches given character
12379 elmt ::= [nschar @{nschar@}] -- matches any character listed
12380 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
12381 elmt ::= [char - char] -- matches chars in given range
12382 elmt ::= \ char -- matches given character
12383 elmt ::= . -- matches any single character
12384 elmt ::= ( regexp ) -- parens used for grouping
12386 char ::= any character, including special characters
12387 nschar ::= any character except ()[].*+?^^^
12391 Following are a few examples:
12395 will match any of the two strings @samp{abcde} and @samp{fghi},
12398 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
12399 @samp{abcccd}, and so on,
12402 will match any string which has only lowercase characters in it (and at
12403 least one character.
12408 @node Examples of gnatxref Usage
12409 @section Examples of @code{gnatxref} Usage
12411 @subsection General Usage
12414 For the following examples, we will consider the following units:
12416 @smallexample @c ada
12422 3: procedure Foo (B : in Integer);
12429 1: package body Main is
12430 2: procedure Foo (B : in Integer) is
12441 2: procedure Print (B : Integer);
12450 The first thing to do is to recompile your application (for instance, in
12451 that case just by doing a @samp{gnatmake main}, so that GNAT generates
12452 the cross-referencing information.
12453 You can then issue any of the following commands:
12455 @item gnatxref main.adb
12456 @code{gnatxref} generates cross-reference information for main.adb
12457 and every unit 'with'ed by main.adb.
12459 The output would be:
12467 Decl: main.ads 3:20
12468 Body: main.adb 2:20
12469 Ref: main.adb 4:13 5:13 6:19
12472 Ref: main.adb 6:8 7:8
12482 Decl: main.ads 3:15
12483 Body: main.adb 2:15
12486 Body: main.adb 1:14
12489 Ref: main.adb 6:12 7:12
12493 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
12494 its body is in main.adb, line 1, column 14 and is not referenced any where.
12496 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
12497 it referenced in main.adb, line 6 column 12 and line 7 column 12.
12499 @item gnatxref package1.adb package2.ads
12500 @code{gnatxref} will generates cross-reference information for
12501 package1.adb, package2.ads and any other package 'with'ed by any
12507 @subsection Using gnatxref with vi
12509 @code{gnatxref} can generate a tags file output, which can be used
12510 directly from @command{vi}. Note that the standard version of @command{vi}
12511 will not work properly with overloaded symbols. Consider using another
12512 free implementation of @command{vi}, such as @command{vim}.
12515 $ gnatxref -v gnatfind.adb > tags
12519 will generate the tags file for @code{gnatfind} itself (if the sources
12520 are in the search path!).
12522 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
12523 (replacing @var{entity} by whatever you are looking for), and vi will
12524 display a new file with the corresponding declaration of entity.
12527 @node Examples of gnatfind Usage
12528 @section Examples of @code{gnatfind} Usage
12532 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
12533 Find declarations for all entities xyz referenced at least once in
12534 main.adb. The references are search in every library file in the search
12537 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
12540 The output will look like:
12542 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12543 ^directory/^[directory]^main.adb:24:10: xyz <= body
12544 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12548 that is to say, one of the entities xyz found in main.adb is declared at
12549 line 12 of main.ads (and its body is in main.adb), and another one is
12550 declared at line 45 of foo.ads
12552 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
12553 This is the same command as the previous one, instead @code{gnatfind} will
12554 display the content of the Ada source file lines.
12556 The output will look like:
12559 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12561 ^directory/^[directory]^main.adb:24:10: xyz <= body
12563 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12568 This can make it easier to find exactly the location your are looking
12571 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
12572 Find references to all entities containing an x that are
12573 referenced on line 123 of main.ads.
12574 The references will be searched only in main.ads and foo.adb.
12576 @item gnatfind main.ads:123
12577 Find declarations and bodies for all entities that are referenced on
12578 line 123 of main.ads.
12580 This is the same as @code{gnatfind "*":main.adb:123}.
12582 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
12583 Find the declaration for the entity referenced at column 45 in
12584 line 123 of file main.adb in directory mydir. Note that it
12585 is usual to omit the identifier name when the column is given,
12586 since the column position identifies a unique reference.
12588 The column has to be the beginning of the identifier, and should not
12589 point to any character in the middle of the identifier.
12593 @c *********************************
12594 @node The GNAT Pretty-Printer gnatpp
12595 @chapter The GNAT Pretty-Printer @command{gnatpp}
12597 @cindex Pretty-Printer
12600 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
12601 for source reformatting / pretty-printing.
12602 It takes an Ada source file as input and generates a reformatted
12604 You can specify various style directives via switches; e.g.,
12605 identifier case conventions, rules of indentation, and comment layout.
12607 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
12608 tree for the input source and thus requires the input to be syntactically and
12609 semantically legal.
12610 If this condition is not met, @command{gnatpp} will terminate with an
12611 error message; no output file will be generated.
12613 If the source files presented to @command{gnatpp} contain
12614 preprocessing directives, then the output file will
12615 correspond to the generated source after all
12616 preprocessing is carried out. There is no way
12617 using @command{gnatpp} to obtain pretty printed files that
12618 include the preprocessing directives.
12620 If the compilation unit
12621 contained in the input source depends semantically upon units located
12622 outside the current directory, you have to provide the source search path
12623 when invoking @command{gnatpp}, if these units are contained in files with
12624 names that do not follow the GNAT file naming rules, you have to provide
12625 the configuration file describing the corresponding naming scheme;
12626 see the description of the @command{gnatpp}
12627 switches below. Another possibility is to use a project file and to
12628 call @command{gnatpp} through the @command{gnat} driver
12630 The @command{gnatpp} command has the form
12633 @c $ gnatpp @ovar{switches} @var{filename}
12634 @c Expanding @ovar macro inline (explanation in macro def comments)
12635 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
12642 @var{switches} is an optional sequence of switches defining such properties as
12643 the formatting rules, the source search path, and the destination for the
12647 @var{filename} is the name (including the extension) of the source file to
12648 reformat; ``wildcards'' or several file names on the same gnatpp command are
12649 allowed. The file name may contain path information; it does not have to
12650 follow the GNAT file naming rules
12653 @samp{@var{gcc_switches}} is a list of switches for
12654 @command{gcc}. They will be passed on to all compiler invocations made by
12655 @command{gnatelim} to generate the ASIS trees. Here you can provide
12656 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
12657 use the @option{-gnatec} switch to set the configuration file,
12658 use the @option{-gnat05} switch if sources should be compiled in
12663 * Switches for gnatpp::
12664 * Formatting Rules::
12667 @node Switches for gnatpp
12668 @section Switches for @command{gnatpp}
12671 The following subsections describe the various switches accepted by
12672 @command{gnatpp}, organized by category.
12675 You specify a switch by supplying a name and generally also a value.
12676 In many cases the values for a switch with a given name are incompatible with
12678 (for example the switch that controls the casing of a reserved word may have
12679 exactly one value: upper case, lower case, or
12680 mixed case) and thus exactly one such switch can be in effect for an
12681 invocation of @command{gnatpp}.
12682 If more than one is supplied, the last one is used.
12683 However, some values for the same switch are mutually compatible.
12684 You may supply several such switches to @command{gnatpp}, but then
12685 each must be specified in full, with both the name and the value.
12686 Abbreviated forms (the name appearing once, followed by each value) are
12688 For example, to set
12689 the alignment of the assignment delimiter both in declarations and in
12690 assignment statements, you must write @option{-A2A3}
12691 (or @option{-A2 -A3}), but not @option{-A23}.
12695 In many cases the set of options for a given qualifier are incompatible with
12696 each other (for example the qualifier that controls the casing of a reserved
12697 word may have exactly one option, which specifies either upper case, lower
12698 case, or mixed case), and thus exactly one such option can be in effect for
12699 an invocation of @command{gnatpp}.
12700 If more than one is supplied, the last one is used.
12701 However, some qualifiers have options that are mutually compatible,
12702 and then you may then supply several such options when invoking
12706 In most cases, it is obvious whether or not the
12707 ^values for a switch with a given name^options for a given qualifier^
12708 are compatible with each other.
12709 When the semantics might not be evident, the summaries below explicitly
12710 indicate the effect.
12713 * Alignment Control::
12715 * Construct Layout Control::
12716 * General Text Layout Control::
12717 * Other Formatting Options::
12718 * Setting the Source Search Path::
12719 * Output File Control::
12720 * Other gnatpp Switches::
12723 @node Alignment Control
12724 @subsection Alignment Control
12725 @cindex Alignment control in @command{gnatpp}
12728 Programs can be easier to read if certain constructs are vertically aligned.
12729 By default all alignments are set ON.
12730 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
12731 OFF, and then use one or more of the other
12732 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
12733 to activate alignment for specific constructs.
12736 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
12740 Set all alignments to ON
12743 @item ^-A0^/ALIGN=OFF^
12744 Set all alignments to OFF
12746 @item ^-A1^/ALIGN=COLONS^
12747 Align @code{:} in declarations
12749 @item ^-A2^/ALIGN=DECLARATIONS^
12750 Align @code{:=} in initializations in declarations
12752 @item ^-A3^/ALIGN=STATEMENTS^
12753 Align @code{:=} in assignment statements
12755 @item ^-A4^/ALIGN=ARROWS^
12756 Align @code{=>} in associations
12758 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
12759 Align @code{at} keywords in the component clauses in record
12760 representation clauses
12764 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
12767 @node Casing Control
12768 @subsection Casing Control
12769 @cindex Casing control in @command{gnatpp}
12772 @command{gnatpp} allows you to specify the casing for reserved words,
12773 pragma names, attribute designators and identifiers.
12774 For identifiers you may define a
12775 general rule for name casing but also override this rule
12776 via a set of dictionary files.
12778 Three types of casing are supported: lower case, upper case, and mixed case.
12779 Lower and upper case are self-explanatory (but since some letters in
12780 Latin1 and other GNAT-supported character sets
12781 exist only in lower-case form, an upper case conversion will have no
12783 ``Mixed case'' means that the first letter, and also each letter immediately
12784 following an underscore, are converted to their uppercase forms;
12785 all the other letters are converted to their lowercase forms.
12788 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
12789 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
12790 Attribute designators are lower case
12792 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
12793 Attribute designators are upper case
12795 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
12796 Attribute designators are mixed case (this is the default)
12798 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
12799 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
12800 Keywords (technically, these are known in Ada as @emph{reserved words}) are
12801 lower case (this is the default)
12803 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
12804 Keywords are upper case
12806 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
12807 @item ^-nD^/NAME_CASING=AS_DECLARED^
12808 Name casing for defining occurrences are as they appear in the source file
12809 (this is the default)
12811 @item ^-nU^/NAME_CASING=UPPER_CASE^
12812 Names are in upper case
12814 @item ^-nL^/NAME_CASING=LOWER_CASE^
12815 Names are in lower case
12817 @item ^-nM^/NAME_CASING=MIXED_CASE^
12818 Names are in mixed case
12820 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
12821 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
12822 Pragma names are lower case
12824 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
12825 Pragma names are upper case
12827 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
12828 Pragma names are mixed case (this is the default)
12830 @item ^-D@var{file}^/DICTIONARY=@var{file}^
12831 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
12832 Use @var{file} as a @emph{dictionary file} that defines
12833 the casing for a set of specified names,
12834 thereby overriding the effect on these names by
12835 any explicit or implicit
12836 ^-n^/NAME_CASING^ switch.
12837 To supply more than one dictionary file,
12838 use ^several @option{-D} switches^a list of files as options^.
12841 @option{gnatpp} implicitly uses a @emph{default dictionary file}
12842 to define the casing for the Ada predefined names and
12843 the names declared in the GNAT libraries.
12845 @item ^-D-^/SPECIFIC_CASING^
12846 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
12847 Do not use the default dictionary file;
12848 instead, use the casing
12849 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
12854 The structure of a dictionary file, and details on the conventions
12855 used in the default dictionary file, are defined in @ref{Name Casing}.
12857 The @option{^-D-^/SPECIFIC_CASING^} and
12858 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
12861 @node Construct Layout Control
12862 @subsection Construct Layout Control
12863 @cindex Layout control in @command{gnatpp}
12866 This group of @command{gnatpp} switches controls the layout of comments and
12867 complex syntactic constructs. See @ref{Formatting Comments} for details
12871 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
12872 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
12873 All the comments remain unchanged
12875 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
12876 GNAT-style comment line indentation (this is the default).
12878 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
12879 Reference-manual comment line indentation.
12881 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
12882 GNAT-style comment beginning
12884 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
12885 Reformat comment blocks
12887 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
12888 Keep unchanged special form comments
12890 Reformat comment blocks
12892 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
12893 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
12894 GNAT-style layout (this is the default)
12896 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
12899 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
12902 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
12904 All the VT characters are removed from the comment text. All the HT characters
12905 are expanded with the sequences of space characters to get to the next tab
12908 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
12909 @item ^--no-separate-is^/NO_SEPARATE_IS^
12910 Do not place the keyword @code{is} on a separate line in a subprogram body in
12911 case if the spec occupies more then one line.
12913 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
12914 @item ^--separate-label^/SEPARATE_LABEL^
12915 Place statement label(s) on a separate line, with the following statement
12918 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
12919 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
12920 Place the keyword @code{loop} in FOR and WHILE loop statements and the
12921 keyword @code{then} in IF statements on a separate line.
12923 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
12924 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
12925 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
12926 keyword @code{then} in IF statements on a separate line. This option is
12927 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
12929 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
12930 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
12931 Start each USE clause in a context clause from a separate line.
12933 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
12934 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
12935 Use a separate line for a loop or block statement name, but do not use an extra
12936 indentation level for the statement itself.
12942 The @option{-c1} and @option{-c2} switches are incompatible.
12943 The @option{-c3} and @option{-c4} switches are compatible with each other and
12944 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
12945 the other comment formatting switches.
12947 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
12952 For the @option{/COMMENTS_LAYOUT} qualifier:
12955 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
12957 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
12958 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
12962 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
12963 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
12966 @node General Text Layout Control
12967 @subsection General Text Layout Control
12970 These switches allow control over line length and indentation.
12973 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
12974 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
12975 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
12977 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
12978 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
12979 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
12981 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
12982 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
12983 Indentation level for continuation lines (relative to the line being
12984 continued), @var{nnn} from 1@dots{}9.
12986 value is one less then the (normal) indentation level, unless the
12987 indentation is set to 1 (in which case the default value for continuation
12988 line indentation is also 1)
12991 @node Other Formatting Options
12992 @subsection Other Formatting Options
12995 These switches control the inclusion of missing end/exit labels, and
12996 the indentation level in @b{case} statements.
12999 @item ^-e^/NO_MISSED_LABELS^
13000 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
13001 Do not insert missing end/exit labels. An end label is the name of
13002 a construct that may optionally be repeated at the end of the
13003 construct's declaration;
13004 e.g., the names of packages, subprograms, and tasks.
13005 An exit label is the name of a loop that may appear as target
13006 of an exit statement within the loop.
13007 By default, @command{gnatpp} inserts these end/exit labels when
13008 they are absent from the original source. This option suppresses such
13009 insertion, so that the formatted source reflects the original.
13011 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
13012 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
13013 Insert a Form Feed character after a pragma Page.
13015 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
13016 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
13017 Do not use an additional indentation level for @b{case} alternatives
13018 and variants if there are @var{nnn} or more (the default
13020 If @var{nnn} is 0, an additional indentation level is
13021 used for @b{case} alternatives and variants regardless of their number.
13024 @node Setting the Source Search Path
13025 @subsection Setting the Source Search Path
13028 To define the search path for the input source file, @command{gnatpp}
13029 uses the same switches as the GNAT compiler, with the same effects.
13032 @item ^-I^/SEARCH=^@var{dir}
13033 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
13034 The same as the corresponding gcc switch
13036 @item ^-I-^/NOCURRENT_DIRECTORY^
13037 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
13038 The same as the corresponding gcc switch
13040 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
13041 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
13042 The same as the corresponding gcc switch
13044 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
13045 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
13046 The same as the corresponding gcc switch
13050 @node Output File Control
13051 @subsection Output File Control
13054 By default the output is sent to the file whose name is obtained by appending
13055 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
13056 (if the file with this name already exists, it is unconditionally overwritten).
13057 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
13058 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
13060 The output may be redirected by the following switches:
13063 @item ^-pipe^/STANDARD_OUTPUT^
13064 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
13065 Send the output to @code{Standard_Output}
13067 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
13068 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
13069 Write the output into @var{output_file}.
13070 If @var{output_file} already exists, @command{gnatpp} terminates without
13071 reading or processing the input file.
13073 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
13074 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
13075 Write the output into @var{output_file}, overwriting the existing file
13076 (if one is present).
13078 @item ^-r^/REPLACE^
13079 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
13080 Replace the input source file with the reformatted output, and copy the
13081 original input source into the file whose name is obtained by appending the
13082 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
13083 If a file with this name already exists, @command{gnatpp} terminates without
13084 reading or processing the input file.
13086 @item ^-rf^/OVERRIDING_REPLACE^
13087 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
13088 Like @option{^-r^/REPLACE^} except that if the file with the specified name
13089 already exists, it is overwritten.
13091 @item ^-rnb^/REPLACE_NO_BACKUP^
13092 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
13093 Replace the input source file with the reformatted output without
13094 creating any backup copy of the input source.
13096 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
13097 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
13098 Specifies the format of the reformatted output file. The @var{xxx}
13099 ^string specified with the switch^option^ may be either
13101 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
13102 @item ``@option{^crlf^CRLF^}''
13103 the same as @option{^crlf^CRLF^}
13104 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
13105 @item ``@option{^lf^LF^}''
13106 the same as @option{^unix^UNIX^}
13109 @item ^-W^/RESULT_ENCODING=^@var{e}
13110 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
13111 Specify the wide character encoding method used to write the code in the
13113 @var{e} is one of the following:
13121 Upper half encoding
13123 @item ^s^SHIFT_JIS^
13133 Brackets encoding (default value)
13139 Options @option{^-pipe^/STANDARD_OUTPUT^},
13140 @option{^-o^/OUTPUT^} and
13141 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
13142 contains only one file to reformat.
13144 @option{^--eol^/END_OF_LINE^}
13146 @option{^-W^/RESULT_ENCODING^}
13147 cannot be used together
13148 with @option{^-pipe^/STANDARD_OUTPUT^} option.
13150 @node Other gnatpp Switches
13151 @subsection Other @code{gnatpp} Switches
13154 The additional @command{gnatpp} switches are defined in this subsection.
13157 @item ^-files @var{filename}^/FILES=@var{filename}^
13158 @cindex @option{^-files^/FILES^} (@code{gnatpp})
13159 Take the argument source files from the specified file. This file should be an
13160 ordinary text file containing file names separated by spaces or
13161 line breaks. You can use this switch more than once in the same call to
13162 @command{gnatpp}. You also can combine this switch with an explicit list of
13165 @item ^-v^/VERBOSE^
13166 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
13168 @command{gnatpp} generates version information and then
13169 a trace of the actions it takes to produce or obtain the ASIS tree.
13171 @item ^-w^/WARNINGS^
13172 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
13174 @command{gnatpp} generates a warning whenever it cannot provide
13175 a required layout in the result source.
13178 @node Formatting Rules
13179 @section Formatting Rules
13182 The following subsections show how @command{gnatpp} treats ``white space'',
13183 comments, program layout, and name casing.
13184 They provide the detailed descriptions of the switches shown above.
13187 * White Space and Empty Lines::
13188 * Formatting Comments::
13189 * Construct Layout::
13193 @node White Space and Empty Lines
13194 @subsection White Space and Empty Lines
13197 @command{gnatpp} does not have an option to control space characters.
13198 It will add or remove spaces according to the style illustrated by the
13199 examples in the @cite{Ada Reference Manual}.
13201 The only format effectors
13202 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
13203 that will appear in the output file are platform-specific line breaks,
13204 and also format effectors within (but not at the end of) comments.
13205 In particular, each horizontal tab character that is not inside
13206 a comment will be treated as a space and thus will appear in the
13207 output file as zero or more spaces depending on
13208 the reformatting of the line in which it appears.
13209 The only exception is a Form Feed character, which is inserted after a
13210 pragma @code{Page} when @option{-ff} is set.
13212 The output file will contain no lines with trailing ``white space'' (spaces,
13215 Empty lines in the original source are preserved
13216 only if they separate declarations or statements.
13217 In such contexts, a
13218 sequence of two or more empty lines is replaced by exactly one empty line.
13219 Note that a blank line will be removed if it separates two ``comment blocks''
13220 (a comment block is a sequence of whole-line comments).
13221 In order to preserve a visual separation between comment blocks, use an
13222 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
13223 Likewise, if for some reason you wish to have a sequence of empty lines,
13224 use a sequence of empty comments instead.
13226 @node Formatting Comments
13227 @subsection Formatting Comments
13230 Comments in Ada code are of two kinds:
13233 a @emph{whole-line comment}, which appears by itself (possibly preceded by
13234 ``white space'') on a line
13237 an @emph{end-of-line comment}, which follows some other Ada lexical element
13242 The indentation of a whole-line comment is that of either
13243 the preceding or following line in
13244 the formatted source, depending on switch settings as will be described below.
13246 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
13247 between the end of the preceding Ada lexical element and the beginning
13248 of the comment as appear in the original source,
13249 unless either the comment has to be split to
13250 satisfy the line length limitation, or else the next line contains a
13251 whole line comment that is considered a continuation of this end-of-line
13252 comment (because it starts at the same position).
13254 cases, the start of the end-of-line comment is moved right to the nearest
13255 multiple of the indentation level.
13256 This may result in a ``line overflow'' (the right-shifted comment extending
13257 beyond the maximum line length), in which case the comment is split as
13260 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
13261 (GNAT-style comment line indentation)
13262 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
13263 (reference-manual comment line indentation).
13264 With reference-manual style, a whole-line comment is indented as if it
13265 were a declaration or statement at the same place
13266 (i.e., according to the indentation of the preceding line(s)).
13267 With GNAT style, a whole-line comment that is immediately followed by an
13268 @b{if} or @b{case} statement alternative, a record variant, or the reserved
13269 word @b{begin}, is indented based on the construct that follows it.
13272 @smallexample @c ada
13284 Reference-manual indentation produces:
13286 @smallexample @c ada
13298 while GNAT-style indentation produces:
13300 @smallexample @c ada
13312 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
13313 (GNAT style comment beginning) has the following
13318 For each whole-line comment that does not end with two hyphens,
13319 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
13320 to ensure that there are at least two spaces between these hyphens and the
13321 first non-blank character of the comment.
13325 For an end-of-line comment, if in the original source the next line is a
13326 whole-line comment that starts at the same position
13327 as the end-of-line comment,
13328 then the whole-line comment (and all whole-line comments
13329 that follow it and that start at the same position)
13330 will start at this position in the output file.
13333 That is, if in the original source we have:
13335 @smallexample @c ada
13338 A := B + C; -- B must be in the range Low1..High1
13339 -- C must be in the range Low2..High2
13340 --B+C will be in the range Low1+Low2..High1+High2
13346 Then in the formatted source we get
13348 @smallexample @c ada
13351 A := B + C; -- B must be in the range Low1..High1
13352 -- C must be in the range Low2..High2
13353 -- B+C will be in the range Low1+Low2..High1+High2
13359 A comment that exceeds the line length limit will be split.
13361 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
13362 the line belongs to a reformattable block, splitting the line generates a
13363 @command{gnatpp} warning.
13364 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
13365 comments may be reformatted in typical
13366 word processor style (that is, moving words between lines and putting as
13367 many words in a line as possible).
13370 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
13371 that has a special format (that is, a character that is neither a letter nor digit
13372 not white space nor line break immediately following the leading @code{--} of
13373 the comment) should be without any change moved from the argument source
13374 into reformatted source. This switch allows to preserve comments that are used
13375 as a special marks in the code (e.g.@: SPARK annotation).
13377 @node Construct Layout
13378 @subsection Construct Layout
13381 In several cases the suggested layout in the Ada Reference Manual includes
13382 an extra level of indentation that many programmers prefer to avoid. The
13383 affected cases include:
13387 @item Record type declaration (RM 3.8)
13389 @item Record representation clause (RM 13.5.1)
13391 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
13393 @item Block statement in case if a block has a statement identifier (RM 5.6)
13397 In compact mode (when GNAT style layout or compact layout is set),
13398 the pretty printer uses one level of indentation instead
13399 of two. This is achieved in the record definition and record representation
13400 clause cases by putting the @code{record} keyword on the same line as the
13401 start of the declaration or representation clause, and in the block and loop
13402 case by putting the block or loop header on the same line as the statement
13406 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
13407 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
13408 layout on the one hand, and uncompact layout
13409 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
13410 can be illustrated by the following examples:
13414 @multitable @columnfractions .5 .5
13415 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
13418 @smallexample @c ada
13425 @smallexample @c ada
13434 @smallexample @c ada
13436 a at 0 range 0 .. 31;
13437 b at 4 range 0 .. 31;
13441 @smallexample @c ada
13444 a at 0 range 0 .. 31;
13445 b at 4 range 0 .. 31;
13450 @smallexample @c ada
13458 @smallexample @c ada
13468 @smallexample @c ada
13469 Clear : for J in 1 .. 10 loop
13474 @smallexample @c ada
13476 for J in 1 .. 10 loop
13487 GNAT style, compact layout Uncompact layout
13489 type q is record type q is
13490 a : integer; record
13491 b : integer; a : integer;
13492 end record; b : integer;
13495 for q use record for q use
13496 a at 0 range 0 .. 31; record
13497 b at 4 range 0 .. 31; a at 0 range 0 .. 31;
13498 end record; b at 4 range 0 .. 31;
13501 Block : declare Block :
13502 A : Integer := 3; declare
13503 begin A : Integer := 3;
13505 end Block; Proc (A, A);
13508 Clear : for J in 1 .. 10 loop Clear :
13509 A (J) := 0; for J in 1 .. 10 loop
13510 end loop Clear; A (J) := 0;
13517 A further difference between GNAT style layout and compact layout is that
13518 GNAT style layout inserts empty lines as separation for
13519 compound statements, return statements and bodies.
13521 Note that the layout specified by
13522 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
13523 for named block and loop statements overrides the layout defined by these
13524 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
13525 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
13526 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
13529 @subsection Name Casing
13532 @command{gnatpp} always converts the usage occurrence of a (simple) name to
13533 the same casing as the corresponding defining identifier.
13535 You control the casing for defining occurrences via the
13536 @option{^-n^/NAME_CASING^} switch.
13538 With @option{-nD} (``as declared'', which is the default),
13541 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
13543 defining occurrences appear exactly as in the source file
13544 where they are declared.
13545 The other ^values for this switch^options for this qualifier^ ---
13546 @option{^-nU^UPPER_CASE^},
13547 @option{^-nL^LOWER_CASE^},
13548 @option{^-nM^MIXED_CASE^} ---
13550 ^upper, lower, or mixed case, respectively^the corresponding casing^.
13551 If @command{gnatpp} changes the casing of a defining
13552 occurrence, it analogously changes the casing of all the
13553 usage occurrences of this name.
13555 If the defining occurrence of a name is not in the source compilation unit
13556 currently being processed by @command{gnatpp}, the casing of each reference to
13557 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
13558 switch (subject to the dictionary file mechanism described below).
13559 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
13561 casing for the defining occurrence of the name.
13563 Some names may need to be spelled with casing conventions that are not
13564 covered by the upper-, lower-, and mixed-case transformations.
13565 You can arrange correct casing by placing such names in a
13566 @emph{dictionary file},
13567 and then supplying a @option{^-D^/DICTIONARY^} switch.
13568 The casing of names from dictionary files overrides
13569 any @option{^-n^/NAME_CASING^} switch.
13571 To handle the casing of Ada predefined names and the names from GNAT libraries,
13572 @command{gnatpp} assumes a default dictionary file.
13573 The name of each predefined entity is spelled with the same casing as is used
13574 for the entity in the @cite{Ada Reference Manual}.
13575 The name of each entity in the GNAT libraries is spelled with the same casing
13576 as is used in the declaration of that entity.
13578 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
13579 default dictionary file.
13580 Instead, the casing for predefined and GNAT-defined names will be established
13581 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
13582 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
13583 will appear as just shown,
13584 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
13585 To ensure that even such names are rendered in uppercase,
13586 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
13587 (or else, less conveniently, place these names in upper case in a dictionary
13590 A dictionary file is
13591 a plain text file; each line in this file can be either a blank line
13592 (containing only space characters and ASCII.HT characters), an Ada comment
13593 line, or the specification of exactly one @emph{casing schema}.
13595 A casing schema is a string that has the following syntax:
13599 @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
13601 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
13606 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
13607 @var{identifier} lexical element and the @var{letter_or_digit} category.)
13609 The casing schema string can be followed by white space and/or an Ada-style
13610 comment; any amount of white space is allowed before the string.
13612 If a dictionary file is passed as
13614 the value of a @option{-D@var{file}} switch
13617 an option to the @option{/DICTIONARY} qualifier
13620 simple name and every identifier, @command{gnatpp} checks if the dictionary
13621 defines the casing for the name or for some of its parts (the term ``subword''
13622 is used below to denote the part of a name which is delimited by ``_'' or by
13623 the beginning or end of the word and which does not contain any ``_'' inside):
13627 if the whole name is in the dictionary, @command{gnatpp} uses for this name
13628 the casing defined by the dictionary; no subwords are checked for this word
13631 for every subword @command{gnatpp} checks if the dictionary contains the
13632 corresponding string of the form @code{*@var{simple_identifier}*},
13633 and if it does, the casing of this @var{simple_identifier} is used
13637 if the whole name does not contain any ``_'' inside, and if for this name
13638 the dictionary contains two entries - one of the form @var{identifier},
13639 and another - of the form *@var{simple_identifier}*, then the first one
13640 is applied to define the casing of this name
13643 if more than one dictionary file is passed as @command{gnatpp} switches, each
13644 dictionary adds new casing exceptions and overrides all the existing casing
13645 exceptions set by the previous dictionaries
13648 when @command{gnatpp} checks if the word or subword is in the dictionary,
13649 this check is not case sensitive
13653 For example, suppose we have the following source to reformat:
13655 @smallexample @c ada
13658 name1 : integer := 1;
13659 name4_name3_name2 : integer := 2;
13660 name2_name3_name4 : Boolean;
13663 name2_name3_name4 := name4_name3_name2 > name1;
13669 And suppose we have two dictionaries:
13686 If @command{gnatpp} is called with the following switches:
13690 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
13693 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
13698 then we will get the following name casing in the @command{gnatpp} output:
13700 @smallexample @c ada
13703 NAME1 : Integer := 1;
13704 Name4_NAME3_Name2 : Integer := 2;
13705 Name2_NAME3_Name4 : Boolean;
13708 Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
13713 @c *********************************
13714 @node The GNAT Metric Tool gnatmetric
13715 @chapter The GNAT Metric Tool @command{gnatmetric}
13717 @cindex Metric tool
13720 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
13721 for computing various program metrics.
13722 It takes an Ada source file as input and generates a file containing the
13723 metrics data as output. Various switches control which
13724 metrics are computed and output.
13726 @command{gnatmetric} generates and uses the ASIS
13727 tree for the input source and thus requires the input to be syntactically and
13728 semantically legal.
13729 If this condition is not met, @command{gnatmetric} will generate
13730 an error message; no metric information for this file will be
13731 computed and reported.
13733 If the compilation unit contained in the input source depends semantically
13734 upon units in files located outside the current directory, you have to provide
13735 the source search path when invoking @command{gnatmetric}.
13736 If it depends semantically upon units that are contained
13737 in files with names that do not follow the GNAT file naming rules, you have to
13738 provide the configuration file describing the corresponding naming scheme (see
13739 the description of the @command{gnatmetric} switches below.)
13740 Alternatively, you may use a project file and invoke @command{gnatmetric}
13741 through the @command{gnat} driver.
13743 The @command{gnatmetric} command has the form
13746 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
13747 @c Expanding @ovar macro inline (explanation in macro def comments)
13748 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
13755 @var{switches} specify the metrics to compute and define the destination for
13759 Each @var{filename} is the name (including the extension) of a source
13760 file to process. ``Wildcards'' are allowed, and
13761 the file name may contain path information.
13762 If no @var{filename} is supplied, then the @var{switches} list must contain
13764 @option{-files} switch (@pxref{Other gnatmetric Switches}).
13765 Including both a @option{-files} switch and one or more
13766 @var{filename} arguments is permitted.
13769 @samp{@var{gcc_switches}} is a list of switches for
13770 @command{gcc}. They will be passed on to all compiler invocations made by
13771 @command{gnatmetric} to generate the ASIS trees. Here you can provide
13772 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
13773 and use the @option{-gnatec} switch to set the configuration file,
13774 use the @option{-gnat05} switch if sources should be compiled in
13779 * Switches for gnatmetric::
13782 @node Switches for gnatmetric
13783 @section Switches for @command{gnatmetric}
13786 The following subsections describe the various switches accepted by
13787 @command{gnatmetric}, organized by category.
13790 * Output Files Control::
13791 * Disable Metrics For Local Units::
13792 * Specifying a set of metrics to compute::
13793 * Other gnatmetric Switches::
13794 * Generate project-wide metrics::
13797 @node Output Files Control
13798 @subsection Output File Control
13799 @cindex Output file control in @command{gnatmetric}
13802 @command{gnatmetric} has two output formats. It can generate a
13803 textual (human-readable) form, and also XML. By default only textual
13804 output is generated.
13806 When generating the output in textual form, @command{gnatmetric} creates
13807 for each Ada source file a corresponding text file
13808 containing the computed metrics, except for the case when the set of metrics
13809 specified by gnatmetric parameters consists only of metrics that are computed
13810 for the whole set of analyzed sources, but not for each Ada source.
13811 By default, this file is placed in the same directory as where the source
13812 file is located, and its name is obtained
13813 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
13816 All the output information generated in XML format is placed in a single
13817 file. By default this file is placed in the current directory and has the
13818 name ^@file{metrix.xml}^@file{METRIX$XML}^.
13820 Some of the computed metrics are summed over the units passed to
13821 @command{gnatmetric}; for example, the total number of lines of code.
13822 By default this information is sent to @file{stdout}, but a file
13823 can be specified with the @option{-og} switch.
13825 The following switches control the @command{gnatmetric} output:
13828 @cindex @option{^-x^/XML^} (@command{gnatmetric})
13830 Generate the XML output
13832 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
13834 Generate the XML output and the XML schema file that describes the structure
13835 of the XML metric report, this schema is assigned to the XML file. The schema
13836 file has the same name as the XML output file with @file{.xml} suffix replaced
13839 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
13840 @item ^-nt^/NO_TEXT^
13841 Do not generate the output in text form (implies @option{^-x^/XML^})
13843 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
13844 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
13845 Put text files with detailed metrics into @var{output_dir}
13847 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
13848 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
13849 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
13850 in the name of the output file.
13852 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
13853 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
13854 Put global metrics into @var{file_name}
13856 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
13857 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
13858 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
13860 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
13861 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
13862 Use ``short'' source file names in the output. (The @command{gnatmetric}
13863 output includes the name(s) of the Ada source file(s) from which the metrics
13864 are computed. By default each name includes the absolute path. The
13865 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
13866 to exclude all directory information from the file names that are output.)
13870 @node Disable Metrics For Local Units
13871 @subsection Disable Metrics For Local Units
13872 @cindex Disable Metrics For Local Units in @command{gnatmetric}
13875 @command{gnatmetric} relies on the GNAT compilation model @minus{}
13877 unit per one source file. It computes line metrics for the whole source
13878 file, and it also computes syntax
13879 and complexity metrics for the file's outermost unit.
13881 By default, @command{gnatmetric} will also compute all metrics for certain
13882 kinds of locally declared program units:
13886 subprogram (and generic subprogram) bodies;
13889 package (and generic package) specs and bodies;
13892 task object and type specifications and bodies;
13895 protected object and type specifications and bodies.
13899 These kinds of entities will be referred to as
13900 @emph{eligible local program units}, or simply @emph{eligible local units},
13901 @cindex Eligible local unit (for @command{gnatmetric})
13902 in the discussion below.
13904 Note that a subprogram declaration, generic instantiation,
13905 or renaming declaration only receives metrics
13906 computation when it appear as the outermost entity
13909 Suppression of metrics computation for eligible local units can be
13910 obtained via the following switch:
13913 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
13914 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
13915 Do not compute detailed metrics for eligible local program units
13919 @node Specifying a set of metrics to compute
13920 @subsection Specifying a set of metrics to compute
13923 By default all the metrics are computed and reported. The switches
13924 described in this subsection allow you to control, on an individual
13925 basis, whether metrics are computed and
13926 reported. If at least one positive metric
13927 switch is specified (that is, a switch that defines that a given
13928 metric or set of metrics is to be computed), then only
13929 explicitly specified metrics are reported.
13932 * Line Metrics Control::
13933 * Syntax Metrics Control::
13934 * Complexity Metrics Control::
13935 * Object-Oriented Metrics Control::
13938 @node Line Metrics Control
13939 @subsubsection Line Metrics Control
13940 @cindex Line metrics control in @command{gnatmetric}
13943 For any (legal) source file, and for each of its
13944 eligible local program units, @command{gnatmetric} computes the following
13949 the total number of lines;
13952 the total number of code lines (i.e., non-blank lines that are not comments)
13955 the number of comment lines
13958 the number of code lines containing end-of-line comments;
13961 the comment percentage: the ratio between the number of lines that contain
13962 comments and the number of all non-blank lines, expressed as a percentage;
13965 the number of empty lines and lines containing only space characters and/or
13966 format effectors (blank lines)
13969 the average number of code lines in subprogram bodies, task bodies, entry
13970 bodies and statement sequences in package bodies (this metric is only computed
13971 across the whole set of the analyzed units)
13976 @command{gnatmetric} sums the values of the line metrics for all the
13977 files being processed and then generates the cumulative results. The tool
13978 also computes for all the files being processed the average number of code
13981 You can use the following switches to select the specific line metrics
13982 to be computed and reported.
13985 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
13988 @cindex @option{--no-lines@var{x}}
13991 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
13992 Report all the line metrics
13994 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
13995 Do not report any of line metrics
13997 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
13998 Report the number of all lines
14000 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
14001 Do not report the number of all lines
14003 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
14004 Report the number of code lines
14006 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
14007 Do not report the number of code lines
14009 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
14010 Report the number of comment lines
14012 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
14013 Do not report the number of comment lines
14015 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
14016 Report the number of code lines containing
14017 end-of-line comments
14019 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
14020 Do not report the number of code lines containing
14021 end-of-line comments
14023 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
14024 Report the comment percentage in the program text
14026 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
14027 Do not report the comment percentage in the program text
14029 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
14030 Report the number of blank lines
14032 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
14033 Do not report the number of blank lines
14035 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
14036 Report the average number of code lines in subprogram bodies, task bodies,
14037 entry bodies and statement sequences in package bodies. The metric is computed
14038 and reported for the whole set of processed Ada sources only.
14040 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
14041 Do not report the average number of code lines in subprogram bodies,
14042 task bodies, entry bodies and statement sequences in package bodies.
14046 @node Syntax Metrics Control
14047 @subsubsection Syntax Metrics Control
14048 @cindex Syntax metrics control in @command{gnatmetric}
14051 @command{gnatmetric} computes various syntactic metrics for the
14052 outermost unit and for each eligible local unit:
14055 @item LSLOC (``Logical Source Lines Of Code'')
14056 The total number of declarations and the total number of statements
14058 @item Maximal static nesting level of inner program units
14060 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
14061 package, a task unit, a protected unit, a
14062 protected entry, a generic unit, or an explicitly declared subprogram other
14063 than an enumeration literal.''
14065 @item Maximal nesting level of composite syntactic constructs
14066 This corresponds to the notion of the
14067 maximum nesting level in the GNAT built-in style checks
14068 (@pxref{Style Checking})
14072 For the outermost unit in the file, @command{gnatmetric} additionally computes
14073 the following metrics:
14076 @item Public subprograms
14077 This metric is computed for package specs. It is the
14078 number of subprograms and generic subprograms declared in the visible
14079 part (including the visible part of nested packages, protected objects, and
14082 @item All subprograms
14083 This metric is computed for bodies and subunits. The
14084 metric is equal to a total number of subprogram bodies in the compilation
14086 Neither generic instantiations nor renamings-as-a-body nor body stubs
14087 are counted. Any subprogram body is counted, independently of its nesting
14088 level and enclosing constructs. Generic bodies and bodies of protected
14089 subprograms are counted in the same way as ``usual'' subprogram bodies.
14092 This metric is computed for package specs and
14093 generic package declarations. It is the total number of types
14094 that can be referenced from outside this compilation unit, plus the
14095 number of types from all the visible parts of all the visible generic
14096 packages. Generic formal types are not counted. Only types, not subtypes,
14100 Along with the total number of public types, the following
14101 types are counted and reported separately:
14108 Root tagged types (abstract, non-abstract, private, non-private). Type
14109 extensions are @emph{not} counted
14112 Private types (including private extensions)
14123 This metric is computed for any compilation unit. It is equal to the total
14124 number of the declarations of different types given in the compilation unit.
14125 The private and the corresponding full type declaration are counted as one
14126 type declaration. Incomplete type declarations and generic formal types
14128 No distinction is made among different kinds of types (abstract,
14129 private etc.); the total number of types is computed and reported.
14134 By default, all the syntax metrics are computed and reported. You can use the
14135 following switches to select specific syntax metrics.
14139 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
14142 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
14145 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
14146 Report all the syntax metrics
14148 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
14149 Do not report any of syntax metrics
14151 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
14152 Report the total number of declarations
14154 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
14155 Do not report the total number of declarations
14157 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
14158 Report the total number of statements
14160 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
14161 Do not report the total number of statements
14163 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
14164 Report the number of public subprograms in a compilation unit
14166 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
14167 Do not report the number of public subprograms in a compilation unit
14169 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
14170 Report the number of all the subprograms in a compilation unit
14172 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
14173 Do not report the number of all the subprograms in a compilation unit
14175 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
14176 Report the number of public types in a compilation unit
14178 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
14179 Do not report the number of public types in a compilation unit
14181 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
14182 Report the number of all the types in a compilation unit
14184 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
14185 Do not report the number of all the types in a compilation unit
14187 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
14188 Report the maximal program unit nesting level
14190 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
14191 Do not report the maximal program unit nesting level
14193 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
14194 Report the maximal construct nesting level
14196 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
14197 Do not report the maximal construct nesting level
14201 @node Complexity Metrics Control
14202 @subsubsection Complexity Metrics Control
14203 @cindex Complexity metrics control in @command{gnatmetric}
14206 For a program unit that is an executable body (a subprogram body (including
14207 generic bodies), task body, entry body or a package body containing
14208 its own statement sequence) @command{gnatmetric} computes the following
14209 complexity metrics:
14213 McCabe cyclomatic complexity;
14216 McCabe essential complexity;
14219 maximal loop nesting level
14224 The McCabe complexity metrics are defined
14225 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
14227 According to McCabe, both control statements and short-circuit control forms
14228 should be taken into account when computing cyclomatic complexity. For each
14229 body, we compute three metric values:
14233 the complexity introduced by control
14234 statements only, without taking into account short-circuit forms,
14237 the complexity introduced by short-circuit control forms only, and
14241 cyclomatic complexity, which is the sum of these two values.
14245 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
14246 the code in the exception handlers and in all the nested program units.
14248 By default, all the complexity metrics are computed and reported.
14249 For more fine-grained control you can use
14250 the following switches:
14253 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
14256 @cindex @option{--no-complexity@var{x}}
14259 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
14260 Report all the complexity metrics
14262 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
14263 Do not report any of complexity metrics
14265 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
14266 Report the McCabe Cyclomatic Complexity
14268 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
14269 Do not report the McCabe Cyclomatic Complexity
14271 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
14272 Report the Essential Complexity
14274 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
14275 Do not report the Essential Complexity
14277 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
14278 Report maximal loop nesting level
14280 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
14281 Do not report maximal loop nesting level
14283 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
14284 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
14285 task bodies, entry bodies and statement sequences in package bodies.
14286 The metric is computed and reported for whole set of processed Ada sources
14289 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
14290 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
14291 bodies, task bodies, entry bodies and statement sequences in package bodies
14293 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
14294 @item ^-ne^/NO_EXITS_AS_GOTOS^
14295 Do not consider @code{exit} statements as @code{goto}s when
14296 computing Essential Complexity
14298 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
14299 Report the extra exit points for subprogram bodies. As an exit point, this
14300 metric counts @code{return} statements and raise statements in case when the
14301 raised exception is not handled in the same body. In case of a function this
14302 metric subtracts 1 from the number of exit points, because a function body
14303 must contain at least one @code{return} statement.
14305 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
14306 Do not report the extra exit points for subprogram bodies
14310 @node Object-Oriented Metrics Control
14311 @subsubsection Object-Oriented Metrics Control
14312 @cindex Object-Oriented metrics control in @command{gnatmetric}
14315 @cindex Coupling metrics (in in @command{gnatmetric})
14316 Coupling metrics are object-oriented metrics that measure the
14317 dependencies between a given class (or a group of classes) and the
14318 ``external world'' (that is, the other classes in the program). In this
14319 subsection the term ``class'' is used in its
14320 traditional object-oriented programming sense
14321 (an instantiable module that contains data and/or method members).
14322 A @emph{category} (of classes)
14323 is a group of closely related classes that are reused and/or
14326 A class @code{K}'s @emph{efferent coupling} is the number of classes
14327 that @code{K} depends upon.
14328 A category's efferent coupling is the number of classes outside the
14329 category that the classes inside the category depend upon.
14331 A class @code{K}'s @emph{afferent coupling} is the number of classes
14332 that depend upon @code{K}.
14333 A category's afferent coupling is the number of classes outside the
14334 category that depend on classes belonging to the category.
14336 Ada's implementation of the object-oriented paradigm does not use the
14337 traditional class notion, so the definition of the coupling
14338 metrics for Ada maps the class and class category notions
14339 onto Ada constructs.
14341 For the coupling metrics, several kinds of modules -- a library package,
14342 a library generic package, and a library generic package instantiation --
14343 that define a tagged type or an interface type are
14344 considered to be a class. A category consists of a library package (or
14345 a library generic package) that defines a tagged or an interface type,
14346 together with all its descendant (generic) packages that define tagged
14347 or interface types. For any package counted as a class,
14348 its body and subunits (if any) are considered
14349 together with its spec when counting the dependencies, and coupling
14350 metrics are reported for spec units only. For dependencies
14351 between classes, the Ada semantic dependencies are considered.
14352 For coupling metrics, only dependencies on units that are considered as
14353 classes, are considered.
14355 When computing coupling metrics, @command{gnatmetric} counts only
14356 dependencies between units that are arguments of the gnatmetric call.
14357 Coupling metrics are program-wide (or project-wide) metrics, so to
14358 get a valid result, you should call @command{gnatmetric} for
14359 the whole set of sources that make up your program. It can be done
14360 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
14361 option (see See @ref{The GNAT Driver and Project Files} for details.
14363 By default, all the coupling metrics are disabled. You can use the following
14364 switches to specify the coupling metrics to be computed and reported:
14369 @cindex @option{--package@var{x}} (@command{gnatmetric})
14370 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
14371 @cindex @option{--category@var{x}} (@command{gnatmetric})
14372 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
14376 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
14379 @item ^--coupling-all^/COUPLING_METRICS=ALL^
14380 Report all the coupling metrics
14382 @item ^--no-coupling-all^/COUPLING_METRICS=NONE^
14383 Do not report any of metrics
14385 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT^
14386 Report package efferent coupling
14388 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=NOPACKAGE_EFFERENT^
14389 Do not report package efferent coupling
14391 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT^
14392 Report package afferent coupling
14394 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=NOPACKAGE_AFFERENT^
14395 Do not report package afferent coupling
14397 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT^
14398 Report category efferent coupling
14400 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=NOCATEGORY_EFFERENT^
14401 Do not report category efferent coupling
14403 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT^
14404 Report category afferent coupling
14406 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=NOCATEGORY_AFFERENT^
14407 Do not report category afferent coupling
14411 @node Other gnatmetric Switches
14412 @subsection Other @code{gnatmetric} Switches
14415 Additional @command{gnatmetric} switches are as follows:
14418 @item ^-files @var{filename}^/FILES=@var{filename}^
14419 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
14420 Take the argument source files from the specified file. This file should be an
14421 ordinary text file containing file names separated by spaces or
14422 line breaks. You can use this switch more than once in the same call to
14423 @command{gnatmetric}. You also can combine this switch with
14424 an explicit list of files.
14426 @item ^-v^/VERBOSE^
14427 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
14429 @command{gnatmetric} generates version information and then
14430 a trace of sources being processed.
14432 @item ^-dv^/DEBUG_OUTPUT^
14433 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
14435 @command{gnatmetric} generates various messages useful to understand what
14436 happens during the metrics computation
14439 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
14443 @node Generate project-wide metrics
14444 @subsection Generate project-wide metrics
14446 In order to compute metrics on all units of a given project, you can use
14447 the @command{gnat} driver along with the @option{-P} option:
14453 If the project @code{proj} depends upon other projects, you can compute
14454 the metrics on the project closure using the @option{-U} option:
14456 gnat metric -Pproj -U
14460 Finally, if not all the units are relevant to a particular main
14461 program in the project closure, you can generate metrics for the set
14462 of units needed to create a given main program (unit closure) using
14463 the @option{-U} option followed by the name of the main unit:
14465 gnat metric -Pproj -U main
14469 @c ***********************************
14470 @node File Name Krunching Using gnatkr
14471 @chapter File Name Krunching Using @code{gnatkr}
14475 This chapter discusses the method used by the compiler to shorten
14476 the default file names chosen for Ada units so that they do not
14477 exceed the maximum length permitted. It also describes the
14478 @code{gnatkr} utility that can be used to determine the result of
14479 applying this shortening.
14483 * Krunching Method::
14484 * Examples of gnatkr Usage::
14488 @section About @code{gnatkr}
14491 The default file naming rule in GNAT
14492 is that the file name must be derived from
14493 the unit name. The exact default rule is as follows:
14496 Take the unit name and replace all dots by hyphens.
14498 If such a replacement occurs in the
14499 second character position of a name, and the first character is
14500 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
14501 then replace the dot by the character
14502 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
14503 instead of a minus.
14505 The reason for this exception is to avoid clashes
14506 with the standard names for children of System, Ada, Interfaces,
14507 and GNAT, which use the prefixes
14508 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
14511 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
14512 switch of the compiler activates a ``krunching''
14513 circuit that limits file names to nn characters (where nn is a decimal
14514 integer). For example, using OpenVMS,
14515 where the maximum file name length is
14516 39, the value of nn is usually set to 39, but if you want to generate
14517 a set of files that would be usable if ported to a system with some
14518 different maximum file length, then a different value can be specified.
14519 The default value of 39 for OpenVMS need not be specified.
14521 The @code{gnatkr} utility can be used to determine the krunched name for
14522 a given file, when krunched to a specified maximum length.
14525 @section Using @code{gnatkr}
14528 The @code{gnatkr} command has the form
14532 @c $ gnatkr @var{name} @ovar{length}
14533 @c Expanding @ovar macro inline (explanation in macro def comments)
14534 $ gnatkr @var{name} @r{[}@var{length}@r{]}
14540 $ gnatkr @var{name} /COUNT=nn
14545 @var{name} is the uncrunched file name, derived from the name of the unit
14546 in the standard manner described in the previous section (i.e., in particular
14547 all dots are replaced by hyphens). The file name may or may not have an
14548 extension (defined as a suffix of the form period followed by arbitrary
14549 characters other than period). If an extension is present then it will
14550 be preserved in the output. For example, when krunching @file{hellofile.ads}
14551 to eight characters, the result will be hellofil.ads.
14553 Note: for compatibility with previous versions of @code{gnatkr} dots may
14554 appear in the name instead of hyphens, but the last dot will always be
14555 taken as the start of an extension. So if @code{gnatkr} is given an argument
14556 such as @file{Hello.World.adb} it will be treated exactly as if the first
14557 period had been a hyphen, and for example krunching to eight characters
14558 gives the result @file{hellworl.adb}.
14560 Note that the result is always all lower case (except on OpenVMS where it is
14561 all upper case). Characters of the other case are folded as required.
14563 @var{length} represents the length of the krunched name. The default
14564 when no argument is given is ^8^39^ characters. A length of zero stands for
14565 unlimited, in other words do not chop except for system files where the
14566 implied crunching length is always eight characters.
14569 The output is the krunched name. The output has an extension only if the
14570 original argument was a file name with an extension.
14572 @node Krunching Method
14573 @section Krunching Method
14576 The initial file name is determined by the name of the unit that the file
14577 contains. The name is formed by taking the full expanded name of the
14578 unit and replacing the separating dots with hyphens and
14579 using ^lowercase^uppercase^
14580 for all letters, except that a hyphen in the second character position is
14581 replaced by a ^tilde^dollar sign^ if the first character is
14582 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
14583 The extension is @code{.ads} for a
14584 spec and @code{.adb} for a body.
14585 Krunching does not affect the extension, but the file name is shortened to
14586 the specified length by following these rules:
14590 The name is divided into segments separated by hyphens, tildes or
14591 underscores and all hyphens, tildes, and underscores are
14592 eliminated. If this leaves the name short enough, we are done.
14595 If the name is too long, the longest segment is located (left-most
14596 if there are two of equal length), and shortened by dropping
14597 its last character. This is repeated until the name is short enough.
14599 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
14600 to fit the name into 8 characters as required by some operating systems.
14603 our-strings-wide_fixed 22
14604 our strings wide fixed 19
14605 our string wide fixed 18
14606 our strin wide fixed 17
14607 our stri wide fixed 16
14608 our stri wide fixe 15
14609 our str wide fixe 14
14610 our str wid fixe 13
14616 Final file name: oustwifi.adb
14620 The file names for all predefined units are always krunched to eight
14621 characters. The krunching of these predefined units uses the following
14622 special prefix replacements:
14626 replaced by @file{^a^A^-}
14629 replaced by @file{^g^G^-}
14632 replaced by @file{^i^I^-}
14635 replaced by @file{^s^S^-}
14638 These system files have a hyphen in the second character position. That
14639 is why normal user files replace such a character with a
14640 ^tilde^dollar sign^, to
14641 avoid confusion with system file names.
14643 As an example of this special rule, consider
14644 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
14647 ada-strings-wide_fixed 22
14648 a- strings wide fixed 18
14649 a- string wide fixed 17
14650 a- strin wide fixed 16
14651 a- stri wide fixed 15
14652 a- stri wide fixe 14
14653 a- str wide fixe 13
14659 Final file name: a-stwifi.adb
14663 Of course no file shortening algorithm can guarantee uniqueness over all
14664 possible unit names, and if file name krunching is used then it is your
14665 responsibility to ensure that no name clashes occur. The utility
14666 program @code{gnatkr} is supplied for conveniently determining the
14667 krunched name of a file.
14669 @node Examples of gnatkr Usage
14670 @section Examples of @code{gnatkr} Usage
14677 $ gnatkr very_long_unit_name.ads --> velounna.ads
14678 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
14679 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
14680 $ gnatkr grandparent-parent-child --> grparchi
14682 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
14683 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
14686 @node Preprocessing Using gnatprep
14687 @chapter Preprocessing Using @code{gnatprep}
14691 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
14693 Although designed for use with GNAT, @code{gnatprep} does not depend on any
14694 special GNAT features.
14695 For further discussion of conditional compilation in general, see
14696 @ref{Conditional Compilation}.
14699 * Preprocessing Symbols::
14701 * Switches for gnatprep::
14702 * Form of Definitions File::
14703 * Form of Input Text for gnatprep::
14706 @node Preprocessing Symbols
14707 @section Preprocessing Symbols
14710 Preprocessing symbols are defined in definition files and referred to in
14711 sources to be preprocessed. A Preprocessing symbol is an identifier, following
14712 normal Ada (case-insensitive) rules for its syntax, with the restriction that
14713 all characters need to be in the ASCII set (no accented letters).
14715 @node Using gnatprep
14716 @section Using @code{gnatprep}
14719 To call @code{gnatprep} use
14722 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
14723 @c Expanding @ovar macro inline (explanation in macro def comments)
14724 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
14731 is an optional sequence of switches as described in the next section.
14734 is the full name of the input file, which is an Ada source
14735 file containing preprocessor directives.
14738 is the full name of the output file, which is an Ada source
14739 in standard Ada form. When used with GNAT, this file name will
14740 normally have an ads or adb suffix.
14743 is the full name of a text file containing definitions of
14744 preprocessing symbols to be referenced by the preprocessor. This argument is
14745 optional, and can be replaced by the use of the @option{-D} switch.
14749 @node Switches for gnatprep
14750 @section Switches for @code{gnatprep}
14755 @item ^-b^/BLANK_LINES^
14756 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
14757 Causes both preprocessor lines and the lines deleted by
14758 preprocessing to be replaced by blank lines in the output source file,
14759 preserving line numbers in the output file.
14761 @item ^-c^/COMMENTS^
14762 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
14763 Causes both preprocessor lines and the lines deleted
14764 by preprocessing to be retained in the output source as comments marked
14765 with the special string @code{"--! "}. This option will result in line numbers
14766 being preserved in the output file.
14768 @item ^-C^/REPLACE_IN_COMMENTS^
14769 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
14770 Causes comments to be scanned. Normally comments are ignored by gnatprep.
14771 If this option is specified, then comments are scanned and any $symbol
14772 substitutions performed as in program text. This is particularly useful
14773 when structured comments are used (e.g., when writing programs in the
14774 SPARK dialect of Ada). Note that this switch is not available when
14775 doing integrated preprocessing (it would be useless in this context
14776 since comments are ignored by the compiler in any case).
14778 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
14779 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
14780 Defines a new preprocessing symbol, associated with value. If no value is given
14781 on the command line, then symbol is considered to be @code{True}. This switch
14782 can be used in place of a definition file.
14786 @cindex @option{/REMOVE} (@command{gnatprep})
14787 This is the default setting which causes lines deleted by preprocessing
14788 to be entirely removed from the output file.
14791 @item ^-r^/REFERENCE^
14792 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
14793 Causes a @code{Source_Reference} pragma to be generated that
14794 references the original input file, so that error messages will use
14795 the file name of this original file. The use of this switch implies
14796 that preprocessor lines are not to be removed from the file, so its
14797 use will force @option{^-b^/BLANK_LINES^} mode if
14798 @option{^-c^/COMMENTS^}
14799 has not been specified explicitly.
14801 Note that if the file to be preprocessed contains multiple units, then
14802 it will be necessary to @code{gnatchop} the output file from
14803 @code{gnatprep}. If a @code{Source_Reference} pragma is present
14804 in the preprocessed file, it will be respected by
14805 @code{gnatchop ^-r^/REFERENCE^}
14806 so that the final chopped files will correctly refer to the original
14807 input source file for @code{gnatprep}.
14809 @item ^-s^/SYMBOLS^
14810 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
14811 Causes a sorted list of symbol names and values to be
14812 listed on the standard output file.
14814 @item ^-u^/UNDEFINED^
14815 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
14816 Causes undefined symbols to be treated as having the value FALSE in the context
14817 of a preprocessor test. In the absence of this option, an undefined symbol in
14818 a @code{#if} or @code{#elsif} test will be treated as an error.
14824 Note: if neither @option{-b} nor @option{-c} is present,
14825 then preprocessor lines and
14826 deleted lines are completely removed from the output, unless -r is
14827 specified, in which case -b is assumed.
14830 @node Form of Definitions File
14831 @section Form of Definitions File
14834 The definitions file contains lines of the form
14841 where symbol is a preprocessing symbol, and value is one of the following:
14845 Empty, corresponding to a null substitution
14847 A string literal using normal Ada syntax
14849 Any sequence of characters from the set
14850 (letters, digits, period, underline).
14854 Comment lines may also appear in the definitions file, starting with
14855 the usual @code{--},
14856 and comments may be added to the definitions lines.
14858 @node Form of Input Text for gnatprep
14859 @section Form of Input Text for @code{gnatprep}
14862 The input text may contain preprocessor conditional inclusion lines,
14863 as well as general symbol substitution sequences.
14865 The preprocessor conditional inclusion commands have the form
14870 #if @i{expression} @r{[}then@r{]}
14872 #elsif @i{expression} @r{[}then@r{]}
14874 #elsif @i{expression} @r{[}then@r{]}
14885 In this example, @i{expression} is defined by the following grammar:
14887 @i{expression} ::= <symbol>
14888 @i{expression} ::= <symbol> = "<value>"
14889 @i{expression} ::= <symbol> = <symbol>
14890 @i{expression} ::= <symbol> 'Defined
14891 @i{expression} ::= not @i{expression}
14892 @i{expression} ::= @i{expression} and @i{expression}
14893 @i{expression} ::= @i{expression} or @i{expression}
14894 @i{expression} ::= @i{expression} and then @i{expression}
14895 @i{expression} ::= @i{expression} or else @i{expression}
14896 @i{expression} ::= ( @i{expression} )
14899 The following restriction exists: it is not allowed to have "and" or "or"
14900 following "not" in the same expression without parentheses. For example, this
14907 This should be one of the following:
14915 For the first test (@i{expression} ::= <symbol>) the symbol must have
14916 either the value true or false, that is to say the right-hand of the
14917 symbol definition must be one of the (case-insensitive) literals
14918 @code{True} or @code{False}. If the value is true, then the
14919 corresponding lines are included, and if the value is false, they are
14922 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
14923 the symbol has been defined in the definition file or by a @option{-D}
14924 switch on the command line. Otherwise, the test is false.
14926 The equality tests are case insensitive, as are all the preprocessor lines.
14928 If the symbol referenced is not defined in the symbol definitions file,
14929 then the effect depends on whether or not switch @option{-u}
14930 is specified. If so, then the symbol is treated as if it had the value
14931 false and the test fails. If this switch is not specified, then
14932 it is an error to reference an undefined symbol. It is also an error to
14933 reference a symbol that is defined with a value other than @code{True}
14936 The use of the @code{not} operator inverts the sense of this logical test.
14937 The @code{not} operator cannot be combined with the @code{or} or @code{and}
14938 operators, without parentheses. For example, "if not X or Y then" is not
14939 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
14941 The @code{then} keyword is optional as shown
14943 The @code{#} must be the first non-blank character on a line, but
14944 otherwise the format is free form. Spaces or tabs may appear between
14945 the @code{#} and the keyword. The keywords and the symbols are case
14946 insensitive as in normal Ada code. Comments may be used on a
14947 preprocessor line, but other than that, no other tokens may appear on a
14948 preprocessor line. Any number of @code{elsif} clauses can be present,
14949 including none at all. The @code{else} is optional, as in Ada.
14951 The @code{#} marking the start of a preprocessor line must be the first
14952 non-blank character on the line, i.e., it must be preceded only by
14953 spaces or horizontal tabs.
14955 Symbol substitution outside of preprocessor lines is obtained by using
14963 anywhere within a source line, except in a comment or within a
14964 string literal. The identifier
14965 following the @code{$} must match one of the symbols defined in the symbol
14966 definition file, and the result is to substitute the value of the
14967 symbol in place of @code{$symbol} in the output file.
14969 Note that although the substitution of strings within a string literal
14970 is not possible, it is possible to have a symbol whose defined value is
14971 a string literal. So instead of setting XYZ to @code{hello} and writing:
14974 Header : String := "$XYZ";
14978 you should set XYZ to @code{"hello"} and write:
14981 Header : String := $XYZ;
14985 and then the substitution will occur as desired.
14987 @node The GNAT Library Browser gnatls
14988 @chapter The GNAT Library Browser @code{gnatls}
14990 @cindex Library browser
14993 @code{gnatls} is a tool that outputs information about compiled
14994 units. It gives the relationship between objects, unit names and source
14995 files. It can also be used to check the source dependencies of a unit
14996 as well as various characteristics.
14998 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
14999 driver (see @ref{The GNAT Driver and Project Files}).
15003 * Switches for gnatls::
15004 * Examples of gnatls Usage::
15007 @node Running gnatls
15008 @section Running @code{gnatls}
15011 The @code{gnatls} command has the form
15014 $ gnatls switches @var{object_or_ali_file}
15018 The main argument is the list of object or @file{ali} files
15019 (@pxref{The Ada Library Information Files})
15020 for which information is requested.
15022 In normal mode, without additional option, @code{gnatls} produces a
15023 four-column listing. Each line represents information for a specific
15024 object. The first column gives the full path of the object, the second
15025 column gives the name of the principal unit in this object, the third
15026 column gives the status of the source and the fourth column gives the
15027 full path of the source representing this unit.
15028 Here is a simple example of use:
15032 ^./^[]^demo1.o demo1 DIF demo1.adb
15033 ^./^[]^demo2.o demo2 OK demo2.adb
15034 ^./^[]^hello.o h1 OK hello.adb
15035 ^./^[]^instr-child.o instr.child MOK instr-child.adb
15036 ^./^[]^instr.o instr OK instr.adb
15037 ^./^[]^tef.o tef DIF tef.adb
15038 ^./^[]^text_io_example.o text_io_example OK text_io_example.adb
15039 ^./^[]^tgef.o tgef DIF tgef.adb
15043 The first line can be interpreted as follows: the main unit which is
15045 object file @file{demo1.o} is demo1, whose main source is in
15046 @file{demo1.adb}. Furthermore, the version of the source used for the
15047 compilation of demo1 has been modified (DIF). Each source file has a status
15048 qualifier which can be:
15051 @item OK (unchanged)
15052 The version of the source file used for the compilation of the
15053 specified unit corresponds exactly to the actual source file.
15055 @item MOK (slightly modified)
15056 The version of the source file used for the compilation of the
15057 specified unit differs from the actual source file but not enough to
15058 require recompilation. If you use gnatmake with the qualifier
15059 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
15060 MOK will not be recompiled.
15062 @item DIF (modified)
15063 No version of the source found on the path corresponds to the source
15064 used to build this object.
15066 @item ??? (file not found)
15067 No source file was found for this unit.
15069 @item HID (hidden, unchanged version not first on PATH)
15070 The version of the source that corresponds exactly to the source used
15071 for compilation has been found on the path but it is hidden by another
15072 version of the same source that has been modified.
15076 @node Switches for gnatls
15077 @section Switches for @code{gnatls}
15080 @code{gnatls} recognizes the following switches:
15084 @cindex @option{--version} @command{gnatls}
15085 Display Copyright and version, then exit disregarding all other options.
15088 @cindex @option{--help} @command{gnatls}
15089 If @option{--version} was not used, display usage, then exit disregarding
15092 @item ^-a^/ALL_UNITS^
15093 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
15094 Consider all units, including those of the predefined Ada library.
15095 Especially useful with @option{^-d^/DEPENDENCIES^}.
15097 @item ^-d^/DEPENDENCIES^
15098 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
15099 List sources from which specified units depend on.
15101 @item ^-h^/OUTPUT=OPTIONS^
15102 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
15103 Output the list of options.
15105 @item ^-o^/OUTPUT=OBJECTS^
15106 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
15107 Only output information about object files.
15109 @item ^-s^/OUTPUT=SOURCES^
15110 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
15111 Only output information about source files.
15113 @item ^-u^/OUTPUT=UNITS^
15114 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
15115 Only output information about compilation units.
15117 @item ^-files^/FILES^=@var{file}
15118 @cindex @option{^-files^/FILES^} (@code{gnatls})
15119 Take as arguments the files listed in text file @var{file}.
15120 Text file @var{file} may contain empty lines that are ignored.
15121 Each nonempty line should contain the name of an existing file.
15122 Several such switches may be specified simultaneously.
15124 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15125 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
15126 @itemx ^-I^/SEARCH=^@var{dir}
15127 @itemx ^-I-^/NOCURRENT_DIRECTORY^
15129 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
15130 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
15131 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
15132 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
15133 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
15134 flags (@pxref{Switches for gnatmake}).
15136 @item --RTS=@var{rts-path}
15137 @cindex @option{--RTS} (@code{gnatls})
15138 Specifies the default location of the runtime library. Same meaning as the
15139 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15141 @item ^-v^/OUTPUT=VERBOSE^
15142 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
15143 Verbose mode. Output the complete source, object and project paths. Do not use
15144 the default column layout but instead use long format giving as much as
15145 information possible on each requested units, including special
15146 characteristics such as:
15149 @item Preelaborable
15150 The unit is preelaborable in the Ada sense.
15153 No elaboration code has been produced by the compiler for this unit.
15156 The unit is pure in the Ada sense.
15158 @item Elaborate_Body
15159 The unit contains a pragma Elaborate_Body.
15162 The unit contains a pragma Remote_Types.
15164 @item Shared_Passive
15165 The unit contains a pragma Shared_Passive.
15168 This unit is part of the predefined environment and cannot be modified
15171 @item Remote_Call_Interface
15172 The unit contains a pragma Remote_Call_Interface.
15178 @node Examples of gnatls Usage
15179 @section Example of @code{gnatls} Usage
15183 Example of using the verbose switch. Note how the source and
15184 object paths are affected by the -I switch.
15187 $ gnatls -v -I.. demo1.o
15189 GNATLS 5.03w (20041123-34)
15190 Copyright 1997-2004 Free Software Foundation, Inc.
15192 Source Search Path:
15193 <Current_Directory>
15195 /home/comar/local/adainclude/
15197 Object Search Path:
15198 <Current_Directory>
15200 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
15202 Project Search Path:
15203 <Current_Directory>
15204 /home/comar/local/lib/gnat/
15209 Kind => subprogram body
15210 Flags => No_Elab_Code
15211 Source => demo1.adb modified
15215 The following is an example of use of the dependency list.
15216 Note the use of the -s switch
15217 which gives a straight list of source files. This can be useful for
15218 building specialized scripts.
15221 $ gnatls -d demo2.o
15222 ./demo2.o demo2 OK demo2.adb
15228 $ gnatls -d -s -a demo1.o
15230 /home/comar/local/adainclude/ada.ads
15231 /home/comar/local/adainclude/a-finali.ads
15232 /home/comar/local/adainclude/a-filico.ads
15233 /home/comar/local/adainclude/a-stream.ads
15234 /home/comar/local/adainclude/a-tags.ads
15237 /home/comar/local/adainclude/gnat.ads
15238 /home/comar/local/adainclude/g-io.ads
15240 /home/comar/local/adainclude/system.ads
15241 /home/comar/local/adainclude/s-exctab.ads
15242 /home/comar/local/adainclude/s-finimp.ads
15243 /home/comar/local/adainclude/s-finroo.ads
15244 /home/comar/local/adainclude/s-secsta.ads
15245 /home/comar/local/adainclude/s-stalib.ads
15246 /home/comar/local/adainclude/s-stoele.ads
15247 /home/comar/local/adainclude/s-stratt.ads
15248 /home/comar/local/adainclude/s-tasoli.ads
15249 /home/comar/local/adainclude/s-unstyp.ads
15250 /home/comar/local/adainclude/unchconv.ads
15256 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
15258 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
15259 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
15260 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
15261 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
15262 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
15266 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
15267 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
15269 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
15270 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
15271 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
15272 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
15273 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
15274 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
15275 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
15276 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
15277 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
15278 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
15279 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
15283 @node Cleaning Up Using gnatclean
15284 @chapter Cleaning Up Using @code{gnatclean}
15286 @cindex Cleaning tool
15289 @code{gnatclean} is a tool that allows the deletion of files produced by the
15290 compiler, binder and linker, including ALI files, object files, tree files,
15291 expanded source files, library files, interface copy source files, binder
15292 generated files and executable files.
15295 * Running gnatclean::
15296 * Switches for gnatclean::
15297 @c * Examples of gnatclean Usage::
15300 @node Running gnatclean
15301 @section Running @code{gnatclean}
15304 The @code{gnatclean} command has the form:
15307 $ gnatclean switches @var{names}
15311 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
15312 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
15313 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
15316 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
15317 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
15318 the linker. In informative-only mode, specified by switch
15319 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
15320 normal mode is listed, but no file is actually deleted.
15322 @node Switches for gnatclean
15323 @section Switches for @code{gnatclean}
15326 @code{gnatclean} recognizes the following switches:
15330 @cindex @option{--version} @command{gnatclean}
15331 Display Copyright and version, then exit disregarding all other options.
15334 @cindex @option{--help} @command{gnatclean}
15335 If @option{--version} was not used, display usage, then exit disregarding
15338 @item ^--subdirs^/SUBDIRS^=subdir
15339 Actual object directory of each project file is the subdirectory subdir of the
15340 object directory specified or defauted in the project file.
15342 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
15343 By default, shared library projects are not allowed to import static library
15344 projects. When this switch is used on the command line, this restriction is
15347 @item ^-c^/COMPILER_FILES_ONLY^
15348 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
15349 Only attempt to delete the files produced by the compiler, not those produced
15350 by the binder or the linker. The files that are not to be deleted are library
15351 files, interface copy files, binder generated files and executable files.
15353 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
15354 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
15355 Indicate that ALI and object files should normally be found in directory
15358 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
15359 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
15360 When using project files, if some errors or warnings are detected during
15361 parsing and verbose mode is not in effect (no use of switch
15362 ^-v^/VERBOSE^), then error lines start with the full path name of the project
15363 file, rather than its simple file name.
15366 @cindex @option{^-h^/HELP^} (@code{gnatclean})
15367 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
15369 @item ^-n^/NODELETE^
15370 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
15371 Informative-only mode. Do not delete any files. Output the list of the files
15372 that would have been deleted if this switch was not specified.
15374 @item ^-P^/PROJECT_FILE=^@var{project}
15375 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
15376 Use project file @var{project}. Only one such switch can be used.
15377 When cleaning a project file, the files produced by the compilation of the
15378 immediate sources or inherited sources of the project files are to be
15379 deleted. This is not depending on the presence or not of executable names
15380 on the command line.
15383 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
15384 Quiet output. If there are no errors, do not output anything, except in
15385 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
15386 (switch ^-n^/NODELETE^).
15388 @item ^-r^/RECURSIVE^
15389 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
15390 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
15391 clean all imported and extended project files, recursively. If this switch
15392 is not specified, only the files related to the main project file are to be
15393 deleted. This switch has no effect if no project file is specified.
15395 @item ^-v^/VERBOSE^
15396 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
15399 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
15400 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
15401 Indicates the verbosity of the parsing of GNAT project files.
15402 @xref{Switches Related to Project Files}.
15404 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
15405 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
15406 Indicates that external variable @var{name} has the value @var{value}.
15407 The Project Manager will use this value for occurrences of
15408 @code{external(name)} when parsing the project file.
15409 @xref{Switches Related to Project Files}.
15411 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15412 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
15413 When searching for ALI and object files, look in directory
15416 @item ^-I^/SEARCH=^@var{dir}
15417 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
15418 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
15420 @item ^-I-^/NOCURRENT_DIRECTORY^
15421 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
15422 @cindex Source files, suppressing search
15423 Do not look for ALI or object files in the directory
15424 where @code{gnatclean} was invoked.
15428 @c @node Examples of gnatclean Usage
15429 @c @section Examples of @code{gnatclean} Usage
15432 @node GNAT and Libraries
15433 @chapter GNAT and Libraries
15434 @cindex Library, building, installing, using
15437 This chapter describes how to build and use libraries with GNAT, and also shows
15438 how to recompile the GNAT run-time library. You should be familiar with the
15439 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
15443 * Introduction to Libraries in GNAT::
15444 * General Ada Libraries::
15445 * Stand-alone Ada Libraries::
15446 * Rebuilding the GNAT Run-Time Library::
15449 @node Introduction to Libraries in GNAT
15450 @section Introduction to Libraries in GNAT
15453 A library is, conceptually, a collection of objects which does not have its
15454 own main thread of execution, but rather provides certain services to the
15455 applications that use it. A library can be either statically linked with the
15456 application, in which case its code is directly included in the application,
15457 or, on platforms that support it, be dynamically linked, in which case
15458 its code is shared by all applications making use of this library.
15460 GNAT supports both types of libraries.
15461 In the static case, the compiled code can be provided in different ways. The
15462 simplest approach is to provide directly the set of objects resulting from
15463 compilation of the library source files. Alternatively, you can group the
15464 objects into an archive using whatever commands are provided by the operating
15465 system. For the latter case, the objects are grouped into a shared library.
15467 In the GNAT environment, a library has three types of components:
15473 @xref{The Ada Library Information Files}.
15475 Object files, an archive or a shared library.
15479 A GNAT library may expose all its source files, which is useful for
15480 documentation purposes. Alternatively, it may expose only the units needed by
15481 an external user to make use of the library. That is to say, the specs
15482 reflecting the library services along with all the units needed to compile
15483 those specs, which can include generic bodies or any body implementing an
15484 inlined routine. In the case of @emph{stand-alone libraries} those exposed
15485 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
15487 All compilation units comprising an application, including those in a library,
15488 need to be elaborated in an order partially defined by Ada's semantics. GNAT
15489 computes the elaboration order from the @file{ALI} files and this is why they
15490 constitute a mandatory part of GNAT libraries.
15491 @emph{Stand-alone libraries} are the exception to this rule because a specific
15492 library elaboration routine is produced independently of the application(s)
15495 @node General Ada Libraries
15496 @section General Ada Libraries
15499 * Building a library::
15500 * Installing a library::
15501 * Using a library::
15504 @node Building a library
15505 @subsection Building a library
15508 The easiest way to build a library is to use the Project Manager,
15509 which supports a special type of project called a @emph{Library Project}
15510 (@pxref{Library Projects}).
15512 A project is considered a library project, when two project-level attributes
15513 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
15514 control different aspects of library configuration, additional optional
15515 project-level attributes can be specified:
15518 This attribute controls whether the library is to be static or dynamic
15520 @item Library_Version
15521 This attribute specifies the library version; this value is used
15522 during dynamic linking of shared libraries to determine if the currently
15523 installed versions of the binaries are compatible.
15525 @item Library_Options
15527 These attributes specify additional low-level options to be used during
15528 library generation, and redefine the actual application used to generate
15533 The GNAT Project Manager takes full care of the library maintenance task,
15534 including recompilation of the source files for which objects do not exist
15535 or are not up to date, assembly of the library archive, and installation of
15536 the library (i.e., copying associated source, object and @file{ALI} files
15537 to the specified location).
15539 Here is a simple library project file:
15540 @smallexample @c ada
15542 for Source_Dirs use ("src1", "src2");
15543 for Object_Dir use "obj";
15544 for Library_Name use "mylib";
15545 for Library_Dir use "lib";
15546 for Library_Kind use "dynamic";
15551 and the compilation command to build and install the library:
15553 @smallexample @c ada
15554 $ gnatmake -Pmy_lib
15558 It is not entirely trivial to perform manually all the steps required to
15559 produce a library. We recommend that you use the GNAT Project Manager
15560 for this task. In special cases where this is not desired, the necessary
15561 steps are discussed below.
15563 There are various possibilities for compiling the units that make up the
15564 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
15565 with a conventional script. For simple libraries, it is also possible to create
15566 a dummy main program which depends upon all the packages that comprise the
15567 interface of the library. This dummy main program can then be given to
15568 @command{gnatmake}, which will ensure that all necessary objects are built.
15570 After this task is accomplished, you should follow the standard procedure
15571 of the underlying operating system to produce the static or shared library.
15573 Here is an example of such a dummy program:
15574 @smallexample @c ada
15576 with My_Lib.Service1;
15577 with My_Lib.Service2;
15578 with My_Lib.Service3;
15579 procedure My_Lib_Dummy is
15587 Here are the generic commands that will build an archive or a shared library.
15590 # compiling the library
15591 $ gnatmake -c my_lib_dummy.adb
15593 # we don't need the dummy object itself
15594 $ rm my_lib_dummy.o my_lib_dummy.ali
15596 # create an archive with the remaining objects
15597 $ ar rc libmy_lib.a *.o
15598 # some systems may require "ranlib" to be run as well
15600 # or create a shared library
15601 $ gcc -shared -o libmy_lib.so *.o
15602 # some systems may require the code to have been compiled with -fPIC
15604 # remove the object files that are now in the library
15607 # Make the ALI files read-only so that gnatmake will not try to
15608 # regenerate the objects that are in the library
15613 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
15614 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
15615 be accessed by the directive @option{-l@var{xxx}} at link time.
15617 @node Installing a library
15618 @subsection Installing a library
15619 @cindex @code{ADA_PROJECT_PATH}
15620 @cindex @code{GPR_PROJECT_PATH}
15623 If you use project files, library installation is part of the library build
15624 process (@pxref{Installing a library with project files}).
15626 When project files are not an option, it is also possible, but not recommended,
15627 to install the library so that the sources needed to use the library are on the
15628 Ada source path and the ALI files & libraries be on the Ada Object path (see
15629 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
15630 administrator can place general-purpose libraries in the default compiler
15631 paths, by specifying the libraries' location in the configuration files
15632 @file{ada_source_path} and @file{ada_object_path}. These configuration files
15633 must be located in the GNAT installation tree at the same place as the gcc spec
15634 file. The location of the gcc spec file can be determined as follows:
15640 The configuration files mentioned above have a simple format: each line
15641 must contain one unique directory name.
15642 Those names are added to the corresponding path
15643 in their order of appearance in the file. The names can be either absolute
15644 or relative; in the latter case, they are relative to where theses files
15647 The files @file{ada_source_path} and @file{ada_object_path} might not be
15649 GNAT installation, in which case, GNAT will look for its run-time library in
15650 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
15651 objects and @file{ALI} files). When the files exist, the compiler does not
15652 look in @file{adainclude} and @file{adalib}, and thus the
15653 @file{ada_source_path} file
15654 must contain the location for the GNAT run-time sources (which can simply
15655 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
15656 contain the location for the GNAT run-time objects (which can simply
15659 You can also specify a new default path to the run-time library at compilation
15660 time with the switch @option{--RTS=rts-path}. You can thus choose / change
15661 the run-time library you want your program to be compiled with. This switch is
15662 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
15663 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
15665 It is possible to install a library before or after the standard GNAT
15666 library, by reordering the lines in the configuration files. In general, a
15667 library must be installed before the GNAT library if it redefines
15670 @node Using a library
15671 @subsection Using a library
15673 @noindent Once again, the project facility greatly simplifies the use of
15674 libraries. In this context, using a library is just a matter of adding a
15675 @code{with} clause in the user project. For instance, to make use of the
15676 library @code{My_Lib} shown in examples in earlier sections, you can
15679 @smallexample @c projectfile
15686 Even if you have a third-party, non-Ada library, you can still use GNAT's
15687 Project Manager facility to provide a wrapper for it. For example, the
15688 following project, when @code{with}ed by your main project, will link with the
15689 third-party library @file{liba.a}:
15691 @smallexample @c projectfile
15694 for Externally_Built use "true";
15695 for Source_Files use ();
15696 for Library_Dir use "lib";
15697 for Library_Name use "a";
15698 for Library_Kind use "static";
15702 This is an alternative to the use of @code{pragma Linker_Options}. It is
15703 especially interesting in the context of systems with several interdependent
15704 static libraries where finding a proper linker order is not easy and best be
15705 left to the tools having visibility over project dependence information.
15708 In order to use an Ada library manually, you need to make sure that this
15709 library is on both your source and object path
15710 (see @ref{Search Paths and the Run-Time Library (RTL)}
15711 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
15712 in an archive or a shared library, you need to specify the desired
15713 library at link time.
15715 For example, you can use the library @file{mylib} installed in
15716 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
15719 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
15724 This can be expressed more simply:
15729 when the following conditions are met:
15732 @file{/dir/my_lib_src} has been added by the user to the environment
15733 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
15734 @file{ada_source_path}
15736 @file{/dir/my_lib_obj} has been added by the user to the environment
15737 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
15738 @file{ada_object_path}
15740 a pragma @code{Linker_Options} has been added to one of the sources.
15743 @smallexample @c ada
15744 pragma Linker_Options ("-lmy_lib");
15748 @node Stand-alone Ada Libraries
15749 @section Stand-alone Ada Libraries
15750 @cindex Stand-alone library, building, using
15753 * Introduction to Stand-alone Libraries::
15754 * Building a Stand-alone Library::
15755 * Creating a Stand-alone Library to be used in a non-Ada context::
15756 * Restrictions in Stand-alone Libraries::
15759 @node Introduction to Stand-alone Libraries
15760 @subsection Introduction to Stand-alone Libraries
15763 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
15765 elaborate the Ada units that are included in the library. In contrast with
15766 an ordinary library, which consists of all sources, objects and @file{ALI}
15768 library, a SAL may specify a restricted subset of compilation units
15769 to serve as a library interface. In this case, the fully
15770 self-sufficient set of files will normally consist of an objects
15771 archive, the sources of interface units' specs, and the @file{ALI}
15772 files of interface units.
15773 If an interface spec contains a generic unit or an inlined subprogram,
15775 source must also be provided; if the units that must be provided in the source
15776 form depend on other units, the source and @file{ALI} files of those must
15779 The main purpose of a SAL is to minimize the recompilation overhead of client
15780 applications when a new version of the library is installed. Specifically,
15781 if the interface sources have not changed, client applications do not need to
15782 be recompiled. If, furthermore, a SAL is provided in the shared form and its
15783 version, controlled by @code{Library_Version} attribute, is not changed,
15784 then the clients do not need to be relinked.
15786 SALs also allow the library providers to minimize the amount of library source
15787 text exposed to the clients. Such ``information hiding'' might be useful or
15788 necessary for various reasons.
15790 Stand-alone libraries are also well suited to be used in an executable whose
15791 main routine is not written in Ada.
15793 @node Building a Stand-alone Library
15794 @subsection Building a Stand-alone Library
15797 GNAT's Project facility provides a simple way of building and installing
15798 stand-alone libraries; see @ref{Stand-alone Library Projects}.
15799 To be a Stand-alone Library Project, in addition to the two attributes
15800 that make a project a Library Project (@code{Library_Name} and
15801 @code{Library_Dir}; see @ref{Library Projects}), the attribute
15802 @code{Library_Interface} must be defined. For example:
15804 @smallexample @c projectfile
15806 for Library_Dir use "lib_dir";
15807 for Library_Name use "dummy";
15808 for Library_Interface use ("int1", "int1.child");
15813 Attribute @code{Library_Interface} has a non-empty string list value,
15814 each string in the list designating a unit contained in an immediate source
15815 of the project file.
15817 When a Stand-alone Library is built, first the binder is invoked to build
15818 a package whose name depends on the library name
15819 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
15820 This binder-generated package includes initialization and
15821 finalization procedures whose
15822 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
15824 above). The object corresponding to this package is included in the library.
15826 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
15827 calling of these procedures if a static SAL is built, or if a shared SAL
15829 with the project-level attribute @code{Library_Auto_Init} set to
15832 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
15833 (those that are listed in attribute @code{Library_Interface}) are copied to
15834 the Library Directory. As a consequence, only the Interface Units may be
15835 imported from Ada units outside of the library. If other units are imported,
15836 the binding phase will fail.
15838 The attribute @code{Library_Src_Dir} may be specified for a
15839 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
15840 single string value. Its value must be the path (absolute or relative to the
15841 project directory) of an existing directory. This directory cannot be the
15842 object directory or one of the source directories, but it can be the same as
15843 the library directory. The sources of the Interface
15844 Units of the library that are needed by an Ada client of the library will be
15845 copied to the designated directory, called the Interface Copy directory.
15846 These sources include the specs of the Interface Units, but they may also
15847 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
15848 are used, or when there is a generic unit in the spec. Before the sources
15849 are copied to the Interface Copy directory, an attempt is made to delete all
15850 files in the Interface Copy directory.
15852 Building stand-alone libraries by hand is somewhat tedious, but for those
15853 occasions when it is necessary here are the steps that you need to perform:
15856 Compile all library sources.
15859 Invoke the binder with the switch @option{-n} (No Ada main program),
15860 with all the @file{ALI} files of the interfaces, and
15861 with the switch @option{-L} to give specific names to the @code{init}
15862 and @code{final} procedures. For example:
15864 gnatbind -n int1.ali int2.ali -Lsal1
15868 Compile the binder generated file:
15874 Link the dynamic library with all the necessary object files,
15875 indicating to the linker the names of the @code{init} (and possibly
15876 @code{final}) procedures for automatic initialization (and finalization).
15877 The built library should be placed in a directory different from
15878 the object directory.
15881 Copy the @code{ALI} files of the interface to the library directory,
15882 add in this copy an indication that it is an interface to a SAL
15883 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
15884 with letter ``P'') and make the modified copy of the @file{ALI} file
15889 Using SALs is not different from using other libraries
15890 (see @ref{Using a library}).
15892 @node Creating a Stand-alone Library to be used in a non-Ada context
15893 @subsection Creating a Stand-alone Library to be used in a non-Ada context
15896 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
15899 The only extra step required is to ensure that library interface subprograms
15900 are compatible with the main program, by means of @code{pragma Export}
15901 or @code{pragma Convention}.
15903 Here is an example of simple library interface for use with C main program:
15905 @smallexample @c ada
15906 package My_Package is
15908 procedure Do_Something;
15909 pragma Export (C, Do_Something, "do_something");
15911 procedure Do_Something_Else;
15912 pragma Export (C, Do_Something_Else, "do_something_else");
15918 On the foreign language side, you must provide a ``foreign'' view of the
15919 library interface; remember that it should contain elaboration routines in
15920 addition to interface subprograms.
15922 The example below shows the content of @code{mylib_interface.h} (note
15923 that there is no rule for the naming of this file, any name can be used)
15925 /* the library elaboration procedure */
15926 extern void mylibinit (void);
15928 /* the library finalization procedure */
15929 extern void mylibfinal (void);
15931 /* the interface exported by the library */
15932 extern void do_something (void);
15933 extern void do_something_else (void);
15937 Libraries built as explained above can be used from any program, provided
15938 that the elaboration procedures (named @code{mylibinit} in the previous
15939 example) are called before the library services are used. Any number of
15940 libraries can be used simultaneously, as long as the elaboration
15941 procedure of each library is called.
15943 Below is an example of a C program that uses the @code{mylib} library.
15946 #include "mylib_interface.h"
15951 /* First, elaborate the library before using it */
15954 /* Main program, using the library exported entities */
15956 do_something_else ();
15958 /* Library finalization at the end of the program */
15965 Note that invoking any library finalization procedure generated by
15966 @code{gnatbind} shuts down the Ada run-time environment.
15968 finalization of all Ada libraries must be performed at the end of the program.
15969 No call to these libraries or to the Ada run-time library should be made
15970 after the finalization phase.
15972 @node Restrictions in Stand-alone Libraries
15973 @subsection Restrictions in Stand-alone Libraries
15976 The pragmas listed below should be used with caution inside libraries,
15977 as they can create incompatibilities with other Ada libraries:
15979 @item pragma @code{Locking_Policy}
15980 @item pragma @code{Queuing_Policy}
15981 @item pragma @code{Task_Dispatching_Policy}
15982 @item pragma @code{Unreserve_All_Interrupts}
15986 When using a library that contains such pragmas, the user must make sure
15987 that all libraries use the same pragmas with the same values. Otherwise,
15988 @code{Program_Error} will
15989 be raised during the elaboration of the conflicting
15990 libraries. The usage of these pragmas and its consequences for the user
15991 should therefore be well documented.
15993 Similarly, the traceback in the exception occurrence mechanism should be
15994 enabled or disabled in a consistent manner across all libraries.
15995 Otherwise, Program_Error will be raised during the elaboration of the
15996 conflicting libraries.
15998 If the @code{Version} or @code{Body_Version}
15999 attributes are used inside a library, then you need to
16000 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
16001 libraries, so that version identifiers can be properly computed.
16002 In practice these attributes are rarely used, so this is unlikely
16003 to be a consideration.
16005 @node Rebuilding the GNAT Run-Time Library
16006 @section Rebuilding the GNAT Run-Time Library
16007 @cindex GNAT Run-Time Library, rebuilding
16008 @cindex Building the GNAT Run-Time Library
16009 @cindex Rebuilding the GNAT Run-Time Library
16010 @cindex Run-Time Library, rebuilding
16013 It may be useful to recompile the GNAT library in various contexts, the
16014 most important one being the use of partition-wide configuration pragmas
16015 such as @code{Normalize_Scalars}. A special Makefile called
16016 @code{Makefile.adalib} is provided to that effect and can be found in
16017 the directory containing the GNAT library. The location of this
16018 directory depends on the way the GNAT environment has been installed and can
16019 be determined by means of the command:
16026 The last entry in the object search path usually contains the
16027 gnat library. This Makefile contains its own documentation and in
16028 particular the set of instructions needed to rebuild a new library and
16031 @node Using the GNU make Utility
16032 @chapter Using the GNU @code{make} Utility
16036 This chapter offers some examples of makefiles that solve specific
16037 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
16038 make, make, GNU @code{make}}), nor does it try to replace the
16039 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
16041 All the examples in this section are specific to the GNU version of
16042 make. Although @command{make} is a standard utility, and the basic language
16043 is the same, these examples use some advanced features found only in
16047 * Using gnatmake in a Makefile::
16048 * Automatically Creating a List of Directories::
16049 * Generating the Command Line Switches::
16050 * Overcoming Command Line Length Limits::
16053 @node Using gnatmake in a Makefile
16054 @section Using gnatmake in a Makefile
16059 Complex project organizations can be handled in a very powerful way by
16060 using GNU make combined with gnatmake. For instance, here is a Makefile
16061 which allows you to build each subsystem of a big project into a separate
16062 shared library. Such a makefile allows you to significantly reduce the link
16063 time of very big applications while maintaining full coherence at
16064 each step of the build process.
16066 The list of dependencies are handled automatically by
16067 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
16068 the appropriate directories.
16070 Note that you should also read the example on how to automatically
16071 create the list of directories
16072 (@pxref{Automatically Creating a List of Directories})
16073 which might help you in case your project has a lot of subdirectories.
16078 @font@heightrm=cmr8
16081 ## This Makefile is intended to be used with the following directory
16083 ## - The sources are split into a series of csc (computer software components)
16084 ## Each of these csc is put in its own directory.
16085 ## Their name are referenced by the directory names.
16086 ## They will be compiled into shared library (although this would also work
16087 ## with static libraries
16088 ## - The main program (and possibly other packages that do not belong to any
16089 ## csc is put in the top level directory (where the Makefile is).
16090 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
16091 ## \_ second_csc (sources) __ lib (will contain the library)
16093 ## Although this Makefile is build for shared library, it is easy to modify
16094 ## to build partial link objects instead (modify the lines with -shared and
16097 ## With this makefile, you can change any file in the system or add any new
16098 ## file, and everything will be recompiled correctly (only the relevant shared
16099 ## objects will be recompiled, and the main program will be re-linked).
16101 # The list of computer software component for your project. This might be
16102 # generated automatically.
16105 # Name of the main program (no extension)
16108 # If we need to build objects with -fPIC, uncomment the following line
16111 # The following variable should give the directory containing libgnat.so
16112 # You can get this directory through 'gnatls -v'. This is usually the last
16113 # directory in the Object_Path.
16116 # The directories for the libraries
16117 # (This macro expands the list of CSC to the list of shared libraries, you
16118 # could simply use the expanded form:
16119 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16120 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16122 $@{MAIN@}: objects $@{LIB_DIR@}
16123 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16124 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16127 # recompile the sources
16128 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16130 # Note: In a future version of GNAT, the following commands will be simplified
16131 # by a new tool, gnatmlib
16133 mkdir -p $@{dir $@@ @}
16134 cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16135 cd $@{dir $@@ @} && cp -f ../*.ali .
16137 # The dependencies for the modules
16138 # Note that we have to force the expansion of *.o, since in some cases
16139 # make won't be able to do it itself.
16140 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16141 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16142 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16144 # Make sure all of the shared libraries are in the path before starting the
16147 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16150 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16151 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16152 $@{RM@} $@{CSC_LIST:%=%/*.o@}
16153 $@{RM@} *.o *.ali $@{MAIN@}
16156 @node Automatically Creating a List of Directories
16157 @section Automatically Creating a List of Directories
16160 In most makefiles, you will have to specify a list of directories, and
16161 store it in a variable. For small projects, it is often easier to
16162 specify each of them by hand, since you then have full control over what
16163 is the proper order for these directories, which ones should be
16166 However, in larger projects, which might involve hundreds of
16167 subdirectories, it might be more convenient to generate this list
16170 The example below presents two methods. The first one, although less
16171 general, gives you more control over the list. It involves wildcard
16172 characters, that are automatically expanded by @command{make}. Its
16173 shortcoming is that you need to explicitly specify some of the
16174 organization of your project, such as for instance the directory tree
16175 depth, whether some directories are found in a separate tree, @enddots{}
16177 The second method is the most general one. It requires an external
16178 program, called @command{find}, which is standard on all Unix systems. All
16179 the directories found under a given root directory will be added to the
16185 @font@heightrm=cmr8
16188 # The examples below are based on the following directory hierarchy:
16189 # All the directories can contain any number of files
16190 # ROOT_DIRECTORY -> a -> aa -> aaa
16193 # -> b -> ba -> baa
16196 # This Makefile creates a variable called DIRS, that can be reused any time
16197 # you need this list (see the other examples in this section)
16199 # The root of your project's directory hierarchy
16203 # First method: specify explicitly the list of directories
16204 # This allows you to specify any subset of all the directories you need.
16207 DIRS := a/aa/ a/ab/ b/ba/
16210 # Second method: use wildcards
16211 # Note that the argument(s) to wildcard below should end with a '/'.
16212 # Since wildcards also return file names, we have to filter them out
16213 # to avoid duplicate directory names.
16214 # We thus use make's @code{dir} and @code{sort} functions.
16215 # It sets DIRs to the following value (note that the directories aaa and baa
16216 # are not given, unless you change the arguments to wildcard).
16217 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16220 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16221 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16224 # Third method: use an external program
16225 # This command is much faster if run on local disks, avoiding NFS slowdowns.
16226 # This is the most complete command: it sets DIRs to the following value:
16227 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16230 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16234 @node Generating the Command Line Switches
16235 @section Generating the Command Line Switches
16238 Once you have created the list of directories as explained in the
16239 previous section (@pxref{Automatically Creating a List of Directories}),
16240 you can easily generate the command line arguments to pass to gnatmake.
16242 For the sake of completeness, this example assumes that the source path
16243 is not the same as the object path, and that you have two separate lists
16247 # see "Automatically creating a list of directories" to create
16252 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16253 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16256 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16259 @node Overcoming Command Line Length Limits
16260 @section Overcoming Command Line Length Limits
16263 One problem that might be encountered on big projects is that many
16264 operating systems limit the length of the command line. It is thus hard to give
16265 gnatmake the list of source and object directories.
16267 This example shows how you can set up environment variables, which will
16268 make @command{gnatmake} behave exactly as if the directories had been
16269 specified on the command line, but have a much higher length limit (or
16270 even none on most systems).
16272 It assumes that you have created a list of directories in your Makefile,
16273 using one of the methods presented in
16274 @ref{Automatically Creating a List of Directories}.
16275 For the sake of completeness, we assume that the object
16276 path (where the ALI files are found) is different from the sources patch.
16278 Note a small trick in the Makefile below: for efficiency reasons, we
16279 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16280 expanded immediately by @code{make}. This way we overcome the standard
16281 make behavior which is to expand the variables only when they are
16284 On Windows, if you are using the standard Windows command shell, you must
16285 replace colons with semicolons in the assignments to these variables.
16290 @font@heightrm=cmr8
16293 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
16294 # This is the same thing as putting the -I arguments on the command line.
16295 # (the equivalent of using -aI on the command line would be to define
16296 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
16297 # You can of course have different values for these variables.
16299 # Note also that we need to keep the previous values of these variables, since
16300 # they might have been set before running 'make' to specify where the GNAT
16301 # library is installed.
16303 # see "Automatically creating a list of directories" to create these
16309 space:=$@{empty@} $@{empty@}
16310 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16311 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16312 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16313 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
16314 export ADA_INCLUDE_PATH
16315 export ADA_OBJECT_PATH
16322 @node Memory Management Issues
16323 @chapter Memory Management Issues
16326 This chapter describes some useful memory pools provided in the GNAT library
16327 and in particular the GNAT Debug Pool facility, which can be used to detect
16328 incorrect uses of access values (including ``dangling references'').
16330 It also describes the @command{gnatmem} tool, which can be used to track down
16335 * Some Useful Memory Pools::
16336 * The GNAT Debug Pool Facility::
16338 * The gnatmem Tool::
16342 @node Some Useful Memory Pools
16343 @section Some Useful Memory Pools
16344 @findex Memory Pool
16345 @cindex storage, pool
16348 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
16349 storage pool. Allocations use the standard system call @code{malloc} while
16350 deallocations use the standard system call @code{free}. No reclamation is
16351 performed when the pool goes out of scope. For performance reasons, the
16352 standard default Ada allocators/deallocators do not use any explicit storage
16353 pools but if they did, they could use this storage pool without any change in
16354 behavior. That is why this storage pool is used when the user
16355 manages to make the default implicit allocator explicit as in this example:
16356 @smallexample @c ada
16357 type T1 is access Something;
16358 -- no Storage pool is defined for T2
16359 type T2 is access Something_Else;
16360 for T2'Storage_Pool use T1'Storage_Pool;
16361 -- the above is equivalent to
16362 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
16366 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
16367 pool. The allocation strategy is similar to @code{Pool_Local}'s
16368 except that the all
16369 storage allocated with this pool is reclaimed when the pool object goes out of
16370 scope. This pool provides a explicit mechanism similar to the implicit one
16371 provided by several Ada 83 compilers for allocations performed through a local
16372 access type and whose purpose was to reclaim memory when exiting the
16373 scope of a given local access. As an example, the following program does not
16374 leak memory even though it does not perform explicit deallocation:
16376 @smallexample @c ada
16377 with System.Pool_Local;
16378 procedure Pooloc1 is
16379 procedure Internal is
16380 type A is access Integer;
16381 X : System.Pool_Local.Unbounded_Reclaim_Pool;
16382 for A'Storage_Pool use X;
16385 for I in 1 .. 50 loop
16390 for I in 1 .. 100 loop
16397 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
16398 @code{Storage_Size} is specified for an access type.
16399 The whole storage for the pool is
16400 allocated at once, usually on the stack at the point where the access type is
16401 elaborated. It is automatically reclaimed when exiting the scope where the
16402 access type is defined. This package is not intended to be used directly by the
16403 user and it is implicitly used for each such declaration:
16405 @smallexample @c ada
16406 type T1 is access Something;
16407 for T1'Storage_Size use 10_000;
16410 @node The GNAT Debug Pool Facility
16411 @section The GNAT Debug Pool Facility
16413 @cindex storage, pool, memory corruption
16416 The use of unchecked deallocation and unchecked conversion can easily
16417 lead to incorrect memory references. The problems generated by such
16418 references are usually difficult to tackle because the symptoms can be
16419 very remote from the origin of the problem. In such cases, it is
16420 very helpful to detect the problem as early as possible. This is the
16421 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
16423 In order to use the GNAT specific debugging pool, the user must
16424 associate a debug pool object with each of the access types that may be
16425 related to suspected memory problems. See Ada Reference Manual 13.11.
16426 @smallexample @c ada
16427 type Ptr is access Some_Type;
16428 Pool : GNAT.Debug_Pools.Debug_Pool;
16429 for Ptr'Storage_Pool use Pool;
16433 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
16434 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
16435 allow the user to redefine allocation and deallocation strategies. They
16436 also provide a checkpoint for each dereference, through the use of
16437 the primitive operation @code{Dereference} which is implicitly called at
16438 each dereference of an access value.
16440 Once an access type has been associated with a debug pool, operations on
16441 values of the type may raise four distinct exceptions,
16442 which correspond to four potential kinds of memory corruption:
16445 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
16447 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
16449 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
16451 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
16455 For types associated with a Debug_Pool, dynamic allocation is performed using
16456 the standard GNAT allocation routine. References to all allocated chunks of
16457 memory are kept in an internal dictionary. Several deallocation strategies are
16458 provided, whereupon the user can choose to release the memory to the system,
16459 keep it allocated for further invalid access checks, or fill it with an easily
16460 recognizable pattern for debug sessions. The memory pattern is the old IBM
16461 hexadecimal convention: @code{16#DEADBEEF#}.
16463 See the documentation in the file g-debpoo.ads for more information on the
16464 various strategies.
16466 Upon each dereference, a check is made that the access value denotes a
16467 properly allocated memory location. Here is a complete example of use of
16468 @code{Debug_Pools}, that includes typical instances of memory corruption:
16469 @smallexample @c ada
16473 with Gnat.Io; use Gnat.Io;
16474 with Unchecked_Deallocation;
16475 with Unchecked_Conversion;
16476 with GNAT.Debug_Pools;
16477 with System.Storage_Elements;
16478 with Ada.Exceptions; use Ada.Exceptions;
16479 procedure Debug_Pool_Test is
16481 type T is access Integer;
16482 type U is access all T;
16484 P : GNAT.Debug_Pools.Debug_Pool;
16485 for T'Storage_Pool use P;
16487 procedure Free is new Unchecked_Deallocation (Integer, T);
16488 function UC is new Unchecked_Conversion (U, T);
16491 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
16501 Put_Line (Integer'Image(B.all));
16503 when E : others => Put_Line ("raised: " & Exception_Name (E));
16508 when E : others => Put_Line ("raised: " & Exception_Name (E));
16512 Put_Line (Integer'Image(B.all));
16514 when E : others => Put_Line ("raised: " & Exception_Name (E));
16519 when E : others => Put_Line ("raised: " & Exception_Name (E));
16522 end Debug_Pool_Test;
16526 The debug pool mechanism provides the following precise diagnostics on the
16527 execution of this erroneous program:
16530 Total allocated bytes : 0
16531 Total deallocated bytes : 0
16532 Current Water Mark: 0
16536 Total allocated bytes : 8
16537 Total deallocated bytes : 0
16538 Current Water Mark: 8
16541 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
16542 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
16543 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
16544 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
16546 Total allocated bytes : 8
16547 Total deallocated bytes : 4
16548 Current Water Mark: 4
16553 @node The gnatmem Tool
16554 @section The @command{gnatmem} Tool
16558 The @code{gnatmem} utility monitors dynamic allocation and
16559 deallocation activity in a program, and displays information about
16560 incorrect deallocations and possible sources of memory leaks.
16561 It is designed to work in association with a static runtime library
16562 only and in this context provides three types of information:
16565 General information concerning memory management, such as the total
16566 number of allocations and deallocations, the amount of allocated
16567 memory and the high water mark, i.e.@: the largest amount of allocated
16568 memory in the course of program execution.
16571 Backtraces for all incorrect deallocations, that is to say deallocations
16572 which do not correspond to a valid allocation.
16575 Information on each allocation that is potentially the origin of a memory
16580 * Running gnatmem::
16581 * Switches for gnatmem::
16582 * Example of gnatmem Usage::
16585 @node Running gnatmem
16586 @subsection Running @code{gnatmem}
16589 @code{gnatmem} makes use of the output created by the special version of
16590 allocation and deallocation routines that record call information. This
16591 allows to obtain accurate dynamic memory usage history at a minimal cost to
16592 the execution speed. Note however, that @code{gnatmem} is not supported on
16593 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
16594 Solaris and Windows NT/2000/XP (x86).
16597 The @code{gnatmem} command has the form
16600 @c $ gnatmem @ovar{switches} user_program
16601 @c Expanding @ovar macro inline (explanation in macro def comments)
16602 $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
16606 The program must have been linked with the instrumented version of the
16607 allocation and deallocation routines. This is done by linking with the
16608 @file{libgmem.a} library. For correct symbolic backtrace information,
16609 the user program should be compiled with debugging options
16610 (see @ref{Switches for gcc}). For example to build @file{my_program}:
16613 $ gnatmake -g my_program -largs -lgmem
16617 As library @file{libgmem.a} contains an alternate body for package
16618 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
16619 when an executable is linked with library @file{libgmem.a}. It is then not
16620 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
16623 When @file{my_program} is executed, the file @file{gmem.out} is produced.
16624 This file contains information about all allocations and deallocations
16625 performed by the program. It is produced by the instrumented allocations and
16626 deallocations routines and will be used by @code{gnatmem}.
16628 In order to produce symbolic backtrace information for allocations and
16629 deallocations performed by the GNAT run-time library, you need to use a
16630 version of that library that has been compiled with the @option{-g} switch
16631 (see @ref{Rebuilding the GNAT Run-Time Library}).
16633 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
16634 examine. If the location of @file{gmem.out} file was not explicitly supplied by
16635 @option{-i} switch, gnatmem will assume that this file can be found in the
16636 current directory. For example, after you have executed @file{my_program},
16637 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
16640 $ gnatmem my_program
16644 This will produce the output with the following format:
16646 *************** debut cc
16648 $ gnatmem my_program
16652 Total number of allocations : 45
16653 Total number of deallocations : 6
16654 Final Water Mark (non freed mem) : 11.29 Kilobytes
16655 High Water Mark : 11.40 Kilobytes
16660 Allocation Root # 2
16661 -------------------
16662 Number of non freed allocations : 11
16663 Final Water Mark (non freed mem) : 1.16 Kilobytes
16664 High Water Mark : 1.27 Kilobytes
16666 my_program.adb:23 my_program.alloc
16672 The first block of output gives general information. In this case, the
16673 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
16674 Unchecked_Deallocation routine occurred.
16677 Subsequent paragraphs display information on all allocation roots.
16678 An allocation root is a specific point in the execution of the program
16679 that generates some dynamic allocation, such as a ``@code{@b{new}}''
16680 construct. This root is represented by an execution backtrace (or subprogram
16681 call stack). By default the backtrace depth for allocations roots is 1, so
16682 that a root corresponds exactly to a source location. The backtrace can
16683 be made deeper, to make the root more specific.
16685 @node Switches for gnatmem
16686 @subsection Switches for @code{gnatmem}
16689 @code{gnatmem} recognizes the following switches:
16694 @cindex @option{-q} (@code{gnatmem})
16695 Quiet. Gives the minimum output needed to identify the origin of the
16696 memory leaks. Omits statistical information.
16699 @cindex @var{N} (@code{gnatmem})
16700 N is an integer literal (usually between 1 and 10) which controls the
16701 depth of the backtraces defining allocation root. The default value for
16702 N is 1. The deeper the backtrace, the more precise the localization of
16703 the root. Note that the total number of roots can depend on this
16704 parameter. This parameter must be specified @emph{before} the name of the
16705 executable to be analyzed, to avoid ambiguity.
16708 @cindex @option{-b} (@code{gnatmem})
16709 This switch has the same effect as just depth parameter.
16711 @item -i @var{file}
16712 @cindex @option{-i} (@code{gnatmem})
16713 Do the @code{gnatmem} processing starting from @file{file}, rather than
16714 @file{gmem.out} in the current directory.
16717 @cindex @option{-m} (@code{gnatmem})
16718 This switch causes @code{gnatmem} to mask the allocation roots that have less
16719 than n leaks. The default value is 1. Specifying the value of 0 will allow to
16720 examine even the roots that didn't result in leaks.
16723 @cindex @option{-s} (@code{gnatmem})
16724 This switch causes @code{gnatmem} to sort the allocation roots according to the
16725 specified order of sort criteria, each identified by a single letter. The
16726 currently supported criteria are @code{n, h, w} standing respectively for
16727 number of unfreed allocations, high watermark, and final watermark
16728 corresponding to a specific root. The default order is @code{nwh}.
16732 @node Example of gnatmem Usage
16733 @subsection Example of @code{gnatmem} Usage
16736 The following example shows the use of @code{gnatmem}
16737 on a simple memory-leaking program.
16738 Suppose that we have the following Ada program:
16740 @smallexample @c ada
16743 with Unchecked_Deallocation;
16744 procedure Test_Gm is
16746 type T is array (1..1000) of Integer;
16747 type Ptr is access T;
16748 procedure Free is new Unchecked_Deallocation (T, Ptr);
16751 procedure My_Alloc is
16756 procedure My_DeAlloc is
16764 for I in 1 .. 5 loop
16765 for J in I .. 5 loop
16776 The program needs to be compiled with debugging option and linked with
16777 @code{gmem} library:
16780 $ gnatmake -g test_gm -largs -lgmem
16784 Then we execute the program as usual:
16791 Then @code{gnatmem} is invoked simply with
16797 which produces the following output (result may vary on different platforms):
16802 Total number of allocations : 18
16803 Total number of deallocations : 5
16804 Final Water Mark (non freed mem) : 53.00 Kilobytes
16805 High Water Mark : 56.90 Kilobytes
16807 Allocation Root # 1
16808 -------------------
16809 Number of non freed allocations : 11
16810 Final Water Mark (non freed mem) : 42.97 Kilobytes
16811 High Water Mark : 46.88 Kilobytes
16813 test_gm.adb:11 test_gm.my_alloc
16815 Allocation Root # 2
16816 -------------------
16817 Number of non freed allocations : 1
16818 Final Water Mark (non freed mem) : 10.02 Kilobytes
16819 High Water Mark : 10.02 Kilobytes
16821 s-secsta.adb:81 system.secondary_stack.ss_init
16823 Allocation Root # 3
16824 -------------------
16825 Number of non freed allocations : 1
16826 Final Water Mark (non freed mem) : 12 Bytes
16827 High Water Mark : 12 Bytes
16829 s-secsta.adb:181 system.secondary_stack.ss_init
16833 Note that the GNAT run time contains itself a certain number of
16834 allocations that have no corresponding deallocation,
16835 as shown here for root #2 and root
16836 #3. This is a normal behavior when the number of non-freed allocations
16837 is one, it allocates dynamic data structures that the run time needs for
16838 the complete lifetime of the program. Note also that there is only one
16839 allocation root in the user program with a single line back trace:
16840 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
16841 program shows that 'My_Alloc' is called at 2 different points in the
16842 source (line 21 and line 24). If those two allocation roots need to be
16843 distinguished, the backtrace depth parameter can be used:
16846 $ gnatmem 3 test_gm
16850 which will give the following output:
16855 Total number of allocations : 18
16856 Total number of deallocations : 5
16857 Final Water Mark (non freed mem) : 53.00 Kilobytes
16858 High Water Mark : 56.90 Kilobytes
16860 Allocation Root # 1
16861 -------------------
16862 Number of non freed allocations : 10
16863 Final Water Mark (non freed mem) : 39.06 Kilobytes
16864 High Water Mark : 42.97 Kilobytes
16866 test_gm.adb:11 test_gm.my_alloc
16867 test_gm.adb:24 test_gm
16868 b_test_gm.c:52 main
16870 Allocation Root # 2
16871 -------------------
16872 Number of non freed allocations : 1
16873 Final Water Mark (non freed mem) : 10.02 Kilobytes
16874 High Water Mark : 10.02 Kilobytes
16876 s-secsta.adb:81 system.secondary_stack.ss_init
16877 s-secsta.adb:283 <system__secondary_stack___elabb>
16878 b_test_gm.c:33 adainit
16880 Allocation Root # 3
16881 -------------------
16882 Number of non freed allocations : 1
16883 Final Water Mark (non freed mem) : 3.91 Kilobytes
16884 High Water Mark : 3.91 Kilobytes
16886 test_gm.adb:11 test_gm.my_alloc
16887 test_gm.adb:21 test_gm
16888 b_test_gm.c:52 main
16890 Allocation Root # 4
16891 -------------------
16892 Number of non freed allocations : 1
16893 Final Water Mark (non freed mem) : 12 Bytes
16894 High Water Mark : 12 Bytes
16896 s-secsta.adb:181 system.secondary_stack.ss_init
16897 s-secsta.adb:283 <system__secondary_stack___elabb>
16898 b_test_gm.c:33 adainit
16902 The allocation root #1 of the first example has been split in 2 roots #1
16903 and #3 thanks to the more precise associated backtrace.
16907 @node Stack Related Facilities
16908 @chapter Stack Related Facilities
16911 This chapter describes some useful tools associated with stack
16912 checking and analysis. In
16913 particular, it deals with dynamic and static stack usage measurements.
16916 * Stack Overflow Checking::
16917 * Static Stack Usage Analysis::
16918 * Dynamic Stack Usage Analysis::
16921 @node Stack Overflow Checking
16922 @section Stack Overflow Checking
16923 @cindex Stack Overflow Checking
16924 @cindex -fstack-check
16927 For most operating systems, @command{gcc} does not perform stack overflow
16928 checking by default. This means that if the main environment task or
16929 some other task exceeds the available stack space, then unpredictable
16930 behavior will occur. Most native systems offer some level of protection by
16931 adding a guard page at the end of each task stack. This mechanism is usually
16932 not enough for dealing properly with stack overflow situations because
16933 a large local variable could ``jump'' above the guard page.
16934 Furthermore, when the
16935 guard page is hit, there may not be any space left on the stack for executing
16936 the exception propagation code. Enabling stack checking avoids
16939 To activate stack checking, compile all units with the gcc option
16940 @option{-fstack-check}. For example:
16943 gcc -c -fstack-check package1.adb
16947 Units compiled with this option will generate extra instructions to check
16948 that any use of the stack (for procedure calls or for declaring local
16949 variables in declare blocks) does not exceed the available stack space.
16950 If the space is exceeded, then a @code{Storage_Error} exception is raised.
16952 For declared tasks, the stack size is controlled by the size
16953 given in an applicable @code{Storage_Size} pragma or by the value specified
16954 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
16955 the default size as defined in the GNAT runtime otherwise.
16957 For the environment task, the stack size depends on
16958 system defaults and is unknown to the compiler. Stack checking
16959 may still work correctly if a fixed
16960 size stack is allocated, but this cannot be guaranteed.
16962 To ensure that a clean exception is signalled for stack
16963 overflow, set the environment variable
16964 @env{GNAT_STACK_LIMIT} to indicate the maximum
16965 stack area that can be used, as in:
16966 @cindex GNAT_STACK_LIMIT
16969 SET GNAT_STACK_LIMIT 1600
16973 The limit is given in kilobytes, so the above declaration would
16974 set the stack limit of the environment task to 1.6 megabytes.
16975 Note that the only purpose of this usage is to limit the amount
16976 of stack used by the environment task. If it is necessary to
16977 increase the amount of stack for the environment task, then this
16978 is an operating systems issue, and must be addressed with the
16979 appropriate operating systems commands.
16982 To have a fixed size stack in the environment task, the stack must be put
16983 in the P0 address space and its size specified. Use these switches to
16987 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
16991 The quotes are required to keep case. The number after @samp{STACK=} is the
16992 size of the environmental task stack in pagelets (512 bytes). In this example
16993 the stack size is about 2 megabytes.
16996 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
16997 be placed in P0 space. Refer to @cite{HP OpenVMS Linker Utility Manual} for
16998 more details about the @option{/p0image} qualifier and the @option{stack}
17002 @node Static Stack Usage Analysis
17003 @section Static Stack Usage Analysis
17004 @cindex Static Stack Usage Analysis
17005 @cindex -fstack-usage
17008 A unit compiled with @option{-fstack-usage} will generate an extra file
17010 the maximum amount of stack used, on a per-function basis.
17011 The file has the same
17012 basename as the target object file with a @file{.su} extension.
17013 Each line of this file is made up of three fields:
17017 The name of the function.
17021 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
17024 The second field corresponds to the size of the known part of the function
17027 The qualifier @code{static} means that the function frame size
17029 It usually means that all local variables have a static size.
17030 In this case, the second field is a reliable measure of the function stack
17033 The qualifier @code{dynamic} means that the function frame size is not static.
17034 It happens mainly when some local variables have a dynamic size. When this
17035 qualifier appears alone, the second field is not a reliable measure
17036 of the function stack analysis. When it is qualified with @code{bounded}, it
17037 means that the second field is a reliable maximum of the function stack
17040 @node Dynamic Stack Usage Analysis
17041 @section Dynamic Stack Usage Analysis
17044 It is possible to measure the maximum amount of stack used by a task, by
17045 adding a switch to @command{gnatbind}, as:
17048 $ gnatbind -u0 file
17052 With this option, at each task termination, its stack usage is output on
17054 It is not always convenient to output the stack usage when the program
17055 is still running. Hence, it is possible to delay this output until program
17056 termination. for a given number of tasks specified as the argument of the
17057 @option{-u} option. For instance:
17060 $ gnatbind -u100 file
17064 will buffer the stack usage information of the first 100 tasks to terminate and
17065 output this info at program termination. Results are displayed in four
17069 Index | Task Name | Stack Size | Stack Usage [Value +/- Variation]
17076 is a number associated with each task.
17079 is the name of the task analyzed.
17082 is the maximum size for the stack.
17085 is the measure done by the stack analyzer. In order to prevent overflow, the stack
17086 is not entirely analyzed, and it's not possible to know exactly how
17087 much has actually been used. The report thus contains the theoretical stack usage
17088 (Value) and the possible variation (Variation) around this value.
17093 The environment task stack, e.g., the stack that contains the main unit, is
17094 only processed when the environment variable GNAT_STACK_LIMIT is set.
17097 @c *********************************
17099 @c *********************************
17100 @node Verifying Properties Using gnatcheck
17101 @chapter Verifying Properties Using @command{gnatcheck}
17103 @cindex @command{gnatcheck}
17106 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
17107 of Ada source files according to a given set of semantic rules.
17110 In order to check compliance with a given rule, @command{gnatcheck} has to
17111 semantically analyze the Ada sources.
17112 Therefore, checks can only be performed on
17113 legal Ada units. Moreover, when a unit depends semantically upon units located
17114 outside the current directory, the source search path has to be provided when
17115 calling @command{gnatcheck}, either through a specified project file or
17116 through @command{gnatcheck} switches as described below.
17118 A number of rules are predefined in @command{gnatcheck} and are described
17119 later in this chapter.
17120 You can also add new rules, by modifying the @command{gnatcheck} code and
17121 rebuilding the tool. In order to add a simple rule making some local checks,
17122 a small amount of straightforward ASIS-based programming is usually needed.
17124 Project support for @command{gnatcheck} is provided by the GNAT
17125 driver (see @ref{The GNAT Driver and Project Files}).
17127 Invoking @command{gnatcheck} on the command line has the form:
17130 @c $ gnatcheck @ovar{switches} @{@var{filename}@}
17131 @c @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
17132 @c @r{[}-cargs @var{gcc_switches}@r{]} -rules @var{rule_options}
17133 @c Expanding @ovar macro inline (explanation in macro def comments)
17134 $ gnatcheck @r{[}@var{switches}@r{]} @{@var{filename}@}
17135 @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
17136 @r{[}-cargs @var{gcc_switches}@r{]} -rules @var{rule_options}
17143 @var{switches} specify the general tool options
17146 Each @var{filename} is the name (including the extension) of a source
17147 file to process. ``Wildcards'' are allowed, and
17148 the file name may contain path information.
17151 Each @var{arg_list_filename} is the name (including the extension) of a text
17152 file containing the names of the source files to process, separated by spaces
17156 @var{gcc_switches} is a list of switches for
17157 @command{gcc}. They will be passed on to all compiler invocations made by
17158 @command{gnatcheck} to generate the ASIS trees. Here you can provide
17159 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17160 and use the @option{-gnatec} switch to set the configuration file,
17161 use the @option{-gnat05} switch if sources should be compiled in
17165 @var{rule_options} is a list of options for controlling a set of
17166 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
17170 Either a @file{@var{filename}} or an @file{@var{arg_list_filename}} must be
17174 * Format of the Report File::
17175 * General gnatcheck Switches::
17176 * gnatcheck Rule Options::
17177 * Adding the Results of Compiler Checks to gnatcheck Output::
17178 * Project-Wide Checks::
17180 * Predefined Rules::
17181 * Example of gnatcheck Usage::
17184 @node Format of the Report File
17185 @section Format of the Report File
17186 @cindex Report file (for @code{gnatcheck})
17189 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
17191 It also creates a text file that
17192 contains the complete report of the last gnatcheck run. By default this file
17193 is named named @file{^gnatcheck.out^GNATCHECK.OUT^} and it is located in the
17194 current directory; the @option{^-o^/OUTPUT^} option can be used to change the
17195 name and/or location of the report file. This report contains:
17197 @item date and time of @command{gnatcheck} run, the version of
17198 the tool that has generated this report and the full parameters
17199 of the @command{gnatcheck} invocation;
17200 @item list of enabled rules;
17201 @item total number of detected violations;
17202 @item list of source files where rule violations have been detected;
17203 @item list of source files where no violations have been detected.
17206 @node General gnatcheck Switches
17207 @section General @command{gnatcheck} Switches
17210 The following switches control the general @command{gnatcheck} behavior
17214 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
17216 Process all units including those with read-only ALI files such as
17217 those from the GNAT Run-Time library.
17221 @cindex @option{-d} (@command{gnatcheck})
17226 @cindex @option{-dd} (@command{gnatcheck})
17228 Progress indicator mode (for use in GPS).
17231 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
17233 List the predefined and user-defined rules. For more details see
17234 @ref{Predefined Rules}.
17236 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
17238 Use full source locations references in the report file. For a construct from
17239 a generic instantiation a full source location is a chain from the location
17240 of this construct in the generic unit to the place where this unit is
17243 @cindex @option{^-log^/LOG^} (@command{gnatcheck})
17245 Duplicate all the output sent to @file{stderr} into a log file. The log file
17246 is named @file{gnatcheck.log} and is located in the current directory.
17248 @cindex @option{^-m^/DIAGNOSTIC_LIMIT^} (@command{gnatcheck})
17249 @item ^-m@i{nnnn}^/DIAGNOSTIC_LIMIT=@i{nnnn}^
17250 Maximum number of diagnostics to be sent to @file{stdout}, where @i{nnnn} is in
17251 the range 0@dots{}1000;
17252 the default value is 500. Zero means that there is no limitation on
17253 the number of diagnostic messages to be output.
17255 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
17257 Quiet mode. All the diagnostics about rule violations are placed in the
17258 @command{gnatcheck} report file only, without duplication on @file{stdout}.
17260 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
17262 Short format of the report file (no version information, no list of applied
17263 rules, no list of checked sources is included)
17265 @cindex @option{^--include-file=@var{file}^/INCLUDE_FILE=@var{file}^} (@command{gnatcheck})
17266 @item ^--include-file^/INCLUDE_FILE^
17267 Append the content of the specified text file to the report file
17269 @cindex @option{^-t^/TIME^} (@command{gnatcheck})
17271 Print out execution time.
17273 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
17274 @item ^-v^/VERBOSE^
17275 Verbose mode; @command{gnatcheck} generates version information and then
17276 a trace of sources being processed.
17278 @cindex @option{^-o ^/OUTPUT^} (@command{gnatcheck})
17279 @item ^-o ^/OUTPUT=^@var{report_file}
17280 Set name of report file file to @var{report_file} .
17284 @node gnatcheck Rule Options
17285 @section @command{gnatcheck} Rule Options
17288 The following options control the processing performed by
17289 @command{gnatcheck}.
17292 @cindex @option{+ALL} (@command{gnatcheck})
17294 Turn all the rule checks ON.
17296 @cindex @option{-ALL} (@command{gnatcheck})
17298 Turn all the rule checks OFF.
17300 @cindex @option{+R} (@command{gnatcheck})
17301 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
17302 Turn on the check for a specified rule with the specified parameter, if any.
17303 @var{rule_id} must be the identifier of one of the currently implemented rules
17304 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
17305 are not case-sensitive. The @var{param} item must
17306 be a string representing a valid parameter(s) for the specified rule.
17307 If it contains any space characters then this string must be enclosed in
17310 @cindex @option{-R} (@command{gnatcheck})
17311 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
17312 Turn off the check for a specified rule with the specified parameter, if any.
17314 @cindex @option{-from} (@command{gnatcheck})
17315 @item -from=@var{rule_option_filename}
17316 Read the rule options from the text file @var{rule_option_filename}, referred
17317 to as a ``coding standard file'' below.
17322 The default behavior is that all the rule checks are disabled.
17324 A coding standard file is a text file that contains a set of rule options
17326 @cindex Coding standard file (for @code{gnatcheck})
17327 The file may contain empty lines and Ada-style comments (comment
17328 lines and end-of-line comments). There can be several rule options on a
17329 single line (separated by a space).
17331 A coding standard file may reference other coding standard files by including
17332 more @option{-from=@var{rule_option_filename}}
17333 options, each such option being replaced with the content of the
17334 corresponding coding standard file during processing. In case a
17335 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
17336 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
17337 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
17338 processing fails with an error message.
17341 @node Adding the Results of Compiler Checks to gnatcheck Output
17342 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
17345 The @command{gnatcheck} tool can include in the generated diagnostic messages
17347 the report file the results of the checks performed by the compiler. Though
17348 disabled by default, this effect may be obtained by using @option{+R} with
17349 the following rule identifiers and parameters:
17353 To record restrictions violations (which are performed by the compiler if the
17354 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
17355 use the @code{Restrictions} rule
17356 with the same parameters as pragma
17357 @code{Restrictions} or @code{Restriction_Warnings}.
17360 To record compiler style checks (@pxref{Style Checking}), use the
17361 @code{Style_Checks} rule.
17362 This rule takes a parameter in one of the following forms:
17366 which enables the standard style checks corresponding to the @option{-gnatyy}
17367 GNAT style check option, or
17370 a string with the same
17371 structure and semantics as the @code{string_LITERAL} parameter of the
17372 GNAT pragma @code{Style_Checks}
17373 (for further information about this pragma,
17374 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}).
17379 @code{+RStyle_Checks:O} rule option activates
17380 the compiler style check that corresponds to
17381 @code{-gnatyO} style check option.
17384 To record compiler warnings (@pxref{Warning Message Control}), use the
17385 @code{Warnings} rule with a parameter that is a valid
17386 @i{static_string_expression} argument of the GNAT pragma @code{Warnings}
17387 (for further information about this pragma,
17388 @pxref{Pragma Warnings,,,gnat_rm, GNAT Reference Manual}).
17389 Note that in case of gnatcheck
17390 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
17391 all the specific warnings, but not suppresses the warning mode,
17392 and 'e' parameter, corresponding to @option{-gnatwe} that means
17393 "treat warnings as errors", does not have any effect.
17397 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
17398 option with the corresponding restriction name as a parameter. @code{-R} is
17399 not available for @code{Style_Checks} and @code{Warnings} options, to disable
17400 warnings and style checks, use the corresponding warning and style options.
17402 @node Project-Wide Checks
17403 @section Project-Wide Checks
17404 @cindex Project-wide checks (for @command{gnatcheck})
17407 In order to perform checks on all units of a given project, you can use
17408 the GNAT driver along with the @option{-P} option:
17410 gnat check -Pproj -rules -from=my_rules
17414 If the project @code{proj} depends upon other projects, you can perform
17415 checks on the project closure using the @option{-U} option:
17417 gnat check -Pproj -U -rules -from=my_rules
17421 Finally, if not all the units are relevant to a particular main
17422 program in the project closure, you can perform checks for the set
17423 of units needed to create a given main program (unit closure) using
17424 the @option{-U} option followed by the name of the main unit:
17426 gnat check -Pproj -U main -rules -from=my_rules
17430 @node Rule exemption
17431 @section Rule exemption
17432 @cindex Rule exemption (for @command{gnatcheck})
17435 One of the most useful applications of @command{gnatcheck} is to
17436 automate the enforcement of project-specific coding standards,
17437 for example in safety-critical systems where particular features
17438 must be restricted in order to simplify the certification effort.
17439 However, it may sometimes be appropriate to violate a coding standard rule,
17440 and in such cases the rationale for the violation should be provided
17441 in the source program itself so that the individuals
17442 reviewing or maintaining the program can immediately understand the intent.
17444 The @command{gnatcheck} tool supports this practice with the notion of
17445 a ``rule exemption'' covering a specific source code section. Normally
17446 rule violation messages are issued both on @file{stderr}
17447 and in a report file. In contrast, exempted violations are not listed on
17448 @file{stderr}; thus users invoking @command{gnatcheck} interactively
17449 (e.g. in its GPS interface) do not need to pay attention to known and
17450 justified violations. However, exempted violations along with their
17451 justification are documented in a special section of the report file that
17452 @command{gnatcheck} generates.
17455 * Using pragma Annotate to Control Rule Exemption::
17456 * gnatcheck Annotations Rules::
17459 @node Using pragma Annotate to Control Rule Exemption
17460 @subsection Using pragma @code{Annotate} to Control Rule Exemption
17461 @cindex Using pragma Annotate to control rule exemption
17464 Rule exemption is controlled by pragma @code{Annotate} when its first
17465 argument is ``gnatcheck''. The syntax of @command{gnatcheck}'s
17466 exemption control annotations is as follows:
17468 @smallexample @c ada
17470 pragma Annotate (gnatcheck, @i{exemption_control}, @i{Rule_Name}, [@i{justification}]);
17472 @i{exemption_control} ::= Exempt_On | Exempt_Off
17474 @i{Rule_Name} ::= string_literal
17476 @i{justification} ::= string_literal
17481 When a @command{gnatcheck} annotation has more then four arguments,
17482 @command{gnatcheck} issues a warning and ignores the additional arguments.
17483 If the additional arguments do not follow the syntax above,
17484 @command{gnatcheck} emits a warning and ignores the annotation.
17486 The @i{@code{Rule_Name}} argument should be the name of some existing
17487 @command{gnatcheck} rule.
17488 Otherwise a warning message is generated and the pragma is
17489 ignored. If @code{Rule_Name} denotes a rule that is not activated by the given
17490 @command{gnatcheck} call, the pragma is ignored and no warning is issued.
17492 A source code section where an exemption is active for a given rule is
17493 delimited by an @code{exempt_on} and @code{exempt_off} annotation pair:
17495 @smallexample @c ada
17496 pragma Annotate (gnatcheck, Exempt_On, Rule_Name, "justification");
17497 -- source code section
17498 pragma Annotate (gnatcheck, Exempt_Off, Rule_Name);
17502 @node gnatcheck Annotations Rules
17503 @subsection @command{gnatcheck} Annotations Rules
17504 @cindex @command{gnatcheck} annotations rules
17509 An ``Exempt_Off'' annotation can only appear after a corresponding
17510 ``Exempt_On'' annotation.
17513 Exempted source code sections are only based on the source location of the
17514 annotations. Any source construct between the two
17515 annotations is part of the exempted source code section.
17518 Exempted source code sections for different rules are independent. They can
17519 be nested or intersect with one another without limitation.
17520 Creating nested or intersecting source code sections for the same rule is
17524 Malformed exempted source code sections are reported by a warning, and
17525 the corresponding rule exemptions are ignored.
17528 When an exempted source code section does not contain at least one violation
17529 of the exempted rule, a warning is emitted on @file{stderr}.
17532 If an ``Exempt_On'' annotation pragma does not have a matching
17533 ``Exempt_Off'' annotation pragma in the same compilation unit, then the
17534 exemption for the given rule is ignored and a warning is issued.
17538 @node Predefined Rules
17539 @section Predefined Rules
17540 @cindex Predefined rules (for @command{gnatcheck})
17543 @c (Jan 2007) Since the global rules are still under development and are not
17544 @c documented, there is no point in explaining the difference between
17545 @c global and local rules
17547 A rule in @command{gnatcheck} is either local or global.
17548 A @emph{local rule} is a rule that applies to a well-defined section
17549 of a program and that can be checked by analyzing only this section.
17550 A @emph{global rule} requires analysis of some global properties of the
17551 whole program (mostly related to the program call graph).
17552 As of @value{NOW}, the implementation of global rules should be
17553 considered to be at a preliminary stage. You can use the
17554 @option{+GLOBAL} option to enable all the global rules, and the
17555 @option{-GLOBAL} rule option to disable all the global rules.
17557 All the global rules in the list below are
17558 so indicated by marking them ``GLOBAL''.
17559 This +GLOBAL and -GLOBAL options are not
17560 included in the list of gnatcheck options above, because at the moment they
17561 are considered as a temporary debug options.
17563 @command{gnatcheck} performs rule checks for generic
17564 instances only for global rules. This limitation may be relaxed in a later
17569 The predefined rules implemented in @command{gnatcheck}
17570 are described in a companion document,
17571 @cite{GNATcheck Reference Manual -- Predefined Rules}.
17572 The rule identifier is
17573 used as a parameter of @command{gnatcheck}'s @option{+R} or @option{-R}
17577 @node Example of gnatcheck Usage
17578 @section Example of @command{gnatcheck} Usage
17581 Here is a simple example. Suppose that in the current directory we have a
17582 project file named @file{gnatcheck_example.gpr} with the following content:
17584 @smallexample @c projectfile
17585 project Gnatcheck_Example is
17587 for Source_Dirs use ("src");
17588 for Object_Dir use "obj";
17589 for Main use ("main.adb");
17592 for Default_Switches ("ada") use ("-rules", "-from=coding_standard");
17595 end Gnatcheck_Example;
17599 And the file named @file{coding_standard} is also located in the current
17600 directory and has the following content:
17603 -----------------------------------------------------
17604 -- This is a sample gnatcheck coding standard file --
17605 -----------------------------------------------------
17607 -- First, turning on rules, that are directly implemented in gnatcheck
17608 +RAbstract_Type_Declarations
17611 +RFloat_Equality_Checks
17612 +REXIT_Statements_With_No_Loop_Name
17614 -- Then, activating compiler checks of interest:
17616 -- This style check checks if a unit name is present on END keyword that
17617 -- is the end of the unit declaration
17621 And the subdirectory @file{src} contains the following Ada sources:
17625 @smallexample @c ada
17627 type T is abstract tagged private;
17628 procedure P (X : T) is abstract;
17631 type My_Float is digits 8;
17632 function Is_Equal (L, R : My_Float) return Boolean;
17635 type T is abstract tagged null record;
17642 @smallexample @c ada
17643 package body Pack is
17644 package body Inner is
17645 function Is_Equal (L, R : My_Float) return Boolean is
17654 and @file{main.adb}
17656 @smallexample @c ada
17657 with Pack; use Pack;
17661 (gnatcheck, Exempt_On, "Anonymous_Arrays", "this one is fine");
17662 Float_Array : array (1 .. 10) of Inner.My_Float;
17663 pragma Annotate (gnatcheck, Exempt_Off, "Anonymous_Arrays");
17665 Another_Float_Array : array (1 .. 10) of Inner.My_Float;
17669 B : Boolean := False;
17672 for J in Float_Array'Range loop
17673 if Is_Equal (Float_Array (J), Another_Float_Array (J)) then
17682 And suppose we call @command{gnatcheck} from the current directory using
17683 the @command{gnat} driver:
17686 gnat check -Pgnatcheck_example.gpr
17690 As a result, @command{gnatcheck} is called to check all the files from the
17691 project @file{gnatcheck_example.gpr} using the coding standard defined by
17692 the file @file{coding_standard}. As the result, the @command{gnatcheck}
17693 report file named @file{gnatcheck.out} will be created in the current
17694 directory, and it will have the following content:
17697 RULE CHECKING REPORT
17701 Date and time of execution: 2009.10.28 14:17
17702 Tool version: GNATCHECK (built with ASIS 2.0.R for GNAT Pro 6.3.0w (20091016))
17705 gnatcheck -files=.../GNAT-TEMP-000004.TMP -cargs -gnatec=.../GNAT-TEMP-000003.TMP -rules -from=coding_standard
17707 Coding standard (applied rules):
17708 Abstract_Type_Declarations
17710 EXIT_Statements_With_No_Loop_Name
17711 Float_Equality_Checks
17714 Compiler style checks: -gnatye
17716 Number of coding standard violations: 6
17717 Number of exempted coding standard violations: 1
17719 2. DETECTED RULE VIOLATIONS
17721 2.1. NON-EXEMPTED VIOLATIONS
17723 Source files with non-exempted violations
17728 List of violations grouped by files, and ordered by increasing source location:
17730 pack.ads:2:4: declaration of abstract type
17731 pack.ads:5:4: declaration of local package
17732 pack.ads:10:30: declaration of abstract type
17733 pack.ads:11:1: (style) "end Pack" required
17734 pack.adb:5:19: use of equality operation for float values
17735 pack.adb:6:7: (style) "end Is_Equal" required
17736 main.adb:9:26: anonymous array type
17737 main.adb:19:10: exit statement with no loop name
17739 2.2. EXEMPTED VIOLATIONS
17741 Source files with exempted violations
17744 List of violations grouped by files, and ordered by increasing source location:
17746 main.adb:6:18: anonymous array type
17749 2.3. SOURCE FILES WITH NO VIOLATION
17751 No files without violations
17757 @c *********************************
17758 @node Creating Sample Bodies Using gnatstub
17759 @chapter Creating Sample Bodies Using @command{gnatstub}
17763 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
17764 for library unit declarations.
17766 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
17767 driver (see @ref{The GNAT Driver and Project Files}).
17769 To create a body stub, @command{gnatstub} has to compile the library
17770 unit declaration. Therefore, bodies can be created only for legal
17771 library units. Moreover, if a library unit depends semantically upon
17772 units located outside the current directory, you have to provide
17773 the source search path when calling @command{gnatstub}, see the description
17774 of @command{gnatstub} switches below.
17776 By default, all the program unit body stubs generated by @code{gnatstub}
17777 raise the predefined @code{Program_Error} exception, which will catch
17778 accidental calls of generated stubs. This behavior can be changed with
17779 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
17782 * Running gnatstub::
17783 * Switches for gnatstub::
17786 @node Running gnatstub
17787 @section Running @command{gnatstub}
17790 @command{gnatstub} has the command-line interface of the form
17793 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
17794 @c Expanding @ovar macro inline (explanation in macro def comments)
17795 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
17802 is the name of the source file that contains a library unit declaration
17803 for which a body must be created. The file name may contain the path
17805 The file name does not have to follow the GNAT file name conventions. If the
17807 does not follow GNAT file naming conventions, the name of the body file must
17809 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
17810 If the file name follows the GNAT file naming
17811 conventions and the name of the body file is not provided,
17814 of the body file from the argument file name by replacing the @file{.ads}
17816 with the @file{.adb} suffix.
17819 indicates the directory in which the body stub is to be placed (the default
17823 @item @samp{@var{gcc_switches}} is a list of switches for
17824 @command{gcc}. They will be passed on to all compiler invocations made by
17825 @command{gnatelim} to generate the ASIS trees. Here you can provide
17826 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17827 use the @option{-gnatec} switch to set the configuration file,
17828 use the @option{-gnat05} switch if sources should be compiled in
17832 is an optional sequence of switches as described in the next section
17835 @node Switches for gnatstub
17836 @section Switches for @command{gnatstub}
17842 @cindex @option{^-f^/FULL^} (@command{gnatstub})
17843 If the destination directory already contains a file with the name of the
17845 for the argument spec file, replace it with the generated body stub.
17847 @item ^-hs^/HEADER=SPEC^
17848 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
17849 Put the comment header (i.e., all the comments preceding the
17850 compilation unit) from the source of the library unit declaration
17851 into the body stub.
17853 @item ^-hg^/HEADER=GENERAL^
17854 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
17855 Put a sample comment header into the body stub.
17857 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
17858 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
17859 Use the content of the file as the comment header for a generated body stub.
17863 @cindex @option{-IDIR} (@command{gnatstub})
17865 @cindex @option{-I-} (@command{gnatstub})
17868 @item /NOCURRENT_DIRECTORY
17869 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
17871 ^These switches have ^This switch has^ the same meaning as in calls to
17873 ^They define ^It defines ^ the source search path in the call to
17874 @command{gcc} issued
17875 by @command{gnatstub} to compile an argument source file.
17877 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
17878 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
17879 This switch has the same meaning as in calls to @command{gcc}.
17880 It defines the additional configuration file to be passed to the call to
17881 @command{gcc} issued
17882 by @command{gnatstub} to compile an argument source file.
17884 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
17885 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
17886 (@var{n} is a non-negative integer). Set the maximum line length in the
17887 body stub to @var{n}; the default is 79. The maximum value that can be
17888 specified is 32767. Note that in the special case of configuration
17889 pragma files, the maximum is always 32767 regardless of whether or
17890 not this switch appears.
17892 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
17893 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
17894 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
17895 the generated body sample to @var{n}.
17896 The default indentation is 3.
17898 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
17899 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
17900 Order local bodies alphabetically. (By default local bodies are ordered
17901 in the same way as the corresponding local specs in the argument spec file.)
17903 @item ^-i^/INDENTATION=^@var{n}
17904 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
17905 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
17907 @item ^-k^/TREE_FILE=SAVE^
17908 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
17909 Do not remove the tree file (i.e., the snapshot of the compiler internal
17910 structures used by @command{gnatstub}) after creating the body stub.
17912 @item ^-l^/LINE_LENGTH=^@var{n}
17913 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
17914 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
17916 @item ^--no-exception^/NO_EXCEPTION^
17917 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
17918 Avoind raising PROGRAM_ERROR in the generated bodies of program unit stubs.
17919 This is not always possible for function stubs.
17921 @item ^--no-local-header^/NO_LOCAL_HEADER^
17922 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
17923 Do not place local comment header with unit name before body stub for a
17926 @item ^-o ^/BODY=^@var{body-name}
17927 @cindex @option{^-o^/BODY^} (@command{gnatstub})
17928 Body file name. This should be set if the argument file name does not
17930 the GNAT file naming
17931 conventions. If this switch is omitted the default name for the body will be
17933 from the argument file name according to the GNAT file naming conventions.
17936 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
17937 Quiet mode: do not generate a confirmation when a body is
17938 successfully created, and do not generate a message when a body is not
17942 @item ^-r^/TREE_FILE=REUSE^
17943 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
17944 Reuse the tree file (if it exists) instead of creating it. Instead of
17945 creating the tree file for the library unit declaration, @command{gnatstub}
17946 tries to find it in the current directory and use it for creating
17947 a body. If the tree file is not found, no body is created. This option
17948 also implies @option{^-k^/SAVE^}, whether or not
17949 the latter is set explicitly.
17951 @item ^-t^/TREE_FILE=OVERWRITE^
17952 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
17953 Overwrite the existing tree file. If the current directory already
17954 contains the file which, according to the GNAT file naming rules should
17955 be considered as a tree file for the argument source file,
17957 will refuse to create the tree file needed to create a sample body
17958 unless this option is set.
17960 @item ^-v^/VERBOSE^
17961 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
17962 Verbose mode: generate version information.
17966 @c *********************************
17967 @node Generating Ada Bindings for C and C++ headers
17968 @chapter Generating Ada Bindings for C and C++ headers
17972 GNAT now comes with a binding generator for C and C++ headers which is
17973 intended to do 95% of the tedious work of generating Ada specs from C
17974 or C++ header files.
17976 Note that this capability is not intended to generate 100% correct Ada specs,
17977 and will is some cases require manual adjustments, although it can often
17978 be used out of the box in practice.
17980 Some of the known limitations include:
17983 @item only very simple character constant macros are translated into Ada
17984 constants. Function macros (macros with arguments) are partially translated
17985 as comments, to be completed manually if needed.
17986 @item some extensions (e.g. vector types) are not supported
17987 @item pointers to pointers or complex structures are mapped to System.Address
17990 The code generated is using the Ada 2005 syntax, which makes it
17991 easier to interface with other languages than previous versions of Ada.
17994 * Running the binding generator::
17995 * Generating bindings for C++ headers::
17999 @node Running the binding generator
18000 @section Running the binding generator
18003 The binding generator is part of the @command{gcc} compiler and can be
18004 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
18005 spec files for the header files specified on the command line, and all
18006 header files needed by these files transitivitely. For example:
18009 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
18010 $ gcc -c -gnat05 *.ads
18013 will generate, under GNU/Linux, the following files: @file{time_h.ads},
18014 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
18015 correspond to the files @file{/usr/include/time.h},
18016 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
18017 mode these Ada specs.
18019 The @code{-C} switch tells @command{gcc} to extract comments from headers,
18020 and will attempt to generate corresponding Ada comments.
18022 If you want to generate a single Ada file and not the transitive closure, you
18023 can use instead the @option{-fdump-ada-spec-slim} switch.
18025 Note that we recommend when possible to use the @command{g++} driver to
18026 generate bindings, even for most C headers, since this will in general
18027 generate better Ada specs. For generating bindings for C++ headers, it is
18028 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
18029 is equivalent in this case. If @command{g++} cannot work on your C headers
18030 because of incompatibilities between C and C++, then you can fallback to
18031 @command{gcc} instead.
18033 For an example of better bindings generated from the C++ front-end,
18034 the name of the parameters (when available) are actually ignored by the C
18035 front-end. Consider the following C header:
18038 extern void foo (int variable);
18041 with the C front-end, @code{variable} is ignored, and the above is handled as:
18044 extern void foo (int);
18047 generating a generic:
18050 procedure foo (param1 : int);
18053 with the C++ front-end, the name is available, and we generate:
18056 procedure foo (variable : int);
18059 In some cases, the generated bindings will be more complete or more meaningful
18060 when defining some macros, which you can do via the @option{-D} switch. This
18061 is for example the case with @file{Xlib.h} under GNU/Linux:
18064 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
18067 The above will generate more complete bindings than a straight call without
18068 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
18070 In other cases, it is not possible to parse a header file in a stand alone
18071 manner, because other include files need to be included first. In this
18072 case, the solution is to create a small header file including the needed
18073 @code{#include} and possible @code{#define} directives. For example, to
18074 generate Ada bindings for @file{readline/readline.h}, you need to first
18075 include @file{stdio.h}, so you can create a file with the following two
18076 lines in e.g. @file{readline1.h}:
18080 #include <readline/readline.h>
18083 and then generate Ada bindings from this file:
18086 $ g++ -c -fdump-ada-spec readline1.h
18089 @node Generating bindings for C++ headers
18090 @section Generating bindings for C++ headers
18093 Generating bindings for C++ headers is done using the same options, always
18094 with the @command{g++} compiler.
18096 In this mode, C++ classes will be mapped to Ada tagged types, constructors
18097 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
18098 multiple inheritance of abstract classes will be mapped to Ada interfaces
18099 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
18100 information on interfacing to C++).
18102 For example, given the following C++ header file:
18109 virtual int Number_Of_Teeth () = 0;
18114 virtual void Set_Owner (char* Name) = 0;
18120 virtual void Set_Age (int New_Age);
18123 class Dog : Animal, Carnivore, Domestic @{
18128 virtual int Number_Of_Teeth ();
18129 virtual void Set_Owner (char* Name);
18137 The corresponding Ada code is generated:
18139 @smallexample @c ada
18142 package Class_Carnivore is
18143 type Carnivore is limited interface;
18144 pragma Import (CPP, Carnivore);
18146 function Number_Of_Teeth (this : access Carnivore) return int is abstract;
18148 use Class_Carnivore;
18150 package Class_Domestic is
18151 type Domestic is limited interface;
18152 pragma Import (CPP, Domestic);
18154 procedure Set_Owner
18155 (this : access Domestic;
18156 Name : Interfaces.C.Strings.chars_ptr) is abstract;
18158 use Class_Domestic;
18160 package Class_Animal is
18161 type Animal is tagged limited record
18162 Age_Count : aliased int;
18164 pragma Import (CPP, Animal);
18166 procedure Set_Age (this : access Animal; New_Age : int);
18167 pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
18171 package Class_Dog is
18172 type Dog is new Animal and Carnivore and Domestic with record
18173 Tooth_Count : aliased int;
18174 Owner : Interfaces.C.Strings.chars_ptr;
18176 pragma Import (CPP, Dog);
18178 function Number_Of_Teeth (this : access Dog) return int;
18179 pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
18181 procedure Set_Owner
18182 (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
18183 pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
18185 function New_Dog return Dog;
18186 pragma CPP_Constructor (New_Dog);
18187 pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
18198 @item -fdump-ada-spec
18199 @cindex @option{-fdump-ada-spec} (@command{gcc})
18200 Generate Ada spec files for the given header files transitively (including
18201 all header files that these headers depend upon).
18203 @item -fdump-ada-spec-slim
18204 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
18205 Generate Ada spec files for the header files specified on the command line
18209 @cindex @option{-C} (@command{gcc})
18210 Extract comments from headers and generate Ada comments in the Ada spec files.
18213 @node Other Utility Programs
18214 @chapter Other Utility Programs
18217 This chapter discusses some other utility programs available in the Ada
18221 * Using Other Utility Programs with GNAT::
18222 * The External Symbol Naming Scheme of GNAT::
18223 * Converting Ada Files to html with gnathtml::
18224 * Installing gnathtml::
18231 @node Using Other Utility Programs with GNAT
18232 @section Using Other Utility Programs with GNAT
18235 The object files generated by GNAT are in standard system format and in
18236 particular the debugging information uses this format. This means
18237 programs generated by GNAT can be used with existing utilities that
18238 depend on these formats.
18241 In general, any utility program that works with C will also often work with
18242 Ada programs generated by GNAT. This includes software utilities such as
18243 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
18247 @node The External Symbol Naming Scheme of GNAT
18248 @section The External Symbol Naming Scheme of GNAT
18251 In order to interpret the output from GNAT, when using tools that are
18252 originally intended for use with other languages, it is useful to
18253 understand the conventions used to generate link names from the Ada
18256 All link names are in all lowercase letters. With the exception of library
18257 procedure names, the mechanism used is simply to use the full expanded
18258 Ada name with dots replaced by double underscores. For example, suppose
18259 we have the following package spec:
18261 @smallexample @c ada
18272 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
18273 the corresponding link name is @code{qrs__mn}.
18275 Of course if a @code{pragma Export} is used this may be overridden:
18277 @smallexample @c ada
18282 pragma Export (Var1, C, External_Name => "var1_name");
18284 pragma Export (Var2, C, Link_Name => "var2_link_name");
18291 In this case, the link name for @var{Var1} is whatever link name the
18292 C compiler would assign for the C function @var{var1_name}. This typically
18293 would be either @var{var1_name} or @var{_var1_name}, depending on operating
18294 system conventions, but other possibilities exist. The link name for
18295 @var{Var2} is @var{var2_link_name}, and this is not operating system
18299 One exception occurs for library level procedures. A potential ambiguity
18300 arises between the required name @code{_main} for the C main program,
18301 and the name we would otherwise assign to an Ada library level procedure
18302 called @code{Main} (which might well not be the main program).
18304 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
18305 names. So if we have a library level procedure such as
18307 @smallexample @c ada
18310 procedure Hello (S : String);
18316 the external name of this procedure will be @var{_ada_hello}.
18319 @node Converting Ada Files to html with gnathtml
18320 @section Converting Ada Files to HTML with @code{gnathtml}
18323 This @code{Perl} script allows Ada source files to be browsed using
18324 standard Web browsers. For installation procedure, see the section
18325 @xref{Installing gnathtml}.
18327 Ada reserved keywords are highlighted in a bold font and Ada comments in
18328 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
18329 switch to suppress the generation of cross-referencing information, user
18330 defined variables and types will appear in a different color; you will
18331 be able to click on any identifier and go to its declaration.
18333 The command line is as follow:
18335 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
18336 @c Expanding @ovar macro inline (explanation in macro def comments)
18337 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
18341 You can pass it as many Ada files as you want. @code{gnathtml} will generate
18342 an html file for every ada file, and a global file called @file{index.htm}.
18343 This file is an index of every identifier defined in the files.
18345 The available ^switches^options^ are the following ones:
18349 @cindex @option{-83} (@code{gnathtml})
18350 Only the Ada 83 subset of keywords will be highlighted.
18352 @item -cc @var{color}
18353 @cindex @option{-cc} (@code{gnathtml})
18354 This option allows you to change the color used for comments. The default
18355 value is green. The color argument can be any name accepted by html.
18358 @cindex @option{-d} (@code{gnathtml})
18359 If the Ada files depend on some other files (for instance through
18360 @code{with} clauses, the latter files will also be converted to html.
18361 Only the files in the user project will be converted to html, not the files
18362 in the run-time library itself.
18365 @cindex @option{-D} (@code{gnathtml})
18366 This command is the same as @option{-d} above, but @command{gnathtml} will
18367 also look for files in the run-time library, and generate html files for them.
18369 @item -ext @var{extension}
18370 @cindex @option{-ext} (@code{gnathtml})
18371 This option allows you to change the extension of the generated HTML files.
18372 If you do not specify an extension, it will default to @file{htm}.
18375 @cindex @option{-f} (@code{gnathtml})
18376 By default, gnathtml will generate html links only for global entities
18377 ('with'ed units, global variables and types,@dots{}). If you specify
18378 @option{-f} on the command line, then links will be generated for local
18381 @item -l @var{number}
18382 @cindex @option{-l} (@code{gnathtml})
18383 If this ^switch^option^ is provided and @var{number} is not 0, then
18384 @code{gnathtml} will number the html files every @var{number} line.
18387 @cindex @option{-I} (@code{gnathtml})
18388 Specify a directory to search for library files (@file{.ALI} files) and
18389 source files. You can provide several -I switches on the command line,
18390 and the directories will be parsed in the order of the command line.
18393 @cindex @option{-o} (@code{gnathtml})
18394 Specify the output directory for html files. By default, gnathtml will
18395 saved the generated html files in a subdirectory named @file{html/}.
18397 @item -p @var{file}
18398 @cindex @option{-p} (@code{gnathtml})
18399 If you are using Emacs and the most recent Emacs Ada mode, which provides
18400 a full Integrated Development Environment for compiling, checking,
18401 running and debugging applications, you may use @file{.gpr} files
18402 to give the directories where Emacs can find sources and object files.
18404 Using this ^switch^option^, you can tell gnathtml to use these files.
18405 This allows you to get an html version of your application, even if it
18406 is spread over multiple directories.
18408 @item -sc @var{color}
18409 @cindex @option{-sc} (@code{gnathtml})
18410 This ^switch^option^ allows you to change the color used for symbol
18412 The default value is red. The color argument can be any name accepted by html.
18414 @item -t @var{file}
18415 @cindex @option{-t} (@code{gnathtml})
18416 This ^switch^option^ provides the name of a file. This file contains a list of
18417 file names to be converted, and the effect is exactly as though they had
18418 appeared explicitly on the command line. This
18419 is the recommended way to work around the command line length limit on some
18424 @node Installing gnathtml
18425 @section Installing @code{gnathtml}
18428 @code{Perl} needs to be installed on your machine to run this script.
18429 @code{Perl} is freely available for almost every architecture and
18430 Operating System via the Internet.
18432 On Unix systems, you may want to modify the first line of the script
18433 @code{gnathtml}, to explicitly tell the Operating system where Perl
18434 is. The syntax of this line is:
18436 #!full_path_name_to_perl
18440 Alternatively, you may run the script using the following command line:
18443 @c $ perl gnathtml.pl @ovar{switches} @var{files}
18444 @c Expanding @ovar macro inline (explanation in macro def comments)
18445 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
18454 The GNAT distribution provides an Ada 95 template for the HP Language
18455 Sensitive Editor (LSE), a component of DECset. In order to
18456 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
18463 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
18464 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
18465 the collection phase with the /DEBUG qualifier.
18468 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
18469 $ DEFINE LIB$DEBUG PCA$COLLECTOR
18470 $ RUN/DEBUG <PROGRAM_NAME>
18476 @c ******************************
18477 @node Code Coverage and Profiling
18478 @chapter Code Coverage and Profiling
18479 @cindex Code Coverage
18483 This chapter describes how to use @code{gcov} - coverage testing tool - and
18484 @code{gprof} - profiler tool - on your Ada programs.
18487 * Code Coverage of Ada Programs using gcov::
18488 * Profiling an Ada Program using gprof::
18491 @node Code Coverage of Ada Programs using gcov
18492 @section Code Coverage of Ada Programs using gcov
18494 @cindex -fprofile-arcs
18495 @cindex -ftest-coverage
18497 @cindex Code Coverage
18500 @code{gcov} is a test coverage program: it analyzes the execution of a given
18501 program on selected tests, to help you determine the portions of the program
18502 that are still untested.
18504 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
18505 User's Guide. You can refer to this documentation for a more complete
18508 This chapter provides a quick startup guide, and
18509 details some Gnat-specific features.
18512 * Quick startup guide::
18516 @node Quick startup guide
18517 @subsection Quick startup guide
18519 In order to perform coverage analysis of a program using @code{gcov}, 3
18524 Code instrumentation during the compilation process
18526 Execution of the instrumented program
18528 Execution of the @code{gcov} tool to generate the result.
18531 The code instrumentation needed by gcov is created at the object level:
18532 The source code is not modified in any way, because the instrumentation code is
18533 inserted by gcc during the compilation process. To compile your code with code
18534 coverage activated, you need to recompile your whole project using the
18536 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
18537 @code{-fprofile-arcs}.
18540 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
18541 -largs -fprofile-arcs
18544 This compilation process will create @file{.gcno} files together with
18545 the usual object files.
18547 Once the program is compiled with coverage instrumentation, you can
18548 run it as many times as needed - on portions of a test suite for
18549 example. The first execution will produce @file{.gcda} files at the
18550 same location as the @file{.gcno} files. The following executions
18551 will update those files, so that a cumulative result of the covered
18552 portions of the program is generated.
18554 Finally, you need to call the @code{gcov} tool. The different options of
18555 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
18557 This will create annotated source files with a @file{.gcov} extension:
18558 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
18560 @node Gnat specifics
18561 @subsection Gnat specifics
18563 Because Ada semantics, portions of the source code may be shared among
18564 several object files. This is the case for example when generics are
18565 involved, when inlining is active or when declarations generate initialisation
18566 calls. In order to take
18567 into account this shared code, you need to call @code{gcov} on all
18568 source files of the tested program at once.
18570 The list of source files might exceed the system's maximum command line
18571 length. In order to bypass this limitation, a new mechanism has been
18572 implemented in @code{gcov}: you can now list all your project's files into a
18573 text file, and provide this file to gcov as a parameter, preceded by a @@
18574 (e.g. @samp{gcov @@mysrclist.txt}).
18576 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
18577 not supported as there can be unresolved symbols during the final link.
18579 @node Profiling an Ada Program using gprof
18580 @section Profiling an Ada Program using gprof
18586 This section is not meant to be an exhaustive documentation of @code{gprof}.
18587 Full documentation for it can be found in the GNU Profiler User's Guide
18588 documentation that is part of this GNAT distribution.
18590 Profiling a program helps determine the parts of a program that are executed
18591 most often, and are therefore the most time-consuming.
18593 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
18594 better handle Ada programs and multitasking.
18595 It is currently supported on the following platforms
18600 solaris sparc/sparc64/x86
18606 In order to profile a program using @code{gprof}, 3 steps are needed:
18610 Code instrumentation, requiring a full recompilation of the project with the
18613 Execution of the program under the analysis conditions, i.e. with the desired
18616 Analysis of the results using the @code{gprof} tool.
18620 The following sections detail the different steps, and indicate how
18621 to interpret the results:
18623 * Compilation for profiling::
18624 * Program execution::
18626 * Interpretation of profiling results::
18629 @node Compilation for profiling
18630 @subsection Compilation for profiling
18634 In order to profile a program the first step is to tell the compiler
18635 to generate the necessary profiling information. The compiler switch to be used
18636 is @code{-pg}, which must be added to other compilation switches. This
18637 switch needs to be specified both during compilation and link stages, and can
18638 be specified once when using gnatmake:
18641 gnatmake -f -pg -P my_project
18645 Note that only the objects that were compiled with the @samp{-pg} switch will be
18646 profiled; if you need to profile your whole project, use the
18647 @samp{-f} gnatmake switch to force full recompilation.
18649 @node Program execution
18650 @subsection Program execution
18653 Once the program has been compiled for profiling, you can run it as usual.
18655 The only constraint imposed by profiling is that the program must terminate
18656 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
18659 Once the program completes execution, a data file called @file{gmon.out} is
18660 generated in the directory where the program was launched from. If this file
18661 already exists, it will be overwritten.
18663 @node Running gprof
18664 @subsection Running gprof
18667 The @code{gprof} tool is called as follow:
18670 gprof my_prog gmon.out
18681 The complete form of the gprof command line is the following:
18684 gprof [^switches^options^] [executable [data-file]]
18688 @code{gprof} supports numerous ^switch^options^. The order of these
18689 ^switch^options^ does not matter. The full list of options can be found in
18690 the GNU Profiler User's Guide documentation that comes with this documentation.
18692 The following is the subset of those switches that is most relevant:
18696 @item --demangle[=@var{style}]
18697 @itemx --no-demangle
18698 @cindex @option{--demangle} (@code{gprof})
18699 These options control whether symbol names should be demangled when
18700 printing output. The default is to demangle C++ symbols. The
18701 @code{--no-demangle} option may be used to turn off demangling. Different
18702 compilers have different mangling styles. The optional demangling style
18703 argument can be used to choose an appropriate demangling style for your
18704 compiler, in particular Ada symbols generated by GNAT can be demangled using
18705 @code{--demangle=gnat}.
18707 @item -e @var{function_name}
18708 @cindex @option{-e} (@code{gprof})
18709 The @samp{-e @var{function}} option tells @code{gprof} not to print
18710 information about the function @var{function_name} (and its
18711 children@dots{}) in the call graph. The function will still be listed
18712 as a child of any functions that call it, but its index number will be
18713 shown as @samp{[not printed]}. More than one @samp{-e} option may be
18714 given; only one @var{function_name} may be indicated with each @samp{-e}
18717 @item -E @var{function_name}
18718 @cindex @option{-E} (@code{gprof})
18719 The @code{-E @var{function}} option works like the @code{-e} option, but
18720 execution time spent in the function (and children who were not called from
18721 anywhere else), will not be used to compute the percentages-of-time for
18722 the call graph. More than one @samp{-E} option may be given; only one
18723 @var{function_name} may be indicated with each @samp{-E} option.
18725 @item -f @var{function_name}
18726 @cindex @option{-f} (@code{gprof})
18727 The @samp{-f @var{function}} option causes @code{gprof} to limit the
18728 call graph to the function @var{function_name} and its children (and
18729 their children@dots{}). More than one @samp{-f} option may be given;
18730 only one @var{function_name} may be indicated with each @samp{-f}
18733 @item -F @var{function_name}
18734 @cindex @option{-F} (@code{gprof})
18735 The @samp{-F @var{function}} option works like the @code{-f} option, but
18736 only time spent in the function and its children (and their
18737 children@dots{}) will be used to determine total-time and
18738 percentages-of-time for the call graph. More than one @samp{-F} option
18739 may be given; only one @var{function_name} may be indicated with each
18740 @samp{-F} option. The @samp{-F} option overrides the @samp{-E} option.
18744 @node Interpretation of profiling results
18745 @subsection Interpretation of profiling results
18749 The results of the profiling analysis are represented by two arrays: the
18750 'flat profile' and the 'call graph'. Full documentation of those outputs
18751 can be found in the GNU Profiler User's Guide.
18753 The flat profile shows the time spent in each function of the program, and how
18754 many time it has been called. This allows you to locate easily the most
18755 time-consuming functions.
18757 The call graph shows, for each subprogram, the subprograms that call it,
18758 and the subprograms that it calls. It also provides an estimate of the time
18759 spent in each of those callers/called subprograms.
18762 @c ******************************
18763 @node Running and Debugging Ada Programs
18764 @chapter Running and Debugging Ada Programs
18768 This chapter discusses how to debug Ada programs.
18770 It applies to GNAT on the Alpha OpenVMS platform;
18771 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
18772 since HP has implemented Ada support in the OpenVMS debugger on I64.
18775 An incorrect Ada program may be handled in three ways by the GNAT compiler:
18779 The illegality may be a violation of the static semantics of Ada. In
18780 that case GNAT diagnoses the constructs in the program that are illegal.
18781 It is then a straightforward matter for the user to modify those parts of
18785 The illegality may be a violation of the dynamic semantics of Ada. In
18786 that case the program compiles and executes, but may generate incorrect
18787 results, or may terminate abnormally with some exception.
18790 When presented with a program that contains convoluted errors, GNAT
18791 itself may terminate abnormally without providing full diagnostics on
18792 the incorrect user program.
18796 * The GNAT Debugger GDB::
18798 * Introduction to GDB Commands::
18799 * Using Ada Expressions::
18800 * Calling User-Defined Subprograms::
18801 * Using the Next Command in a Function::
18804 * Debugging Generic Units::
18805 * Remote Debugging using gdbserver::
18806 * GNAT Abnormal Termination or Failure to Terminate::
18807 * Naming Conventions for GNAT Source Files::
18808 * Getting Internal Debugging Information::
18809 * Stack Traceback::
18815 @node The GNAT Debugger GDB
18816 @section The GNAT Debugger GDB
18819 @code{GDB} is a general purpose, platform-independent debugger that
18820 can be used to debug mixed-language programs compiled with @command{gcc},
18821 and in particular is capable of debugging Ada programs compiled with
18822 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
18823 complex Ada data structures.
18825 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
18827 located in the GNU:[DOCS] directory,
18829 for full details on the usage of @code{GDB}, including a section on
18830 its usage on programs. This manual should be consulted for full
18831 details. The section that follows is a brief introduction to the
18832 philosophy and use of @code{GDB}.
18834 When GNAT programs are compiled, the compiler optionally writes debugging
18835 information into the generated object file, including information on
18836 line numbers, and on declared types and variables. This information is
18837 separate from the generated code. It makes the object files considerably
18838 larger, but it does not add to the size of the actual executable that
18839 will be loaded into memory, and has no impact on run-time performance. The
18840 generation of debug information is triggered by the use of the
18841 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
18842 used to carry out the compilations. It is important to emphasize that
18843 the use of these options does not change the generated code.
18845 The debugging information is written in standard system formats that
18846 are used by many tools, including debuggers and profilers. The format
18847 of the information is typically designed to describe C types and
18848 semantics, but GNAT implements a translation scheme which allows full
18849 details about Ada types and variables to be encoded into these
18850 standard C formats. Details of this encoding scheme may be found in
18851 the file exp_dbug.ads in the GNAT source distribution. However, the
18852 details of this encoding are, in general, of no interest to a user,
18853 since @code{GDB} automatically performs the necessary decoding.
18855 When a program is bound and linked, the debugging information is
18856 collected from the object files, and stored in the executable image of
18857 the program. Again, this process significantly increases the size of
18858 the generated executable file, but it does not increase the size of
18859 the executable program itself. Furthermore, if this program is run in
18860 the normal manner, it runs exactly as if the debug information were
18861 not present, and takes no more actual memory.
18863 However, if the program is run under control of @code{GDB}, the
18864 debugger is activated. The image of the program is loaded, at which
18865 point it is ready to run. If a run command is given, then the program
18866 will run exactly as it would have if @code{GDB} were not present. This
18867 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
18868 entirely non-intrusive until a breakpoint is encountered. If no
18869 breakpoint is ever hit, the program will run exactly as it would if no
18870 debugger were present. When a breakpoint is hit, @code{GDB} accesses
18871 the debugging information and can respond to user commands to inspect
18872 variables, and more generally to report on the state of execution.
18876 @section Running GDB
18879 This section describes how to initiate the debugger.
18880 @c The above sentence is really just filler, but it was otherwise
18881 @c clumsy to get the first paragraph nonindented given the conditional
18882 @c nature of the description
18885 The debugger can be launched from a @code{GPS} menu or
18886 directly from the command line. The description below covers the latter use.
18887 All the commands shown can be used in the @code{GPS} debug console window,
18888 but there are usually more GUI-based ways to achieve the same effect.
18891 The command to run @code{GDB} is
18894 $ ^gdb program^GDB PROGRAM^
18898 where @code{^program^PROGRAM^} is the name of the executable file. This
18899 activates the debugger and results in a prompt for debugger commands.
18900 The simplest command is simply @code{run}, which causes the program to run
18901 exactly as if the debugger were not present. The following section
18902 describes some of the additional commands that can be given to @code{GDB}.
18904 @c *******************************
18905 @node Introduction to GDB Commands
18906 @section Introduction to GDB Commands
18909 @code{GDB} contains a large repertoire of commands. @xref{Top,,
18910 Debugging with GDB, gdb, Debugging with GDB},
18912 located in the GNU:[DOCS] directory,
18914 for extensive documentation on the use
18915 of these commands, together with examples of their use. Furthermore,
18916 the command @command{help} invoked from within GDB activates a simple help
18917 facility which summarizes the available commands and their options.
18918 In this section we summarize a few of the most commonly
18919 used commands to give an idea of what @code{GDB} is about. You should create
18920 a simple program with debugging information and experiment with the use of
18921 these @code{GDB} commands on the program as you read through the
18925 @item set args @var{arguments}
18926 The @var{arguments} list above is a list of arguments to be passed to
18927 the program on a subsequent run command, just as though the arguments
18928 had been entered on a normal invocation of the program. The @code{set args}
18929 command is not needed if the program does not require arguments.
18932 The @code{run} command causes execution of the program to start from
18933 the beginning. If the program is already running, that is to say if
18934 you are currently positioned at a breakpoint, then a prompt will ask
18935 for confirmation that you want to abandon the current execution and
18938 @item breakpoint @var{location}
18939 The breakpoint command sets a breakpoint, that is to say a point at which
18940 execution will halt and @code{GDB} will await further
18941 commands. @var{location} is
18942 either a line number within a file, given in the format @code{file:linenumber},
18943 or it is the name of a subprogram. If you request that a breakpoint be set on
18944 a subprogram that is overloaded, a prompt will ask you to specify on which of
18945 those subprograms you want to breakpoint. You can also
18946 specify that all of them should be breakpointed. If the program is run
18947 and execution encounters the breakpoint, then the program
18948 stops and @code{GDB} signals that the breakpoint was encountered by
18949 printing the line of code before which the program is halted.
18951 @item catch exception @var{name}
18952 This command causes the program execution to stop whenever exception
18953 @var{name} is raised. If @var{name} is omitted, then the execution is
18954 suspended when any exception is raised.
18956 @item print @var{expression}
18957 This will print the value of the given expression. Most simple
18958 Ada expression formats are properly handled by @code{GDB}, so the expression
18959 can contain function calls, variables, operators, and attribute references.
18962 Continues execution following a breakpoint, until the next breakpoint or the
18963 termination of the program.
18966 Executes a single line after a breakpoint. If the next statement
18967 is a subprogram call, execution continues into (the first statement of)
18968 the called subprogram.
18971 Executes a single line. If this line is a subprogram call, executes and
18972 returns from the call.
18975 Lists a few lines around the current source location. In practice, it
18976 is usually more convenient to have a separate edit window open with the
18977 relevant source file displayed. Successive applications of this command
18978 print subsequent lines. The command can be given an argument which is a
18979 line number, in which case it displays a few lines around the specified one.
18982 Displays a backtrace of the call chain. This command is typically
18983 used after a breakpoint has occurred, to examine the sequence of calls that
18984 leads to the current breakpoint. The display includes one line for each
18985 activation record (frame) corresponding to an active subprogram.
18988 At a breakpoint, @code{GDB} can display the values of variables local
18989 to the current frame. The command @code{up} can be used to
18990 examine the contents of other active frames, by moving the focus up
18991 the stack, that is to say from callee to caller, one frame at a time.
18994 Moves the focus of @code{GDB} down from the frame currently being
18995 examined to the frame of its callee (the reverse of the previous command),
18997 @item frame @var{n}
18998 Inspect the frame with the given number. The value 0 denotes the frame
18999 of the current breakpoint, that is to say the top of the call stack.
19004 The above list is a very short introduction to the commands that
19005 @code{GDB} provides. Important additional capabilities, including conditional
19006 breakpoints, the ability to execute command sequences on a breakpoint,
19007 the ability to debug at the machine instruction level and many other
19008 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
19009 Debugging with GDB}. Note that most commands can be abbreviated
19010 (for example, c for continue, bt for backtrace).
19012 @node Using Ada Expressions
19013 @section Using Ada Expressions
19014 @cindex Ada expressions
19017 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
19018 extensions. The philosophy behind the design of this subset is
19022 That @code{GDB} should provide basic literals and access to operations for
19023 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19024 leaving more sophisticated computations to subprograms written into the
19025 program (which therefore may be called from @code{GDB}).
19028 That type safety and strict adherence to Ada language restrictions
19029 are not particularly important to the @code{GDB} user.
19032 That brevity is important to the @code{GDB} user.
19036 Thus, for brevity, the debugger acts as if there were
19037 implicit @code{with} and @code{use} clauses in effect for all user-written
19038 packages, thus making it unnecessary to fully qualify most names with
19039 their packages, regardless of context. Where this causes ambiguity,
19040 @code{GDB} asks the user's intent.
19042 For details on the supported Ada syntax, see @ref{Top,, Debugging with
19043 GDB, gdb, Debugging with GDB}.
19045 @node Calling User-Defined Subprograms
19046 @section Calling User-Defined Subprograms
19049 An important capability of @code{GDB} is the ability to call user-defined
19050 subprograms while debugging. This is achieved simply by entering
19051 a subprogram call statement in the form:
19054 call subprogram-name (parameters)
19058 The keyword @code{call} can be omitted in the normal case where the
19059 @code{subprogram-name} does not coincide with any of the predefined
19060 @code{GDB} commands.
19062 The effect is to invoke the given subprogram, passing it the
19063 list of parameters that is supplied. The parameters can be expressions and
19064 can include variables from the program being debugged. The
19065 subprogram must be defined
19066 at the library level within your program, and @code{GDB} will call the
19067 subprogram within the environment of your program execution (which
19068 means that the subprogram is free to access or even modify variables
19069 within your program).
19071 The most important use of this facility is in allowing the inclusion of
19072 debugging routines that are tailored to particular data structures
19073 in your program. Such debugging routines can be written to provide a suitably
19074 high-level description of an abstract type, rather than a low-level dump
19075 of its physical layout. After all, the standard
19076 @code{GDB print} command only knows the physical layout of your
19077 types, not their abstract meaning. Debugging routines can provide information
19078 at the desired semantic level and are thus enormously useful.
19080 For example, when debugging GNAT itself, it is crucial to have access to
19081 the contents of the tree nodes used to represent the program internally.
19082 But tree nodes are represented simply by an integer value (which in turn
19083 is an index into a table of nodes).
19084 Using the @code{print} command on a tree node would simply print this integer
19085 value, which is not very useful. But the PN routine (defined in file
19086 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19087 a useful high level representation of the tree node, which includes the
19088 syntactic category of the node, its position in the source, the integers
19089 that denote descendant nodes and parent node, as well as varied
19090 semantic information. To study this example in more detail, you might want to
19091 look at the body of the PN procedure in the stated file.
19093 @node Using the Next Command in a Function
19094 @section Using the Next Command in a Function
19097 When you use the @code{next} command in a function, the current source
19098 location will advance to the next statement as usual. A special case
19099 arises in the case of a @code{return} statement.
19101 Part of the code for a return statement is the ``epilog'' of the function.
19102 This is the code that returns to the caller. There is only one copy of
19103 this epilog code, and it is typically associated with the last return
19104 statement in the function if there is more than one return. In some
19105 implementations, this epilog is associated with the first statement
19108 The result is that if you use the @code{next} command from a return
19109 statement that is not the last return statement of the function you
19110 may see a strange apparent jump to the last return statement or to
19111 the start of the function. You should simply ignore this odd jump.
19112 The value returned is always that from the first return statement
19113 that was stepped through.
19115 @node Ada Exceptions
19116 @section Stopping when Ada Exceptions are Raised
19120 You can set catchpoints that stop the program execution when your program
19121 raises selected exceptions.
19124 @item catch exception
19125 Set a catchpoint that stops execution whenever (any task in the) program
19126 raises any exception.
19128 @item catch exception @var{name}
19129 Set a catchpoint that stops execution whenever (any task in the) program
19130 raises the exception @var{name}.
19132 @item catch exception unhandled
19133 Set a catchpoint that stops executino whenever (any task in the) program
19134 raises an exception for which there is no handler.
19136 @item info exceptions
19137 @itemx info exceptions @var{regexp}
19138 The @code{info exceptions} command permits the user to examine all defined
19139 exceptions within Ada programs. With a regular expression, @var{regexp}, as
19140 argument, prints out only those exceptions whose name matches @var{regexp}.
19148 @code{GDB} allows the following task-related commands:
19152 This command shows a list of current Ada tasks, as in the following example:
19159 ID TID P-ID Thread Pri State Name
19160 1 8088000 0 807e000 15 Child Activation Wait main_task
19161 2 80a4000 1 80ae000 15 Accept/Select Wait b
19162 3 809a800 1 80a4800 15 Child Activation Wait a
19163 * 4 80ae800 3 80b8000 15 Running c
19167 In this listing, the asterisk before the first task indicates it to be the
19168 currently running task. The first column lists the task ID that is used
19169 to refer to tasks in the following commands.
19171 @item break @var{linespec} task @var{taskid}
19172 @itemx break @var{linespec} task @var{taskid} if @dots{}
19173 @cindex Breakpoints and tasks
19174 These commands are like the @code{break @dots{} thread @dots{}}.
19175 @var{linespec} specifies source lines.
19177 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
19178 to specify that you only want @code{GDB} to stop the program when a
19179 particular Ada task reaches this breakpoint. @var{taskid} is one of the
19180 numeric task identifiers assigned by @code{GDB}, shown in the first
19181 column of the @samp{info tasks} display.
19183 If you do not specify @samp{task @var{taskid}} when you set a
19184 breakpoint, the breakpoint applies to @emph{all} tasks of your
19187 You can use the @code{task} qualifier on conditional breakpoints as
19188 well; in this case, place @samp{task @var{taskid}} before the
19189 breakpoint condition (before the @code{if}).
19191 @item task @var{taskno}
19192 @cindex Task switching
19194 This command allows to switch to the task referred by @var{taskno}. In
19195 particular, This allows to browse the backtrace of the specified
19196 task. It is advised to switch back to the original task before
19197 continuing execution otherwise the scheduling of the program may be
19202 For more detailed information on the tasking support,
19203 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
19205 @node Debugging Generic Units
19206 @section Debugging Generic Units
19207 @cindex Debugging Generic Units
19211 GNAT always uses code expansion for generic instantiation. This means that
19212 each time an instantiation occurs, a complete copy of the original code is
19213 made, with appropriate substitutions of formals by actuals.
19215 It is not possible to refer to the original generic entities in
19216 @code{GDB}, but it is always possible to debug a particular instance of
19217 a generic, by using the appropriate expanded names. For example, if we have
19219 @smallexample @c ada
19224 generic package k is
19225 procedure kp (v1 : in out integer);
19229 procedure kp (v1 : in out integer) is
19235 package k1 is new k;
19236 package k2 is new k;
19238 var : integer := 1;
19251 Then to break on a call to procedure kp in the k2 instance, simply
19255 (gdb) break g.k2.kp
19259 When the breakpoint occurs, you can step through the code of the
19260 instance in the normal manner and examine the values of local variables, as for
19263 @node Remote Debugging using gdbserver
19264 @section Remote Debugging using gdbserver
19265 @cindex Remote Debugging using gdbserver
19268 On platforms where gdbserver is supported, it is possible to use this tool
19269 to debug your application remotely. This can be useful in situations
19270 where the program needs to be run on a target host that is different
19271 from the host used for development, particularly when the target has
19272 a limited amount of resources (either CPU and/or memory).
19274 To do so, start your program using gdbserver on the target machine.
19275 gdbserver then automatically suspends the execution of your program
19276 at its entry point, waiting for a debugger to connect to it. The
19277 following commands starts an application and tells gdbserver to
19278 wait for a connection with the debugger on localhost port 4444.
19281 $ gdbserver localhost:4444 program
19282 Process program created; pid = 5685
19283 Listening on port 4444
19286 Once gdbserver has started listening, we can tell the debugger to establish
19287 a connection with this gdbserver, and then start the same debugging session
19288 as if the program was being debugged on the same host, directly under
19289 the control of GDB.
19293 (gdb) target remote targethost:4444
19294 Remote debugging using targethost:4444
19295 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
19297 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
19301 Breakpoint 1, foo () at foo.adb:4
19305 It is also possible to use gdbserver to attach to an already running
19306 program, in which case the execution of that program is simply suspended
19307 until the connection between the debugger and gdbserver is established.
19309 For more information on how to use gdbserver, @ref{Top, Server, Using
19310 the gdbserver Program, gdb, Debugging with GDB}. GNAT Pro provides support
19311 for gdbserver on x86-linux, x86-windows and x86_64-linux.
19313 @node GNAT Abnormal Termination or Failure to Terminate
19314 @section GNAT Abnormal Termination or Failure to Terminate
19315 @cindex GNAT Abnormal Termination or Failure to Terminate
19318 When presented with programs that contain serious errors in syntax
19320 GNAT may on rare occasions experience problems in operation, such
19322 segmentation fault or illegal memory access, raising an internal
19323 exception, terminating abnormally, or failing to terminate at all.
19324 In such cases, you can activate
19325 various features of GNAT that can help you pinpoint the construct in your
19326 program that is the likely source of the problem.
19328 The following strategies are presented in increasing order of
19329 difficulty, corresponding to your experience in using GNAT and your
19330 familiarity with compiler internals.
19334 Run @command{gcc} with the @option{-gnatf}. This first
19335 switch causes all errors on a given line to be reported. In its absence,
19336 only the first error on a line is displayed.
19338 The @option{-gnatdO} switch causes errors to be displayed as soon as they
19339 are encountered, rather than after compilation is terminated. If GNAT
19340 terminates prematurely or goes into an infinite loop, the last error
19341 message displayed may help to pinpoint the culprit.
19344 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
19345 mode, @command{gcc} produces ongoing information about the progress of the
19346 compilation and provides the name of each procedure as code is
19347 generated. This switch allows you to find which Ada procedure was being
19348 compiled when it encountered a code generation problem.
19351 @cindex @option{-gnatdc} switch
19352 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
19353 switch that does for the front-end what @option{^-v^VERBOSE^} does
19354 for the back end. The system prints the name of each unit,
19355 either a compilation unit or nested unit, as it is being analyzed.
19357 Finally, you can start
19358 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19359 front-end of GNAT, and can be run independently (normally it is just
19360 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
19361 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
19362 @code{where} command is the first line of attack; the variable
19363 @code{lineno} (seen by @code{print lineno}), used by the second phase of
19364 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
19365 which the execution stopped, and @code{input_file name} indicates the name of
19369 @node Naming Conventions for GNAT Source Files
19370 @section Naming Conventions for GNAT Source Files
19373 In order to examine the workings of the GNAT system, the following
19374 brief description of its organization may be helpful:
19378 Files with prefix @file{^sc^SC^} contain the lexical scanner.
19381 All files prefixed with @file{^par^PAR^} are components of the parser. The
19382 numbers correspond to chapters of the Ada Reference Manual. For example,
19383 parsing of select statements can be found in @file{par-ch9.adb}.
19386 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
19387 numbers correspond to chapters of the Ada standard. For example, all
19388 issues involving context clauses can be found in @file{sem_ch10.adb}. In
19389 addition, some features of the language require sufficient special processing
19390 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19391 dynamic dispatching, etc.
19394 All files prefixed with @file{^exp^EXP^} perform normalization and
19395 expansion of the intermediate representation (abstract syntax tree, or AST).
19396 these files use the same numbering scheme as the parser and semantics files.
19397 For example, the construction of record initialization procedures is done in
19398 @file{exp_ch3.adb}.
19401 The files prefixed with @file{^bind^BIND^} implement the binder, which
19402 verifies the consistency of the compilation, determines an order of
19403 elaboration, and generates the bind file.
19406 The files @file{atree.ads} and @file{atree.adb} detail the low-level
19407 data structures used by the front-end.
19410 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
19411 the abstract syntax tree as produced by the parser.
19414 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
19415 all entities, computed during semantic analysis.
19418 Library management issues are dealt with in files with prefix
19424 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
19425 defined in Annex A.
19430 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
19431 defined in Annex B.
19435 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
19436 both language-defined children and GNAT run-time routines.
19440 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
19441 general-purpose packages, fully documented in their specs. All
19442 the other @file{.c} files are modifications of common @command{gcc} files.
19445 @node Getting Internal Debugging Information
19446 @section Getting Internal Debugging Information
19449 Most compilers have internal debugging switches and modes. GNAT
19450 does also, except GNAT internal debugging switches and modes are not
19451 secret. A summary and full description of all the compiler and binder
19452 debug flags are in the file @file{debug.adb}. You must obtain the
19453 sources of the compiler to see the full detailed effects of these flags.
19455 The switches that print the source of the program (reconstructed from
19456 the internal tree) are of general interest for user programs, as are the
19458 the full internal tree, and the entity table (the symbol table
19459 information). The reconstructed source provides a readable version of the
19460 program after the front-end has completed analysis and expansion,
19461 and is useful when studying the performance of specific constructs.
19462 For example, constraint checks are indicated, complex aggregates
19463 are replaced with loops and assignments, and tasking primitives
19464 are replaced with run-time calls.
19466 @node Stack Traceback
19467 @section Stack Traceback
19469 @cindex stack traceback
19470 @cindex stack unwinding
19473 Traceback is a mechanism to display the sequence of subprogram calls that
19474 leads to a specified execution point in a program. Often (but not always)
19475 the execution point is an instruction at which an exception has been raised.
19476 This mechanism is also known as @i{stack unwinding} because it obtains
19477 its information by scanning the run-time stack and recovering the activation
19478 records of all active subprograms. Stack unwinding is one of the most
19479 important tools for program debugging.
19481 The first entry stored in traceback corresponds to the deepest calling level,
19482 that is to say the subprogram currently executing the instruction
19483 from which we want to obtain the traceback.
19485 Note that there is no runtime performance penalty when stack traceback
19486 is enabled, and no exception is raised during program execution.
19489 * Non-Symbolic Traceback::
19490 * Symbolic Traceback::
19493 @node Non-Symbolic Traceback
19494 @subsection Non-Symbolic Traceback
19495 @cindex traceback, non-symbolic
19498 Note: this feature is not supported on all platforms. See
19499 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
19503 * Tracebacks From an Unhandled Exception::
19504 * Tracebacks From Exception Occurrences (non-symbolic)::
19505 * Tracebacks From Anywhere in a Program (non-symbolic)::
19508 @node Tracebacks From an Unhandled Exception
19509 @subsubsection Tracebacks From an Unhandled Exception
19512 A runtime non-symbolic traceback is a list of addresses of call instructions.
19513 To enable this feature you must use the @option{-E}
19514 @code{gnatbind}'s option. With this option a stack traceback is stored as part
19515 of exception information. You can retrieve this information using the
19516 @code{addr2line} tool.
19518 Here is a simple example:
19520 @smallexample @c ada
19526 raise Constraint_Error;
19541 $ gnatmake stb -bargs -E
19544 Execution terminated by unhandled exception
19545 Exception name: CONSTRAINT_ERROR
19547 Call stack traceback locations:
19548 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19552 As we see the traceback lists a sequence of addresses for the unhandled
19553 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19554 guess that this exception come from procedure P1. To translate these
19555 addresses into the source lines where the calls appear, the
19556 @code{addr2line} tool, described below, is invaluable. The use of this tool
19557 requires the program to be compiled with debug information.
19560 $ gnatmake -g stb -bargs -E
19563 Execution terminated by unhandled exception
19564 Exception name: CONSTRAINT_ERROR
19566 Call stack traceback locations:
19567 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19569 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19570 0x4011f1 0x77e892a4
19572 00401373 at d:/stb/stb.adb:5
19573 0040138B at d:/stb/stb.adb:10
19574 0040139C at d:/stb/stb.adb:14
19575 00401335 at d:/stb/b~stb.adb:104
19576 004011C4 at /build/@dots{}/crt1.c:200
19577 004011F1 at /build/@dots{}/crt1.c:222
19578 77E892A4 in ?? at ??:0
19582 The @code{addr2line} tool has several other useful options:
19586 to get the function name corresponding to any location
19588 @item --demangle=gnat
19589 to use the gnat decoding mode for the function names. Note that
19590 for binutils version 2.9.x the option is simply @option{--demangle}.
19594 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
19595 0x40139c 0x401335 0x4011c4 0x4011f1
19597 00401373 in stb.p1 at d:/stb/stb.adb:5
19598 0040138B in stb.p2 at d:/stb/stb.adb:10
19599 0040139C in stb at d:/stb/stb.adb:14
19600 00401335 in main at d:/stb/b~stb.adb:104
19601 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
19602 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
19606 From this traceback we can see that the exception was raised in
19607 @file{stb.adb} at line 5, which was reached from a procedure call in
19608 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
19609 which contains the call to the main program.
19610 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
19611 and the output will vary from platform to platform.
19613 It is also possible to use @code{GDB} with these traceback addresses to debug
19614 the program. For example, we can break at a given code location, as reported
19615 in the stack traceback:
19621 Furthermore, this feature is not implemented inside Windows DLL. Only
19622 the non-symbolic traceback is reported in this case.
19625 (gdb) break *0x401373
19626 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19630 It is important to note that the stack traceback addresses
19631 do not change when debug information is included. This is particularly useful
19632 because it makes it possible to release software without debug information (to
19633 minimize object size), get a field report that includes a stack traceback
19634 whenever an internal bug occurs, and then be able to retrieve the sequence
19635 of calls with the same program compiled with debug information.
19637 @node Tracebacks From Exception Occurrences (non-symbolic)
19638 @subsubsection Tracebacks From Exception Occurrences
19641 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
19642 The stack traceback is attached to the exception information string, and can
19643 be retrieved in an exception handler within the Ada program, by means of the
19644 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19646 @smallexample @c ada
19648 with Ada.Exceptions;
19653 use Ada.Exceptions;
19661 Text_IO.Put_Line (Exception_Information (E));
19675 This program will output:
19680 Exception name: CONSTRAINT_ERROR
19681 Message: stb.adb:12
19682 Call stack traceback locations:
19683 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19686 @node Tracebacks From Anywhere in a Program (non-symbolic)
19687 @subsubsection Tracebacks From Anywhere in a Program
19690 It is also possible to retrieve a stack traceback from anywhere in a
19691 program. For this you need to
19692 use the @code{GNAT.Traceback} API. This package includes a procedure called
19693 @code{Call_Chain} that computes a complete stack traceback, as well as useful
19694 display procedures described below. It is not necessary to use the
19695 @option{-E gnatbind} option in this case, because the stack traceback mechanism
19696 is invoked explicitly.
19699 In the following example we compute a traceback at a specific location in
19700 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
19701 convert addresses to strings:
19703 @smallexample @c ada
19705 with GNAT.Traceback;
19706 with GNAT.Debug_Utilities;
19712 use GNAT.Traceback;
19715 TB : Tracebacks_Array (1 .. 10);
19716 -- We are asking for a maximum of 10 stack frames.
19718 -- Len will receive the actual number of stack frames returned.
19720 Call_Chain (TB, Len);
19722 Text_IO.Put ("In STB.P1 : ");
19724 for K in 1 .. Len loop
19725 Text_IO.Put (Debug_Utilities.Image (TB (K)));
19746 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
19747 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
19751 You can then get further information by invoking the @code{addr2line}
19752 tool as described earlier (note that the hexadecimal addresses
19753 need to be specified in C format, with a leading ``0x'').
19755 @node Symbolic Traceback
19756 @subsection Symbolic Traceback
19757 @cindex traceback, symbolic
19760 A symbolic traceback is a stack traceback in which procedure names are
19761 associated with each code location.
19764 Note that this feature is not supported on all platforms. See
19765 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
19766 list of currently supported platforms.
19769 Note that the symbolic traceback requires that the program be compiled
19770 with debug information. If it is not compiled with debug information
19771 only the non-symbolic information will be valid.
19774 * Tracebacks From Exception Occurrences (symbolic)::
19775 * Tracebacks From Anywhere in a Program (symbolic)::
19778 @node Tracebacks From Exception Occurrences (symbolic)
19779 @subsubsection Tracebacks From Exception Occurrences
19781 @smallexample @c ada
19783 with GNAT.Traceback.Symbolic;
19789 raise Constraint_Error;
19806 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
19811 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
19814 0040149F in stb.p1 at stb.adb:8
19815 004014B7 in stb.p2 at stb.adb:13
19816 004014CF in stb.p3 at stb.adb:18
19817 004015DD in ada.stb at stb.adb:22
19818 00401461 in main at b~stb.adb:168
19819 004011C4 in __mingw_CRTStartup at crt1.c:200
19820 004011F1 in mainCRTStartup at crt1.c:222
19821 77E892A4 in ?? at ??:0
19825 In the above example the ``.\'' syntax in the @command{gnatmake} command
19826 is currently required by @command{addr2line} for files that are in
19827 the current working directory.
19828 Moreover, the exact sequence of linker options may vary from platform
19830 The above @option{-largs} section is for Windows platforms. By contrast,
19831 under Unix there is no need for the @option{-largs} section.
19832 Differences across platforms are due to details of linker implementation.
19834 @node Tracebacks From Anywhere in a Program (symbolic)
19835 @subsubsection Tracebacks From Anywhere in a Program
19838 It is possible to get a symbolic stack traceback
19839 from anywhere in a program, just as for non-symbolic tracebacks.
19840 The first step is to obtain a non-symbolic
19841 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
19842 information. Here is an example:
19844 @smallexample @c ada
19846 with GNAT.Traceback;
19847 with GNAT.Traceback.Symbolic;
19852 use GNAT.Traceback;
19853 use GNAT.Traceback.Symbolic;
19856 TB : Tracebacks_Array (1 .. 10);
19857 -- We are asking for a maximum of 10 stack frames.
19859 -- Len will receive the actual number of stack frames returned.
19861 Call_Chain (TB, Len);
19862 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
19875 @c ******************************
19877 @node Compatibility with HP Ada
19878 @chapter Compatibility with HP Ada
19879 @cindex Compatibility
19884 @cindex Compatibility between GNAT and HP Ada
19885 This chapter compares HP Ada (formerly known as ``DEC Ada'')
19886 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
19887 GNAT is highly compatible
19888 with HP Ada, and it should generally be straightforward to port code
19889 from the HP Ada environment to GNAT. However, there are a few language
19890 and implementation differences of which the user must be aware. These
19891 differences are discussed in this chapter. In
19892 addition, the operating environment and command structure for the
19893 compiler are different, and these differences are also discussed.
19895 For further details on these and other compatibility issues,
19896 see Appendix E of the HP publication
19897 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
19899 Except where otherwise indicated, the description of GNAT for OpenVMS
19900 applies to both the Alpha and I64 platforms.
19902 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
19903 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
19905 The discussion in this chapter addresses specifically the implementation
19906 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
19907 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
19908 GNAT always follows the Alpha implementation.
19910 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
19911 attributes are recognized, although only a subset of them can sensibly
19912 be implemented. The description of pragmas in
19913 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
19914 indicates whether or not they are applicable to non-VMS systems.
19917 * Ada Language Compatibility::
19918 * Differences in the Definition of Package System::
19919 * Language-Related Features::
19920 * The Package STANDARD::
19921 * The Package SYSTEM::
19922 * Tasking and Task-Related Features::
19923 * Pragmas and Pragma-Related Features::
19924 * Library of Predefined Units::
19926 * Main Program Definition::
19927 * Implementation-Defined Attributes::
19928 * Compiler and Run-Time Interfacing::
19929 * Program Compilation and Library Management::
19931 * Implementation Limits::
19932 * Tools and Utilities::
19935 @node Ada Language Compatibility
19936 @section Ada Language Compatibility
19939 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
19940 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
19941 with Ada 83, and therefore Ada 83 programs will compile
19942 and run under GNAT with
19943 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
19944 provides details on specific incompatibilities.
19946 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
19947 as well as the pragma @code{ADA_83}, to force the compiler to
19948 operate in Ada 83 mode. This mode does not guarantee complete
19949 conformance to Ada 83, but in practice is sufficient to
19950 eliminate most sources of incompatibilities.
19951 In particular, it eliminates the recognition of the
19952 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
19953 in Ada 83 programs is legal, and handles the cases of packages
19954 with optional bodies, and generics that instantiate unconstrained
19955 types without the use of @code{(<>)}.
19957 @node Differences in the Definition of Package System
19958 @section Differences in the Definition of Package @code{System}
19961 An Ada compiler is allowed to add
19962 implementation-dependent declarations to package @code{System}.
19964 GNAT does not take advantage of this permission, and the version of
19965 @code{System} provided by GNAT exactly matches that defined in the Ada
19968 However, HP Ada adds an extensive set of declarations to package
19970 as fully documented in the HP Ada manuals. To minimize changes required
19971 for programs that make use of these extensions, GNAT provides the pragma
19972 @code{Extend_System} for extending the definition of package System. By using:
19973 @cindex pragma @code{Extend_System}
19974 @cindex @code{Extend_System} pragma
19976 @smallexample @c ada
19979 pragma Extend_System (Aux_DEC);
19985 the set of definitions in @code{System} is extended to include those in
19986 package @code{System.Aux_DEC}.
19987 @cindex @code{System.Aux_DEC} package
19988 @cindex @code{Aux_DEC} package (child of @code{System})
19989 These definitions are incorporated directly into package @code{System},
19990 as though they had been declared there. For a
19991 list of the declarations added, see the spec of this package,
19992 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
19993 @cindex @file{s-auxdec.ads} file
19994 The pragma @code{Extend_System} is a configuration pragma, which means that
19995 it can be placed in the file @file{gnat.adc}, so that it will automatically
19996 apply to all subsequent compilations. See @ref{Configuration Pragmas},
19997 for further details.
19999 An alternative approach that avoids the use of the non-standard
20000 @code{Extend_System} pragma is to add a context clause to the unit that
20001 references these facilities:
20003 @smallexample @c ada
20005 with System.Aux_DEC;
20006 use System.Aux_DEC;
20011 The effect is not quite semantically identical to incorporating
20012 the declarations directly into package @code{System},
20013 but most programs will not notice a difference
20014 unless they use prefix notation (e.g.@: @code{System.Integer_8})
20015 to reference the entities directly in package @code{System}.
20016 For units containing such references,
20017 the prefixes must either be removed, or the pragma @code{Extend_System}
20020 @node Language-Related Features
20021 @section Language-Related Features
20024 The following sections highlight differences in types,
20025 representations of types, operations, alignment, and
20029 * Integer Types and Representations::
20030 * Floating-Point Types and Representations::
20031 * Pragmas Float_Representation and Long_Float::
20032 * Fixed-Point Types and Representations::
20033 * Record and Array Component Alignment::
20034 * Address Clauses::
20035 * Other Representation Clauses::
20038 @node Integer Types and Representations
20039 @subsection Integer Types and Representations
20042 The set of predefined integer types is identical in HP Ada and GNAT.
20043 Furthermore the representation of these integer types is also identical,
20044 including the capability of size clauses forcing biased representation.
20047 HP Ada for OpenVMS Alpha systems has defined the
20048 following additional integer types in package @code{System}:
20065 @code{LARGEST_INTEGER}
20069 In GNAT, the first four of these types may be obtained from the
20070 standard Ada package @code{Interfaces}.
20071 Alternatively, by use of the pragma @code{Extend_System}, identical
20072 declarations can be referenced directly in package @code{System}.
20073 On both GNAT and HP Ada, the maximum integer size is 64 bits.
20075 @node Floating-Point Types and Representations
20076 @subsection Floating-Point Types and Representations
20077 @cindex Floating-Point types
20080 The set of predefined floating-point types is identical in HP Ada and GNAT.
20081 Furthermore the representation of these floating-point
20082 types is also identical. One important difference is that the default
20083 representation for HP Ada is @code{VAX_Float}, but the default representation
20086 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
20087 pragma @code{Float_Representation} as described in the HP Ada
20089 For example, the declarations:
20091 @smallexample @c ada
20093 type F_Float is digits 6;
20094 pragma Float_Representation (VAX_Float, F_Float);
20099 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
20101 This set of declarations actually appears in @code{System.Aux_DEC},
20103 the full set of additional floating-point declarations provided in
20104 the HP Ada version of package @code{System}.
20105 This and similar declarations may be accessed in a user program
20106 by using pragma @code{Extend_System}. The use of this
20107 pragma, and the related pragma @code{Long_Float} is described in further
20108 detail in the following section.
20110 @node Pragmas Float_Representation and Long_Float
20111 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
20114 HP Ada provides the pragma @code{Float_Representation}, which
20115 acts as a program library switch to allow control over
20116 the internal representation chosen for the predefined
20117 floating-point types declared in the package @code{Standard}.
20118 The format of this pragma is as follows:
20120 @smallexample @c ada
20122 pragma Float_Representation(VAX_Float | IEEE_Float);
20127 This pragma controls the representation of floating-point
20132 @code{VAX_Float} specifies that floating-point
20133 types are represented by default with the VAX system hardware types
20134 @code{F-floating}, @code{D-floating}, @code{G-floating}.
20135 Note that the @code{H-floating}
20136 type was available only on VAX systems, and is not available
20137 in either HP Ada or GNAT.
20140 @code{IEEE_Float} specifies that floating-point
20141 types are represented by default with the IEEE single and
20142 double floating-point types.
20146 GNAT provides an identical implementation of the pragma
20147 @code{Float_Representation}, except that it functions as a
20148 configuration pragma. Note that the
20149 notion of configuration pragma corresponds closely to the
20150 HP Ada notion of a program library switch.
20152 When no pragma is used in GNAT, the default is @code{IEEE_Float},
20154 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
20155 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
20156 advisable to change the format of numbers passed to standard library
20157 routines, and if necessary explicit type conversions may be needed.
20159 The use of @code{IEEE_Float} is recommended in GNAT since it is more
20160 efficient, and (given that it conforms to an international standard)
20161 potentially more portable.
20162 The situation in which @code{VAX_Float} may be useful is in interfacing
20163 to existing code and data that expect the use of @code{VAX_Float}.
20164 In such a situation use the predefined @code{VAX_Float}
20165 types in package @code{System}, as extended by
20166 @code{Extend_System}. For example, use @code{System.F_Float}
20167 to specify the 32-bit @code{F-Float} format.
20170 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
20171 to allow control over the internal representation chosen
20172 for the predefined type @code{Long_Float} and for floating-point
20173 type declarations with digits specified in the range 7 .. 15.
20174 The format of this pragma is as follows:
20176 @smallexample @c ada
20178 pragma Long_Float (D_FLOAT | G_FLOAT);
20182 @node Fixed-Point Types and Representations
20183 @subsection Fixed-Point Types and Representations
20186 On HP Ada for OpenVMS Alpha systems, rounding is
20187 away from zero for both positive and negative numbers.
20188 Therefore, @code{+0.5} rounds to @code{1},
20189 and @code{-0.5} rounds to @code{-1}.
20191 On GNAT the results of operations
20192 on fixed-point types are in accordance with the Ada
20193 rules. In particular, results of operations on decimal
20194 fixed-point types are truncated.
20196 @node Record and Array Component Alignment
20197 @subsection Record and Array Component Alignment
20200 On HP Ada for OpenVMS Alpha, all non-composite components
20201 are aligned on natural boundaries. For example, 1-byte
20202 components are aligned on byte boundaries, 2-byte
20203 components on 2-byte boundaries, 4-byte components on 4-byte
20204 byte boundaries, and so on. The OpenVMS Alpha hardware
20205 runs more efficiently with naturally aligned data.
20207 On GNAT, alignment rules are compatible
20208 with HP Ada for OpenVMS Alpha.
20210 @node Address Clauses
20211 @subsection Address Clauses
20214 In HP Ada and GNAT, address clauses are supported for
20215 objects and imported subprograms.
20216 The predefined type @code{System.Address} is a private type
20217 in both compilers on Alpha OpenVMS, with the same representation
20218 (it is simply a machine pointer). Addition, subtraction, and comparison
20219 operations are available in the standard Ada package
20220 @code{System.Storage_Elements}, or in package @code{System}
20221 if it is extended to include @code{System.Aux_DEC} using a
20222 pragma @code{Extend_System} as previously described.
20224 Note that code that @code{with}'s both this extended package @code{System}
20225 and the package @code{System.Storage_Elements} should not @code{use}
20226 both packages, or ambiguities will result. In general it is better
20227 not to mix these two sets of facilities. The Ada package was
20228 designed specifically to provide the kind of features that HP Ada
20229 adds directly to package @code{System}.
20231 The type @code{System.Address} is a 64-bit integer type in GNAT for
20232 I64 OpenVMS. For more information,
20233 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
20235 GNAT is compatible with HP Ada in its handling of address
20236 clauses, except for some limitations in
20237 the form of address clauses for composite objects with
20238 initialization. Such address clauses are easily replaced
20239 by the use of an explicitly-defined constant as described
20240 in the Ada Reference Manual (13.1(22)). For example, the sequence
20243 @smallexample @c ada
20245 X, Y : Integer := Init_Func;
20246 Q : String (X .. Y) := "abc";
20248 for Q'Address use Compute_Address;
20253 will be rejected by GNAT, since the address cannot be computed at the time
20254 that @code{Q} is declared. To achieve the intended effect, write instead:
20256 @smallexample @c ada
20259 X, Y : Integer := Init_Func;
20260 Q_Address : constant Address := Compute_Address;
20261 Q : String (X .. Y) := "abc";
20263 for Q'Address use Q_Address;
20269 which will be accepted by GNAT (and other Ada compilers), and is also
20270 compatible with Ada 83. A fuller description of the restrictions
20271 on address specifications is found in @ref{Top, GNAT Reference Manual,
20272 About This Guide, gnat_rm, GNAT Reference Manual}.
20274 @node Other Representation Clauses
20275 @subsection Other Representation Clauses
20278 GNAT implements in a compatible manner all the representation
20279 clauses supported by HP Ada. In addition, GNAT
20280 implements the representation clause forms that were introduced in Ada 95,
20281 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
20283 @node The Package STANDARD
20284 @section The Package @code{STANDARD}
20287 The package @code{STANDARD}, as implemented by HP Ada, is fully
20288 described in the @cite{Ada Reference Manual} and in the
20289 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
20290 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
20292 In addition, HP Ada supports the Latin-1 character set in
20293 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
20294 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
20295 the type @code{WIDE_CHARACTER}.
20297 The floating-point types supported by GNAT are those
20298 supported by HP Ada, but the defaults are different, and are controlled by
20299 pragmas. See @ref{Floating-Point Types and Representations}, for details.
20301 @node The Package SYSTEM
20302 @section The Package @code{SYSTEM}
20305 HP Ada provides a specific version of the package
20306 @code{SYSTEM} for each platform on which the language is implemented.
20307 For the complete spec of the package @code{SYSTEM}, see
20308 Appendix F of the @cite{HP Ada Language Reference Manual}.
20310 On HP Ada, the package @code{SYSTEM} includes the following conversion
20313 @item @code{TO_ADDRESS(INTEGER)}
20315 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
20317 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
20319 @item @code{TO_INTEGER(ADDRESS)}
20321 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
20323 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
20324 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
20328 By default, GNAT supplies a version of @code{SYSTEM} that matches
20329 the definition given in the @cite{Ada Reference Manual}.
20331 is a subset of the HP system definitions, which is as
20332 close as possible to the original definitions. The only difference
20333 is that the definition of @code{SYSTEM_NAME} is different:
20335 @smallexample @c ada
20337 type Name is (SYSTEM_NAME_GNAT);
20338 System_Name : constant Name := SYSTEM_NAME_GNAT;
20343 Also, GNAT adds the Ada declarations for
20344 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
20346 However, the use of the following pragma causes GNAT
20347 to extend the definition of package @code{SYSTEM} so that it
20348 encompasses the full set of HP-specific extensions,
20349 including the functions listed above:
20351 @smallexample @c ada
20353 pragma Extend_System (Aux_DEC);
20358 The pragma @code{Extend_System} is a configuration pragma that
20359 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
20360 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
20362 HP Ada does not allow the recompilation of the package
20363 @code{SYSTEM}. Instead HP Ada provides several pragmas
20364 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
20365 to modify values in the package @code{SYSTEM}.
20366 On OpenVMS Alpha systems, the pragma
20367 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
20368 its single argument.
20370 GNAT does permit the recompilation of package @code{SYSTEM} using
20371 the special switch @option{-gnatg}, and this switch can be used if
20372 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
20373 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
20374 or @code{MEMORY_SIZE} by any other means.
20376 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
20377 enumeration literal @code{SYSTEM_NAME_GNAT}.
20379 The definitions provided by the use of
20381 @smallexample @c ada
20382 pragma Extend_System (AUX_Dec);
20386 are virtually identical to those provided by the HP Ada 83 package
20387 @code{SYSTEM}. One important difference is that the name of the
20389 function for type @code{UNSIGNED_LONGWORD} is changed to
20390 @code{TO_ADDRESS_LONG}.
20391 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
20392 discussion of why this change was necessary.
20395 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
20397 an extension to Ada 83 not strictly compatible with the reference manual.
20398 GNAT, in order to be exactly compatible with the standard,
20399 does not provide this capability. In HP Ada 83, the
20400 point of this definition is to deal with a call like:
20402 @smallexample @c ada
20403 TO_ADDRESS (16#12777#);
20407 Normally, according to Ada 83 semantics, one would expect this to be
20408 ambiguous, since it matches both the @code{INTEGER} and
20409 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
20410 However, in HP Ada 83, there is no ambiguity, since the
20411 definition using @i{universal_integer} takes precedence.
20413 In GNAT, since the version with @i{universal_integer} cannot be supplied,
20415 not possible to be 100% compatible. Since there are many programs using
20416 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
20418 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
20419 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
20421 @smallexample @c ada
20422 function To_Address (X : Integer) return Address;
20423 pragma Pure_Function (To_Address);
20425 function To_Address_Long (X : Unsigned_Longword) return Address;
20426 pragma Pure_Function (To_Address_Long);
20430 This means that programs using @code{TO_ADDRESS} for
20431 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
20433 @node Tasking and Task-Related Features
20434 @section Tasking and Task-Related Features
20437 This section compares the treatment of tasking in GNAT
20438 and in HP Ada for OpenVMS Alpha.
20439 The GNAT description applies to both Alpha and I64 OpenVMS.
20440 For detailed information on tasking in
20441 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
20442 relevant run-time reference manual.
20445 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
20446 * Assigning Task IDs::
20447 * Task IDs and Delays::
20448 * Task-Related Pragmas::
20449 * Scheduling and Task Priority::
20451 * External Interrupts::
20454 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20455 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20458 On OpenVMS Alpha systems, each Ada task (except a passive
20459 task) is implemented as a single stream of execution
20460 that is created and managed by the kernel. On these
20461 systems, HP Ada tasking support is based on DECthreads,
20462 an implementation of the POSIX standard for threads.
20464 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
20465 code that calls DECthreads routines can be used together.
20466 The interaction between Ada tasks and DECthreads routines
20467 can have some benefits. For example when on OpenVMS Alpha,
20468 HP Ada can call C code that is already threaded.
20470 GNAT uses the facilities of DECthreads,
20471 and Ada tasks are mapped to threads.
20473 @node Assigning Task IDs
20474 @subsection Assigning Task IDs
20477 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
20478 the environment task that executes the main program. On
20479 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
20480 that have been created but are not yet activated.
20482 On OpenVMS Alpha systems, task IDs are assigned at
20483 activation. On GNAT systems, task IDs are also assigned at
20484 task creation but do not have the same form or values as
20485 task ID values in HP Ada. There is no null task, and the
20486 environment task does not have a specific task ID value.
20488 @node Task IDs and Delays
20489 @subsection Task IDs and Delays
20492 On OpenVMS Alpha systems, tasking delays are implemented
20493 using Timer System Services. The Task ID is used for the
20494 identification of the timer request (the @code{REQIDT} parameter).
20495 If Timers are used in the application take care not to use
20496 @code{0} for the identification, because cancelling such a timer
20497 will cancel all timers and may lead to unpredictable results.
20499 @node Task-Related Pragmas
20500 @subsection Task-Related Pragmas
20503 Ada supplies the pragma @code{TASK_STORAGE}, which allows
20504 specification of the size of the guard area for a task
20505 stack. (The guard area forms an area of memory that has no
20506 read or write access and thus helps in the detection of
20507 stack overflow.) On OpenVMS Alpha systems, if the pragma
20508 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
20509 area is created. In the absence of a pragma @code{TASK_STORAGE},
20510 a default guard area is created.
20512 GNAT supplies the following task-related pragmas:
20515 @item @code{TASK_INFO}
20517 This pragma appears within a task definition and
20518 applies to the task in which it appears. The argument
20519 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
20521 @item @code{TASK_STORAGE}
20523 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
20524 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
20525 @code{SUPPRESS}, and @code{VOLATILE}.
20527 @node Scheduling and Task Priority
20528 @subsection Scheduling and Task Priority
20531 HP Ada implements the Ada language requirement that
20532 when two tasks are eligible for execution and they have
20533 different priorities, the lower priority task does not
20534 execute while the higher priority task is waiting. The HP
20535 Ada Run-Time Library keeps a task running until either the
20536 task is suspended or a higher priority task becomes ready.
20538 On OpenVMS Alpha systems, the default strategy is round-
20539 robin with preemption. Tasks of equal priority take turns
20540 at the processor. A task is run for a certain period of
20541 time and then placed at the tail of the ready queue for
20542 its priority level.
20544 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
20545 which can be used to enable or disable round-robin
20546 scheduling of tasks with the same priority.
20547 See the relevant HP Ada run-time reference manual for
20548 information on using the pragmas to control HP Ada task
20551 GNAT follows the scheduling rules of Annex D (Real-Time
20552 Annex) of the @cite{Ada Reference Manual}. In general, this
20553 scheduling strategy is fully compatible with HP Ada
20554 although it provides some additional constraints (as
20555 fully documented in Annex D).
20556 GNAT implements time slicing control in a manner compatible with
20557 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
20558 are identical to the HP Ada 83 pragma of the same name.
20559 Note that it is not possible to mix GNAT tasking and
20560 HP Ada 83 tasking in the same program, since the two run-time
20561 libraries are not compatible.
20563 @node The Task Stack
20564 @subsection The Task Stack
20567 In HP Ada, a task stack is allocated each time a
20568 non-passive task is activated. As soon as the task is
20569 terminated, the storage for the task stack is deallocated.
20570 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
20571 a default stack size is used. Also, regardless of the size
20572 specified, some additional space is allocated for task
20573 management purposes. On OpenVMS Alpha systems, at least
20574 one page is allocated.
20576 GNAT handles task stacks in a similar manner. In accordance with
20577 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
20578 an alternative method for controlling the task stack size.
20579 The specification of the attribute @code{T'STORAGE_SIZE} is also
20580 supported in a manner compatible with HP Ada.
20582 @node External Interrupts
20583 @subsection External Interrupts
20586 On HP Ada, external interrupts can be associated with task entries.
20587 GNAT is compatible with HP Ada in its handling of external interrupts.
20589 @node Pragmas and Pragma-Related Features
20590 @section Pragmas and Pragma-Related Features
20593 Both HP Ada and GNAT supply all language-defined pragmas
20594 as specified by the Ada 83 standard. GNAT also supplies all
20595 language-defined pragmas introduced by Ada 95 and Ada 2005.
20596 In addition, GNAT implements the implementation-defined pragmas
20600 @item @code{AST_ENTRY}
20602 @item @code{COMMON_OBJECT}
20604 @item @code{COMPONENT_ALIGNMENT}
20606 @item @code{EXPORT_EXCEPTION}
20608 @item @code{EXPORT_FUNCTION}
20610 @item @code{EXPORT_OBJECT}
20612 @item @code{EXPORT_PROCEDURE}
20614 @item @code{EXPORT_VALUED_PROCEDURE}
20616 @item @code{FLOAT_REPRESENTATION}
20620 @item @code{IMPORT_EXCEPTION}
20622 @item @code{IMPORT_FUNCTION}
20624 @item @code{IMPORT_OBJECT}
20626 @item @code{IMPORT_PROCEDURE}
20628 @item @code{IMPORT_VALUED_PROCEDURE}
20630 @item @code{INLINE_GENERIC}
20632 @item @code{INTERFACE_NAME}
20634 @item @code{LONG_FLOAT}
20636 @item @code{MAIN_STORAGE}
20638 @item @code{PASSIVE}
20640 @item @code{PSECT_OBJECT}
20642 @item @code{SHARE_GENERIC}
20644 @item @code{SUPPRESS_ALL}
20646 @item @code{TASK_STORAGE}
20648 @item @code{TIME_SLICE}
20654 These pragmas are all fully implemented, with the exception of @code{TITLE},
20655 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
20656 recognized, but which have no
20657 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
20658 use of Ada protected objects. In GNAT, all generics are inlined.
20660 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
20661 a separate subprogram specification which must appear before the
20664 GNAT also supplies a number of implementation-defined pragmas including the
20668 @item @code{ABORT_DEFER}
20670 @item @code{ADA_83}
20672 @item @code{ADA_95}
20674 @item @code{ADA_05}
20676 @item @code{Ada_2005}
20678 @item @code{Ada_12}
20680 @item @code{Ada_2012}
20682 @item @code{ANNOTATE}
20684 @item @code{ASSERT}
20686 @item @code{C_PASS_BY_COPY}
20688 @item @code{CPP_CLASS}
20690 @item @code{CPP_CONSTRUCTOR}
20692 @item @code{CPP_DESTRUCTOR}
20696 @item @code{EXTEND_SYSTEM}
20698 @item @code{LINKER_ALIAS}
20700 @item @code{LINKER_SECTION}
20702 @item @code{MACHINE_ATTRIBUTE}
20704 @item @code{NO_RETURN}
20706 @item @code{PURE_FUNCTION}
20708 @item @code{SOURCE_FILE_NAME}
20710 @item @code{SOURCE_REFERENCE}
20712 @item @code{TASK_INFO}
20714 @item @code{UNCHECKED_UNION}
20716 @item @code{UNIMPLEMENTED_UNIT}
20718 @item @code{UNIVERSAL_DATA}
20720 @item @code{UNSUPPRESS}
20722 @item @code{WARNINGS}
20724 @item @code{WEAK_EXTERNAL}
20728 For full details on these and other GNAT implementation-defined pragmas,
20729 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
20733 * Restrictions on the Pragma INLINE::
20734 * Restrictions on the Pragma INTERFACE::
20735 * Restrictions on the Pragma SYSTEM_NAME::
20738 @node Restrictions on the Pragma INLINE
20739 @subsection Restrictions on Pragma @code{INLINE}
20742 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
20744 @item Parameters cannot have a task type.
20746 @item Function results cannot be task types, unconstrained
20747 array types, or unconstrained types with discriminants.
20749 @item Bodies cannot declare the following:
20751 @item Subprogram body or stub (imported subprogram is allowed)
20755 @item Generic declarations
20757 @item Instantiations
20761 @item Access types (types derived from access types allowed)
20763 @item Array or record types
20765 @item Dependent tasks
20767 @item Direct recursive calls of subprogram or containing
20768 subprogram, directly or via a renaming
20774 In GNAT, the only restriction on pragma @code{INLINE} is that the
20775 body must occur before the call if both are in the same
20776 unit, and the size must be appropriately small. There are
20777 no other specific restrictions which cause subprograms to
20778 be incapable of being inlined.
20780 @node Restrictions on the Pragma INTERFACE
20781 @subsection Restrictions on Pragma @code{INTERFACE}
20784 The following restrictions on pragma @code{INTERFACE}
20785 are enforced by both HP Ada and GNAT:
20787 @item Languages accepted: Ada, Bliss, C, Fortran, Default.
20788 Default is the default on OpenVMS Alpha systems.
20790 @item Parameter passing: Language specifies default
20791 mechanisms but can be overridden with an @code{EXPORT} pragma.
20794 @item Ada: Use internal Ada rules.
20796 @item Bliss, C: Parameters must be mode @code{in}; cannot be
20797 record or task type. Result cannot be a string, an
20798 array, or a record.
20800 @item Fortran: Parameters cannot have a task type. Result cannot
20801 be a string, an array, or a record.
20806 GNAT is entirely upwards compatible with HP Ada, and in addition allows
20807 record parameters for all languages.
20809 @node Restrictions on the Pragma SYSTEM_NAME
20810 @subsection Restrictions on Pragma @code{SYSTEM_NAME}
20813 For HP Ada for OpenVMS Alpha, the enumeration literal
20814 for the type @code{NAME} is @code{OPENVMS_AXP}.
20815 In GNAT, the enumeration
20816 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
20818 @node Library of Predefined Units
20819 @section Library of Predefined Units
20822 A library of predefined units is provided as part of the
20823 HP Ada and GNAT implementations. HP Ada does not provide
20824 the package @code{MACHINE_CODE} but instead recommends importing
20827 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
20828 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
20830 The HP Ada Predefined Library units are modified to remove post-Ada 83
20831 incompatibilities and to make them interoperable with GNAT
20832 (@pxref{Changes to DECLIB}, for details).
20833 The units are located in the @file{DECLIB} directory.
20835 The GNAT RTL is contained in
20836 the @file{ADALIB} directory, and
20837 the default search path is set up to find @code{DECLIB} units in preference
20838 to @code{ADALIB} units with the same name (@code{TEXT_IO},
20839 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
20842 * Changes to DECLIB::
20845 @node Changes to DECLIB
20846 @subsection Changes to @code{DECLIB}
20849 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
20850 compatibility are minor and include the following:
20853 @item Adjusting the location of pragmas and record representation
20854 clauses to obey Ada 95 (and thus Ada 2005) rules
20856 @item Adding the proper notation to generic formal parameters
20857 that take unconstrained types in instantiation
20859 @item Adding pragma @code{ELABORATE_BODY} to package specs
20860 that have package bodies not otherwise allowed
20862 @item Replacing occurrences of the identifier ``@code{PROTECTED}'' by
20863 ``@code{PROTECTD}''.
20864 Currently these are found only in the @code{STARLET} package spec.
20866 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
20867 where the address size is constrained to 32 bits.
20871 None of the above changes is visible to users.
20877 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
20880 @item Command Language Interpreter (CLI interface)
20882 @item DECtalk Run-Time Library (DTK interface)
20884 @item Librarian utility routines (LBR interface)
20886 @item General Purpose Run-Time Library (LIB interface)
20888 @item Math Run-Time Library (MTH interface)
20890 @item National Character Set Run-Time Library (NCS interface)
20892 @item Compiled Code Support Run-Time Library (OTS interface)
20894 @item Parallel Processing Run-Time Library (PPL interface)
20896 @item Screen Management Run-Time Library (SMG interface)
20898 @item Sort Run-Time Library (SOR interface)
20900 @item String Run-Time Library (STR interface)
20902 @item STARLET System Library
20905 @item X Window System Version 11R4 and 11R5 (X, XLIB interface)
20907 @item X Windows Toolkit (XT interface)
20909 @item X/Motif Version 1.1.3 and 1.2 (XM interface)
20913 GNAT provides implementations of these HP bindings in the @code{DECLIB}
20914 directory, on both the Alpha and I64 OpenVMS platforms.
20916 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
20918 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
20919 A pragma @code{Linker_Options} has been added to packages @code{Xm},
20920 @code{Xt}, and @code{X_Lib}
20921 causing the default X/Motif sharable image libraries to be linked in. This
20922 is done via options files named @file{xm.opt}, @file{xt.opt}, and
20923 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
20925 It may be necessary to edit these options files to update or correct the
20926 library names if, for example, the newer X/Motif bindings from
20927 @file{ADA$EXAMPLES}
20928 had been (previous to installing GNAT) copied and renamed to supersede the
20929 default @file{ADA$PREDEFINED} versions.
20932 * Shared Libraries and Options Files::
20933 * Interfaces to C::
20936 @node Shared Libraries and Options Files
20937 @subsection Shared Libraries and Options Files
20940 When using the HP Ada
20941 predefined X and Motif bindings, the linking with their sharable images is
20942 done automatically by @command{GNAT LINK}.
20943 When using other X and Motif bindings, you need
20944 to add the corresponding sharable images to the command line for
20945 @code{GNAT LINK}. When linking with shared libraries, or with
20946 @file{.OPT} files, you must
20947 also add them to the command line for @command{GNAT LINK}.
20949 A shared library to be used with GNAT is built in the same way as other
20950 libraries under VMS. The VMS Link command can be used in standard fashion.
20952 @node Interfaces to C
20953 @subsection Interfaces to C
20957 provides the following Ada types and operations:
20960 @item C types package (@code{C_TYPES})
20962 @item C strings (@code{C_TYPES.NULL_TERMINATED})
20964 @item Other_types (@code{SHORT_INT})
20968 Interfacing to C with GNAT, you can use the above approach
20969 described for HP Ada or the facilities of Annex B of
20970 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
20971 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
20972 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
20974 The @option{-gnatF} qualifier forces default and explicit
20975 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
20976 to be uppercased for compatibility with the default behavior
20977 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
20979 @node Main Program Definition
20980 @section Main Program Definition
20983 The following section discusses differences in the
20984 definition of main programs on HP Ada and GNAT.
20985 On HP Ada, main programs are defined to meet the
20986 following conditions:
20988 @item Procedure with no formal parameters (returns @code{0} upon
20991 @item Procedure with no formal parameters (returns @code{42} when
20992 an unhandled exception is raised)
20994 @item Function with no formal parameters whose returned value
20995 is of a discrete type
20997 @item Procedure with one @code{out} formal of a discrete type for
20998 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
21003 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
21004 a main function or main procedure returns a discrete
21005 value whose size is less than 64 bits (32 on VAX systems),
21006 the value is zero- or sign-extended as appropriate.
21007 On GNAT, main programs are defined as follows:
21009 @item Must be a non-generic, parameterless subprogram that
21010 is either a procedure or function returning an Ada
21011 @code{STANDARD.INTEGER} (the predefined type)
21013 @item Cannot be a generic subprogram or an instantiation of a
21017 @node Implementation-Defined Attributes
21018 @section Implementation-Defined Attributes
21021 GNAT provides all HP Ada implementation-defined
21024 @node Compiler and Run-Time Interfacing
21025 @section Compiler and Run-Time Interfacing
21028 HP Ada provides the following qualifiers to pass options to the linker
21031 @item @option{/WAIT} and @option{/SUBMIT}
21033 @item @option{/COMMAND}
21035 @item @option{/@r{[}NO@r{]}MAP}
21037 @item @option{/OUTPUT=@var{file-spec}}
21039 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21043 To pass options to the linker, GNAT provides the following
21047 @item @option{/EXECUTABLE=@var{exec-name}}
21049 @item @option{/VERBOSE}
21051 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21055 For more information on these switches, see
21056 @ref{Switches for gnatlink}.
21057 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
21058 to control optimization. HP Ada also supplies the
21061 @item @code{OPTIMIZE}
21063 @item @code{INLINE}
21065 @item @code{INLINE_GENERIC}
21067 @item @code{SUPPRESS_ALL}
21069 @item @code{PASSIVE}
21073 In GNAT, optimization is controlled strictly by command
21074 line parameters, as described in the corresponding section of this guide.
21075 The HP pragmas for control of optimization are
21076 recognized but ignored.
21078 Note that in GNAT, the default is optimization off, whereas in HP Ada
21079 the default is that optimization is turned on.
21081 @node Program Compilation and Library Management
21082 @section Program Compilation and Library Management
21085 HP Ada and GNAT provide a comparable set of commands to
21086 build programs. HP Ada also provides a program library,
21087 which is a concept that does not exist on GNAT. Instead,
21088 GNAT provides directories of sources that are compiled as
21091 The following table summarizes
21092 the HP Ada commands and provides
21093 equivalent GNAT commands. In this table, some GNAT
21094 equivalents reflect the fact that GNAT does not use the
21095 concept of a program library. Instead, it uses a model
21096 in which collections of source and object files are used
21097 in a manner consistent with other languages like C and
21098 Fortran. Therefore, standard system file commands are used
21099 to manipulate these elements. Those GNAT commands are marked with
21101 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
21104 @multitable @columnfractions .35 .65
21106 @item @emph{HP Ada Command}
21107 @tab @emph{GNAT Equivalent / Description}
21109 @item @command{ADA}
21110 @tab @command{GNAT COMPILE}@*
21111 Invokes the compiler to compile one or more Ada source files.
21113 @item @command{ACS ATTACH}@*
21114 @tab [No equivalent]@*
21115 Switches control of terminal from current process running the program
21118 @item @command{ACS CHECK}
21119 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
21120 Forms the execution closure of one
21121 or more compiled units and checks completeness and currency.
21123 @item @command{ACS COMPILE}
21124 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21125 Forms the execution closure of one or
21126 more specified units, checks completeness and currency,
21127 identifies units that have revised source files, compiles same,
21128 and recompiles units that are or will become obsolete.
21129 Also completes incomplete generic instantiations.
21131 @item @command{ACS COPY FOREIGN}
21133 Copies a foreign object file into the program library as a
21136 @item @command{ACS COPY UNIT}
21138 Copies a compiled unit from one program library to another.
21140 @item @command{ACS CREATE LIBRARY}
21141 @tab Create /directory (*)@*
21142 Creates a program library.
21144 @item @command{ACS CREATE SUBLIBRARY}
21145 @tab Create /directory (*)@*
21146 Creates a program sublibrary.
21148 @item @command{ACS DELETE LIBRARY}
21150 Deletes a program library and its contents.
21152 @item @command{ACS DELETE SUBLIBRARY}
21154 Deletes a program sublibrary and its contents.
21156 @item @command{ACS DELETE UNIT}
21157 @tab Delete file (*)@*
21158 On OpenVMS systems, deletes one or more compiled units from
21159 the current program library.
21161 @item @command{ACS DIRECTORY}
21162 @tab Directory (*)@*
21163 On OpenVMS systems, lists units contained in the current
21166 @item @command{ACS ENTER FOREIGN}
21168 Allows the import of a foreign body as an Ada library
21169 spec and enters a reference to a pointer.
21171 @item @command{ACS ENTER UNIT}
21173 Enters a reference (pointer) from the current program library to
21174 a unit compiled into another program library.
21176 @item @command{ACS EXIT}
21177 @tab [No equivalent]@*
21178 Exits from the program library manager.
21180 @item @command{ACS EXPORT}
21182 Creates an object file that contains system-specific object code
21183 for one or more units. With GNAT, object files can simply be copied
21184 into the desired directory.
21186 @item @command{ACS EXTRACT SOURCE}
21188 Allows access to the copied source file for each Ada compilation unit
21190 @item @command{ACS HELP}
21191 @tab @command{HELP GNAT}@*
21192 Provides online help.
21194 @item @command{ACS LINK}
21195 @tab @command{GNAT LINK}@*
21196 Links an object file containing Ada units into an executable file.
21198 @item @command{ACS LOAD}
21200 Loads (partially compiles) Ada units into the program library.
21201 Allows loading a program from a collection of files into a library
21202 without knowing the relationship among units.
21204 @item @command{ACS MERGE}
21206 Merges into the current program library, one or more units from
21207 another library where they were modified.
21209 @item @command{ACS RECOMPILE}
21210 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21211 Recompiles from external or copied source files any obsolete
21212 unit in the closure. Also, completes any incomplete generic
21215 @item @command{ACS REENTER}
21216 @tab @command{GNAT MAKE}@*
21217 Reenters current references to units compiled after last entered
21218 with the @command{ACS ENTER UNIT} command.
21220 @item @command{ACS SET LIBRARY}
21221 @tab Set default (*)@*
21222 Defines a program library to be the compilation context as well
21223 as the target library for compiler output and commands in general.
21225 @item @command{ACS SET PRAGMA}
21226 @tab Edit @file{gnat.adc} (*)@*
21227 Redefines specified values of the library characteristics
21228 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
21229 and @code{Float_Representation}.
21231 @item @command{ACS SET SOURCE}
21232 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
21233 Defines the source file search list for the @command{ACS COMPILE} command.
21235 @item @command{ACS SHOW LIBRARY}
21236 @tab Directory (*)@*
21237 Lists information about one or more program libraries.
21239 @item @command{ACS SHOW PROGRAM}
21240 @tab [No equivalent]@*
21241 Lists information about the execution closure of one or
21242 more units in the program library.
21244 @item @command{ACS SHOW SOURCE}
21245 @tab Show logical @code{ADA_INCLUDE_PATH}@*
21246 Shows the source file search used when compiling units.
21248 @item @command{ACS SHOW VERSION}
21249 @tab Compile with @option{VERBOSE} option
21250 Displays the version number of the compiler and program library
21253 @item @command{ACS SPAWN}
21254 @tab [No equivalent]@*
21255 Creates a subprocess of the current process (same as @command{DCL SPAWN}
21258 @item @command{ACS VERIFY}
21259 @tab [No equivalent]@*
21260 Performs a series of consistency checks on a program library to
21261 determine whether the library structure and library files are in
21268 @section Input-Output
21271 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
21272 Management Services (RMS) to perform operations on
21276 HP Ada and GNAT predefine an identical set of input-
21277 output packages. To make the use of the
21278 generic @code{TEXT_IO} operations more convenient, HP Ada
21279 provides predefined library packages that instantiate the
21280 integer and floating-point operations for the predefined
21281 integer and floating-point types as shown in the following table.
21283 @multitable @columnfractions .45 .55
21284 @item @emph{Package Name} @tab Instantiation
21286 @item @code{INTEGER_TEXT_IO}
21287 @tab @code{INTEGER_IO(INTEGER)}
21289 @item @code{SHORT_INTEGER_TEXT_IO}
21290 @tab @code{INTEGER_IO(SHORT_INTEGER)}
21292 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
21293 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
21295 @item @code{FLOAT_TEXT_IO}
21296 @tab @code{FLOAT_IO(FLOAT)}
21298 @item @code{LONG_FLOAT_TEXT_IO}
21299 @tab @code{FLOAT_IO(LONG_FLOAT)}
21303 The HP Ada predefined packages and their operations
21304 are implemented using OpenVMS Alpha files and input-output
21305 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
21306 Familiarity with the following is recommended:
21308 @item RMS file organizations and access methods
21310 @item OpenVMS file specifications and directories
21312 @item OpenVMS File Definition Language (FDL)
21316 GNAT provides I/O facilities that are completely
21317 compatible with HP Ada. The distribution includes the
21318 standard HP Ada versions of all I/O packages, operating
21319 in a manner compatible with HP Ada. In particular, the
21320 following packages are by default the HP Ada (Ada 83)
21321 versions of these packages rather than the renamings
21322 suggested in Annex J of the Ada Reference Manual:
21324 @item @code{TEXT_IO}
21326 @item @code{SEQUENTIAL_IO}
21328 @item @code{DIRECT_IO}
21332 The use of the standard child package syntax (for
21333 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
21335 GNAT provides HP-compatible predefined instantiations
21336 of the @code{TEXT_IO} packages, and also
21337 provides the standard predefined instantiations required
21338 by the @cite{Ada Reference Manual}.
21340 For further information on how GNAT interfaces to the file
21341 system or how I/O is implemented in programs written in
21342 mixed languages, see @ref{Implementation of the Standard I/O,,,
21343 gnat_rm, GNAT Reference Manual}.
21344 This chapter covers the following:
21346 @item Standard I/O packages
21348 @item @code{FORM} strings
21350 @item @code{ADA.DIRECT_IO}
21352 @item @code{ADA.SEQUENTIAL_IO}
21354 @item @code{ADA.TEXT_IO}
21356 @item Stream pointer positioning
21358 @item Reading and writing non-regular files
21360 @item @code{GET_IMMEDIATE}
21362 @item Treating @code{TEXT_IO} files as streams
21369 @node Implementation Limits
21370 @section Implementation Limits
21373 The following table lists implementation limits for HP Ada
21375 @multitable @columnfractions .60 .20 .20
21377 @item @emph{Compilation Parameter}
21382 @item In a subprogram or entry declaration, maximum number of
21383 formal parameters that are of an unconstrained record type
21388 @item Maximum identifier length (number of characters)
21393 @item Maximum number of characters in a source line
21398 @item Maximum collection size (number of bytes)
21403 @item Maximum number of discriminants for a record type
21408 @item Maximum number of formal parameters in an entry or
21409 subprogram declaration
21414 @item Maximum number of dimensions in an array type
21419 @item Maximum number of library units and subunits in a compilation.
21424 @item Maximum number of library units and subunits in an execution.
21429 @item Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
21430 or @code{PSECT_OBJECT}
21435 @item Maximum number of enumeration literals in an enumeration type
21441 @item Maximum number of lines in a source file
21446 @item Maximum number of bits in any object
21451 @item Maximum size of the static portion of a stack frame (approximate)
21456 @node Tools and Utilities
21457 @section Tools and Utilities
21460 The following table lists some of the OpenVMS development tools
21461 available for HP Ada, and the corresponding tools for
21462 use with @value{EDITION} on Alpha and I64 platforms.
21463 Aside from the debugger, all the OpenVMS tools identified are part
21464 of the DECset package.
21467 @c Specify table in TeX since Texinfo does a poor job
21471 \settabs\+Language-Sensitive Editor\quad
21472 &Product with HP Ada\quad
21475 &\it Product with HP Ada
21476 & \it Product with GNAT Pro\cr
21478 \+Code Management System
21482 \+Language-Sensitive Editor
21484 & emacs or HP LSE (Alpha)\cr
21494 & OpenVMS Debug (I64)\cr
21496 \+Source Code Analyzer /
21513 \+Coverage Analyzer
21517 \+Module Management
21519 & Not applicable\cr
21529 @c This is the Texinfo version of the table. It renders poorly in pdf, hence
21530 @c the TeX version above for the printed version
21532 @c @multitable @columnfractions .3 .4 .4
21533 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
21535 @tab @i{Tool with HP Ada}
21536 @tab @i{Tool with @value{EDITION}}
21537 @item Code Management@*System
21540 @item Language-Sensitive@*Editor
21542 @tab emacs or HP LSE (Alpha)
21551 @tab OpenVMS Debug (I64)
21552 @item Source Code Analyzer /@*Cross Referencer
21556 @tab HP Digital Test@*Manager (DTM)
21558 @item Performance and@*Coverage Analyzer
21561 @item Module Management@*System
21563 @tab Not applicable
21570 @c **************************************
21571 @node Platform-Specific Information for the Run-Time Libraries
21572 @appendix Platform-Specific Information for the Run-Time Libraries
21573 @cindex Tasking and threads libraries
21574 @cindex Threads libraries and tasking
21575 @cindex Run-time libraries (platform-specific information)
21578 The GNAT run-time implementation may vary with respect to both the
21579 underlying threads library and the exception handling scheme.
21580 For threads support, one or more of the following are supplied:
21582 @item @b{native threads library}, a binding to the thread package from
21583 the underlying operating system
21585 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
21586 POSIX thread package
21590 For exception handling, either or both of two models are supplied:
21592 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
21593 Most programs should experience a substantial speed improvement by
21594 being compiled with a ZCX run-time.
21595 This is especially true for
21596 tasking applications or applications with many exception handlers.}
21597 @cindex Zero-Cost Exceptions
21598 @cindex ZCX (Zero-Cost Exceptions)
21599 which uses binder-generated tables that
21600 are interrogated at run time to locate a handler
21602 @item @b{setjmp / longjmp} (``SJLJ''),
21603 @cindex setjmp/longjmp Exception Model
21604 @cindex SJLJ (setjmp/longjmp Exception Model)
21605 which uses dynamically-set data to establish
21606 the set of handlers
21610 This appendix summarizes which combinations of threads and exception support
21611 are supplied on various GNAT platforms.
21612 It then shows how to select a particular library either
21613 permanently or temporarily,
21614 explains the properties of (and tradeoffs among) the various threads
21615 libraries, and provides some additional
21616 information about several specific platforms.
21619 * Summary of Run-Time Configurations::
21620 * Specifying a Run-Time Library::
21621 * Choosing the Scheduling Policy::
21622 * Solaris-Specific Considerations::
21623 * Linux-Specific Considerations::
21624 * AIX-Specific Considerations::
21625 * Irix-Specific Considerations::
21626 * RTX-Specific Considerations::
21627 * HP-UX-Specific Considerations::
21630 @node Summary of Run-Time Configurations
21631 @section Summary of Run-Time Configurations
21633 @multitable @columnfractions .30 .70
21634 @item @b{alpha-openvms}
21635 @item @code{@ @ }@i{rts-native (default)}
21636 @item @code{@ @ @ @ }Tasking @tab native VMS threads
21637 @item @code{@ @ @ @ }Exceptions @tab ZCX
21639 @item @b{alpha-tru64}
21640 @item @code{@ @ }@i{rts-native (default)}
21641 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
21642 @item @code{@ @ @ @ }Exceptions @tab ZCX
21644 @item @code{@ @ }@i{rts-sjlj}
21645 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
21646 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21648 @item @b{ia64-hp_linux}
21649 @item @code{@ @ }@i{rts-native (default)}
21650 @item @code{@ @ @ @ }Tasking @tab pthread library
21651 @item @code{@ @ @ @ }Exceptions @tab ZCX
21653 @item @b{ia64-hpux}
21654 @item @code{@ @ }@i{rts-native (default)}
21655 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
21656 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21658 @item @b{ia64-openvms}
21659 @item @code{@ @ }@i{rts-native (default)}
21660 @item @code{@ @ @ @ }Tasking @tab native VMS threads
21661 @item @code{@ @ @ @ }Exceptions @tab ZCX
21663 @item @b{ia64-sgi_linux}
21664 @item @code{@ @ }@i{rts-native (default)}
21665 @item @code{@ @ @ @ }Tasking @tab pthread library
21666 @item @code{@ @ @ @ }Exceptions @tab ZCX
21668 @item @b{mips-irix}
21669 @item @code{@ @ }@i{rts-native (default)}
21670 @item @code{@ @ @ @ }Tasking @tab native IRIX threads
21671 @item @code{@ @ @ @ }Exceptions @tab ZCX
21674 @item @code{@ @ }@i{rts-native (default)}
21675 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
21676 @item @code{@ @ @ @ }Exceptions @tab ZCX
21678 @item @code{@ @ }@i{rts-sjlj}
21679 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
21680 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21683 @item @code{@ @ }@i{rts-native (default)}
21684 @item @code{@ @ @ @ }Tasking @tab native AIX threads
21685 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21687 @item @b{ppc-darwin}
21688 @item @code{@ @ }@i{rts-native (default)}
21689 @item @code{@ @ @ @ }Tasking @tab native MacOS threads
21690 @item @code{@ @ @ @ }Exceptions @tab ZCX
21692 @item @b{sparc-solaris} @tab
21693 @item @code{@ @ }@i{rts-native (default)}
21694 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
21695 @item @code{@ @ @ @ }Exceptions @tab ZCX
21697 @item @code{@ @ }@i{rts-pthread}
21698 @item @code{@ @ @ @ }Tasking @tab pthread library
21699 @item @code{@ @ @ @ }Exceptions @tab ZCX
21701 @item @code{@ @ }@i{rts-sjlj}
21702 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
21703 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21705 @item @b{sparc64-solaris} @tab
21706 @item @code{@ @ }@i{rts-native (default)}
21707 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
21708 @item @code{@ @ @ @ }Exceptions @tab ZCX
21710 @item @b{x86-linux}
21711 @item @code{@ @ }@i{rts-native (default)}
21712 @item @code{@ @ @ @ }Tasking @tab pthread library
21713 @item @code{@ @ @ @ }Exceptions @tab ZCX
21715 @item @code{@ @ }@i{rts-sjlj}
21716 @item @code{@ @ @ @ }Tasking @tab pthread library
21717 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21720 @item @code{@ @ }@i{rts-native (default)}
21721 @item @code{@ @ @ @ }Tasking @tab native LynxOS threads
21722 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21724 @item @b{x86-solaris}
21725 @item @code{@ @ }@i{rts-native (default)}
21726 @item @code{@ @ @ @ }Tasking @tab native Solaris threads
21727 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21729 @item @b{x86-windows}
21730 @item @code{@ @ }@i{rts-native (default)}
21731 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
21732 @item @code{@ @ @ @ }Exceptions @tab ZCX
21734 @item @code{@ @ }@i{rts-sjlj (default)}
21735 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
21736 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21738 @item @b{x86-windows-rtx}
21739 @item @code{@ @ }@i{rts-rtx-rtss (default)}
21740 @item @code{@ @ @ @ }Tasking @tab RTX real-time subsystem RTSS threads (kernel mode)
21741 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21743 @item @code{@ @ }@i{rts-rtx-w32}
21744 @item @code{@ @ @ @ }Tasking @tab RTX Win32 threads (user mode)
21745 @item @code{@ @ @ @ }Exceptions @tab ZCX
21747 @item @b{x86_64-linux}
21748 @item @code{@ @ }@i{rts-native (default)}
21749 @item @code{@ @ @ @ }Tasking @tab pthread library
21750 @item @code{@ @ @ @ }Exceptions @tab ZCX
21752 @item @code{@ @ }@i{rts-sjlj}
21753 @item @code{@ @ @ @ }Tasking @tab pthread library
21754 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21758 @node Specifying a Run-Time Library
21759 @section Specifying a Run-Time Library
21762 The @file{adainclude} subdirectory containing the sources of the GNAT
21763 run-time library, and the @file{adalib} subdirectory containing the
21764 @file{ALI} files and the static and/or shared GNAT library, are located
21765 in the gcc target-dependent area:
21768 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
21772 As indicated above, on some platforms several run-time libraries are supplied.
21773 These libraries are installed in the target dependent area and
21774 contain a complete source and binary subdirectory. The detailed description
21775 below explains the differences between the different libraries in terms of
21776 their thread support.
21778 The default run-time library (when GNAT is installed) is @emph{rts-native}.
21779 This default run time is selected by the means of soft links.
21780 For example on x86-linux:
21786 +--- adainclude----------+
21788 +--- adalib-----------+ |
21790 +--- rts-native | |
21792 | +--- adainclude <---+
21794 | +--- adalib <----+
21805 If the @i{rts-sjlj} library is to be selected on a permanent basis,
21806 these soft links can be modified with the following commands:
21810 $ rm -f adainclude adalib
21811 $ ln -s rts-sjlj/adainclude adainclude
21812 $ ln -s rts-sjlj/adalib adalib
21816 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
21817 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
21818 @file{$target/ada_object_path}.
21820 Selecting another run-time library temporarily can be
21821 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
21822 @cindex @option{--RTS} option
21824 @node Choosing the Scheduling Policy
21825 @section Choosing the Scheduling Policy
21828 When using a POSIX threads implementation, you have a choice of several
21829 scheduling policies: @code{SCHED_FIFO},
21830 @cindex @code{SCHED_FIFO} scheduling policy
21832 @cindex @code{SCHED_RR} scheduling policy
21833 and @code{SCHED_OTHER}.
21834 @cindex @code{SCHED_OTHER} scheduling policy
21835 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
21836 or @code{SCHED_RR} requires special (e.g., root) privileges.
21838 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
21840 @cindex @code{SCHED_FIFO} scheduling policy
21841 you can use one of the following:
21845 @code{pragma Time_Slice (0.0)}
21846 @cindex pragma Time_Slice
21848 the corresponding binder option @option{-T0}
21849 @cindex @option{-T0} option
21851 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21852 @cindex pragma Task_Dispatching_Policy
21856 To specify @code{SCHED_RR},
21857 @cindex @code{SCHED_RR} scheduling policy
21858 you should use @code{pragma Time_Slice} with a
21859 value greater than @code{0.0}, or else use the corresponding @option{-T}
21862 @node Solaris-Specific Considerations
21863 @section Solaris-Specific Considerations
21864 @cindex Solaris Sparc threads libraries
21867 This section addresses some topics related to the various threads libraries
21871 * Solaris Threads Issues::
21874 @node Solaris Threads Issues
21875 @subsection Solaris Threads Issues
21878 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
21879 library based on POSIX threads --- @emph{rts-pthread}.
21880 @cindex rts-pthread threads library
21881 This run-time library has the advantage of being mostly shared across all
21882 POSIX-compliant thread implementations, and it also provides under
21883 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
21884 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
21885 and @code{PTHREAD_PRIO_PROTECT}
21886 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
21887 semantics that can be selected using the predefined pragma
21888 @code{Locking_Policy}
21889 @cindex pragma Locking_Policy (under rts-pthread)
21891 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
21892 @cindex @code{Inheritance_Locking} (under rts-pthread)
21893 @cindex @code{Ceiling_Locking} (under rts-pthread)
21895 As explained above, the native run-time library is based on the Solaris thread
21896 library (@code{libthread}) and is the default library.
21898 When the Solaris threads library is used (this is the default), programs
21899 compiled with GNAT can automatically take advantage of
21900 and can thus execute on multiple processors.
21901 The user can alternatively specify a processor on which the program should run
21902 to emulate a single-processor system. The multiprocessor / uniprocessor choice
21904 setting the environment variable @env{GNAT_PROCESSOR}
21905 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
21906 to one of the following:
21910 Use the default configuration (run the program on all
21911 available processors) - this is the same as having @code{GNAT_PROCESSOR}
21915 Let the run-time implementation choose one processor and run the program on
21918 @item 0 .. Last_Proc
21919 Run the program on the specified processor.
21920 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
21921 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
21924 @node Linux-Specific Considerations
21925 @section Linux-Specific Considerations
21926 @cindex Linux threads libraries
21929 On GNU/Linux without NPTL support (usually system with GNU C Library
21930 older than 2.3), the signal model is not POSIX compliant, which means
21931 that to send a signal to the process, you need to send the signal to all
21932 threads, e.g.@: by using @code{killpg()}.
21934 @node AIX-Specific Considerations
21935 @section AIX-Specific Considerations
21936 @cindex AIX resolver library
21939 On AIX, the resolver library initializes some internal structure on
21940 the first call to @code{get*by*} functions, which are used to implement
21941 @code{GNAT.Sockets.Get_Host_By_Name} and
21942 @code{GNAT.Sockets.Get_Host_By_Address}.
21943 If such initialization occurs within an Ada task, and the stack size for
21944 the task is the default size, a stack overflow may occur.
21946 To avoid this overflow, the user should either ensure that the first call
21947 to @code{GNAT.Sockets.Get_Host_By_Name} or
21948 @code{GNAT.Sockets.Get_Host_By_Addrss}
21949 occurs in the environment task, or use @code{pragma Storage_Size} to
21950 specify a sufficiently large size for the stack of the task that contains
21953 @node Irix-Specific Considerations
21954 @section Irix-Specific Considerations
21955 @cindex Irix libraries
21958 The GCC support libraries coming with the Irix compiler have moved to
21959 their canonical place with respect to the general Irix ABI related
21960 conventions. Running applications built with the default shared GNAT
21961 run-time now requires the LD_LIBRARY_PATH environment variable to
21962 include this location. A possible way to achieve this is to issue the
21963 following command line on a bash prompt:
21967 $ LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
21971 @node RTX-Specific Considerations
21972 @section RTX-Specific Considerations
21973 @cindex RTX libraries
21976 The Real-time Extension (RTX) to Windows is based on the Windows Win32
21977 API. Applications can be built to work in two different modes:
21981 Windows executables that run in Ring 3 to utilize memory protection
21982 (@emph{rts-rtx-w32}).
21985 Real-time subsystem (RTSS) executables that run in Ring 0, where
21986 performance can be optimized with RTSS applications taking precedent
21987 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
21988 the Microsoft linker to handle RTSS libraries.
21992 @node HP-UX-Specific Considerations
21993 @section HP-UX-Specific Considerations
21994 @cindex HP-UX Scheduling
21997 On HP-UX, appropriate privileges are required to change the scheduling
21998 parameters of a task. The calling process must have appropriate
21999 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
22000 successfully change the scheduling parameters.
22002 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
22003 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
22004 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
22006 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
22007 one of the following:
22011 @code{pragma Time_Slice (0.0)}
22012 @cindex pragma Time_Slice
22014 the corresponding binder option @option{-T0}
22015 @cindex @option{-T0} option
22017 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22018 @cindex pragma Task_Dispatching_Policy
22022 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
22023 you should use @code{pragma Time_Slice} with a
22024 value greater than @code{0.0}, or use the corresponding @option{-T}
22025 binder option, or set the @code{pragma Task_Dispatching_Policy
22026 (Round_Robin_Within_Priorities)}.
22028 @c *******************************
22029 @node Example of Binder Output File
22030 @appendix Example of Binder Output File
22033 This Appendix displays the source code for @command{gnatbind}'s output
22034 file generated for a simple ``Hello World'' program.
22035 Comments have been added for clarification purposes.
22037 @smallexample @c adanocomment
22041 -- The package is called Ada_Main unless this name is actually used
22042 -- as a unit name in the partition, in which case some other unique
22046 package ada_main is
22048 Elab_Final_Code : Integer;
22049 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
22051 -- The main program saves the parameters (argument count,
22052 -- argument values, environment pointer) in global variables
22053 -- for later access by other units including
22054 -- Ada.Command_Line.
22056 gnat_argc : Integer;
22057 gnat_argv : System.Address;
22058 gnat_envp : System.Address;
22060 -- The actual variables are stored in a library routine. This
22061 -- is useful for some shared library situations, where there
22062 -- are problems if variables are not in the library.
22064 pragma Import (C, gnat_argc);
22065 pragma Import (C, gnat_argv);
22066 pragma Import (C, gnat_envp);
22068 -- The exit status is similarly an external location
22070 gnat_exit_status : Integer;
22071 pragma Import (C, gnat_exit_status);
22073 GNAT_Version : constant String :=
22074 "GNAT Version: 6.0.0w (20061115)";
22075 pragma Export (C, GNAT_Version, "__gnat_version");
22077 -- This is the generated adafinal routine that performs
22078 -- finalization at the end of execution. In the case where
22079 -- Ada is the main program, this main program makes a call
22080 -- to adafinal at program termination.
22082 procedure adafinal;
22083 pragma Export (C, adafinal, "adafinal");
22085 -- This is the generated adainit routine that performs
22086 -- initialization at the start of execution. In the case
22087 -- where Ada is the main program, this main program makes
22088 -- a call to adainit at program startup.
22091 pragma Export (C, adainit, "adainit");
22093 -- This routine is called at the start of execution. It is
22094 -- a dummy routine that is used by the debugger to breakpoint
22095 -- at the start of execution.
22097 procedure Break_Start;
22098 pragma Import (C, Break_Start, "__gnat_break_start");
22100 -- This is the actual generated main program (it would be
22101 -- suppressed if the no main program switch were used). As
22102 -- required by standard system conventions, this program has
22103 -- the external name main.
22107 argv : System.Address;
22108 envp : System.Address)
22110 pragma Export (C, main, "main");
22112 -- The following set of constants give the version
22113 -- identification values for every unit in the bound
22114 -- partition. This identification is computed from all
22115 -- dependent semantic units, and corresponds to the
22116 -- string that would be returned by use of the
22117 -- Body_Version or Version attributes.
22119 type Version_32 is mod 2 ** 32;
22120 u00001 : constant Version_32 := 16#7880BEB3#;
22121 u00002 : constant Version_32 := 16#0D24CBD0#;
22122 u00003 : constant Version_32 := 16#3283DBEB#;
22123 u00004 : constant Version_32 := 16#2359F9ED#;
22124 u00005 : constant Version_32 := 16#664FB847#;
22125 u00006 : constant Version_32 := 16#68E803DF#;
22126 u00007 : constant Version_32 := 16#5572E604#;
22127 u00008 : constant Version_32 := 16#46B173D8#;
22128 u00009 : constant Version_32 := 16#156A40CF#;
22129 u00010 : constant Version_32 := 16#033DABE0#;
22130 u00011 : constant Version_32 := 16#6AB38FEA#;
22131 u00012 : constant Version_32 := 16#22B6217D#;
22132 u00013 : constant Version_32 := 16#68A22947#;
22133 u00014 : constant Version_32 := 16#18CC4A56#;
22134 u00015 : constant Version_32 := 16#08258E1B#;
22135 u00016 : constant Version_32 := 16#367D5222#;
22136 u00017 : constant Version_32 := 16#20C9ECA4#;
22137 u00018 : constant Version_32 := 16#50D32CB6#;
22138 u00019 : constant Version_32 := 16#39A8BB77#;
22139 u00020 : constant Version_32 := 16#5CF8FA2B#;
22140 u00021 : constant Version_32 := 16#2F1EB794#;
22141 u00022 : constant Version_32 := 16#31AB6444#;
22142 u00023 : constant Version_32 := 16#1574B6E9#;
22143 u00024 : constant Version_32 := 16#5109C189#;
22144 u00025 : constant Version_32 := 16#56D770CD#;
22145 u00026 : constant Version_32 := 16#02F9DE3D#;
22146 u00027 : constant Version_32 := 16#08AB6B2C#;
22147 u00028 : constant Version_32 := 16#3FA37670#;
22148 u00029 : constant Version_32 := 16#476457A0#;
22149 u00030 : constant Version_32 := 16#731E1B6E#;
22150 u00031 : constant Version_32 := 16#23C2E789#;
22151 u00032 : constant Version_32 := 16#0F1BD6A1#;
22152 u00033 : constant Version_32 := 16#7C25DE96#;
22153 u00034 : constant Version_32 := 16#39ADFFA2#;
22154 u00035 : constant Version_32 := 16#571DE3E7#;
22155 u00036 : constant Version_32 := 16#5EB646AB#;
22156 u00037 : constant Version_32 := 16#4249379B#;
22157 u00038 : constant Version_32 := 16#0357E00A#;
22158 u00039 : constant Version_32 := 16#3784FB72#;
22159 u00040 : constant Version_32 := 16#2E723019#;
22160 u00041 : constant Version_32 := 16#623358EA#;
22161 u00042 : constant Version_32 := 16#107F9465#;
22162 u00043 : constant Version_32 := 16#6843F68A#;
22163 u00044 : constant Version_32 := 16#63305874#;
22164 u00045 : constant Version_32 := 16#31E56CE1#;
22165 u00046 : constant Version_32 := 16#02917970#;
22166 u00047 : constant Version_32 := 16#6CCBA70E#;
22167 u00048 : constant Version_32 := 16#41CD4204#;
22168 u00049 : constant Version_32 := 16#572E3F58#;
22169 u00050 : constant Version_32 := 16#20729FF5#;
22170 u00051 : constant Version_32 := 16#1D4F93E8#;
22171 u00052 : constant Version_32 := 16#30B2EC3D#;
22172 u00053 : constant Version_32 := 16#34054F96#;
22173 u00054 : constant Version_32 := 16#5A199860#;
22174 u00055 : constant Version_32 := 16#0E7F912B#;
22175 u00056 : constant Version_32 := 16#5760634A#;
22176 u00057 : constant Version_32 := 16#5D851835#;
22178 -- The following Export pragmas export the version numbers
22179 -- with symbolic names ending in B (for body) or S
22180 -- (for spec) so that they can be located in a link. The
22181 -- information provided here is sufficient to track down
22182 -- the exact versions of units used in a given build.
22184 pragma Export (C, u00001, "helloB");
22185 pragma Export (C, u00002, "system__standard_libraryB");
22186 pragma Export (C, u00003, "system__standard_libraryS");
22187 pragma Export (C, u00004, "adaS");
22188 pragma Export (C, u00005, "ada__text_ioB");
22189 pragma Export (C, u00006, "ada__text_ioS");
22190 pragma Export (C, u00007, "ada__exceptionsB");
22191 pragma Export (C, u00008, "ada__exceptionsS");
22192 pragma Export (C, u00009, "gnatS");
22193 pragma Export (C, u00010, "gnat__heap_sort_aB");
22194 pragma Export (C, u00011, "gnat__heap_sort_aS");
22195 pragma Export (C, u00012, "systemS");
22196 pragma Export (C, u00013, "system__exception_tableB");
22197 pragma Export (C, u00014, "system__exception_tableS");
22198 pragma Export (C, u00015, "gnat__htableB");
22199 pragma Export (C, u00016, "gnat__htableS");
22200 pragma Export (C, u00017, "system__exceptionsS");
22201 pragma Export (C, u00018, "system__machine_state_operationsB");
22202 pragma Export (C, u00019, "system__machine_state_operationsS");
22203 pragma Export (C, u00020, "system__machine_codeS");
22204 pragma Export (C, u00021, "system__storage_elementsB");
22205 pragma Export (C, u00022, "system__storage_elementsS");
22206 pragma Export (C, u00023, "system__secondary_stackB");
22207 pragma Export (C, u00024, "system__secondary_stackS");
22208 pragma Export (C, u00025, "system__parametersB");
22209 pragma Export (C, u00026, "system__parametersS");
22210 pragma Export (C, u00027, "system__soft_linksB");
22211 pragma Export (C, u00028, "system__soft_linksS");
22212 pragma Export (C, u00029, "system__stack_checkingB");
22213 pragma Export (C, u00030, "system__stack_checkingS");
22214 pragma Export (C, u00031, "system__tracebackB");
22215 pragma Export (C, u00032, "system__tracebackS");
22216 pragma Export (C, u00033, "ada__streamsS");
22217 pragma Export (C, u00034, "ada__tagsB");
22218 pragma Export (C, u00035, "ada__tagsS");
22219 pragma Export (C, u00036, "system__string_opsB");
22220 pragma Export (C, u00037, "system__string_opsS");
22221 pragma Export (C, u00038, "interfacesS");
22222 pragma Export (C, u00039, "interfaces__c_streamsB");
22223 pragma Export (C, u00040, "interfaces__c_streamsS");
22224 pragma Export (C, u00041, "system__file_ioB");
22225 pragma Export (C, u00042, "system__file_ioS");
22226 pragma Export (C, u00043, "ada__finalizationB");
22227 pragma Export (C, u00044, "ada__finalizationS");
22228 pragma Export (C, u00045, "system__finalization_rootB");
22229 pragma Export (C, u00046, "system__finalization_rootS");
22230 pragma Export (C, u00047, "system__finalization_implementationB");
22231 pragma Export (C, u00048, "system__finalization_implementationS");
22232 pragma Export (C, u00049, "system__string_ops_concat_3B");
22233 pragma Export (C, u00050, "system__string_ops_concat_3S");
22234 pragma Export (C, u00051, "system__stream_attributesB");
22235 pragma Export (C, u00052, "system__stream_attributesS");
22236 pragma Export (C, u00053, "ada__io_exceptionsS");
22237 pragma Export (C, u00054, "system__unsigned_typesS");
22238 pragma Export (C, u00055, "system__file_control_blockS");
22239 pragma Export (C, u00056, "ada__finalization__list_controllerB");
22240 pragma Export (C, u00057, "ada__finalization__list_controllerS");
22242 -- BEGIN ELABORATION ORDER
22245 -- gnat.heap_sort_a (spec)
22246 -- gnat.heap_sort_a (body)
22247 -- gnat.htable (spec)
22248 -- gnat.htable (body)
22249 -- interfaces (spec)
22251 -- system.machine_code (spec)
22252 -- system.parameters (spec)
22253 -- system.parameters (body)
22254 -- interfaces.c_streams (spec)
22255 -- interfaces.c_streams (body)
22256 -- system.standard_library (spec)
22257 -- ada.exceptions (spec)
22258 -- system.exception_table (spec)
22259 -- system.exception_table (body)
22260 -- ada.io_exceptions (spec)
22261 -- system.exceptions (spec)
22262 -- system.storage_elements (spec)
22263 -- system.storage_elements (body)
22264 -- system.machine_state_operations (spec)
22265 -- system.machine_state_operations (body)
22266 -- system.secondary_stack (spec)
22267 -- system.stack_checking (spec)
22268 -- system.soft_links (spec)
22269 -- system.soft_links (body)
22270 -- system.stack_checking (body)
22271 -- system.secondary_stack (body)
22272 -- system.standard_library (body)
22273 -- system.string_ops (spec)
22274 -- system.string_ops (body)
22277 -- ada.streams (spec)
22278 -- system.finalization_root (spec)
22279 -- system.finalization_root (body)
22280 -- system.string_ops_concat_3 (spec)
22281 -- system.string_ops_concat_3 (body)
22282 -- system.traceback (spec)
22283 -- system.traceback (body)
22284 -- ada.exceptions (body)
22285 -- system.unsigned_types (spec)
22286 -- system.stream_attributes (spec)
22287 -- system.stream_attributes (body)
22288 -- system.finalization_implementation (spec)
22289 -- system.finalization_implementation (body)
22290 -- ada.finalization (spec)
22291 -- ada.finalization (body)
22292 -- ada.finalization.list_controller (spec)
22293 -- ada.finalization.list_controller (body)
22294 -- system.file_control_block (spec)
22295 -- system.file_io (spec)
22296 -- system.file_io (body)
22297 -- ada.text_io (spec)
22298 -- ada.text_io (body)
22300 -- END ELABORATION ORDER
22304 -- The following source file name pragmas allow the generated file
22305 -- names to be unique for different main programs. They are needed
22306 -- since the package name will always be Ada_Main.
22308 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
22309 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
22311 -- Generated package body for Ada_Main starts here
22313 package body ada_main is
22315 -- The actual finalization is performed by calling the
22316 -- library routine in System.Standard_Library.Adafinal
22318 procedure Do_Finalize;
22319 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
22326 procedure adainit is
22328 -- These booleans are set to True once the associated unit has
22329 -- been elaborated. It is also used to avoid elaborating the
22330 -- same unit twice.
22333 pragma Import (Ada, E040, "interfaces__c_streams_E");
22336 pragma Import (Ada, E008, "ada__exceptions_E");
22339 pragma Import (Ada, E014, "system__exception_table_E");
22342 pragma Import (Ada, E053, "ada__io_exceptions_E");
22345 pragma Import (Ada, E017, "system__exceptions_E");
22348 pragma Import (Ada, E024, "system__secondary_stack_E");
22351 pragma Import (Ada, E030, "system__stack_checking_E");
22354 pragma Import (Ada, E028, "system__soft_links_E");
22357 pragma Import (Ada, E035, "ada__tags_E");
22360 pragma Import (Ada, E033, "ada__streams_E");
22363 pragma Import (Ada, E046, "system__finalization_root_E");
22366 pragma Import (Ada, E048, "system__finalization_implementation_E");
22369 pragma Import (Ada, E044, "ada__finalization_E");
22372 pragma Import (Ada, E057, "ada__finalization__list_controller_E");
22375 pragma Import (Ada, E055, "system__file_control_block_E");
22378 pragma Import (Ada, E042, "system__file_io_E");
22381 pragma Import (Ada, E006, "ada__text_io_E");
22383 -- Set_Globals is a library routine that stores away the
22384 -- value of the indicated set of global values in global
22385 -- variables within the library.
22387 procedure Set_Globals
22388 (Main_Priority : Integer;
22389 Time_Slice_Value : Integer;
22390 WC_Encoding : Character;
22391 Locking_Policy : Character;
22392 Queuing_Policy : Character;
22393 Task_Dispatching_Policy : Character;
22394 Adafinal : System.Address;
22395 Unreserve_All_Interrupts : Integer;
22396 Exception_Tracebacks : Integer);
22397 @findex __gnat_set_globals
22398 pragma Import (C, Set_Globals, "__gnat_set_globals");
22400 -- SDP_Table_Build is a library routine used to build the
22401 -- exception tables. See unit Ada.Exceptions in files
22402 -- a-except.ads/adb for full details of how zero cost
22403 -- exception handling works. This procedure, the call to
22404 -- it, and the two following tables are all omitted if the
22405 -- build is in longjmp/setjmp exception mode.
22407 @findex SDP_Table_Build
22408 @findex Zero Cost Exceptions
22409 procedure SDP_Table_Build
22410 (SDP_Addresses : System.Address;
22411 SDP_Count : Natural;
22412 Elab_Addresses : System.Address;
22413 Elab_Addr_Count : Natural);
22414 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22416 -- Table of Unit_Exception_Table addresses. Used for zero
22417 -- cost exception handling to build the top level table.
22419 ST : aliased constant array (1 .. 23) of System.Address := (
22421 Ada.Text_Io'UET_Address,
22422 Ada.Exceptions'UET_Address,
22423 Gnat.Heap_Sort_A'UET_Address,
22424 System.Exception_Table'UET_Address,
22425 System.Machine_State_Operations'UET_Address,
22426 System.Secondary_Stack'UET_Address,
22427 System.Parameters'UET_Address,
22428 System.Soft_Links'UET_Address,
22429 System.Stack_Checking'UET_Address,
22430 System.Traceback'UET_Address,
22431 Ada.Streams'UET_Address,
22432 Ada.Tags'UET_Address,
22433 System.String_Ops'UET_Address,
22434 Interfaces.C_Streams'UET_Address,
22435 System.File_Io'UET_Address,
22436 Ada.Finalization'UET_Address,
22437 System.Finalization_Root'UET_Address,
22438 System.Finalization_Implementation'UET_Address,
22439 System.String_Ops_Concat_3'UET_Address,
22440 System.Stream_Attributes'UET_Address,
22441 System.File_Control_Block'UET_Address,
22442 Ada.Finalization.List_Controller'UET_Address);
22444 -- Table of addresses of elaboration routines. Used for
22445 -- zero cost exception handling to make sure these
22446 -- addresses are included in the top level procedure
22449 EA : aliased constant array (1 .. 23) of System.Address := (
22450 adainit'Code_Address,
22451 Do_Finalize'Code_Address,
22452 Ada.Exceptions'Elab_Spec'Address,
22453 System.Exceptions'Elab_Spec'Address,
22454 Interfaces.C_Streams'Elab_Spec'Address,
22455 System.Exception_Table'Elab_Body'Address,
22456 Ada.Io_Exceptions'Elab_Spec'Address,
22457 System.Stack_Checking'Elab_Spec'Address,
22458 System.Soft_Links'Elab_Body'Address,
22459 System.Secondary_Stack'Elab_Body'Address,
22460 Ada.Tags'Elab_Spec'Address,
22461 Ada.Tags'Elab_Body'Address,
22462 Ada.Streams'Elab_Spec'Address,
22463 System.Finalization_Root'Elab_Spec'Address,
22464 Ada.Exceptions'Elab_Body'Address,
22465 System.Finalization_Implementation'Elab_Spec'Address,
22466 System.Finalization_Implementation'Elab_Body'Address,
22467 Ada.Finalization'Elab_Spec'Address,
22468 Ada.Finalization.List_Controller'Elab_Spec'Address,
22469 System.File_Control_Block'Elab_Spec'Address,
22470 System.File_Io'Elab_Body'Address,
22471 Ada.Text_Io'Elab_Spec'Address,
22472 Ada.Text_Io'Elab_Body'Address);
22474 -- Start of processing for adainit
22478 -- Call SDP_Table_Build to build the top level procedure
22479 -- table for zero cost exception handling (omitted in
22480 -- longjmp/setjmp mode).
22482 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
22484 -- Call Set_Globals to record various information for
22485 -- this partition. The values are derived by the binder
22486 -- from information stored in the ali files by the compiler.
22488 @findex __gnat_set_globals
22490 (Main_Priority => -1,
22491 -- Priority of main program, -1 if no pragma Priority used
22493 Time_Slice_Value => -1,
22494 -- Time slice from Time_Slice pragma, -1 if none used
22496 WC_Encoding => 'b',
22497 -- Wide_Character encoding used, default is brackets
22499 Locking_Policy => ' ',
22500 -- Locking_Policy used, default of space means not
22501 -- specified, otherwise it is the first character of
22502 -- the policy name.
22504 Queuing_Policy => ' ',
22505 -- Queuing_Policy used, default of space means not
22506 -- specified, otherwise it is the first character of
22507 -- the policy name.
22509 Task_Dispatching_Policy => ' ',
22510 -- Task_Dispatching_Policy used, default of space means
22511 -- not specified, otherwise first character of the
22514 Adafinal => System.Null_Address,
22515 -- Address of Adafinal routine, not used anymore
22517 Unreserve_All_Interrupts => 0,
22518 -- Set true if pragma Unreserve_All_Interrupts was used
22520 Exception_Tracebacks => 0);
22521 -- Indicates if exception tracebacks are enabled
22523 Elab_Final_Code := 1;
22525 -- Now we have the elaboration calls for all units in the partition.
22526 -- The Elab_Spec and Elab_Body attributes generate references to the
22527 -- implicit elaboration procedures generated by the compiler for
22528 -- each unit that requires elaboration.
22531 Interfaces.C_Streams'Elab_Spec;
22535 Ada.Exceptions'Elab_Spec;
22538 System.Exception_Table'Elab_Body;
22542 Ada.Io_Exceptions'Elab_Spec;
22546 System.Exceptions'Elab_Spec;
22550 System.Stack_Checking'Elab_Spec;
22553 System.Soft_Links'Elab_Body;
22558 System.Secondary_Stack'Elab_Body;
22562 Ada.Tags'Elab_Spec;
22565 Ada.Tags'Elab_Body;
22569 Ada.Streams'Elab_Spec;
22573 System.Finalization_Root'Elab_Spec;
22577 Ada.Exceptions'Elab_Body;
22581 System.Finalization_Implementation'Elab_Spec;
22584 System.Finalization_Implementation'Elab_Body;
22588 Ada.Finalization'Elab_Spec;
22592 Ada.Finalization.List_Controller'Elab_Spec;
22596 System.File_Control_Block'Elab_Spec;
22600 System.File_Io'Elab_Body;
22604 Ada.Text_Io'Elab_Spec;
22607 Ada.Text_Io'Elab_Body;
22611 Elab_Final_Code := 0;
22619 procedure adafinal is
22628 -- main is actually a function, as in the ANSI C standard,
22629 -- defined to return the exit status. The three parameters
22630 -- are the argument count, argument values and environment
22633 @findex Main Program
22636 argv : System.Address;
22637 envp : System.Address)
22640 -- The initialize routine performs low level system
22641 -- initialization using a standard library routine which
22642 -- sets up signal handling and performs any other
22643 -- required setup. The routine can be found in file
22646 @findex __gnat_initialize
22647 procedure initialize;
22648 pragma Import (C, initialize, "__gnat_initialize");
22650 -- The finalize routine performs low level system
22651 -- finalization using a standard library routine. The
22652 -- routine is found in file a-final.c and in the standard
22653 -- distribution is a dummy routine that does nothing, so
22654 -- really this is a hook for special user finalization.
22656 @findex __gnat_finalize
22657 procedure finalize;
22658 pragma Import (C, finalize, "__gnat_finalize");
22660 -- We get to the main program of the partition by using
22661 -- pragma Import because if we try to with the unit and
22662 -- call it Ada style, then not only do we waste time
22663 -- recompiling it, but also, we don't really know the right
22664 -- switches (e.g.@: identifier character set) to be used
22667 procedure Ada_Main_Program;
22668 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
22670 -- Start of processing for main
22673 -- Save global variables
22679 -- Call low level system initialization
22683 -- Call our generated Ada initialization routine
22687 -- This is the point at which we want the debugger to get
22692 -- Now we call the main program of the partition
22696 -- Perform Ada finalization
22700 -- Perform low level system finalization
22704 -- Return the proper exit status
22705 return (gnat_exit_status);
22708 -- This section is entirely comments, so it has no effect on the
22709 -- compilation of the Ada_Main package. It provides the list of
22710 -- object files and linker options, as well as some standard
22711 -- libraries needed for the link. The gnatlink utility parses
22712 -- this b~hello.adb file to read these comment lines to generate
22713 -- the appropriate command line arguments for the call to the
22714 -- system linker. The BEGIN/END lines are used for sentinels for
22715 -- this parsing operation.
22717 -- The exact file names will of course depend on the environment,
22718 -- host/target and location of files on the host system.
22720 @findex Object file list
22721 -- BEGIN Object file/option list
22724 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
22725 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22726 -- END Object file/option list
22732 The Ada code in the above example is exactly what is generated by the
22733 binder. We have added comments to more clearly indicate the function
22734 of each part of the generated @code{Ada_Main} package.
22736 The code is standard Ada in all respects, and can be processed by any
22737 tools that handle Ada. In particular, it is possible to use the debugger
22738 in Ada mode to debug the generated @code{Ada_Main} package. For example,
22739 suppose that for reasons that you do not understand, your program is crashing
22740 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
22741 you can place a breakpoint on the call:
22743 @smallexample @c ada
22744 Ada.Text_Io'Elab_Body;
22748 and trace the elaboration routine for this package to find out where
22749 the problem might be (more usually of course you would be debugging
22750 elaboration code in your own application).
22752 @node Elaboration Order Handling in GNAT
22753 @appendix Elaboration Order Handling in GNAT
22754 @cindex Order of elaboration
22755 @cindex Elaboration control
22758 * Elaboration Code::
22759 * Checking the Elaboration Order::
22760 * Controlling the Elaboration Order::
22761 * Controlling Elaboration in GNAT - Internal Calls::
22762 * Controlling Elaboration in GNAT - External Calls::
22763 * Default Behavior in GNAT - Ensuring Safety::
22764 * Treatment of Pragma Elaborate::
22765 * Elaboration Issues for Library Tasks::
22766 * Mixing Elaboration Models::
22767 * What to Do If the Default Elaboration Behavior Fails::
22768 * Elaboration for Access-to-Subprogram Values::
22769 * Summary of Procedures for Elaboration Control::
22770 * Other Elaboration Order Considerations::
22774 This chapter describes the handling of elaboration code in Ada and
22775 in GNAT, and discusses how the order of elaboration of program units can
22776 be controlled in GNAT, either automatically or with explicit programming
22779 @node Elaboration Code
22780 @section Elaboration Code
22783 Ada provides rather general mechanisms for executing code at elaboration
22784 time, that is to say before the main program starts executing. Such code arises
22788 @item Initializers for variables.
22789 Variables declared at the library level, in package specs or bodies, can
22790 require initialization that is performed at elaboration time, as in:
22791 @smallexample @c ada
22793 Sqrt_Half : Float := Sqrt (0.5);
22797 @item Package initialization code
22798 Code in a @code{BEGIN-END} section at the outer level of a package body is
22799 executed as part of the package body elaboration code.
22801 @item Library level task allocators
22802 Tasks that are declared using task allocators at the library level
22803 start executing immediately and hence can execute at elaboration time.
22807 Subprogram calls are possible in any of these contexts, which means that
22808 any arbitrary part of the program may be executed as part of the elaboration
22809 code. It is even possible to write a program which does all its work at
22810 elaboration time, with a null main program, although stylistically this
22811 would usually be considered an inappropriate way to structure
22814 An important concern arises in the context of elaboration code:
22815 we have to be sure that it is executed in an appropriate order. What we
22816 have is a series of elaboration code sections, potentially one section
22817 for each unit in the program. It is important that these execute
22818 in the correct order. Correctness here means that, taking the above
22819 example of the declaration of @code{Sqrt_Half},
22820 if some other piece of
22821 elaboration code references @code{Sqrt_Half},
22822 then it must run after the
22823 section of elaboration code that contains the declaration of
22826 There would never be any order of elaboration problem if we made a rule
22827 that whenever you @code{with} a unit, you must elaborate both the spec and body
22828 of that unit before elaborating the unit doing the @code{with}'ing:
22830 @smallexample @c ada
22834 package Unit_2 is @dots{}
22840 would require that both the body and spec of @code{Unit_1} be elaborated
22841 before the spec of @code{Unit_2}. However, a rule like that would be far too
22842 restrictive. In particular, it would make it impossible to have routines
22843 in separate packages that were mutually recursive.
22845 You might think that a clever enough compiler could look at the actual
22846 elaboration code and determine an appropriate correct order of elaboration,
22847 but in the general case, this is not possible. Consider the following
22850 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
22852 the variable @code{Sqrt_1}, which is declared in the elaboration code
22853 of the body of @code{Unit_1}:
22855 @smallexample @c ada
22857 Sqrt_1 : Float := Sqrt (0.1);
22862 The elaboration code of the body of @code{Unit_1} also contains:
22864 @smallexample @c ada
22867 if expression_1 = 1 then
22868 Q := Unit_2.Func_2;
22875 @code{Unit_2} is exactly parallel,
22876 it has a procedure @code{Func_2} that references
22877 the variable @code{Sqrt_2}, which is declared in the elaboration code of
22878 the body @code{Unit_2}:
22880 @smallexample @c ada
22882 Sqrt_2 : Float := Sqrt (0.1);
22887 The elaboration code of the body of @code{Unit_2} also contains:
22889 @smallexample @c ada
22892 if expression_2 = 2 then
22893 Q := Unit_1.Func_1;
22900 Now the question is, which of the following orders of elaboration is
22925 If you carefully analyze the flow here, you will see that you cannot tell
22926 at compile time the answer to this question.
22927 If @code{expression_1} is not equal to 1,
22928 and @code{expression_2} is not equal to 2,
22929 then either order is acceptable, because neither of the function calls is
22930 executed. If both tests evaluate to true, then neither order is acceptable
22931 and in fact there is no correct order.
22933 If one of the two expressions is true, and the other is false, then one
22934 of the above orders is correct, and the other is incorrect. For example,
22935 if @code{expression_1} /= 1 and @code{expression_2} = 2,
22936 then the call to @code{Func_1}
22937 will occur, but not the call to @code{Func_2.}
22938 This means that it is essential
22939 to elaborate the body of @code{Unit_1} before
22940 the body of @code{Unit_2}, so the first
22941 order of elaboration is correct and the second is wrong.
22943 By making @code{expression_1} and @code{expression_2}
22944 depend on input data, or perhaps
22945 the time of day, we can make it impossible for the compiler or binder
22946 to figure out which of these expressions will be true, and hence it
22947 is impossible to guarantee a safe order of elaboration at run time.
22949 @node Checking the Elaboration Order
22950 @section Checking the Elaboration Order
22953 In some languages that involve the same kind of elaboration problems,
22954 e.g.@: Java and C++, the programmer is expected to worry about these
22955 ordering problems himself, and it is common to
22956 write a program in which an incorrect elaboration order gives
22957 surprising results, because it references variables before they
22959 Ada is designed to be a safe language, and a programmer-beware approach is
22960 clearly not sufficient. Consequently, the language provides three lines
22964 @item Standard rules
22965 Some standard rules restrict the possible choice of elaboration
22966 order. In particular, if you @code{with} a unit, then its spec is always
22967 elaborated before the unit doing the @code{with}. Similarly, a parent
22968 spec is always elaborated before the child spec, and finally
22969 a spec is always elaborated before its corresponding body.
22971 @item Dynamic elaboration checks
22972 @cindex Elaboration checks
22973 @cindex Checks, elaboration
22974 Dynamic checks are made at run time, so that if some entity is accessed
22975 before it is elaborated (typically by means of a subprogram call)
22976 then the exception (@code{Program_Error}) is raised.
22978 @item Elaboration control
22979 Facilities are provided for the programmer to specify the desired order
22983 Let's look at these facilities in more detail. First, the rules for
22984 dynamic checking. One possible rule would be simply to say that the
22985 exception is raised if you access a variable which has not yet been
22986 elaborated. The trouble with this approach is that it could require
22987 expensive checks on every variable reference. Instead Ada has two
22988 rules which are a little more restrictive, but easier to check, and
22992 @item Restrictions on calls
22993 A subprogram can only be called at elaboration time if its body
22994 has been elaborated. The rules for elaboration given above guarantee
22995 that the spec of the subprogram has been elaborated before the
22996 call, but not the body. If this rule is violated, then the
22997 exception @code{Program_Error} is raised.
22999 @item Restrictions on instantiations
23000 A generic unit can only be instantiated if the body of the generic
23001 unit has been elaborated. Again, the rules for elaboration given above
23002 guarantee that the spec of the generic unit has been elaborated
23003 before the instantiation, but not the body. If this rule is
23004 violated, then the exception @code{Program_Error} is raised.
23008 The idea is that if the body has been elaborated, then any variables
23009 it references must have been elaborated; by checking for the body being
23010 elaborated we guarantee that none of its references causes any
23011 trouble. As we noted above, this is a little too restrictive, because a
23012 subprogram that has no non-local references in its body may in fact be safe
23013 to call. However, it really would be unsafe to rely on this, because
23014 it would mean that the caller was aware of details of the implementation
23015 in the body. This goes against the basic tenets of Ada.
23017 A plausible implementation can be described as follows.
23018 A Boolean variable is associated with each subprogram
23019 and each generic unit. This variable is initialized to False, and is set to
23020 True at the point body is elaborated. Every call or instantiation checks the
23021 variable, and raises @code{Program_Error} if the variable is False.
23023 Note that one might think that it would be good enough to have one Boolean
23024 variable for each package, but that would not deal with cases of trying
23025 to call a body in the same package as the call
23026 that has not been elaborated yet.
23027 Of course a compiler may be able to do enough analysis to optimize away
23028 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
23029 does such optimizations, but still the easiest conceptual model is to
23030 think of there being one variable per subprogram.
23032 @node Controlling the Elaboration Order
23033 @section Controlling the Elaboration Order
23036 In the previous section we discussed the rules in Ada which ensure
23037 that @code{Program_Error} is raised if an incorrect elaboration order is
23038 chosen. This prevents erroneous executions, but we need mechanisms to
23039 specify a correct execution and avoid the exception altogether.
23040 To achieve this, Ada provides a number of features for controlling
23041 the order of elaboration. We discuss these features in this section.
23043 First, there are several ways of indicating to the compiler that a given
23044 unit has no elaboration problems:
23047 @item packages that do not require a body
23048 A library package that does not require a body does not permit
23049 a body (this rule was introduced in Ada 95).
23050 Thus if we have a such a package, as in:
23052 @smallexample @c ada
23055 package Definitions is
23057 type m is new integer;
23059 type a is array (1 .. 10) of m;
23060 type b is array (1 .. 20) of m;
23068 A package that @code{with}'s @code{Definitions} may safely instantiate
23069 @code{Definitions.Subp} because the compiler can determine that there
23070 definitely is no package body to worry about in this case
23073 @cindex pragma Pure
23075 Places sufficient restrictions on a unit to guarantee that
23076 no call to any subprogram in the unit can result in an
23077 elaboration problem. This means that the compiler does not need
23078 to worry about the point of elaboration of such units, and in
23079 particular, does not need to check any calls to any subprograms
23082 @item pragma Preelaborate
23083 @findex Preelaborate
23084 @cindex pragma Preelaborate
23085 This pragma places slightly less stringent restrictions on a unit than
23087 but these restrictions are still sufficient to ensure that there
23088 are no elaboration problems with any calls to the unit.
23090 @item pragma Elaborate_Body
23091 @findex Elaborate_Body
23092 @cindex pragma Elaborate_Body
23093 This pragma requires that the body of a unit be elaborated immediately
23094 after its spec. Suppose a unit @code{A} has such a pragma,
23095 and unit @code{B} does
23096 a @code{with} of unit @code{A}. Recall that the standard rules require
23097 the spec of unit @code{A}
23098 to be elaborated before the @code{with}'ing unit; given the pragma in
23099 @code{A}, we also know that the body of @code{A}
23100 will be elaborated before @code{B}, so
23101 that calls to @code{A} are safe and do not need a check.
23106 unlike pragma @code{Pure} and pragma @code{Preelaborate},
23108 @code{Elaborate_Body} does not guarantee that the program is
23109 free of elaboration problems, because it may not be possible
23110 to satisfy the requested elaboration order.
23111 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
23113 marks @code{Unit_1} as @code{Elaborate_Body},
23114 and not @code{Unit_2,} then the order of
23115 elaboration will be:
23127 Now that means that the call to @code{Func_1} in @code{Unit_2}
23128 need not be checked,
23129 it must be safe. But the call to @code{Func_2} in
23130 @code{Unit_1} may still fail if
23131 @code{Expression_1} is equal to 1,
23132 and the programmer must still take
23133 responsibility for this not being the case.
23135 If all units carry a pragma @code{Elaborate_Body}, then all problems are
23136 eliminated, except for calls entirely within a body, which are
23137 in any case fully under programmer control. However, using the pragma
23138 everywhere is not always possible.
23139 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
23140 we marked both of them as having pragma @code{Elaborate_Body}, then
23141 clearly there would be no possible elaboration order.
23143 The above pragmas allow a server to guarantee safe use by clients, and
23144 clearly this is the preferable approach. Consequently a good rule
23145 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
23146 and if this is not possible,
23147 mark them as @code{Elaborate_Body} if possible.
23148 As we have seen, there are situations where neither of these
23149 three pragmas can be used.
23150 So we also provide methods for clients to control the
23151 order of elaboration of the servers on which they depend:
23154 @item pragma Elaborate (unit)
23156 @cindex pragma Elaborate
23157 This pragma is placed in the context clause, after a @code{with} clause,
23158 and it requires that the body of the named unit be elaborated before
23159 the unit in which the pragma occurs. The idea is to use this pragma
23160 if the current unit calls at elaboration time, directly or indirectly,
23161 some subprogram in the named unit.
23163 @item pragma Elaborate_All (unit)
23164 @findex Elaborate_All
23165 @cindex pragma Elaborate_All
23166 This is a stronger version of the Elaborate pragma. Consider the
23170 Unit A @code{with}'s unit B and calls B.Func in elab code
23171 Unit B @code{with}'s unit C, and B.Func calls C.Func
23175 Now if we put a pragma @code{Elaborate (B)}
23176 in unit @code{A}, this ensures that the
23177 body of @code{B} is elaborated before the call, but not the
23178 body of @code{C}, so
23179 the call to @code{C.Func} could still cause @code{Program_Error} to
23182 The effect of a pragma @code{Elaborate_All} is stronger, it requires
23183 not only that the body of the named unit be elaborated before the
23184 unit doing the @code{with}, but also the bodies of all units that the
23185 named unit uses, following @code{with} links transitively. For example,
23186 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
23188 not only that the body of @code{B} be elaborated before @code{A},
23190 body of @code{C}, because @code{B} @code{with}'s @code{C}.
23194 We are now in a position to give a usage rule in Ada for avoiding
23195 elaboration problems, at least if dynamic dispatching and access to
23196 subprogram values are not used. We will handle these cases separately
23199 The rule is simple. If a unit has elaboration code that can directly or
23200 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
23201 a generic package in a @code{with}'ed unit,
23202 then if the @code{with}'ed unit does not have
23203 pragma @code{Pure} or @code{Preelaborate}, then the client should have
23204 a pragma @code{Elaborate_All}
23205 for the @code{with}'ed unit. By following this rule a client is
23206 assured that calls can be made without risk of an exception.
23208 For generic subprogram instantiations, the rule can be relaxed to
23209 require only a pragma @code{Elaborate} since elaborating the body
23210 of a subprogram cannot cause any transitive elaboration (we are
23211 not calling the subprogram in this case, just elaborating its
23214 If this rule is not followed, then a program may be in one of four
23218 @item No order exists
23219 No order of elaboration exists which follows the rules, taking into
23220 account any @code{Elaborate}, @code{Elaborate_All},
23221 or @code{Elaborate_Body} pragmas. In
23222 this case, an Ada compiler must diagnose the situation at bind
23223 time, and refuse to build an executable program.
23225 @item One or more orders exist, all incorrect
23226 One or more acceptable elaboration orders exist, and all of them
23227 generate an elaboration order problem. In this case, the binder
23228 can build an executable program, but @code{Program_Error} will be raised
23229 when the program is run.
23231 @item Several orders exist, some right, some incorrect
23232 One or more acceptable elaboration orders exists, and some of them
23233 work, and some do not. The programmer has not controlled
23234 the order of elaboration, so the binder may or may not pick one of
23235 the correct orders, and the program may or may not raise an
23236 exception when it is run. This is the worst case, because it means
23237 that the program may fail when moved to another compiler, or even
23238 another version of the same compiler.
23240 @item One or more orders exists, all correct
23241 One ore more acceptable elaboration orders exist, and all of them
23242 work. In this case the program runs successfully. This state of
23243 affairs can be guaranteed by following the rule we gave above, but
23244 may be true even if the rule is not followed.
23248 Note that one additional advantage of following our rules on the use
23249 of @code{Elaborate} and @code{Elaborate_All}
23250 is that the program continues to stay in the ideal (all orders OK) state
23251 even if maintenance
23252 changes some bodies of some units. Conversely, if a program that does
23253 not follow this rule happens to be safe at some point, this state of affairs
23254 may deteriorate silently as a result of maintenance changes.
23256 You may have noticed that the above discussion did not mention
23257 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
23258 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
23259 code in the body makes calls to some other unit, so it is still necessary
23260 to use @code{Elaborate_All} on such units.
23262 @node Controlling Elaboration in GNAT - Internal Calls
23263 @section Controlling Elaboration in GNAT - Internal Calls
23266 In the case of internal calls, i.e., calls within a single package, the
23267 programmer has full control over the order of elaboration, and it is up
23268 to the programmer to elaborate declarations in an appropriate order. For
23271 @smallexample @c ada
23274 function One return Float;
23278 function One return Float is
23287 will obviously raise @code{Program_Error} at run time, because function
23288 One will be called before its body is elaborated. In this case GNAT will
23289 generate a warning that the call will raise @code{Program_Error}:
23295 2. function One return Float;
23297 4. Q : Float := One;
23299 >>> warning: cannot call "One" before body is elaborated
23300 >>> warning: Program_Error will be raised at run time
23303 6. function One return Float is
23316 Note that in this particular case, it is likely that the call is safe, because
23317 the function @code{One} does not access any global variables.
23318 Nevertheless in Ada, we do not want the validity of the check to depend on
23319 the contents of the body (think about the separate compilation case), so this
23320 is still wrong, as we discussed in the previous sections.
23322 The error is easily corrected by rearranging the declarations so that the
23323 body of @code{One} appears before the declaration containing the call
23324 (note that in Ada 95 and Ada 2005,
23325 declarations can appear in any order, so there is no restriction that
23326 would prevent this reordering, and if we write:
23328 @smallexample @c ada
23331 function One return Float;
23333 function One return Float is
23344 then all is well, no warning is generated, and no
23345 @code{Program_Error} exception
23347 Things are more complicated when a chain of subprograms is executed:
23349 @smallexample @c ada
23352 function A return Integer;
23353 function B return Integer;
23354 function C return Integer;
23356 function B return Integer is begin return A; end;
23357 function C return Integer is begin return B; end;
23361 function A return Integer is begin return 1; end;
23367 Now the call to @code{C}
23368 at elaboration time in the declaration of @code{X} is correct, because
23369 the body of @code{C} is already elaborated,
23370 and the call to @code{B} within the body of
23371 @code{C} is correct, but the call
23372 to @code{A} within the body of @code{B} is incorrect, because the body
23373 of @code{A} has not been elaborated, so @code{Program_Error}
23374 will be raised on the call to @code{A}.
23375 In this case GNAT will generate a
23376 warning that @code{Program_Error} may be
23377 raised at the point of the call. Let's look at the warning:
23383 2. function A return Integer;
23384 3. function B return Integer;
23385 4. function C return Integer;
23387 6. function B return Integer is begin return A; end;
23389 >>> warning: call to "A" before body is elaborated may
23390 raise Program_Error
23391 >>> warning: "B" called at line 7
23392 >>> warning: "C" called at line 9
23394 7. function C return Integer is begin return B; end;
23396 9. X : Integer := C;
23398 11. function A return Integer is begin return 1; end;
23408 Note that the message here says ``may raise'', instead of the direct case,
23409 where the message says ``will be raised''. That's because whether
23411 actually called depends in general on run-time flow of control.
23412 For example, if the body of @code{B} said
23414 @smallexample @c ada
23417 function B return Integer is
23419 if some-condition-depending-on-input-data then
23430 then we could not know until run time whether the incorrect call to A would
23431 actually occur, so @code{Program_Error} might
23432 or might not be raised. It is possible for a compiler to
23433 do a better job of analyzing bodies, to
23434 determine whether or not @code{Program_Error}
23435 might be raised, but it certainly
23436 couldn't do a perfect job (that would require solving the halting problem
23437 and is provably impossible), and because this is a warning anyway, it does
23438 not seem worth the effort to do the analysis. Cases in which it
23439 would be relevant are rare.
23441 In practice, warnings of either of the forms given
23442 above will usually correspond to
23443 real errors, and should be examined carefully and eliminated.
23444 In the rare case where a warning is bogus, it can be suppressed by any of
23445 the following methods:
23449 Compile with the @option{-gnatws} switch set
23452 Suppress @code{Elaboration_Check} for the called subprogram
23455 Use pragma @code{Warnings_Off} to turn warnings off for the call
23459 For the internal elaboration check case,
23460 GNAT by default generates the
23461 necessary run-time checks to ensure
23462 that @code{Program_Error} is raised if any
23463 call fails an elaboration check. Of course this can only happen if a
23464 warning has been issued as described above. The use of pragma
23465 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23466 some of these checks, meaning that it may be possible (but is not
23467 guaranteed) for a program to be able to call a subprogram whose body
23468 is not yet elaborated, without raising a @code{Program_Error} exception.
23470 @node Controlling Elaboration in GNAT - External Calls
23471 @section Controlling Elaboration in GNAT - External Calls
23474 The previous section discussed the case in which the execution of a
23475 particular thread of elaboration code occurred entirely within a
23476 single unit. This is the easy case to handle, because a programmer
23477 has direct and total control over the order of elaboration, and
23478 furthermore, checks need only be generated in cases which are rare
23479 and which the compiler can easily detect.
23480 The situation is more complex when separate compilation is taken into account.
23481 Consider the following:
23483 @smallexample @c ada
23487 function Sqrt (Arg : Float) return Float;
23490 package body Math is
23491 function Sqrt (Arg : Float) return Float is
23500 X : Float := Math.Sqrt (0.5);
23513 where @code{Main} is the main program. When this program is executed, the
23514 elaboration code must first be executed, and one of the jobs of the
23515 binder is to determine the order in which the units of a program are
23516 to be elaborated. In this case we have four units: the spec and body
23518 the spec of @code{Stuff} and the body of @code{Main}).
23519 In what order should the four separate sections of elaboration code
23522 There are some restrictions in the order of elaboration that the binder
23523 can choose. In particular, if unit U has a @code{with}
23524 for a package @code{X}, then you
23525 are assured that the spec of @code{X}
23526 is elaborated before U , but you are
23527 not assured that the body of @code{X}
23528 is elaborated before U.
23529 This means that in the above case, the binder is allowed to choose the
23540 but that's not good, because now the call to @code{Math.Sqrt}
23541 that happens during
23542 the elaboration of the @code{Stuff}
23543 spec happens before the body of @code{Math.Sqrt} is
23544 elaborated, and hence causes @code{Program_Error} exception to be raised.
23545 At first glance, one might say that the binder is misbehaving, because
23546 obviously you want to elaborate the body of something you @code{with}
23548 that is not a general rule that can be followed in all cases. Consider
23550 @smallexample @c ada
23553 package X is @dots{}
23555 package Y is @dots{}
23558 package body Y is @dots{}
23561 package body X is @dots{}
23567 This is a common arrangement, and, apart from the order of elaboration
23568 problems that might arise in connection with elaboration code, this works fine.
23569 A rule that says that you must first elaborate the body of anything you
23570 @code{with} cannot work in this case:
23571 the body of @code{X} @code{with}'s @code{Y},
23572 which means you would have to
23573 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
23575 you have to elaborate the body of @code{X} first, but @dots{} and we have a
23576 loop that cannot be broken.
23578 It is true that the binder can in many cases guess an order of elaboration
23579 that is unlikely to cause a @code{Program_Error}
23580 exception to be raised, and it tries to do so (in the
23581 above example of @code{Math/Stuff/Spec}, the GNAT binder will
23583 elaborate the body of @code{Math} right after its spec, so all will be well).
23585 However, a program that blindly relies on the binder to be helpful can
23586 get into trouble, as we discussed in the previous sections, so
23588 provides a number of facilities for assisting the programmer in
23589 developing programs that are robust with respect to elaboration order.
23591 @node Default Behavior in GNAT - Ensuring Safety
23592 @section Default Behavior in GNAT - Ensuring Safety
23595 The default behavior in GNAT ensures elaboration safety. In its
23596 default mode GNAT implements the
23597 rule we previously described as the right approach. Let's restate it:
23601 @emph{If a unit has elaboration code that can directly or indirectly make a
23602 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
23603 package in a @code{with}'ed unit, then if the @code{with}'ed unit
23604 does not have pragma @code{Pure} or
23605 @code{Preelaborate}, then the client should have an
23606 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
23608 @emph{In the case of instantiating a generic subprogram, it is always
23609 sufficient to have only an @code{Elaborate} pragma for the
23610 @code{with}'ed unit.}
23614 By following this rule a client is assured that calls and instantiations
23615 can be made without risk of an exception.
23617 In this mode GNAT traces all calls that are potentially made from
23618 elaboration code, and puts in any missing implicit @code{Elaborate}
23619 and @code{Elaborate_All} pragmas.
23620 The advantage of this approach is that no elaboration problems
23621 are possible if the binder can find an elaboration order that is
23622 consistent with these implicit @code{Elaborate} and
23623 @code{Elaborate_All} pragmas. The
23624 disadvantage of this approach is that no such order may exist.
23626 If the binder does not generate any diagnostics, then it means that it has
23627 found an elaboration order that is guaranteed to be safe. However, the binder
23628 may still be relying on implicitly generated @code{Elaborate} and
23629 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
23632 If it is important to guarantee portability, then the compilations should
23635 (warn on elaboration problems) switch. This will cause warning messages
23636 to be generated indicating the missing @code{Elaborate} and
23637 @code{Elaborate_All} pragmas.
23638 Consider the following source program:
23640 @smallexample @c ada
23645 m : integer := k.r;
23652 where it is clear that there
23653 should be a pragma @code{Elaborate_All}
23654 for unit @code{k}. An implicit pragma will be generated, and it is
23655 likely that the binder will be able to honor it. However, if you want
23656 to port this program to some other Ada compiler than GNAT.
23657 it is safer to include the pragma explicitly in the source. If this
23658 unit is compiled with the
23660 switch, then the compiler outputs a warning:
23667 3. m : integer := k.r;
23669 >>> warning: call to "r" may raise Program_Error
23670 >>> warning: missing pragma Elaborate_All for "k"
23678 and these warnings can be used as a guide for supplying manually
23679 the missing pragmas. It is usually a bad idea to use this warning
23680 option during development. That's because it will warn you when
23681 you need to put in a pragma, but cannot warn you when it is time
23682 to take it out. So the use of pragma @code{Elaborate_All} may lead to
23683 unnecessary dependencies and even false circularities.
23685 This default mode is more restrictive than the Ada Reference
23686 Manual, and it is possible to construct programs which will compile
23687 using the dynamic model described there, but will run into a
23688 circularity using the safer static model we have described.
23690 Of course any Ada compiler must be able to operate in a mode
23691 consistent with the requirements of the Ada Reference Manual,
23692 and in particular must have the capability of implementing the
23693 standard dynamic model of elaboration with run-time checks.
23695 In GNAT, this standard mode can be achieved either by the use of
23696 the @option{-gnatE} switch on the compiler (@command{gcc} or
23697 @command{gnatmake}) command, or by the use of the configuration pragma:
23699 @smallexample @c ada
23700 pragma Elaboration_Checks (DYNAMIC);
23704 Either approach will cause the unit affected to be compiled using the
23705 standard dynamic run-time elaboration checks described in the Ada
23706 Reference Manual. The static model is generally preferable, since it
23707 is clearly safer to rely on compile and link time checks rather than
23708 run-time checks. However, in the case of legacy code, it may be
23709 difficult to meet the requirements of the static model. This
23710 issue is further discussed in
23711 @ref{What to Do If the Default Elaboration Behavior Fails}.
23713 Note that the static model provides a strict subset of the allowed
23714 behavior and programs of the Ada Reference Manual, so if you do
23715 adhere to the static model and no circularities exist,
23716 then you are assured that your program will
23717 work using the dynamic model, providing that you remove any
23718 pragma Elaborate statements from the source.
23720 @node Treatment of Pragma Elaborate
23721 @section Treatment of Pragma Elaborate
23722 @cindex Pragma Elaborate
23725 The use of @code{pragma Elaborate}
23726 should generally be avoided in Ada 95 and Ada 2005 programs,
23727 since there is no guarantee that transitive calls
23728 will be properly handled. Indeed at one point, this pragma was placed
23729 in Annex J (Obsolescent Features), on the grounds that it is never useful.
23731 Now that's a bit restrictive. In practice, the case in which
23732 @code{pragma Elaborate} is useful is when the caller knows that there
23733 are no transitive calls, or that the called unit contains all necessary
23734 transitive @code{pragma Elaborate} statements, and legacy code often
23735 contains such uses.
23737 Strictly speaking the static mode in GNAT should ignore such pragmas,
23738 since there is no assurance at compile time that the necessary safety
23739 conditions are met. In practice, this would cause GNAT to be incompatible
23740 with correctly written Ada 83 code that had all necessary
23741 @code{pragma Elaborate} statements in place. Consequently, we made the
23742 decision that GNAT in its default mode will believe that if it encounters
23743 a @code{pragma Elaborate} then the programmer knows what they are doing,
23744 and it will trust that no elaboration errors can occur.
23746 The result of this decision is two-fold. First to be safe using the
23747 static mode, you should remove all @code{pragma Elaborate} statements.
23748 Second, when fixing circularities in existing code, you can selectively
23749 use @code{pragma Elaborate} statements to convince the static mode of
23750 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
23753 When using the static mode with @option{-gnatwl}, any use of
23754 @code{pragma Elaborate} will generate a warning about possible
23757 @node Elaboration Issues for Library Tasks
23758 @section Elaboration Issues for Library Tasks
23759 @cindex Library tasks, elaboration issues
23760 @cindex Elaboration of library tasks
23763 In this section we examine special elaboration issues that arise for
23764 programs that declare library level tasks.
23766 Generally the model of execution of an Ada program is that all units are
23767 elaborated, and then execution of the program starts. However, the
23768 declaration of library tasks definitely does not fit this model. The
23769 reason for this is that library tasks start as soon as they are declared
23770 (more precisely, as soon as the statement part of the enclosing package
23771 body is reached), that is to say before elaboration
23772 of the program is complete. This means that if such a task calls a
23773 subprogram, or an entry in another task, the callee may or may not be
23774 elaborated yet, and in the standard
23775 Reference Manual model of dynamic elaboration checks, you can even
23776 get timing dependent Program_Error exceptions, since there can be
23777 a race between the elaboration code and the task code.
23779 The static model of elaboration in GNAT seeks to avoid all such
23780 dynamic behavior, by being conservative, and the conservative
23781 approach in this particular case is to assume that all the code
23782 in a task body is potentially executed at elaboration time if
23783 a task is declared at the library level.
23785 This can definitely result in unexpected circularities. Consider
23786 the following example
23788 @smallexample @c ada
23794 type My_Int is new Integer;
23796 function Ident (M : My_Int) return My_Int;
23800 package body Decls is
23801 task body Lib_Task is
23807 function Ident (M : My_Int) return My_Int is
23815 procedure Put_Val (Arg : Decls.My_Int);
23819 package body Utils is
23820 procedure Put_Val (Arg : Decls.My_Int) is
23822 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23829 Decls.Lib_Task.Start;
23834 If the above example is compiled in the default static elaboration
23835 mode, then a circularity occurs. The circularity comes from the call
23836 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
23837 this call occurs in elaboration code, we need an implicit pragma
23838 @code{Elaborate_All} for @code{Utils}. This means that not only must
23839 the spec and body of @code{Utils} be elaborated before the body
23840 of @code{Decls}, but also the spec and body of any unit that is
23841 @code{with'ed} by the body of @code{Utils} must also be elaborated before
23842 the body of @code{Decls}. This is the transitive implication of
23843 pragma @code{Elaborate_All} and it makes sense, because in general
23844 the body of @code{Put_Val} might have a call to something in a
23845 @code{with'ed} unit.
23847 In this case, the body of Utils (actually its spec) @code{with's}
23848 @code{Decls}. Unfortunately this means that the body of @code{Decls}
23849 must be elaborated before itself, in case there is a call from the
23850 body of @code{Utils}.
23852 Here is the exact chain of events we are worrying about:
23856 In the body of @code{Decls} a call is made from within the body of a library
23857 task to a subprogram in the package @code{Utils}. Since this call may
23858 occur at elaboration time (given that the task is activated at elaboration
23859 time), we have to assume the worst, i.e., that the
23860 call does happen at elaboration time.
23863 This means that the body and spec of @code{Util} must be elaborated before
23864 the body of @code{Decls} so that this call does not cause an access before
23868 Within the body of @code{Util}, specifically within the body of
23869 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
23873 One such @code{with}'ed package is package @code{Decls}, so there
23874 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
23875 In fact there is such a call in this example, but we would have to
23876 assume that there was such a call even if it were not there, since
23877 we are not supposed to write the body of @code{Decls} knowing what
23878 is in the body of @code{Utils}; certainly in the case of the
23879 static elaboration model, the compiler does not know what is in
23880 other bodies and must assume the worst.
23883 This means that the spec and body of @code{Decls} must also be
23884 elaborated before we elaborate the unit containing the call, but
23885 that unit is @code{Decls}! This means that the body of @code{Decls}
23886 must be elaborated before itself, and that's a circularity.
23890 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
23891 the body of @code{Decls} you will get a true Ada Reference Manual
23892 circularity that makes the program illegal.
23894 In practice, we have found that problems with the static model of
23895 elaboration in existing code often arise from library tasks, so
23896 we must address this particular situation.
23898 Note that if we compile and run the program above, using the dynamic model of
23899 elaboration (that is to say use the @option{-gnatE} switch),
23900 then it compiles, binds,
23901 links, and runs, printing the expected result of 2. Therefore in some sense
23902 the circularity here is only apparent, and we need to capture
23903 the properties of this program that distinguish it from other library-level
23904 tasks that have real elaboration problems.
23906 We have four possible answers to this question:
23911 Use the dynamic model of elaboration.
23913 If we use the @option{-gnatE} switch, then as noted above, the program works.
23914 Why is this? If we examine the task body, it is apparent that the task cannot
23916 @code{accept} statement until after elaboration has been completed, because
23917 the corresponding entry call comes from the main program, not earlier.
23918 This is why the dynamic model works here. But that's really giving
23919 up on a precise analysis, and we prefer to take this approach only if we cannot
23921 problem in any other manner. So let us examine two ways to reorganize
23922 the program to avoid the potential elaboration problem.
23925 Split library tasks into separate packages.
23927 Write separate packages, so that library tasks are isolated from
23928 other declarations as much as possible. Let us look at a variation on
23931 @smallexample @c ada
23939 package body Decls1 is
23940 task body Lib_Task is
23948 type My_Int is new Integer;
23949 function Ident (M : My_Int) return My_Int;
23953 package body Decls2 is
23954 function Ident (M : My_Int) return My_Int is
23962 procedure Put_Val (Arg : Decls2.My_Int);
23966 package body Utils is
23967 procedure Put_Val (Arg : Decls2.My_Int) is
23969 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
23976 Decls1.Lib_Task.Start;
23981 All we have done is to split @code{Decls} into two packages, one
23982 containing the library task, and one containing everything else. Now
23983 there is no cycle, and the program compiles, binds, links and executes
23984 using the default static model of elaboration.
23987 Declare separate task types.
23989 A significant part of the problem arises because of the use of the
23990 single task declaration form. This means that the elaboration of
23991 the task type, and the elaboration of the task itself (i.e.@: the
23992 creation of the task) happen at the same time. A good rule
23993 of style in Ada is to always create explicit task types. By
23994 following the additional step of placing task objects in separate
23995 packages from the task type declaration, many elaboration problems
23996 are avoided. Here is another modified example of the example program:
23998 @smallexample @c ada
24000 task type Lib_Task_Type is
24004 type My_Int is new Integer;
24006 function Ident (M : My_Int) return My_Int;
24010 package body Decls is
24011 task body Lib_Task_Type is
24017 function Ident (M : My_Int) return My_Int is
24025 procedure Put_Val (Arg : Decls.My_Int);
24029 package body Utils is
24030 procedure Put_Val (Arg : Decls.My_Int) is
24032 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24038 Lib_Task : Decls.Lib_Task_Type;
24044 Declst.Lib_Task.Start;
24049 What we have done here is to replace the @code{task} declaration in
24050 package @code{Decls} with a @code{task type} declaration. Then we
24051 introduce a separate package @code{Declst} to contain the actual
24052 task object. This separates the elaboration issues for
24053 the @code{task type}
24054 declaration, which causes no trouble, from the elaboration issues
24055 of the task object, which is also unproblematic, since it is now independent
24056 of the elaboration of @code{Utils}.
24057 This separation of concerns also corresponds to
24058 a generally sound engineering principle of separating declarations
24059 from instances. This version of the program also compiles, binds, links,
24060 and executes, generating the expected output.
24063 Use No_Entry_Calls_In_Elaboration_Code restriction.
24064 @cindex No_Entry_Calls_In_Elaboration_Code
24066 The previous two approaches described how a program can be restructured
24067 to avoid the special problems caused by library task bodies. in practice,
24068 however, such restructuring may be difficult to apply to existing legacy code,
24069 so we must consider solutions that do not require massive rewriting.
24071 Let us consider more carefully why our original sample program works
24072 under the dynamic model of elaboration. The reason is that the code
24073 in the task body blocks immediately on the @code{accept}
24074 statement. Now of course there is nothing to prohibit elaboration
24075 code from making entry calls (for example from another library level task),
24076 so we cannot tell in isolation that
24077 the task will not execute the accept statement during elaboration.
24079 However, in practice it is very unusual to see elaboration code
24080 make any entry calls, and the pattern of tasks starting
24081 at elaboration time and then immediately blocking on @code{accept} or
24082 @code{select} statements is very common. What this means is that
24083 the compiler is being too pessimistic when it analyzes the
24084 whole package body as though it might be executed at elaboration
24087 If we know that the elaboration code contains no entry calls, (a very safe
24088 assumption most of the time, that could almost be made the default
24089 behavior), then we can compile all units of the program under control
24090 of the following configuration pragma:
24093 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
24097 This pragma can be placed in the @file{gnat.adc} file in the usual
24098 manner. If we take our original unmodified program and compile it
24099 in the presence of a @file{gnat.adc} containing the above pragma,
24100 then once again, we can compile, bind, link, and execute, obtaining
24101 the expected result. In the presence of this pragma, the compiler does
24102 not trace calls in a task body, that appear after the first @code{accept}
24103 or @code{select} statement, and therefore does not report a potential
24104 circularity in the original program.
24106 The compiler will check to the extent it can that the above
24107 restriction is not violated, but it is not always possible to do a
24108 complete check at compile time, so it is important to use this
24109 pragma only if the stated restriction is in fact met, that is to say
24110 no task receives an entry call before elaboration of all units is completed.
24114 @node Mixing Elaboration Models
24115 @section Mixing Elaboration Models
24117 So far, we have assumed that the entire program is either compiled
24118 using the dynamic model or static model, ensuring consistency. It
24119 is possible to mix the two models, but rules have to be followed
24120 if this mixing is done to ensure that elaboration checks are not
24123 The basic rule is that @emph{a unit compiled with the static model cannot
24124 be @code{with'ed} by a unit compiled with the dynamic model}. The
24125 reason for this is that in the static model, a unit assumes that
24126 its clients guarantee to use (the equivalent of) pragma
24127 @code{Elaborate_All} so that no elaboration checks are required
24128 in inner subprograms, and this assumption is violated if the
24129 client is compiled with dynamic checks.
24131 The precise rule is as follows. A unit that is compiled with dynamic
24132 checks can only @code{with} a unit that meets at least one of the
24133 following criteria:
24138 The @code{with'ed} unit is itself compiled with dynamic elaboration
24139 checks (that is with the @option{-gnatE} switch.
24142 The @code{with'ed} unit is an internal GNAT implementation unit from
24143 the System, Interfaces, Ada, or GNAT hierarchies.
24146 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
24149 The @code{with'ing} unit (that is the client) has an explicit pragma
24150 @code{Elaborate_All} for the @code{with'ed} unit.
24155 If this rule is violated, that is if a unit with dynamic elaboration
24156 checks @code{with's} a unit that does not meet one of the above four
24157 criteria, then the binder (@code{gnatbind}) will issue a warning
24158 similar to that in the following example:
24161 warning: "x.ads" has dynamic elaboration checks and with's
24162 warning: "y.ads" which has static elaboration checks
24166 These warnings indicate that the rule has been violated, and that as a result
24167 elaboration checks may be missed in the resulting executable file.
24168 This warning may be suppressed using the @option{-ws} binder switch
24169 in the usual manner.
24171 One useful application of this mixing rule is in the case of a subsystem
24172 which does not itself @code{with} units from the remainder of the
24173 application. In this case, the entire subsystem can be compiled with
24174 dynamic checks to resolve a circularity in the subsystem, while
24175 allowing the main application that uses this subsystem to be compiled
24176 using the more reliable default static model.
24178 @node What to Do If the Default Elaboration Behavior Fails
24179 @section What to Do If the Default Elaboration Behavior Fails
24182 If the binder cannot find an acceptable order, it outputs detailed
24183 diagnostics. For example:
24189 error: elaboration circularity detected
24190 info: "proc (body)" must be elaborated before "pack (body)"
24191 info: reason: Elaborate_All probably needed in unit "pack (body)"
24192 info: recompile "pack (body)" with -gnatwl
24193 info: for full details
24194 info: "proc (body)"
24195 info: is needed by its spec:
24196 info: "proc (spec)"
24197 info: which is withed by:
24198 info: "pack (body)"
24199 info: "pack (body)" must be elaborated before "proc (body)"
24200 info: reason: pragma Elaborate in unit "proc (body)"
24206 In this case we have a cycle that the binder cannot break. On the one
24207 hand, there is an explicit pragma Elaborate in @code{proc} for
24208 @code{pack}. This means that the body of @code{pack} must be elaborated
24209 before the body of @code{proc}. On the other hand, there is elaboration
24210 code in @code{pack} that calls a subprogram in @code{proc}. This means
24211 that for maximum safety, there should really be a pragma
24212 Elaborate_All in @code{pack} for @code{proc} which would require that
24213 the body of @code{proc} be elaborated before the body of
24214 @code{pack}. Clearly both requirements cannot be satisfied.
24215 Faced with a circularity of this kind, you have three different options.
24218 @item Fix the program
24219 The most desirable option from the point of view of long-term maintenance
24220 is to rearrange the program so that the elaboration problems are avoided.
24221 One useful technique is to place the elaboration code into separate
24222 child packages. Another is to move some of the initialization code to
24223 explicitly called subprograms, where the program controls the order
24224 of initialization explicitly. Although this is the most desirable option,
24225 it may be impractical and involve too much modification, especially in
24226 the case of complex legacy code.
24228 @item Perform dynamic checks
24229 If the compilations are done using the
24231 (dynamic elaboration check) switch, then GNAT behaves in a quite different
24232 manner. Dynamic checks are generated for all calls that could possibly result
24233 in raising an exception. With this switch, the compiler does not generate
24234 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
24235 exactly as specified in the @cite{Ada Reference Manual}.
24236 The binder will generate
24237 an executable program that may or may not raise @code{Program_Error}, and then
24238 it is the programmer's job to ensure that it does not raise an exception. Note
24239 that it is important to compile all units with the switch, it cannot be used
24242 @item Suppress checks
24243 The drawback of dynamic checks is that they generate a
24244 significant overhead at run time, both in space and time. If you
24245 are absolutely sure that your program cannot raise any elaboration
24246 exceptions, and you still want to use the dynamic elaboration model,
24247 then you can use the configuration pragma
24248 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
24249 example this pragma could be placed in the @file{gnat.adc} file.
24251 @item Suppress checks selectively
24252 When you know that certain calls or instantiations in elaboration code cannot
24253 possibly lead to an elaboration error, and the binder nevertheless complains
24254 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
24255 elaboration circularities, it is possible to remove those warnings locally and
24256 obtain a program that will bind. Clearly this can be unsafe, and it is the
24257 responsibility of the programmer to make sure that the resulting program has no
24258 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
24259 used with different granularity to suppress warnings and break elaboration
24264 Place the pragma that names the called subprogram in the declarative part
24265 that contains the call.
24268 Place the pragma in the declarative part, without naming an entity. This
24269 disables warnings on all calls in the corresponding declarative region.
24272 Place the pragma in the package spec that declares the called subprogram,
24273 and name the subprogram. This disables warnings on all elaboration calls to
24277 Place the pragma in the package spec that declares the called subprogram,
24278 without naming any entity. This disables warnings on all elaboration calls to
24279 all subprograms declared in this spec.
24281 @item Use Pragma Elaborate
24282 As previously described in section @xref{Treatment of Pragma Elaborate},
24283 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
24284 that no elaboration checks are required on calls to the designated unit.
24285 There may be cases in which the caller knows that no transitive calls
24286 can occur, so that a @code{pragma Elaborate} will be sufficient in a
24287 case where @code{pragma Elaborate_All} would cause a circularity.
24291 These five cases are listed in order of decreasing safety, and therefore
24292 require increasing programmer care in their application. Consider the
24295 @smallexample @c adanocomment
24297 function F1 return Integer;
24302 function F2 return Integer;
24303 function Pure (x : integer) return integer;
24304 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
24305 -- pragma Suppress (Elaboration_Check); -- (4)
24309 package body Pack1 is
24310 function F1 return Integer is
24314 Val : integer := Pack2.Pure (11); -- Elab. call (1)
24317 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
24318 -- pragma Suppress(Elaboration_Check); -- (2)
24320 X1 := Pack2.F2 + 1; -- Elab. call (2)
24325 package body Pack2 is
24326 function F2 return Integer is
24330 function Pure (x : integer) return integer is
24332 return x ** 3 - 3 * x;
24336 with Pack1, Ada.Text_IO;
24339 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24342 In the absence of any pragmas, an attempt to bind this program produces
24343 the following diagnostics:
24349 error: elaboration circularity detected
24350 info: "pack1 (body)" must be elaborated before "pack1 (body)"
24351 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
24352 info: recompile "pack1 (body)" with -gnatwl for full details
24353 info: "pack1 (body)"
24354 info: must be elaborated along with its spec:
24355 info: "pack1 (spec)"
24356 info: which is withed by:
24357 info: "pack2 (body)"
24358 info: which must be elaborated along with its spec:
24359 info: "pack2 (spec)"
24360 info: which is withed by:
24361 info: "pack1 (body)"
24364 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24365 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24366 F2 is safe, even though F2 calls F1, because the call appears after the
24367 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24368 remove the warning on the call. It is also possible to use pragma (2)
24369 because there are no other potentially unsafe calls in the block.
24372 The call to @code{Pure} is safe because this function does not depend on the
24373 state of @code{Pack2}. Therefore any call to this function is safe, and it
24374 is correct to place pragma (3) in the corresponding package spec.
24377 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24378 warnings on all calls to functions declared therein. Note that this is not
24379 necessarily safe, and requires more detailed examination of the subprogram
24380 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24381 be already elaborated.
24385 It is hard to generalize on which of these four approaches should be
24386 taken. Obviously if it is possible to fix the program so that the default
24387 treatment works, this is preferable, but this may not always be practical.
24388 It is certainly simple enough to use
24390 but the danger in this case is that, even if the GNAT binder
24391 finds a correct elaboration order, it may not always do so,
24392 and certainly a binder from another Ada compiler might not. A
24393 combination of testing and analysis (for which the warnings generated
24396 switch can be useful) must be used to ensure that the program is free
24397 of errors. One switch that is useful in this testing is the
24398 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
24401 Normally the binder tries to find an order that has the best chance
24402 of avoiding elaboration problems. However, if this switch is used, the binder
24403 plays a devil's advocate role, and tries to choose the order that
24404 has the best chance of failing. If your program works even with this
24405 switch, then it has a better chance of being error free, but this is still
24408 For an example of this approach in action, consider the C-tests (executable
24409 tests) from the ACVC suite. If these are compiled and run with the default
24410 treatment, then all but one of them succeed without generating any error
24411 diagnostics from the binder. However, there is one test that fails, and
24412 this is not surprising, because the whole point of this test is to ensure
24413 that the compiler can handle cases where it is impossible to determine
24414 a correct order statically, and it checks that an exception is indeed
24415 raised at run time.
24417 This one test must be compiled and run using the
24419 switch, and then it passes. Alternatively, the entire suite can
24420 be run using this switch. It is never wrong to run with the dynamic
24421 elaboration switch if your code is correct, and we assume that the
24422 C-tests are indeed correct (it is less efficient, but efficiency is
24423 not a factor in running the ACVC tests.)
24425 @node Elaboration for Access-to-Subprogram Values
24426 @section Elaboration for Access-to-Subprogram Values
24427 @cindex Access-to-subprogram
24430 Access-to-subprogram types (introduced in Ada 95) complicate
24431 the handling of elaboration. The trouble is that it becomes
24432 impossible to tell at compile time which procedure
24433 is being called. This means that it is not possible for the binder
24434 to analyze the elaboration requirements in this case.
24436 If at the point at which the access value is created
24437 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
24438 the body of the subprogram is
24439 known to have been elaborated, then the access value is safe, and its use
24440 does not require a check. This may be achieved by appropriate arrangement
24441 of the order of declarations if the subprogram is in the current unit,
24442 or, if the subprogram is in another unit, by using pragma
24443 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
24444 on the referenced unit.
24446 If the referenced body is not known to have been elaborated at the point
24447 the access value is created, then any use of the access value must do a
24448 dynamic check, and this dynamic check will fail and raise a
24449 @code{Program_Error} exception if the body has not been elaborated yet.
24450 GNAT will generate the necessary checks, and in addition, if the
24452 switch is set, will generate warnings that such checks are required.
24454 The use of dynamic dispatching for tagged types similarly generates
24455 a requirement for dynamic checks, and premature calls to any primitive
24456 operation of a tagged type before the body of the operation has been
24457 elaborated, will result in the raising of @code{Program_Error}.
24459 @node Summary of Procedures for Elaboration Control
24460 @section Summary of Procedures for Elaboration Control
24461 @cindex Elaboration control
24464 First, compile your program with the default options, using none of
24465 the special elaboration control switches. If the binder successfully
24466 binds your program, then you can be confident that, apart from issues
24467 raised by the use of access-to-subprogram types and dynamic dispatching,
24468 the program is free of elaboration errors. If it is important that the
24469 program be portable, then use the
24471 switch to generate warnings about missing @code{Elaborate} or
24472 @code{Elaborate_All} pragmas, and supply the missing pragmas.
24474 If the program fails to bind using the default static elaboration
24475 handling, then you can fix the program to eliminate the binder
24476 message, or recompile the entire program with the
24477 @option{-gnatE} switch to generate dynamic elaboration checks,
24478 and, if you are sure there really are no elaboration problems,
24479 use a global pragma @code{Suppress (Elaboration_Check)}.
24481 @node Other Elaboration Order Considerations
24482 @section Other Elaboration Order Considerations
24484 This section has been entirely concerned with the issue of finding a valid
24485 elaboration order, as defined by the Ada Reference Manual. In a case
24486 where several elaboration orders are valid, the task is to find one
24487 of the possible valid elaboration orders (and the static model in GNAT
24488 will ensure that this is achieved).
24490 The purpose of the elaboration rules in the Ada Reference Manual is to
24491 make sure that no entity is accessed before it has been elaborated. For
24492 a subprogram, this means that the spec and body must have been elaborated
24493 before the subprogram is called. For an object, this means that the object
24494 must have been elaborated before its value is read or written. A violation
24495 of either of these two requirements is an access before elaboration order,
24496 and this section has been all about avoiding such errors.
24498 In the case where more than one order of elaboration is possible, in the
24499 sense that access before elaboration errors are avoided, then any one of
24500 the orders is ``correct'' in the sense that it meets the requirements of
24501 the Ada Reference Manual, and no such error occurs.
24503 However, it may be the case for a given program, that there are
24504 constraints on the order of elaboration that come not from consideration
24505 of avoiding elaboration errors, but rather from extra-lingual logic
24506 requirements. Consider this example:
24508 @smallexample @c ada
24509 with Init_Constants;
24510 package Constants is
24515 package Init_Constants is
24516 procedure P; -- require a body
24517 end Init_Constants;
24520 package body Init_Constants is
24521 procedure P is begin null; end;
24525 end Init_Constants;
24529 Z : Integer := Constants.X + Constants.Y;
24533 with Text_IO; use Text_IO;
24536 Put_Line (Calc.Z'Img);
24541 In this example, there is more than one valid order of elaboration. For
24542 example both the following are correct orders:
24545 Init_Constants spec
24548 Init_Constants body
24553 Init_Constants spec
24554 Init_Constants body
24561 There is no language rule to prefer one or the other, both are correct
24562 from an order of elaboration point of view. But the programmatic effects
24563 of the two orders are very different. In the first, the elaboration routine
24564 of @code{Calc} initializes @code{Z} to zero, and then the main program
24565 runs with this value of zero. But in the second order, the elaboration
24566 routine of @code{Calc} runs after the body of Init_Constants has set
24567 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
24570 One could perhaps by applying pretty clever non-artificial intelligence
24571 to the situation guess that it is more likely that the second order of
24572 elaboration is the one desired, but there is no formal linguistic reason
24573 to prefer one over the other. In fact in this particular case, GNAT will
24574 prefer the second order, because of the rule that bodies are elaborated
24575 as soon as possible, but it's just luck that this is what was wanted
24576 (if indeed the second order was preferred).
24578 If the program cares about the order of elaboration routines in a case like
24579 this, it is important to specify the order required. In this particular
24580 case, that could have been achieved by adding to the spec of Calc:
24582 @smallexample @c ada
24583 pragma Elaborate_All (Constants);
24587 which requires that the body (if any) and spec of @code{Constants},
24588 as well as the body and spec of any unit @code{with}'ed by
24589 @code{Constants} be elaborated before @code{Calc} is elaborated.
24591 Clearly no automatic method can always guess which alternative you require,
24592 and if you are working with legacy code that had constraints of this kind
24593 which were not properly specified by adding @code{Elaborate} or
24594 @code{Elaborate_All} pragmas, then indeed it is possible that two different
24595 compilers can choose different orders.
24597 However, GNAT does attempt to diagnose the common situation where there
24598 are uninitialized variables in the visible part of a package spec, and the
24599 corresponding package body has an elaboration block that directly or
24600 indirectly initialized one or more of these variables. This is the situation
24601 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
24602 a warning that suggests this addition if it detects this situation.
24604 The @code{gnatbind}
24605 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
24606 out problems. This switch causes bodies to be elaborated as late as possible
24607 instead of as early as possible. In the example above, it would have forced
24608 the choice of the first elaboration order. If you get different results
24609 when using this switch, and particularly if one set of results is right,
24610 and one is wrong as far as you are concerned, it shows that you have some
24611 missing @code{Elaborate} pragmas. For the example above, we have the
24615 gnatmake -f -q main
24618 gnatmake -f -q main -bargs -p
24624 It is of course quite unlikely that both these results are correct, so
24625 it is up to you in a case like this to investigate the source of the
24626 difference, by looking at the two elaboration orders that are chosen,
24627 and figuring out which is correct, and then adding the necessary
24628 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
24632 @c *******************************
24633 @node Conditional Compilation
24634 @appendix Conditional Compilation
24635 @c *******************************
24636 @cindex Conditional compilation
24639 It is often necessary to arrange for a single source program
24640 to serve multiple purposes, where it is compiled in different
24641 ways to achieve these different goals. Some examples of the
24642 need for this feature are
24645 @item Adapting a program to a different hardware environment
24646 @item Adapting a program to a different target architecture
24647 @item Turning debugging features on and off
24648 @item Arranging for a program to compile with different compilers
24652 In C, or C++, the typical approach would be to use the preprocessor
24653 that is defined as part of the language. The Ada language does not
24654 contain such a feature. This is not an oversight, but rather a very
24655 deliberate design decision, based on the experience that overuse of
24656 the preprocessing features in C and C++ can result in programs that
24657 are extremely difficult to maintain. For example, if we have ten
24658 switches that can be on or off, this means that there are a thousand
24659 separate programs, any one of which might not even be syntactically
24660 correct, and even if syntactically correct, the resulting program
24661 might not work correctly. Testing all combinations can quickly become
24664 Nevertheless, the need to tailor programs certainly exists, and in
24665 this Appendix we will discuss how this can
24666 be achieved using Ada in general, and GNAT in particular.
24669 * Use of Boolean Constants::
24670 * Debugging - A Special Case::
24671 * Conditionalizing Declarations::
24672 * Use of Alternative Implementations::
24676 @node Use of Boolean Constants
24677 @section Use of Boolean Constants
24680 In the case where the difference is simply which code
24681 sequence is executed, the cleanest solution is to use Boolean
24682 constants to control which code is executed.
24684 @smallexample @c ada
24686 FP_Initialize_Required : constant Boolean := True;
24688 if FP_Initialize_Required then
24695 Not only will the code inside the @code{if} statement not be executed if
24696 the constant Boolean is @code{False}, but it will also be completely
24697 deleted from the program.
24698 However, the code is only deleted after the @code{if} statement
24699 has been checked for syntactic and semantic correctness.
24700 (In contrast, with preprocessors the code is deleted before the
24701 compiler ever gets to see it, so it is not checked until the switch
24703 @cindex Preprocessors (contrasted with conditional compilation)
24705 Typically the Boolean constants will be in a separate package,
24708 @smallexample @c ada
24711 FP_Initialize_Required : constant Boolean := True;
24712 Reset_Available : constant Boolean := False;
24719 The @code{Config} package exists in multiple forms for the various targets,
24720 with an appropriate script selecting the version of @code{Config} needed.
24721 Then any other unit requiring conditional compilation can do a @code{with}
24722 of @code{Config} to make the constants visible.
24725 @node Debugging - A Special Case
24726 @section Debugging - A Special Case
24729 A common use of conditional code is to execute statements (for example
24730 dynamic checks, or output of intermediate results) under control of a
24731 debug switch, so that the debugging behavior can be turned on and off.
24732 This can be done using a Boolean constant to control whether the code
24735 @smallexample @c ada
24738 Put_Line ("got to the first stage!");
24746 @smallexample @c ada
24748 if Debugging and then Temperature > 999.0 then
24749 raise Temperature_Crazy;
24755 Since this is a common case, there are special features to deal with
24756 this in a convenient manner. For the case of tests, Ada 2005 has added
24757 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
24758 @cindex pragma @code{Assert}
24759 on the @code{Assert} pragma that has always been available in GNAT, so this
24760 feature may be used with GNAT even if you are not using Ada 2005 features.
24761 The use of pragma @code{Assert} is described in
24762 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
24763 example, the last test could be written:
24765 @smallexample @c ada
24766 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
24772 @smallexample @c ada
24773 pragma Assert (Temperature <= 999.0);
24777 In both cases, if assertions are active and the temperature is excessive,
24778 the exception @code{Assert_Failure} will be raised, with the given string in
24779 the first case or a string indicating the location of the pragma in the second
24780 case used as the exception message.
24782 You can turn assertions on and off by using the @code{Assertion_Policy}
24784 @cindex pragma @code{Assertion_Policy}
24785 This is an Ada 2005 pragma which is implemented in all modes by
24786 GNAT, but only in the latest versions of GNAT which include Ada 2005
24787 capability. Alternatively, you can use the @option{-gnata} switch
24788 @cindex @option{-gnata} switch
24789 to enable assertions from the command line (this is recognized by all versions
24792 For the example above with the @code{Put_Line}, the GNAT-specific pragma
24793 @code{Debug} can be used:
24794 @cindex pragma @code{Debug}
24796 @smallexample @c ada
24797 pragma Debug (Put_Line ("got to the first stage!"));
24801 If debug pragmas are enabled, the argument, which must be of the form of
24802 a procedure call, is executed (in this case, @code{Put_Line} will be called).
24803 Only one call can be present, but of course a special debugging procedure
24804 containing any code you like can be included in the program and then
24805 called in a pragma @code{Debug} argument as needed.
24807 One advantage of pragma @code{Debug} over the @code{if Debugging then}
24808 construct is that pragma @code{Debug} can appear in declarative contexts,
24809 such as at the very beginning of a procedure, before local declarations have
24812 Debug pragmas are enabled using either the @option{-gnata} switch that also
24813 controls assertions, or with a separate Debug_Policy pragma.
24814 @cindex pragma @code{Debug_Policy}
24815 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
24816 in Ada 95 and Ada 83 programs as well), and is analogous to
24817 pragma @code{Assertion_Policy} to control assertions.
24819 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
24820 and thus they can appear in @file{gnat.adc} if you are not using a
24821 project file, or in the file designated to contain configuration pragmas
24823 They then apply to all subsequent compilations. In practice the use of
24824 the @option{-gnata} switch is often the most convenient method of controlling
24825 the status of these pragmas.
24827 Note that a pragma is not a statement, so in contexts where a statement
24828 sequence is required, you can't just write a pragma on its own. You have
24829 to add a @code{null} statement.
24831 @smallexample @c ada
24834 @dots{} -- some statements
24836 pragma Assert (Num_Cases < 10);
24843 @node Conditionalizing Declarations
24844 @section Conditionalizing Declarations
24847 In some cases, it may be necessary to conditionalize declarations to meet
24848 different requirements. For example we might want a bit string whose length
24849 is set to meet some hardware message requirement.
24851 In some cases, it may be possible to do this using declare blocks controlled
24852 by conditional constants:
24854 @smallexample @c ada
24856 if Small_Machine then
24858 X : Bit_String (1 .. 10);
24864 X : Large_Bit_String (1 .. 1000);
24873 Note that in this approach, both declarations are analyzed by the
24874 compiler so this can only be used where both declarations are legal,
24875 even though one of them will not be used.
24877 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word}, or
24878 Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
24879 that are parameterized by these constants. For example
24881 @smallexample @c ada
24884 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
24890 If @code{Bits_Per_Word} is set to 32, this generates either
24892 @smallexample @c ada
24895 Field1 at 0 range 0 .. 32;
24901 for the big endian case, or
24903 @smallexample @c ada
24906 Field1 at 0 range 10 .. 32;
24912 for the little endian case. Since a powerful subset of Ada expression
24913 notation is usable for creating static constants, clever use of this
24914 feature can often solve quite difficult problems in conditionalizing
24915 compilation (note incidentally that in Ada 95, the little endian
24916 constant was introduced as @code{System.Default_Bit_Order}, so you do not
24917 need to define this one yourself).
24920 @node Use of Alternative Implementations
24921 @section Use of Alternative Implementations
24924 In some cases, none of the approaches described above are adequate. This
24925 can occur for example if the set of declarations required is radically
24926 different for two different configurations.
24928 In this situation, the official Ada way of dealing with conditionalizing
24929 such code is to write separate units for the different cases. As long as
24930 this does not result in excessive duplication of code, this can be done
24931 without creating maintenance problems. The approach is to share common
24932 code as far as possible, and then isolate the code and declarations
24933 that are different. Subunits are often a convenient method for breaking
24934 out a piece of a unit that is to be conditionalized, with separate files
24935 for different versions of the subunit for different targets, where the
24936 build script selects the right one to give to the compiler.
24937 @cindex Subunits (and conditional compilation)
24939 As an example, consider a situation where a new feature in Ada 2005
24940 allows something to be done in a really nice way. But your code must be able
24941 to compile with an Ada 95 compiler. Conceptually you want to say:
24943 @smallexample @c ada
24946 @dots{} neat Ada 2005 code
24948 @dots{} not quite as neat Ada 95 code
24954 where @code{Ada_2005} is a Boolean constant.
24956 But this won't work when @code{Ada_2005} is set to @code{False},
24957 since the @code{then} clause will be illegal for an Ada 95 compiler.
24958 (Recall that although such unreachable code would eventually be deleted
24959 by the compiler, it still needs to be legal. If it uses features
24960 introduced in Ada 2005, it will be illegal in Ada 95.)
24962 So instead we write
24964 @smallexample @c ada
24965 procedure Insert is separate;
24969 Then we have two files for the subunit @code{Insert}, with the two sets of
24971 If the package containing this is called @code{File_Queries}, then we might
24975 @item @file{file_queries-insert-2005.adb}
24976 @item @file{file_queries-insert-95.adb}
24980 and the build script renames the appropriate file to
24983 file_queries-insert.adb
24987 and then carries out the compilation.
24989 This can also be done with project files' naming schemes. For example:
24991 @smallexample @c project
24992 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
24996 Note also that with project files it is desirable to use a different extension
24997 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
24998 conflict may arise through another commonly used feature: to declare as part
24999 of the project a set of directories containing all the sources obeying the
25000 default naming scheme.
25002 The use of alternative units is certainly feasible in all situations,
25003 and for example the Ada part of the GNAT run-time is conditionalized
25004 based on the target architecture using this approach. As a specific example,
25005 consider the implementation of the AST feature in VMS. There is one
25013 which is the same for all architectures, and three bodies:
25017 used for all non-VMS operating systems
25018 @item s-asthan-vms-alpha.adb
25019 used for VMS on the Alpha
25020 @item s-asthan-vms-ia64.adb
25021 used for VMS on the ia64
25025 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
25026 this operating system feature is not available, and the two remaining
25027 versions interface with the corresponding versions of VMS to provide
25028 VMS-compatible AST handling. The GNAT build script knows the architecture
25029 and operating system, and automatically selects the right version,
25030 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
25032 Another style for arranging alternative implementations is through Ada's
25033 access-to-subprogram facility.
25034 In case some functionality is to be conditionally included,
25035 you can declare an access-to-procedure variable @code{Ref} that is initialized
25036 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
25038 In some library package, set @code{Ref} to @code{Proc'Access} for some
25039 procedure @code{Proc} that performs the relevant processing.
25040 The initialization only occurs if the library package is included in the
25042 The same idea can also be implemented using tagged types and dispatching
25046 @node Preprocessing
25047 @section Preprocessing
25048 @cindex Preprocessing
25051 Although it is quite possible to conditionalize code without the use of
25052 C-style preprocessing, as described earlier in this section, it is
25053 nevertheless convenient in some cases to use the C approach. Moreover,
25054 older Ada compilers have often provided some preprocessing capability,
25055 so legacy code may depend on this approach, even though it is not
25058 To accommodate such use, GNAT provides a preprocessor (modeled to a large
25059 extent on the various preprocessors that have been used
25060 with legacy code on other compilers, to enable easier transition).
25062 The preprocessor may be used in two separate modes. It can be used quite
25063 separately from the compiler, to generate a separate output source file
25064 that is then fed to the compiler as a separate step. This is the
25065 @code{gnatprep} utility, whose use is fully described in
25066 @ref{Preprocessing Using gnatprep}.
25067 @cindex @code{gnatprep}
25069 The preprocessing language allows such constructs as
25073 #if DEBUG or PRIORITY > 4 then
25074 bunch of declarations
25076 completely different bunch of declarations
25082 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
25083 defined either on the command line or in a separate file.
25085 The other way of running the preprocessor is even closer to the C style and
25086 often more convenient. In this approach the preprocessing is integrated into
25087 the compilation process. The compiler is fed the preprocessor input which
25088 includes @code{#if} lines etc, and then the compiler carries out the
25089 preprocessing internally and processes the resulting output.
25090 For more details on this approach, see @ref{Integrated Preprocessing}.
25093 @c *******************************
25094 @node Inline Assembler
25095 @appendix Inline Assembler
25096 @c *******************************
25099 If you need to write low-level software that interacts directly
25100 with the hardware, Ada provides two ways to incorporate assembly
25101 language code into your program. First, you can import and invoke
25102 external routines written in assembly language, an Ada feature fully
25103 supported by GNAT@. However, for small sections of code it may be simpler
25104 or more efficient to include assembly language statements directly
25105 in your Ada source program, using the facilities of the implementation-defined
25106 package @code{System.Machine_Code}, which incorporates the gcc
25107 Inline Assembler. The Inline Assembler approach offers a number of advantages,
25108 including the following:
25111 @item No need to use non-Ada tools
25112 @item Consistent interface over different targets
25113 @item Automatic usage of the proper calling conventions
25114 @item Access to Ada constants and variables
25115 @item Definition of intrinsic routines
25116 @item Possibility of inlining a subprogram comprising assembler code
25117 @item Code optimizer can take Inline Assembler code into account
25120 This chapter presents a series of examples to show you how to use
25121 the Inline Assembler. Although it focuses on the Intel x86,
25122 the general approach applies also to other processors.
25123 It is assumed that you are familiar with Ada
25124 and with assembly language programming.
25127 * Basic Assembler Syntax::
25128 * A Simple Example of Inline Assembler::
25129 * Output Variables in Inline Assembler::
25130 * Input Variables in Inline Assembler::
25131 * Inlining Inline Assembler Code::
25132 * Other Asm Functionality::
25135 @c ---------------------------------------------------------------------------
25136 @node Basic Assembler Syntax
25137 @section Basic Assembler Syntax
25140 The assembler used by GNAT and gcc is based not on the Intel assembly
25141 language, but rather on a language that descends from the AT&T Unix
25142 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
25143 The following table summarizes the main features of @emph{as} syntax
25144 and points out the differences from the Intel conventions.
25145 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
25146 pre-processor) documentation for further information.
25149 @item Register names
25150 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
25152 Intel: No extra punctuation; for example @code{eax}
25154 @item Immediate operand
25155 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
25157 Intel: No extra punctuation; for example @code{4}
25160 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
25162 Intel: No extra punctuation; for example @code{loc}
25164 @item Memory contents
25165 gcc / @emph{as}: No extra punctuation; for example @code{loc}
25167 Intel: Square brackets; for example @code{[loc]}
25169 @item Register contents
25170 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
25172 Intel: Square brackets; for example @code{[eax]}
25174 @item Hexadecimal numbers
25175 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
25177 Intel: Trailing ``h''; for example @code{A0h}
25180 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
25183 Intel: Implicit, deduced by assembler; for example @code{mov}
25185 @item Instruction repetition
25186 gcc / @emph{as}: Split into two lines; for example
25192 Intel: Keep on one line; for example @code{rep stosl}
25194 @item Order of operands
25195 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
25197 Intel: Destination first; for example @code{mov eax, 4}
25200 @c ---------------------------------------------------------------------------
25201 @node A Simple Example of Inline Assembler
25202 @section A Simple Example of Inline Assembler
25205 The following example will generate a single assembly language statement,
25206 @code{nop}, which does nothing. Despite its lack of run-time effect,
25207 the example will be useful in illustrating the basics of
25208 the Inline Assembler facility.
25210 @smallexample @c ada
25212 with System.Machine_Code; use System.Machine_Code;
25213 procedure Nothing is
25220 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
25221 here it takes one parameter, a @emph{template string} that must be a static
25222 expression and that will form the generated instruction.
25223 @code{Asm} may be regarded as a compile-time procedure that parses
25224 the template string and additional parameters (none here),
25225 from which it generates a sequence of assembly language instructions.
25227 The examples in this chapter will illustrate several of the forms
25228 for invoking @code{Asm}; a complete specification of the syntax
25229 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
25232 Under the standard GNAT conventions, the @code{Nothing} procedure
25233 should be in a file named @file{nothing.adb}.
25234 You can build the executable in the usual way:
25238 However, the interesting aspect of this example is not its run-time behavior
25239 but rather the generated assembly code.
25240 To see this output, invoke the compiler as follows:
25242 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
25244 where the options are:
25248 compile only (no bind or link)
25250 generate assembler listing
25251 @item -fomit-frame-pointer
25252 do not set up separate stack frames
25254 do not add runtime checks
25257 This gives a human-readable assembler version of the code. The resulting
25258 file will have the same name as the Ada source file, but with a @code{.s}
25259 extension. In our example, the file @file{nothing.s} has the following
25264 .file "nothing.adb"
25266 ___gnu_compiled_ada:
25269 .globl __ada_nothing
25281 The assembly code you included is clearly indicated by
25282 the compiler, between the @code{#APP} and @code{#NO_APP}
25283 delimiters. The character before the 'APP' and 'NOAPP'
25284 can differ on different targets. For example, GNU/Linux uses '#APP' while
25285 on NT you will see '/APP'.
25287 If you make a mistake in your assembler code (such as using the
25288 wrong size modifier, or using a wrong operand for the instruction) GNAT
25289 will report this error in a temporary file, which will be deleted when
25290 the compilation is finished. Generating an assembler file will help
25291 in such cases, since you can assemble this file separately using the
25292 @emph{as} assembler that comes with gcc.
25294 Assembling the file using the command
25297 as @file{nothing.s}
25300 will give you error messages whose lines correspond to the assembler
25301 input file, so you can easily find and correct any mistakes you made.
25302 If there are no errors, @emph{as} will generate an object file
25303 @file{nothing.out}.
25305 @c ---------------------------------------------------------------------------
25306 @node Output Variables in Inline Assembler
25307 @section Output Variables in Inline Assembler
25310 The examples in this section, showing how to access the processor flags,
25311 illustrate how to specify the destination operands for assembly language
25314 @smallexample @c ada
25316 with Interfaces; use Interfaces;
25317 with Ada.Text_IO; use Ada.Text_IO;
25318 with System.Machine_Code; use System.Machine_Code;
25319 procedure Get_Flags is
25320 Flags : Unsigned_32;
25323 Asm ("pushfl" & LF & HT & -- push flags on stack
25324 "popl %%eax" & LF & HT & -- load eax with flags
25325 "movl %%eax, %0", -- store flags in variable
25326 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25327 Put_Line ("Flags register:" & Flags'Img);
25332 In order to have a nicely aligned assembly listing, we have separated
25333 multiple assembler statements in the Asm template string with linefeed
25334 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
25335 The resulting section of the assembly output file is:
25342 movl %eax, -40(%ebp)
25347 It would have been legal to write the Asm invocation as:
25350 Asm ("pushfl popl %%eax movl %%eax, %0")
25353 but in the generated assembler file, this would come out as:
25357 pushfl popl %eax movl %eax, -40(%ebp)
25361 which is not so convenient for the human reader.
25363 We use Ada comments
25364 at the end of each line to explain what the assembler instructions
25365 actually do. This is a useful convention.
25367 When writing Inline Assembler instructions, you need to precede each register
25368 and variable name with a percent sign. Since the assembler already requires
25369 a percent sign at the beginning of a register name, you need two consecutive
25370 percent signs for such names in the Asm template string, thus @code{%%eax}.
25371 In the generated assembly code, one of the percent signs will be stripped off.
25373 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
25374 variables: operands you later define using @code{Input} or @code{Output}
25375 parameters to @code{Asm}.
25376 An output variable is illustrated in
25377 the third statement in the Asm template string:
25381 The intent is to store the contents of the eax register in a variable that can
25382 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
25383 necessarily work, since the compiler might optimize by using a register
25384 to hold Flags, and the expansion of the @code{movl} instruction would not be
25385 aware of this optimization. The solution is not to store the result directly
25386 but rather to advise the compiler to choose the correct operand form;
25387 that is the purpose of the @code{%0} output variable.
25389 Information about the output variable is supplied in the @code{Outputs}
25390 parameter to @code{Asm}:
25392 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25395 The output is defined by the @code{Asm_Output} attribute of the target type;
25396 the general format is
25398 Type'Asm_Output (constraint_string, variable_name)
25401 The constraint string directs the compiler how
25402 to store/access the associated variable. In the example
25404 Unsigned_32'Asm_Output ("=m", Flags);
25406 the @code{"m"} (memory) constraint tells the compiler that the variable
25407 @code{Flags} should be stored in a memory variable, thus preventing
25408 the optimizer from keeping it in a register. In contrast,
25410 Unsigned_32'Asm_Output ("=r", Flags);
25412 uses the @code{"r"} (register) constraint, telling the compiler to
25413 store the variable in a register.
25415 If the constraint is preceded by the equal character (@strong{=}), it tells
25416 the compiler that the variable will be used to store data into it.
25418 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
25419 allowing the optimizer to choose whatever it deems best.
25421 There are a fairly large number of constraints, but the ones that are
25422 most useful (for the Intel x86 processor) are the following:
25428 global (i.e.@: can be stored anywhere)
25446 use one of eax, ebx, ecx or edx
25448 use one of eax, ebx, ecx, edx, esi or edi
25451 The full set of constraints is described in the gcc and @emph{as}
25452 documentation; note that it is possible to combine certain constraints
25453 in one constraint string.
25455 You specify the association of an output variable with an assembler operand
25456 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
25458 @smallexample @c ada
25460 Asm ("pushfl" & LF & HT & -- push flags on stack
25461 "popl %%eax" & LF & HT & -- load eax with flags
25462 "movl %%eax, %0", -- store flags in variable
25463 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25467 @code{%0} will be replaced in the expanded code by the appropriate operand,
25469 the compiler decided for the @code{Flags} variable.
25471 In general, you may have any number of output variables:
25474 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
25476 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
25477 of @code{Asm_Output} attributes
25481 @smallexample @c ada
25483 Asm ("movl %%eax, %0" & LF & HT &
25484 "movl %%ebx, %1" & LF & HT &
25486 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
25487 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
25488 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
25492 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
25493 in the Ada program.
25495 As a variation on the @code{Get_Flags} example, we can use the constraints
25496 string to direct the compiler to store the eax register into the @code{Flags}
25497 variable, instead of including the store instruction explicitly in the
25498 @code{Asm} template string:
25500 @smallexample @c ada
25502 with Interfaces; use Interfaces;
25503 with Ada.Text_IO; use Ada.Text_IO;
25504 with System.Machine_Code; use System.Machine_Code;
25505 procedure Get_Flags_2 is
25506 Flags : Unsigned_32;
25509 Asm ("pushfl" & LF & HT & -- push flags on stack
25510 "popl %%eax", -- save flags in eax
25511 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
25512 Put_Line ("Flags register:" & Flags'Img);
25518 The @code{"a"} constraint tells the compiler that the @code{Flags}
25519 variable will come from the eax register. Here is the resulting code:
25527 movl %eax,-40(%ebp)
25532 The compiler generated the store of eax into Flags after
25533 expanding the assembler code.
25535 Actually, there was no need to pop the flags into the eax register;
25536 more simply, we could just pop the flags directly into the program variable:
25538 @smallexample @c ada
25540 with Interfaces; use Interfaces;
25541 with Ada.Text_IO; use Ada.Text_IO;
25542 with System.Machine_Code; use System.Machine_Code;
25543 procedure Get_Flags_3 is
25544 Flags : Unsigned_32;
25547 Asm ("pushfl" & LF & HT & -- push flags on stack
25548 "pop %0", -- save flags in Flags
25549 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25550 Put_Line ("Flags register:" & Flags'Img);
25555 @c ---------------------------------------------------------------------------
25556 @node Input Variables in Inline Assembler
25557 @section Input Variables in Inline Assembler
25560 The example in this section illustrates how to specify the source operands
25561 for assembly language statements.
25562 The program simply increments its input value by 1:
25564 @smallexample @c ada
25566 with Interfaces; use Interfaces;
25567 with Ada.Text_IO; use Ada.Text_IO;
25568 with System.Machine_Code; use System.Machine_Code;
25569 procedure Increment is
25571 function Incr (Value : Unsigned_32) return Unsigned_32 is
25572 Result : Unsigned_32;
25575 Inputs => Unsigned_32'Asm_Input ("a", Value),
25576 Outputs => Unsigned_32'Asm_Output ("=a", Result));
25580 Value : Unsigned_32;
25584 Put_Line ("Value before is" & Value'Img);
25585 Value := Incr (Value);
25586 Put_Line ("Value after is" & Value'Img);
25591 The @code{Outputs} parameter to @code{Asm} specifies
25592 that the result will be in the eax register and that it is to be stored
25593 in the @code{Result} variable.
25595 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
25596 but with an @code{Asm_Input} attribute.
25597 The @code{"="} constraint, indicating an output value, is not present.
25599 You can have multiple input variables, in the same way that you can have more
25600 than one output variable.
25602 The parameter count (%0, %1) etc, now starts at the first input
25603 statement, and continues with the output statements.
25604 When both parameters use the same variable, the
25605 compiler will treat them as the same %n operand, which is the case here.
25607 Just as the @code{Outputs} parameter causes the register to be stored into the
25608 target variable after execution of the assembler statements, so does the
25609 @code{Inputs} parameter cause its variable to be loaded into the register
25610 before execution of the assembler statements.
25612 Thus the effect of the @code{Asm} invocation is:
25614 @item load the 32-bit value of @code{Value} into eax
25615 @item execute the @code{incl %eax} instruction
25616 @item store the contents of eax into the @code{Result} variable
25619 The resulting assembler file (with @option{-O2} optimization) contains:
25622 _increment__incr.1:
25635 @c ---------------------------------------------------------------------------
25636 @node Inlining Inline Assembler Code
25637 @section Inlining Inline Assembler Code
25640 For a short subprogram such as the @code{Incr} function in the previous
25641 section, the overhead of the call and return (creating / deleting the stack
25642 frame) can be significant, compared to the amount of code in the subprogram
25643 body. A solution is to apply Ada's @code{Inline} pragma to the subprogram,
25644 which directs the compiler to expand invocations of the subprogram at the
25645 point(s) of call, instead of setting up a stack frame for out-of-line calls.
25646 Here is the resulting program:
25648 @smallexample @c ada
25650 with Interfaces; use Interfaces;
25651 with Ada.Text_IO; use Ada.Text_IO;
25652 with System.Machine_Code; use System.Machine_Code;
25653 procedure Increment_2 is
25655 function Incr (Value : Unsigned_32) return Unsigned_32 is
25656 Result : Unsigned_32;
25659 Inputs => Unsigned_32'Asm_Input ("a", Value),
25660 Outputs => Unsigned_32'Asm_Output ("=a", Result));
25663 pragma Inline (Increment);
25665 Value : Unsigned_32;
25669 Put_Line ("Value before is" & Value'Img);
25670 Value := Increment (Value);
25671 Put_Line ("Value after is" & Value'Img);
25676 Compile the program with both optimization (@option{-O2}) and inlining
25677 (@option{-gnatn}) enabled.
25679 The @code{Incr} function is still compiled as usual, but at the
25680 point in @code{Increment} where our function used to be called:
25685 call _increment__incr.1
25690 the code for the function body directly appears:
25703 thus saving the overhead of stack frame setup and an out-of-line call.
25705 @c ---------------------------------------------------------------------------
25706 @node Other Asm Functionality
25707 @section Other @code{Asm} Functionality
25710 This section describes two important parameters to the @code{Asm}
25711 procedure: @code{Clobber}, which identifies register usage;
25712 and @code{Volatile}, which inhibits unwanted optimizations.
25715 * The Clobber Parameter::
25716 * The Volatile Parameter::
25719 @c ---------------------------------------------------------------------------
25720 @node The Clobber Parameter
25721 @subsection The @code{Clobber} Parameter
25724 One of the dangers of intermixing assembly language and a compiled language
25725 such as Ada is that the compiler needs to be aware of which registers are
25726 being used by the assembly code. In some cases, such as the earlier examples,
25727 the constraint string is sufficient to indicate register usage (e.g.,
25729 the eax register). But more generally, the compiler needs an explicit
25730 identification of the registers that are used by the Inline Assembly
25733 Using a register that the compiler doesn't know about
25734 could be a side effect of an instruction (like @code{mull}
25735 storing its result in both eax and edx).
25736 It can also arise from explicit register usage in your
25737 assembly code; for example:
25740 Asm ("movl %0, %%ebx" & LF & HT &
25742 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
25743 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
25747 where the compiler (since it does not analyze the @code{Asm} template string)
25748 does not know you are using the ebx register.
25750 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
25751 to identify the registers that will be used by your assembly code:
25755 Asm ("movl %0, %%ebx" & LF & HT &
25757 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
25758 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
25763 The Clobber parameter is a static string expression specifying the
25764 register(s) you are using. Note that register names are @emph{not} prefixed
25765 by a percent sign. Also, if more than one register is used then their names
25766 are separated by commas; e.g., @code{"eax, ebx"}
25768 The @code{Clobber} parameter has several additional uses:
25770 @item Use ``register'' name @code{cc} to indicate that flags might have changed
25771 @item Use ``register'' name @code{memory} if you changed a memory location
25774 @c ---------------------------------------------------------------------------
25775 @node The Volatile Parameter
25776 @subsection The @code{Volatile} Parameter
25777 @cindex Volatile parameter
25780 Compiler optimizations in the presence of Inline Assembler may sometimes have
25781 unwanted effects. For example, when an @code{Asm} invocation with an input
25782 variable is inside a loop, the compiler might move the loading of the input
25783 variable outside the loop, regarding it as a one-time initialization.
25785 If this effect is not desired, you can disable such optimizations by setting
25786 the @code{Volatile} parameter to @code{True}; for example:
25788 @smallexample @c ada
25790 Asm ("movl %0, %%ebx" & LF & HT &
25792 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
25793 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
25799 By default, @code{Volatile} is set to @code{False} unless there is no
25800 @code{Outputs} parameter.
25802 Although setting @code{Volatile} to @code{True} prevents unwanted
25803 optimizations, it will also disable other optimizations that might be
25804 important for efficiency. In general, you should set @code{Volatile}
25805 to @code{True} only if the compiler's optimizations have created
25807 @c END OF INLINE ASSEMBLER CHAPTER
25808 @c ===============================
25810 @c ***********************************
25811 @c * Compatibility and Porting Guide *
25812 @c ***********************************
25813 @node Compatibility and Porting Guide
25814 @appendix Compatibility and Porting Guide
25817 This chapter describes the compatibility issues that may arise between
25818 GNAT and other Ada compilation systems (including those for Ada 83),
25819 and shows how GNAT can expedite porting
25820 applications developed in other Ada environments.
25823 * Compatibility with Ada 83::
25824 * Compatibility between Ada 95 and Ada 2005::
25825 * Implementation-dependent characteristics::
25826 * Compatibility with Other Ada Systems::
25827 * Representation Clauses::
25829 @c Brief section is only in non-VMS version
25830 @c Full chapter is in VMS version
25831 * Compatibility with HP Ada 83::
25834 * Transitioning to 64-Bit GNAT for OpenVMS::
25838 @node Compatibility with Ada 83
25839 @section Compatibility with Ada 83
25840 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
25843 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83. In
25844 particular, the design intention was that the difficulties associated
25845 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
25846 that occur when moving from one Ada 83 system to another.
25848 However, there are a number of points at which there are minor
25849 incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains
25850 full details of these issues,
25851 and should be consulted for a complete treatment.
25853 following subsections treat the most likely issues to be encountered.
25856 * Legal Ada 83 programs that are illegal in Ada 95::
25857 * More deterministic semantics::
25858 * Changed semantics::
25859 * Other language compatibility issues::
25862 @node Legal Ada 83 programs that are illegal in Ada 95
25863 @subsection Legal Ada 83 programs that are illegal in Ada 95
25865 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
25866 Ada 95 and thus also in Ada 2005:
25869 @item Character literals
25870 Some uses of character literals are ambiguous. Since Ada 95 has introduced
25871 @code{Wide_Character} as a new predefined character type, some uses of
25872 character literals that were legal in Ada 83 are illegal in Ada 95.
25874 @smallexample @c ada
25875 for Char in 'A' .. 'Z' loop @dots{} end loop;
25879 The problem is that @code{'A'} and @code{'Z'} could be from either
25880 @code{Character} or @code{Wide_Character}. The simplest correction
25881 is to make the type explicit; e.g.:
25882 @smallexample @c ada
25883 for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
25886 @item New reserved words
25887 The identifiers @code{abstract}, @code{aliased}, @code{protected},
25888 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
25889 Existing Ada 83 code using any of these identifiers must be edited to
25890 use some alternative name.
25892 @item Freezing rules
25893 The rules in Ada 95 are slightly different with regard to the point at
25894 which entities are frozen, and representation pragmas and clauses are
25895 not permitted past the freeze point. This shows up most typically in
25896 the form of an error message complaining that a representation item
25897 appears too late, and the appropriate corrective action is to move
25898 the item nearer to the declaration of the entity to which it refers.
25900 A particular case is that representation pragmas
25903 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
25905 cannot be applied to a subprogram body. If necessary, a separate subprogram
25906 declaration must be introduced to which the pragma can be applied.
25908 @item Optional bodies for library packages
25909 In Ada 83, a package that did not require a package body was nevertheless
25910 allowed to have one. This lead to certain surprises in compiling large
25911 systems (situations in which the body could be unexpectedly ignored by the
25912 binder). In Ada 95, if a package does not require a body then it is not
25913 permitted to have a body. To fix this problem, simply remove a redundant
25914 body if it is empty, or, if it is non-empty, introduce a dummy declaration
25915 into the spec that makes the body required. One approach is to add a private
25916 part to the package declaration (if necessary), and define a parameterless
25917 procedure called @code{Requires_Body}, which must then be given a dummy
25918 procedure body in the package body, which then becomes required.
25919 Another approach (assuming that this does not introduce elaboration
25920 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
25921 since one effect of this pragma is to require the presence of a package body.
25923 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
25924 In Ada 95, the exception @code{Numeric_Error} is a renaming of
25925 @code{Constraint_Error}.
25926 This means that it is illegal to have separate exception handlers for
25927 the two exceptions. The fix is simply to remove the handler for the
25928 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
25929 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
25931 @item Indefinite subtypes in generics
25932 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
25933 as the actual for a generic formal private type, but then the instantiation
25934 would be illegal if there were any instances of declarations of variables
25935 of this type in the generic body. In Ada 95, to avoid this clear violation
25936 of the methodological principle known as the ``contract model'',
25937 the generic declaration explicitly indicates whether
25938 or not such instantiations are permitted. If a generic formal parameter
25939 has explicit unknown discriminants, indicated by using @code{(<>)} after the
25940 type name, then it can be instantiated with indefinite types, but no
25941 stand-alone variables can be declared of this type. Any attempt to declare
25942 such a variable will result in an illegality at the time the generic is
25943 declared. If the @code{(<>)} notation is not used, then it is illegal
25944 to instantiate the generic with an indefinite type.
25945 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
25946 It will show up as a compile time error, and
25947 the fix is usually simply to add the @code{(<>)} to the generic declaration.
25950 @node More deterministic semantics
25951 @subsection More deterministic semantics
25955 Conversions from real types to integer types round away from 0. In Ada 83
25956 the conversion Integer(2.5) could deliver either 2 or 3 as its value. This
25957 implementation freedom was intended to support unbiased rounding in
25958 statistical applications, but in practice it interfered with portability.
25959 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
25960 is required. Numeric code may be affected by this change in semantics.
25961 Note, though, that this issue is no worse than already existed in Ada 83
25962 when porting code from one vendor to another.
25965 The Real-Time Annex introduces a set of policies that define the behavior of
25966 features that were implementation dependent in Ada 83, such as the order in
25967 which open select branches are executed.
25970 @node Changed semantics
25971 @subsection Changed semantics
25974 The worst kind of incompatibility is one where a program that is legal in
25975 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
25976 possible in Ada 83. Fortunately this is extremely rare, but the one
25977 situation that you should be alert to is the change in the predefined type
25978 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
25981 @item Range of type @code{Character}
25982 The range of @code{Standard.Character} is now the full 256 characters
25983 of Latin-1, whereas in most Ada 83 implementations it was restricted
25984 to 128 characters. Although some of the effects of
25985 this change will be manifest in compile-time rejection of legal
25986 Ada 83 programs it is possible for a working Ada 83 program to have
25987 a different effect in Ada 95, one that was not permitted in Ada 83.
25988 As an example, the expression
25989 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
25990 delivers @code{255} as its value.
25991 In general, you should look at the logic of any
25992 character-processing Ada 83 program and see whether it needs to be adapted
25993 to work correctly with Latin-1. Note that the predefined Ada 95 API has a
25994 character handling package that may be relevant if code needs to be adapted
25995 to account for the additional Latin-1 elements.
25996 The desirable fix is to
25997 modify the program to accommodate the full character set, but in some cases
25998 it may be convenient to define a subtype or derived type of Character that
25999 covers only the restricted range.
26003 @node Other language compatibility issues
26004 @subsection Other language compatibility issues
26007 @item @option{-gnat83} switch
26008 All implementations of GNAT provide a switch that causes GNAT to operate
26009 in Ada 83 mode. In this mode, some but not all compatibility problems
26010 of the type described above are handled automatically. For example, the
26011 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
26012 as identifiers as in Ada 83.
26014 in practice, it is usually advisable to make the necessary modifications
26015 to the program to remove the need for using this switch.
26016 See @ref{Compiling Different Versions of Ada}.
26018 @item Support for removed Ada 83 pragmas and attributes
26019 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
26020 generally because they were replaced by other mechanisms. Ada 95 and Ada 2005
26021 compilers are allowed, but not required, to implement these missing
26022 elements. In contrast with some other compilers, GNAT implements all
26023 such pragmas and attributes, eliminating this compatibility concern. These
26024 include @code{pragma Interface} and the floating point type attributes
26025 (@code{Emax}, @code{Mantissa}, etc.), among other items.
26029 @node Compatibility between Ada 95 and Ada 2005
26030 @section Compatibility between Ada 95 and Ada 2005
26031 @cindex Compatibility between Ada 95 and Ada 2005
26034 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
26035 a number of incompatibilities. Several are enumerated below;
26036 for a complete description please see the
26037 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
26038 @cite{Rationale for Ada 2005}.
26041 @item New reserved words.
26042 The words @code{interface}, @code{overriding} and @code{synchronized} are
26043 reserved in Ada 2005.
26044 A pre-Ada 2005 program that uses any of these as an identifier will be
26047 @item New declarations in predefined packages.
26048 A number of packages in the predefined environment contain new declarations:
26049 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
26050 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
26051 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
26052 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
26053 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
26054 If an Ada 95 program does a @code{with} and @code{use} of any of these
26055 packages, the new declarations may cause name clashes.
26057 @item Access parameters.
26058 A nondispatching subprogram with an access parameter cannot be renamed
26059 as a dispatching operation. This was permitted in Ada 95.
26061 @item Access types, discriminants, and constraints.
26062 Rule changes in this area have led to some incompatibilities; for example,
26063 constrained subtypes of some access types are not permitted in Ada 2005.
26065 @item Aggregates for limited types.
26066 The allowance of aggregates for limited types in Ada 2005 raises the
26067 possibility of ambiguities in legal Ada 95 programs, since additional types
26068 now need to be considered in expression resolution.
26070 @item Fixed-point multiplication and division.
26071 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
26072 were legal in Ada 95 and invoked the predefined versions of these operations,
26074 The ambiguity may be resolved either by applying a type conversion to the
26075 expression, or by explicitly invoking the operation from package
26078 @item Return-by-reference types.
26079 The Ada 95 return-by-reference mechanism has been removed. Instead, the user
26080 can declare a function returning a value from an anonymous access type.
26084 @node Implementation-dependent characteristics
26085 @section Implementation-dependent characteristics
26087 Although the Ada language defines the semantics of each construct as
26088 precisely as practical, in some situations (for example for reasons of
26089 efficiency, or where the effect is heavily dependent on the host or target
26090 platform) the implementation is allowed some freedom. In porting Ada 83
26091 code to GNAT, you need to be aware of whether / how the existing code
26092 exercised such implementation dependencies. Such characteristics fall into
26093 several categories, and GNAT offers specific support in assisting the
26094 transition from certain Ada 83 compilers.
26097 * Implementation-defined pragmas::
26098 * Implementation-defined attributes::
26100 * Elaboration order::
26101 * Target-specific aspects::
26104 @node Implementation-defined pragmas
26105 @subsection Implementation-defined pragmas
26108 Ada compilers are allowed to supplement the language-defined pragmas, and
26109 these are a potential source of non-portability. All GNAT-defined pragmas
26110 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
26111 Reference Manual}, and these include several that are specifically
26112 intended to correspond to other vendors' Ada 83 pragmas.
26113 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
26114 For compatibility with HP Ada 83, GNAT supplies the pragmas
26115 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
26116 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
26117 and @code{Volatile}.
26118 Other relevant pragmas include @code{External} and @code{Link_With}.
26119 Some vendor-specific
26120 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
26122 avoiding compiler rejection of units that contain such pragmas; they are not
26123 relevant in a GNAT context and hence are not otherwise implemented.
26125 @node Implementation-defined attributes
26126 @subsection Implementation-defined attributes
26128 Analogous to pragmas, the set of attributes may be extended by an
26129 implementation. All GNAT-defined attributes are described in
26130 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
26131 Manual}, and these include several that are specifically intended
26132 to correspond to other vendors' Ada 83 attributes. For migrating from VADS,
26133 the attribute @code{VADS_Size} may be useful. For compatibility with HP
26134 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
26138 @subsection Libraries
26140 Vendors may supply libraries to supplement the standard Ada API. If Ada 83
26141 code uses vendor-specific libraries then there are several ways to manage
26142 this in Ada 95 or Ada 2005:
26145 If the source code for the libraries (specs and bodies) are
26146 available, then the libraries can be migrated in the same way as the
26149 If the source code for the specs but not the bodies are
26150 available, then you can reimplement the bodies.
26152 Some features introduced by Ada 95 obviate the need for library support. For
26153 example most Ada 83 vendors supplied a package for unsigned integers. The
26154 Ada 95 modular type feature is the preferred way to handle this need, so
26155 instead of migrating or reimplementing the unsigned integer package it may
26156 be preferable to retrofit the application using modular types.
26159 @node Elaboration order
26160 @subsection Elaboration order
26162 The implementation can choose any elaboration order consistent with the unit
26163 dependency relationship. This freedom means that some orders can result in
26164 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
26165 to invoke a subprogram its body has been elaborated, or to instantiate a
26166 generic before the generic body has been elaborated. By default GNAT
26167 attempts to choose a safe order (one that will not encounter access before
26168 elaboration problems) by implicitly inserting @code{Elaborate} or
26169 @code{Elaborate_All} pragmas where
26170 needed. However, this can lead to the creation of elaboration circularities
26171 and a resulting rejection of the program by gnatbind. This issue is
26172 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
26173 In brief, there are several
26174 ways to deal with this situation:
26178 Modify the program to eliminate the circularities, e.g.@: by moving
26179 elaboration-time code into explicitly-invoked procedures
26181 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
26182 @code{Elaborate} pragmas, and then inhibit the generation of implicit
26183 @code{Elaborate_All}
26184 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
26185 (by selectively suppressing elaboration checks via pragma
26186 @code{Suppress(Elaboration_Check)} when it is safe to do so).
26189 @node Target-specific aspects
26190 @subsection Target-specific aspects
26192 Low-level applications need to deal with machine addresses, data
26193 representations, interfacing with assembler code, and similar issues. If
26194 such an Ada 83 application is being ported to different target hardware (for
26195 example where the byte endianness has changed) then you will need to
26196 carefully examine the program logic; the porting effort will heavily depend
26197 on the robustness of the original design. Moreover, Ada 95 (and thus
26198 Ada 2005) are sometimes
26199 incompatible with typical Ada 83 compiler practices regarding implicit
26200 packing, the meaning of the Size attribute, and the size of access values.
26201 GNAT's approach to these issues is described in @ref{Representation Clauses}.
26203 @node Compatibility with Other Ada Systems
26204 @section Compatibility with Other Ada Systems
26207 If programs avoid the use of implementation dependent and
26208 implementation defined features, as documented in the @cite{Ada
26209 Reference Manual}, there should be a high degree of portability between
26210 GNAT and other Ada systems. The following are specific items which
26211 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
26212 compilers, but do not affect porting code to GNAT@.
26213 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
26214 the following issues may or may not arise for Ada 2005 programs
26215 when other compilers appear.)
26218 @item Ada 83 Pragmas and Attributes
26219 Ada 95 compilers are allowed, but not required, to implement the missing
26220 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
26221 GNAT implements all such pragmas and attributes, eliminating this as
26222 a compatibility concern, but some other Ada 95 compilers reject these
26223 pragmas and attributes.
26225 @item Specialized Needs Annexes
26226 GNAT implements the full set of special needs annexes. At the
26227 current time, it is the only Ada 95 compiler to do so. This means that
26228 programs making use of these features may not be portable to other Ada
26229 95 compilation systems.
26231 @item Representation Clauses
26232 Some other Ada 95 compilers implement only the minimal set of
26233 representation clauses required by the Ada 95 reference manual. GNAT goes
26234 far beyond this minimal set, as described in the next section.
26237 @node Representation Clauses
26238 @section Representation Clauses
26241 The Ada 83 reference manual was quite vague in describing both the minimal
26242 required implementation of representation clauses, and also their precise
26243 effects. Ada 95 (and thus also Ada 2005) are much more explicit, but the
26244 minimal set of capabilities required is still quite limited.
26246 GNAT implements the full required set of capabilities in
26247 Ada 95 and Ada 2005, but also goes much further, and in particular
26248 an effort has been made to be compatible with existing Ada 83 usage to the
26249 greatest extent possible.
26251 A few cases exist in which Ada 83 compiler behavior is incompatible with
26252 the requirements in Ada 95 (and thus also Ada 2005). These are instances of
26253 intentional or accidental dependence on specific implementation dependent
26254 characteristics of these Ada 83 compilers. The following is a list of
26255 the cases most likely to arise in existing Ada 83 code.
26258 @item Implicit Packing
26259 Some Ada 83 compilers allowed a Size specification to cause implicit
26260 packing of an array or record. This could cause expensive implicit
26261 conversions for change of representation in the presence of derived
26262 types, and the Ada design intends to avoid this possibility.
26263 Subsequent AI's were issued to make it clear that such implicit
26264 change of representation in response to a Size clause is inadvisable,
26265 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
26266 Reference Manuals as implementation advice that is followed by GNAT@.
26267 The problem will show up as an error
26268 message rejecting the size clause. The fix is simply to provide
26269 the explicit pragma @code{Pack}, or for more fine tuned control, provide
26270 a Component_Size clause.
26272 @item Meaning of Size Attribute
26273 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
26274 the minimal number of bits required to hold values of the type. For example,
26275 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
26276 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and
26277 some 32 in this situation. This problem will usually show up as a compile
26278 time error, but not always. It is a good idea to check all uses of the
26279 'Size attribute when porting Ada 83 code. The GNAT specific attribute
26280 Object_Size can provide a useful way of duplicating the behavior of
26281 some Ada 83 compiler systems.
26283 @item Size of Access Types
26284 A common assumption in Ada 83 code is that an access type is in fact a pointer,
26285 and that therefore it will be the same size as a System.Address value. This
26286 assumption is true for GNAT in most cases with one exception. For the case of
26287 a pointer to an unconstrained array type (where the bounds may vary from one
26288 value of the access type to another), the default is to use a ``fat pointer'',
26289 which is represented as two separate pointers, one to the bounds, and one to
26290 the array. This representation has a number of advantages, including improved
26291 efficiency. However, it may cause some difficulties in porting existing Ada 83
26292 code which makes the assumption that, for example, pointers fit in 32 bits on
26293 a machine with 32-bit addressing.
26295 To get around this problem, GNAT also permits the use of ``thin pointers'' for
26296 access types in this case (where the designated type is an unconstrained array
26297 type). These thin pointers are indeed the same size as a System.Address value.
26298 To specify a thin pointer, use a size clause for the type, for example:
26300 @smallexample @c ada
26301 type X is access all String;
26302 for X'Size use Standard'Address_Size;
26306 which will cause the type X to be represented using a single pointer.
26307 When using this representation, the bounds are right behind the array.
26308 This representation is slightly less efficient, and does not allow quite
26309 such flexibility in the use of foreign pointers or in using the
26310 Unrestricted_Access attribute to create pointers to non-aliased objects.
26311 But for any standard portable use of the access type it will work in
26312 a functionally correct manner and allow porting of existing code.
26313 Note that another way of forcing a thin pointer representation
26314 is to use a component size clause for the element size in an array,
26315 or a record representation clause for an access field in a record.
26319 @c This brief section is only in the non-VMS version
26320 @c The complete chapter on HP Ada is in the VMS version
26321 @node Compatibility with HP Ada 83
26322 @section Compatibility with HP Ada 83
26325 The VMS version of GNAT fully implements all the pragmas and attributes
26326 provided by HP Ada 83, as well as providing the standard HP Ada 83
26327 libraries, including Starlet. In addition, data layouts and parameter
26328 passing conventions are highly compatible. This means that porting
26329 existing HP Ada 83 code to GNAT in VMS systems should be easier than
26330 most other porting efforts. The following are some of the most
26331 significant differences between GNAT and HP Ada 83.
26334 @item Default floating-point representation
26335 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
26336 it is VMS format. GNAT does implement the necessary pragmas
26337 (Long_Float, Float_Representation) for changing this default.
26340 The package System in GNAT exactly corresponds to the definition in the
26341 Ada 95 reference manual, which means that it excludes many of the
26342 HP Ada 83 extensions. However, a separate package Aux_DEC is provided
26343 that contains the additional definitions, and a special pragma,
26344 Extend_System allows this package to be treated transparently as an
26345 extension of package System.
26348 The definitions provided by Aux_DEC are exactly compatible with those
26349 in the HP Ada 83 version of System, with one exception.
26350 HP Ada provides the following declarations:
26352 @smallexample @c ada
26353 TO_ADDRESS (INTEGER)
26354 TO_ADDRESS (UNSIGNED_LONGWORD)
26355 TO_ADDRESS (@i{universal_integer})
26359 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
26360 an extension to Ada 83 not strictly compatible with the reference manual.
26361 In GNAT, we are constrained to be exactly compatible with the standard,
26362 and this means we cannot provide this capability. In HP Ada 83, the
26363 point of this definition is to deal with a call like:
26365 @smallexample @c ada
26366 TO_ADDRESS (16#12777#);
26370 Normally, according to the Ada 83 standard, one would expect this to be
26371 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
26372 of TO_ADDRESS@. However, in HP Ada 83, there is no ambiguity, since the
26373 definition using @i{universal_integer} takes precedence.
26375 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
26376 is not possible to be 100% compatible. Since there are many programs using
26377 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
26378 to change the name of the function in the UNSIGNED_LONGWORD case, so the
26379 declarations provided in the GNAT version of AUX_Dec are:
26381 @smallexample @c ada
26382 function To_Address (X : Integer) return Address;
26383 pragma Pure_Function (To_Address);
26385 function To_Address_Long (X : Unsigned_Longword)
26387 pragma Pure_Function (To_Address_Long);
26391 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
26392 change the name to TO_ADDRESS_LONG@.
26394 @item Task_Id values
26395 The Task_Id values assigned will be different in the two systems, and GNAT
26396 does not provide a specified value for the Task_Id of the environment task,
26397 which in GNAT is treated like any other declared task.
26401 For full details on these and other less significant compatibility issues,
26402 see appendix E of the HP publication entitled @cite{HP Ada, Technical
26403 Overview and Comparison on HP Platforms}.
26405 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
26406 attributes are recognized, although only a subset of them can sensibly
26407 be implemented. The description of pragmas in @ref{Implementation
26408 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
26409 indicates whether or not they are applicable to non-VMS systems.
26413 @node Transitioning to 64-Bit GNAT for OpenVMS
26414 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
26417 This section is meant to assist users of pre-2006 @value{EDITION}
26418 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
26419 the version of the GNAT technology supplied in 2006 and later for
26420 OpenVMS on both Alpha and I64.
26423 * Introduction to transitioning::
26424 * Migration of 32 bit code::
26425 * Taking advantage of 64 bit addressing::
26426 * Technical details::
26429 @node Introduction to transitioning
26430 @subsection Introduction
26433 64-bit @value{EDITION} for Open VMS has been designed to meet
26438 Providing a full conforming implementation of Ada 95 and Ada 2005
26441 Allowing maximum backward compatibility, thus easing migration of existing
26445 Supplying a path for exploiting the full 64-bit address range
26449 Ada's strong typing semantics has made it
26450 impractical to have different 32-bit and 64-bit modes. As soon as
26451 one object could possibly be outside the 32-bit address space, this
26452 would make it necessary for the @code{System.Address} type to be 64 bits.
26453 In particular, this would cause inconsistencies if 32-bit code is
26454 called from 64-bit code that raises an exception.
26456 This issue has been resolved by always using 64-bit addressing
26457 at the system level, but allowing for automatic conversions between
26458 32-bit and 64-bit addresses where required. Thus users who
26459 do not currently require 64-bit addressing capabilities, can
26460 recompile their code with only minimal changes (and indeed
26461 if the code is written in portable Ada, with no assumptions about
26462 the size of the @code{Address} type, then no changes at all are necessary).
26464 this approach provides a simple, gradual upgrade path to future
26465 use of larger memories than available for 32-bit systems.
26466 Also, newly written applications or libraries will by default
26467 be fully compatible with future systems exploiting 64-bit
26468 addressing capabilities.
26470 @ref{Migration of 32 bit code}, will focus on porting applications
26471 that do not require more than 2 GB of
26472 addressable memory. This code will be referred to as
26473 @emph{32-bit code}.
26474 For applications intending to exploit the full 64-bit address space,
26475 @ref{Taking advantage of 64 bit addressing},
26476 will consider further changes that may be required.
26477 Such code will be referred to below as @emph{64-bit code}.
26479 @node Migration of 32 bit code
26480 @subsection Migration of 32-bit code
26485 * Unchecked conversions::
26486 * Predefined constants::
26487 * Interfacing with C::
26488 * Experience with source compatibility::
26491 @node Address types
26492 @subsubsection Address types
26495 To solve the problem of mixing 64-bit and 32-bit addressing,
26496 while maintaining maximum backward compatibility, the following
26497 approach has been taken:
26501 @code{System.Address} always has a size of 64 bits
26504 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
26508 Since @code{System.Short_Address} is a subtype of @code{System.Address},
26509 a @code{Short_Address}
26510 may be used where an @code{Address} is required, and vice versa, without
26511 needing explicit type conversions.
26512 By virtue of the Open VMS parameter passing conventions,
26514 and exported subprograms that have 32-bit address parameters are
26515 compatible with those that have 64-bit address parameters.
26516 (See @ref{Making code 64 bit clean} for details.)
26518 The areas that may need attention are those where record types have
26519 been defined that contain components of the type @code{System.Address}, and
26520 where objects of this type are passed to code expecting a record layout with
26523 Different compilers on different platforms cannot be
26524 expected to represent the same type in the same way,
26525 since alignment constraints
26526 and other system-dependent properties affect the compiler's decision.
26527 For that reason, Ada code
26528 generally uses representation clauses to specify the expected
26529 layout where required.
26531 If such a representation clause uses 32 bits for a component having
26532 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
26533 will detect that error and produce a specific diagnostic message.
26534 The developer should then determine whether the representation
26535 should be 64 bits or not and make either of two changes:
26536 change the size to 64 bits and leave the type as @code{System.Address}, or
26537 leave the size as 32 bits and change the type to @code{System.Short_Address}.
26538 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
26539 required in any code setting or accessing the field; the compiler will
26540 automatically perform any needed conversions between address
26544 @subsubsection Access types
26547 By default, objects designated by access values are always
26548 allocated in the 32-bit
26549 address space. Thus legacy code will never contain
26550 any objects that are not addressable with 32-bit addresses, and
26551 the compiler will never raise exceptions as result of mixing
26552 32-bit and 64-bit addresses.
26554 However, the access values themselves are represented in 64 bits, for optimum
26555 performance and future compatibility with 64-bit code. As was
26556 the case with @code{System.Address}, the compiler will give an error message
26557 if an object or record component has a representation clause that
26558 requires the access value to fit in 32 bits. In such a situation,
26559 an explicit size clause for the access type, specifying 32 bits,
26560 will have the desired effect.
26562 General access types (declared with @code{access all}) can never be
26563 32 bits, as values of such types must be able to refer to any object
26564 of the designated type,
26565 including objects residing outside the 32-bit address range.
26566 Existing Ada 83 code will not contain such type definitions,
26567 however, since general access types were introduced in Ada 95.
26569 @node Unchecked conversions
26570 @subsubsection Unchecked conversions
26573 In the case of an @code{Unchecked_Conversion} where the source type is a
26574 64-bit access type or the type @code{System.Address}, and the target
26575 type is a 32-bit type, the compiler will generate a warning.
26576 Even though the generated code will still perform the required
26577 conversions, it is highly recommended in these cases to use
26578 respectively a 32-bit access type or @code{System.Short_Address}
26579 as the source type.
26581 @node Predefined constants
26582 @subsubsection Predefined constants
26585 The following table shows the correspondence between pre-2006 versions of
26586 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
26589 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
26590 @item @b{Constant} @tab @b{Old} @tab @b{New}
26591 @item @code{System.Word_Size} @tab 32 @tab 64
26592 @item @code{System.Memory_Size} @tab 2**32 @tab 2**64
26593 @item @code{System.Short_Memory_Size} @tab 2**32 @tab 2**32
26594 @item @code{System.Address_Size} @tab 32 @tab 64
26598 If you need to refer to the specific
26599 memory size of a 32-bit implementation, instead of the
26600 actual memory size, use @code{System.Short_Memory_Size}
26601 rather than @code{System.Memory_Size}.
26602 Similarly, references to @code{System.Address_Size} may need
26603 to be replaced by @code{System.Short_Address'Size}.
26604 The program @command{gnatfind} may be useful for locating
26605 references to the above constants, so that you can verify that they
26608 @node Interfacing with C
26609 @subsubsection Interfacing with C
26612 In order to minimize the impact of the transition to 64-bit addresses on
26613 legacy programs, some fundamental types in the @code{Interfaces.C}
26614 package hierarchy continue to be represented in 32 bits.
26615 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
26616 This eases integration with the default HP C layout choices, for example
26617 as found in the system routines in @code{DECC$SHR.EXE}.
26618 Because of this implementation choice, the type fully compatible with
26619 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
26620 Depending on the context the compiler will issue a
26621 warning or an error when type @code{Address} is used, alerting the user to a
26622 potential problem. Otherwise 32-bit programs that use
26623 @code{Interfaces.C} should normally not require code modifications
26625 The other issue arising with C interfacing concerns pragma @code{Convention}.
26626 For VMS 64-bit systems, there is an issue of the appropriate default size
26627 of C convention pointers in the absence of an explicit size clause. The HP
26628 C compiler can choose either 32 or 64 bits depending on compiler options.
26629 GNAT chooses 32-bits rather than 64-bits in the default case where no size
26630 clause is given. This proves a better choice for porting 32-bit legacy
26631 applications. In order to have a 64-bit representation, it is necessary to
26632 specify a size representation clause. For example:
26634 @smallexample @c ada
26635 type int_star is access Interfaces.C.int;
26636 pragma Convention(C, int_star);
26637 for int_star'Size use 64; -- Necessary to get 64 and not 32 bits
26640 @node Experience with source compatibility
26641 @subsubsection Experience with source compatibility
26644 The Security Server and STARLET on I64 provide an interesting ``test case''
26645 for source compatibility issues, since it is in such system code
26646 where assumptions about @code{Address} size might be expected to occur.
26647 Indeed, there were a small number of occasions in the Security Server
26648 file @file{jibdef.ads}
26649 where a representation clause for a record type specified
26650 32 bits for a component of type @code{Address}.
26651 All of these errors were detected by the compiler.
26652 The repair was obvious and immediate; to simply replace @code{Address} by
26653 @code{Short_Address}.
26655 In the case of STARLET, there were several record types that should
26656 have had representation clauses but did not. In these record types
26657 there was an implicit assumption that an @code{Address} value occupied
26659 These compiled without error, but their usage resulted in run-time error
26660 returns from STARLET system calls.
26661 Future GNAT technology enhancements may include a tool that detects and flags
26662 these sorts of potential source code porting problems.
26664 @c ****************************************
26665 @node Taking advantage of 64 bit addressing
26666 @subsection Taking advantage of 64-bit addressing
26669 * Making code 64 bit clean::
26670 * Allocating memory from the 64 bit storage pool::
26671 * Restrictions on use of 64 bit objects::
26672 * Using 64 bit storage pools by default::
26673 * General access types::
26674 * STARLET and other predefined libraries::
26677 @node Making code 64 bit clean
26678 @subsubsection Making code 64-bit clean
26681 In order to prevent problems that may occur when (parts of) a
26682 system start using memory outside the 32-bit address range,
26683 we recommend some additional guidelines:
26687 For imported subprograms that take parameters of the
26688 type @code{System.Address}, ensure that these subprograms can
26689 indeed handle 64-bit addresses. If not, or when in doubt,
26690 change the subprogram declaration to specify
26691 @code{System.Short_Address} instead.
26694 Resolve all warnings related to size mismatches in
26695 unchecked conversions. Failing to do so causes
26696 erroneous execution if the source object is outside
26697 the 32-bit address space.
26700 (optional) Explicitly use the 32-bit storage pool
26701 for access types used in a 32-bit context, or use
26702 generic access types where possible
26703 (@pxref{Restrictions on use of 64 bit objects}).
26707 If these rules are followed, the compiler will automatically insert
26708 any necessary checks to ensure that no addresses or access values
26709 passed to 32-bit code ever refer to objects outside the 32-bit
26711 Any attempt to do this will raise @code{Constraint_Error}.
26713 @node Allocating memory from the 64 bit storage pool
26714 @subsubsection Allocating memory from the 64-bit storage pool
26717 For any access type @code{T} that potentially requires memory allocations
26718 beyond the 32-bit address space,
26719 use the following representation clause:
26721 @smallexample @c ada
26722 for T'Storage_Pool use System.Pool_64;
26725 @node Restrictions on use of 64 bit objects
26726 @subsubsection Restrictions on use of 64-bit objects
26729 Taking the address of an object allocated from a 64-bit storage pool,
26730 and then passing this address to a subprogram expecting
26731 @code{System.Short_Address},
26732 or assigning it to a variable of type @code{Short_Address}, will cause
26733 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
26734 (@pxref{Making code 64 bit clean}), or checks are suppressed,
26735 no exception is raised and execution
26736 will become erroneous.
26738 @node Using 64 bit storage pools by default
26739 @subsubsection Using 64-bit storage pools by default
26742 In some cases it may be desirable to have the compiler allocate
26743 from 64-bit storage pools by default. This may be the case for
26744 libraries that are 64-bit clean, but may be used in both 32-bit
26745 and 64-bit contexts. For these cases the following configuration
26746 pragma may be specified:
26748 @smallexample @c ada
26749 pragma Pool_64_Default;
26753 Any code compiled in the context of this pragma will by default
26754 use the @code{System.Pool_64} storage pool. This default may be overridden
26755 for a specific access type @code{T} by the representation clause:
26757 @smallexample @c ada
26758 for T'Storage_Pool use System.Pool_32;
26762 Any object whose address may be passed to a subprogram with a
26763 @code{Short_Address} argument, or assigned to a variable of type
26764 @code{Short_Address}, needs to be allocated from this pool.
26766 @node General access types
26767 @subsubsection General access types
26770 Objects designated by access values from a
26771 general access type (declared with @code{access all}) are never allocated
26772 from a 64-bit storage pool. Code that uses general access types will
26773 accept objects allocated in either 32-bit or 64-bit address spaces,
26774 but never allocate objects outside the 32-bit address space.
26775 Using general access types ensures maximum compatibility with both
26776 32-bit and 64-bit code.
26778 @node STARLET and other predefined libraries
26779 @subsubsection STARLET and other predefined libraries
26782 All code that comes as part of GNAT is 64-bit clean, but the
26783 restrictions given in @ref{Restrictions on use of 64 bit objects},
26784 still apply. Look at the package
26785 specs to see in which contexts objects allocated
26786 in 64-bit address space are acceptable.
26788 @node Technical details
26789 @subsection Technical details
26792 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
26793 Ada standard with respect to the type of @code{System.Address}. Previous
26794 versions of GNAT Pro have defined this type as private and implemented it as a
26797 In order to allow defining @code{System.Short_Address} as a proper subtype,
26798 and to match the implicit sign extension in parameter passing,
26799 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
26800 visible (i.e., non-private) integer type.
26801 Standard operations on the type, such as the binary operators ``+'', ``-'',
26802 etc., that take @code{Address} operands and return an @code{Address} result,
26803 have been hidden by declaring these
26804 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
26805 ambiguities that would otherwise result from overloading.
26806 (Note that, although @code{Address} is a visible integer type,
26807 good programming practice dictates against exploiting the type's
26808 integer properties such as literals, since this will compromise
26811 Defining @code{Address} as a visible integer type helps achieve
26812 maximum compatibility for existing Ada code,
26813 without sacrificing the capabilities of the 64-bit architecture.
26816 @c ************************************************
26818 @node Microsoft Windows Topics
26819 @appendix Microsoft Windows Topics
26825 This chapter describes topics that are specific to the Microsoft Windows
26826 platforms (NT, 2000, and XP Professional).
26829 * Using GNAT on Windows::
26830 * Using a network installation of GNAT::
26831 * CONSOLE and WINDOWS subsystems::
26832 * Temporary Files::
26833 * Mixed-Language Programming on Windows::
26834 * Windows Calling Conventions::
26835 * Introduction to Dynamic Link Libraries (DLLs)::
26836 * Using DLLs with GNAT::
26837 * Building DLLs with GNAT Project files::
26838 * Building DLLs with GNAT::
26839 * Building DLLs with gnatdll::
26840 * GNAT and Windows Resources::
26841 * Debugging a DLL::
26842 * Setting Stack Size from gnatlink::
26843 * Setting Heap Size from gnatlink::
26846 @node Using GNAT on Windows
26847 @section Using GNAT on Windows
26850 One of the strengths of the GNAT technology is that its tool set
26851 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
26852 @code{gdb} debugger, etc.) is used in the same way regardless of the
26855 On Windows this tool set is complemented by a number of Microsoft-specific
26856 tools that have been provided to facilitate interoperability with Windows
26857 when this is required. With these tools:
26862 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
26866 You can use any Dynamically Linked Library (DLL) in your Ada code (both
26867 relocatable and non-relocatable DLLs are supported).
26870 You can build Ada DLLs for use in other applications. These applications
26871 can be written in a language other than Ada (e.g., C, C++, etc). Again both
26872 relocatable and non-relocatable Ada DLLs are supported.
26875 You can include Windows resources in your Ada application.
26878 You can use or create COM/DCOM objects.
26882 Immediately below are listed all known general GNAT-for-Windows restrictions.
26883 Other restrictions about specific features like Windows Resources and DLLs
26884 are listed in separate sections below.
26889 It is not possible to use @code{GetLastError} and @code{SetLastError}
26890 when tasking, protected records, or exceptions are used. In these
26891 cases, in order to implement Ada semantics, the GNAT run-time system
26892 calls certain Win32 routines that set the last error variable to 0 upon
26893 success. It should be possible to use @code{GetLastError} and
26894 @code{SetLastError} when tasking, protected record, and exception
26895 features are not used, but it is not guaranteed to work.
26898 It is not possible to link against Microsoft libraries except for
26899 import libraries. Interfacing must be done by the mean of DLLs.
26902 When the compilation environment is located on FAT32 drives, users may
26903 experience recompilations of the source files that have not changed if
26904 Daylight Saving Time (DST) state has changed since the last time files
26905 were compiled. NTFS drives do not have this problem.
26908 No components of the GNAT toolset use any entries in the Windows
26909 registry. The only entries that can be created are file associations and
26910 PATH settings, provided the user has chosen to create them at installation
26911 time, as well as some minimal book-keeping information needed to correctly
26912 uninstall or integrate different GNAT products.
26915 @node Using a network installation of GNAT
26916 @section Using a network installation of GNAT
26919 Make sure the system on which GNAT is installed is accessible from the
26920 current machine, i.e., the install location is shared over the network.
26921 Shared resources are accessed on Windows by means of UNC paths, which
26922 have the format @code{\\server\sharename\path}
26924 In order to use such a network installation, simply add the UNC path of the
26925 @file{bin} directory of your GNAT installation in front of your PATH. For
26926 example, if GNAT is installed in @file{\GNAT} directory of a share location
26927 called @file{c-drive} on a machine @file{LOKI}, the following command will
26930 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
26932 Be aware that every compilation using the network installation results in the
26933 transfer of large amounts of data across the network and will likely cause
26934 serious performance penalty.
26936 @node CONSOLE and WINDOWS subsystems
26937 @section CONSOLE and WINDOWS subsystems
26938 @cindex CONSOLE Subsystem
26939 @cindex WINDOWS Subsystem
26943 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
26944 (which is the default subsystem) will always create a console when
26945 launching the application. This is not something desirable when the
26946 application has a Windows GUI. To get rid of this console the
26947 application must be using the @code{WINDOWS} subsystem. To do so
26948 the @option{-mwindows} linker option must be specified.
26951 $ gnatmake winprog -largs -mwindows
26954 @node Temporary Files
26955 @section Temporary Files
26956 @cindex Temporary files
26959 It is possible to control where temporary files gets created by setting
26960 the @env{TMP} environment variable. The file will be created:
26963 @item Under the directory pointed to by the @env{TMP} environment variable if
26964 this directory exists.
26966 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
26967 set (or not pointing to a directory) and if this directory exists.
26969 @item Under the current working directory otherwise.
26973 This allows you to determine exactly where the temporary
26974 file will be created. This is particularly useful in networked
26975 environments where you may not have write access to some
26978 @node Mixed-Language Programming on Windows
26979 @section Mixed-Language Programming on Windows
26982 Developing pure Ada applications on Windows is no different than on
26983 other GNAT-supported platforms. However, when developing or porting an
26984 application that contains a mix of Ada and C/C++, the choice of your
26985 Windows C/C++ development environment conditions your overall
26986 interoperability strategy.
26988 If you use @command{gcc} to compile the non-Ada part of your application,
26989 there are no Windows-specific restrictions that affect the overall
26990 interoperability with your Ada code. If you do want to use the
26991 Microsoft tools for your non-Ada code, you have two choices:
26995 Encapsulate your non-Ada code in a DLL to be linked with your Ada
26996 application. In this case, use the Microsoft or whatever environment to
26997 build the DLL and use GNAT to build your executable
26998 (@pxref{Using DLLs with GNAT}).
27001 Or you can encapsulate your Ada code in a DLL to be linked with the
27002 other part of your application. In this case, use GNAT to build the DLL
27003 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
27004 or whatever environment to build your executable.
27007 @node Windows Calling Conventions
27008 @section Windows Calling Conventions
27012 This section pertain only to Win32. On Win64 there is a single native
27013 calling convention. All convention specifiers are ignored on this
27017 * C Calling Convention::
27018 * Stdcall Calling Convention::
27019 * Win32 Calling Convention::
27020 * DLL Calling Convention::
27024 When a subprogram @code{F} (caller) calls a subprogram @code{G}
27025 (callee), there are several ways to push @code{G}'s parameters on the
27026 stack and there are several possible scenarios to clean up the stack
27027 upon @code{G}'s return. A calling convention is an agreed upon software
27028 protocol whereby the responsibilities between the caller (@code{F}) and
27029 the callee (@code{G}) are clearly defined. Several calling conventions
27030 are available for Windows:
27034 @code{C} (Microsoft defined)
27037 @code{Stdcall} (Microsoft defined)
27040 @code{Win32} (GNAT specific)
27043 @code{DLL} (GNAT specific)
27046 @node C Calling Convention
27047 @subsection @code{C} Calling Convention
27050 This is the default calling convention used when interfacing to C/C++
27051 routines compiled with either @command{gcc} or Microsoft Visual C++.
27053 In the @code{C} calling convention subprogram parameters are pushed on the
27054 stack by the caller from right to left. The caller itself is in charge of
27055 cleaning up the stack after the call. In addition, the name of a routine
27056 with @code{C} calling convention is mangled by adding a leading underscore.
27058 The name to use on the Ada side when importing (or exporting) a routine
27059 with @code{C} calling convention is the name of the routine. For
27060 instance the C function:
27063 int get_val (long);
27067 should be imported from Ada as follows:
27069 @smallexample @c ada
27071 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27072 pragma Import (C, Get_Val, External_Name => "get_val");
27077 Note that in this particular case the @code{External_Name} parameter could
27078 have been omitted since, when missing, this parameter is taken to be the
27079 name of the Ada entity in lower case. When the @code{Link_Name} parameter
27080 is missing, as in the above example, this parameter is set to be the
27081 @code{External_Name} with a leading underscore.
27083 When importing a variable defined in C, you should always use the @code{C}
27084 calling convention unless the object containing the variable is part of a
27085 DLL (in which case you should use the @code{Stdcall} calling
27086 convention, @pxref{Stdcall Calling Convention}).
27088 @node Stdcall Calling Convention
27089 @subsection @code{Stdcall} Calling Convention
27092 This convention, which was the calling convention used for Pascal
27093 programs, is used by Microsoft for all the routines in the Win32 API for
27094 efficiency reasons. It must be used to import any routine for which this
27095 convention was specified.
27097 In the @code{Stdcall} calling convention subprogram parameters are pushed
27098 on the stack by the caller from right to left. The callee (and not the
27099 caller) is in charge of cleaning the stack on routine exit. In addition,
27100 the name of a routine with @code{Stdcall} calling convention is mangled by
27101 adding a leading underscore (as for the @code{C} calling convention) and a
27102 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
27103 bytes) of the parameters passed to the routine.
27105 The name to use on the Ada side when importing a C routine with a
27106 @code{Stdcall} calling convention is the name of the C routine. The leading
27107 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
27108 the compiler. For instance the Win32 function:
27111 @b{APIENTRY} int get_val (long);
27115 should be imported from Ada as follows:
27117 @smallexample @c ada
27119 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27120 pragma Import (Stdcall, Get_Val);
27121 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
27126 As for the @code{C} calling convention, when the @code{External_Name}
27127 parameter is missing, it is taken to be the name of the Ada entity in lower
27128 case. If instead of writing the above import pragma you write:
27130 @smallexample @c ada
27132 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27133 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
27138 then the imported routine is @code{_retrieve_val@@4}. However, if instead
27139 of specifying the @code{External_Name} parameter you specify the
27140 @code{Link_Name} as in the following example:
27142 @smallexample @c ada
27144 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27145 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
27150 then the imported routine is @code{retrieve_val}, that is, there is no
27151 decoration at all. No leading underscore and no Stdcall suffix
27152 @code{@@}@code{@var{nn}}.
27155 This is especially important as in some special cases a DLL's entry
27156 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
27157 name generated for a call has it.
27160 It is also possible to import variables defined in a DLL by using an
27161 import pragma for a variable. As an example, if a DLL contains a
27162 variable defined as:
27169 then, to access this variable from Ada you should write:
27171 @smallexample @c ada
27173 My_Var : Interfaces.C.int;
27174 pragma Import (Stdcall, My_Var);
27179 Note that to ease building cross-platform bindings this convention
27180 will be handled as a @code{C} calling convention on non-Windows platforms.
27182 @node Win32 Calling Convention
27183 @subsection @code{Win32} Calling Convention
27186 This convention, which is GNAT-specific is fully equivalent to the
27187 @code{Stdcall} calling convention described above.
27189 @node DLL Calling Convention
27190 @subsection @code{DLL} Calling Convention
27193 This convention, which is GNAT-specific is fully equivalent to the
27194 @code{Stdcall} calling convention described above.
27196 @node Introduction to Dynamic Link Libraries (DLLs)
27197 @section Introduction to Dynamic Link Libraries (DLLs)
27201 A Dynamically Linked Library (DLL) is a library that can be shared by
27202 several applications running under Windows. A DLL can contain any number of
27203 routines and variables.
27205 One advantage of DLLs is that you can change and enhance them without
27206 forcing all the applications that depend on them to be relinked or
27207 recompiled. However, you should be aware than all calls to DLL routines are
27208 slower since, as you will understand below, such calls are indirect.
27210 To illustrate the remainder of this section, suppose that an application
27211 wants to use the services of a DLL @file{API.dll}. To use the services
27212 provided by @file{API.dll} you must statically link against the DLL or
27213 an import library which contains a jump table with an entry for each
27214 routine and variable exported by the DLL. In the Microsoft world this
27215 import library is called @file{API.lib}. When using GNAT this import
27216 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
27217 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
27219 After you have linked your application with the DLL or the import library
27220 and you run your application, here is what happens:
27224 Your application is loaded into memory.
27227 The DLL @file{API.dll} is mapped into the address space of your
27228 application. This means that:
27232 The DLL will use the stack of the calling thread.
27235 The DLL will use the virtual address space of the calling process.
27238 The DLL will allocate memory from the virtual address space of the calling
27242 Handles (pointers) can be safely exchanged between routines in the DLL
27243 routines and routines in the application using the DLL.
27247 The entries in the jump table (from the import library @file{libAPI.dll.a}
27248 or @file{API.lib} or automatically created when linking against a DLL)
27249 which is part of your application are initialized with the addresses
27250 of the routines and variables in @file{API.dll}.
27253 If present in @file{API.dll}, routines @code{DllMain} or
27254 @code{DllMainCRTStartup} are invoked. These routines typically contain
27255 the initialization code needed for the well-being of the routines and
27256 variables exported by the DLL.
27260 There is an additional point which is worth mentioning. In the Windows
27261 world there are two kind of DLLs: relocatable and non-relocatable
27262 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
27263 in the target application address space. If the addresses of two
27264 non-relocatable DLLs overlap and these happen to be used by the same
27265 application, a conflict will occur and the application will run
27266 incorrectly. Hence, when possible, it is always preferable to use and
27267 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
27268 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
27269 User's Guide) removes the debugging symbols from the DLL but the DLL can
27270 still be relocated.
27272 As a side note, an interesting difference between Microsoft DLLs and
27273 Unix shared libraries, is the fact that on most Unix systems all public
27274 routines are exported by default in a Unix shared library, while under
27275 Windows it is possible (but not required) to list exported routines in
27276 a definition file (@pxref{The Definition File}).
27278 @node Using DLLs with GNAT
27279 @section Using DLLs with GNAT
27282 * Creating an Ada Spec for the DLL Services::
27283 * Creating an Import Library::
27287 To use the services of a DLL, say @file{API.dll}, in your Ada application
27292 The Ada spec for the routines and/or variables you want to access in
27293 @file{API.dll}. If not available this Ada spec must be built from the C/C++
27294 header files provided with the DLL.
27297 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
27298 mentioned an import library is a statically linked library containing the
27299 import table which will be filled at load time to point to the actual
27300 @file{API.dll} routines. Sometimes you don't have an import library for the
27301 DLL you want to use. The following sections will explain how to build
27302 one. Note that this is optional.
27305 The actual DLL, @file{API.dll}.
27309 Once you have all the above, to compile an Ada application that uses the
27310 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
27311 you simply issue the command
27314 $ gnatmake my_ada_app -largs -lAPI
27318 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
27319 tells the GNAT linker to look for an import library. The linker will
27320 look for a library name in this specific order:
27323 @item @file{libAPI.dll.a}
27324 @item @file{API.dll.a}
27325 @item @file{libAPI.a}
27326 @item @file{API.lib}
27327 @item @file{libAPI.dll}
27328 @item @file{API.dll}
27331 The first three are the GNU style import libraries. The third is the
27332 Microsoft style import libraries. The last two are the DLL themself.
27334 Note that if the Ada package spec for @file{API.dll} contains the
27337 @smallexample @c ada
27338 pragma Linker_Options ("-lAPI");
27342 you do not have to add @option{-largs -lAPI} at the end of the
27343 @command{gnatmake} command.
27345 If any one of the items above is missing you will have to create it
27346 yourself. The following sections explain how to do so using as an
27347 example a fictitious DLL called @file{API.dll}.
27349 @node Creating an Ada Spec for the DLL Services
27350 @subsection Creating an Ada Spec for the DLL Services
27353 A DLL typically comes with a C/C++ header file which provides the
27354 definitions of the routines and variables exported by the DLL. The Ada
27355 equivalent of this header file is a package spec that contains definitions
27356 for the imported entities. If the DLL you intend to use does not come with
27357 an Ada spec you have to generate one such spec yourself. For example if
27358 the header file of @file{API.dll} is a file @file{api.h} containing the
27359 following two definitions:
27371 then the equivalent Ada spec could be:
27373 @smallexample @c ada
27376 with Interfaces.C.Strings;
27381 function Get (Str : C.Strings.Chars_Ptr) return C.int;
27384 pragma Import (C, Get);
27385 pragma Import (DLL, Some_Var);
27392 Note that a variable is
27393 @strong{always imported with a DLL convention}. A function
27394 can have @code{C} or @code{Stdcall} convention.
27395 (@pxref{Windows Calling Conventions}).
27397 @node Creating an Import Library
27398 @subsection Creating an Import Library
27399 @cindex Import library
27402 * The Definition File::
27403 * GNAT-Style Import Library::
27404 * Microsoft-Style Import Library::
27408 If a Microsoft-style import library @file{API.lib} or a GNAT-style
27409 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
27410 with @file{API.dll} you can skip this section. You can also skip this
27411 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
27412 as in this case it is possible to link directly against the
27413 DLL. Otherwise read on.
27415 @node The Definition File
27416 @subsubsection The Definition File
27417 @cindex Definition file
27421 As previously mentioned, and unlike Unix systems, the list of symbols
27422 that are exported from a DLL must be provided explicitly in Windows.
27423 The main goal of a definition file is precisely that: list the symbols
27424 exported by a DLL. A definition file (usually a file with a @code{.def}
27425 suffix) has the following structure:
27430 @r{[}LIBRARY @var{name}@r{]}
27431 @r{[}DESCRIPTION @var{string}@r{]}
27441 @item LIBRARY @var{name}
27442 This section, which is optional, gives the name of the DLL.
27444 @item DESCRIPTION @var{string}
27445 This section, which is optional, gives a description string that will be
27446 embedded in the import library.
27449 This section gives the list of exported symbols (procedures, functions or
27450 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
27451 section of @file{API.def} looks like:
27465 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
27466 (@pxref{Windows Calling Conventions}) for a Stdcall
27467 calling convention function in the exported symbols list.
27470 There can actually be other sections in a definition file, but these
27471 sections are not relevant to the discussion at hand.
27473 @node GNAT-Style Import Library
27474 @subsubsection GNAT-Style Import Library
27477 To create a static import library from @file{API.dll} with the GNAT tools
27478 you should proceed as follows:
27482 Create the definition file @file{API.def} (@pxref{The Definition File}).
27483 For that use the @code{dll2def} tool as follows:
27486 $ dll2def API.dll > API.def
27490 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
27491 to standard output the list of entry points in the DLL. Note that if
27492 some routines in the DLL have the @code{Stdcall} convention
27493 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
27494 suffix then you'll have to edit @file{api.def} to add it, and specify
27495 @option{-k} to @command{gnatdll} when creating the import library.
27498 Here are some hints to find the right @code{@@}@var{nn} suffix.
27502 If you have the Microsoft import library (.lib), it is possible to get
27503 the right symbols by using Microsoft @code{dumpbin} tool (see the
27504 corresponding Microsoft documentation for further details).
27507 $ dumpbin /exports api.lib
27511 If you have a message about a missing symbol at link time the compiler
27512 tells you what symbol is expected. You just have to go back to the
27513 definition file and add the right suffix.
27517 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
27518 (@pxref{Using gnatdll}) as follows:
27521 $ gnatdll -e API.def -d API.dll
27525 @code{gnatdll} takes as input a definition file @file{API.def} and the
27526 name of the DLL containing the services listed in the definition file
27527 @file{API.dll}. The name of the static import library generated is
27528 computed from the name of the definition file as follows: if the
27529 definition file name is @var{xyz}@code{.def}, the import library name will
27530 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
27531 @option{-e} could have been removed because the name of the definition
27532 file (before the ``@code{.def}'' suffix) is the same as the name of the
27533 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
27536 @node Microsoft-Style Import Library
27537 @subsubsection Microsoft-Style Import Library
27540 With GNAT you can either use a GNAT-style or Microsoft-style import
27541 library. A Microsoft import library is needed only if you plan to make an
27542 Ada DLL available to applications developed with Microsoft
27543 tools (@pxref{Mixed-Language Programming on Windows}).
27545 To create a Microsoft-style import library for @file{API.dll} you
27546 should proceed as follows:
27550 Create the definition file @file{API.def} from the DLL. For this use either
27551 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
27552 tool (see the corresponding Microsoft documentation for further details).
27555 Build the actual import library using Microsoft's @code{lib} utility:
27558 $ lib -machine:IX86 -def:API.def -out:API.lib
27562 If you use the above command the definition file @file{API.def} must
27563 contain a line giving the name of the DLL:
27570 See the Microsoft documentation for further details about the usage of
27574 @node Building DLLs with GNAT Project files
27575 @section Building DLLs with GNAT Project files
27576 @cindex DLLs, building
27579 There is nothing specific to Windows in the build process.
27580 @pxref{Library Projects}.
27583 Due to a system limitation, it is not possible under Windows to create threads
27584 when inside the @code{DllMain} routine which is used for auto-initialization
27585 of shared libraries, so it is not possible to have library level tasks in SALs.
27587 @node Building DLLs with GNAT
27588 @section Building DLLs with GNAT
27589 @cindex DLLs, building
27592 This section explain how to build DLLs using the GNAT built-in DLL
27593 support. With the following procedure it is straight forward to build
27594 and use DLLs with GNAT.
27598 @item building object files
27600 The first step is to build all objects files that are to be included
27601 into the DLL. This is done by using the standard @command{gnatmake} tool.
27603 @item building the DLL
27605 To build the DLL you must use @command{gcc}'s @option{-shared}
27606 option. It is quite simple to use this method:
27609 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
27612 It is important to note that in this case all symbols found in the
27613 object files are automatically exported. It is possible to restrict
27614 the set of symbols to export by passing to @command{gcc} a definition
27615 file, @pxref{The Definition File}. For example:
27618 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
27621 If you use a definition file you must export the elaboration procedures
27622 for every package that required one. Elaboration procedures are named
27623 using the package name followed by "_E".
27625 @item preparing DLL to be used
27627 For the DLL to be used by client programs the bodies must be hidden
27628 from it and the .ali set with read-only attribute. This is very important
27629 otherwise GNAT will recompile all packages and will not actually use
27630 the code in the DLL. For example:
27634 $ copy *.ads *.ali api.dll apilib
27635 $ attrib +R apilib\*.ali
27640 At this point it is possible to use the DLL by directly linking
27641 against it. Note that you must use the GNAT shared runtime when using
27642 GNAT shared libraries. This is achieved by using @option{-shared} binder's
27646 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
27649 @node Building DLLs with gnatdll
27650 @section Building DLLs with gnatdll
27651 @cindex DLLs, building
27654 * Limitations When Using Ada DLLs from Ada::
27655 * Exporting Ada Entities::
27656 * Ada DLLs and Elaboration::
27657 * Ada DLLs and Finalization::
27658 * Creating a Spec for Ada DLLs::
27659 * Creating the Definition File::
27664 Note that it is preferred to use GNAT Project files
27665 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
27666 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
27668 This section explains how to build DLLs containing Ada code using
27669 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
27670 remainder of this section.
27672 The steps required to build an Ada DLL that is to be used by Ada as well as
27673 non-Ada applications are as follows:
27677 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
27678 @code{Stdcall} calling convention to avoid any Ada name mangling for the
27679 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
27680 skip this step if you plan to use the Ada DLL only from Ada applications.
27683 Your Ada code must export an initialization routine which calls the routine
27684 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
27685 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
27686 routine exported by the Ada DLL must be invoked by the clients of the DLL
27687 to initialize the DLL.
27690 When useful, the DLL should also export a finalization routine which calls
27691 routine @code{adafinal} generated by @command{gnatbind} to perform the
27692 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
27693 The finalization routine exported by the Ada DLL must be invoked by the
27694 clients of the DLL when the DLL services are no further needed.
27697 You must provide a spec for the services exported by the Ada DLL in each
27698 of the programming languages to which you plan to make the DLL available.
27701 You must provide a definition file listing the exported entities
27702 (@pxref{The Definition File}).
27705 Finally you must use @code{gnatdll} to produce the DLL and the import
27706 library (@pxref{Using gnatdll}).
27710 Note that a relocatable DLL stripped using the @code{strip}
27711 binutils tool will not be relocatable anymore. To build a DLL without
27712 debug information pass @code{-largs -s} to @code{gnatdll}. This
27713 restriction does not apply to a DLL built using a Library Project.
27714 @pxref{Library Projects}.
27716 @node Limitations When Using Ada DLLs from Ada
27717 @subsection Limitations When Using Ada DLLs from Ada
27720 When using Ada DLLs from Ada applications there is a limitation users
27721 should be aware of. Because on Windows the GNAT run time is not in a DLL of
27722 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
27723 each Ada DLL includes the services of the GNAT run time that are necessary
27724 to the Ada code inside the DLL. As a result, when an Ada program uses an
27725 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
27726 one in the main program.
27728 It is therefore not possible to exchange GNAT run-time objects between the
27729 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
27730 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
27733 It is completely safe to exchange plain elementary, array or record types,
27734 Windows object handles, etc.
27736 @node Exporting Ada Entities
27737 @subsection Exporting Ada Entities
27738 @cindex Export table
27741 Building a DLL is a way to encapsulate a set of services usable from any
27742 application. As a result, the Ada entities exported by a DLL should be
27743 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
27744 any Ada name mangling. As an example here is an Ada package
27745 @code{API}, spec and body, exporting two procedures, a function, and a
27748 @smallexample @c ada
27751 with Interfaces.C; use Interfaces;
27753 Count : C.int := 0;
27754 function Factorial (Val : C.int) return C.int;
27756 procedure Initialize_API;
27757 procedure Finalize_API;
27758 -- Initialization & Finalization routines. More in the next section.
27760 pragma Export (C, Initialize_API);
27761 pragma Export (C, Finalize_API);
27762 pragma Export (C, Count);
27763 pragma Export (C, Factorial);
27769 @smallexample @c ada
27772 package body API is
27773 function Factorial (Val : C.int) return C.int is
27776 Count := Count + 1;
27777 for K in 1 .. Val loop
27783 procedure Initialize_API is
27785 pragma Import (C, Adainit);
27788 end Initialize_API;
27790 procedure Finalize_API is
27791 procedure Adafinal;
27792 pragma Import (C, Adafinal);
27802 If the Ada DLL you are building will only be used by Ada applications
27803 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
27804 convention. As an example, the previous package could be written as
27807 @smallexample @c ada
27811 Count : Integer := 0;
27812 function Factorial (Val : Integer) return Integer;
27814 procedure Initialize_API;
27815 procedure Finalize_API;
27816 -- Initialization and Finalization routines.
27822 @smallexample @c ada
27825 package body API is
27826 function Factorial (Val : Integer) return Integer is
27827 Fact : Integer := 1;
27829 Count := Count + 1;
27830 for K in 1 .. Val loop
27837 -- The remainder of this package body is unchanged.
27844 Note that if you do not export the Ada entities with a @code{C} or
27845 @code{Stdcall} convention you will have to provide the mangled Ada names
27846 in the definition file of the Ada DLL
27847 (@pxref{Creating the Definition File}).
27849 @node Ada DLLs and Elaboration
27850 @subsection Ada DLLs and Elaboration
27851 @cindex DLLs and elaboration
27854 The DLL that you are building contains your Ada code as well as all the
27855 routines in the Ada library that are needed by it. The first thing a
27856 user of your DLL must do is elaborate the Ada code
27857 (@pxref{Elaboration Order Handling in GNAT}).
27859 To achieve this you must export an initialization routine
27860 (@code{Initialize_API} in the previous example), which must be invoked
27861 before using any of the DLL services. This elaboration routine must call
27862 the Ada elaboration routine @code{adainit} generated by the GNAT binder
27863 (@pxref{Binding with Non-Ada Main Programs}). See the body of
27864 @code{Initialize_Api} for an example. Note that the GNAT binder is
27865 automatically invoked during the DLL build process by the @code{gnatdll}
27866 tool (@pxref{Using gnatdll}).
27868 When a DLL is loaded, Windows systematically invokes a routine called
27869 @code{DllMain}. It would therefore be possible to call @code{adainit}
27870 directly from @code{DllMain} without having to provide an explicit
27871 initialization routine. Unfortunately, it is not possible to call
27872 @code{adainit} from the @code{DllMain} if your program has library level
27873 tasks because access to the @code{DllMain} entry point is serialized by
27874 the system (that is, only a single thread can execute ``through'' it at a
27875 time), which means that the GNAT run time will deadlock waiting for the
27876 newly created task to complete its initialization.
27878 @node Ada DLLs and Finalization
27879 @subsection Ada DLLs and Finalization
27880 @cindex DLLs and finalization
27883 When the services of an Ada DLL are no longer needed, the client code should
27884 invoke the DLL finalization routine, if available. The DLL finalization
27885 routine is in charge of releasing all resources acquired by the DLL. In the
27886 case of the Ada code contained in the DLL, this is achieved by calling
27887 routine @code{adafinal} generated by the GNAT binder
27888 (@pxref{Binding with Non-Ada Main Programs}).
27889 See the body of @code{Finalize_Api} for an
27890 example. As already pointed out the GNAT binder is automatically invoked
27891 during the DLL build process by the @code{gnatdll} tool
27892 (@pxref{Using gnatdll}).
27894 @node Creating a Spec for Ada DLLs
27895 @subsection Creating a Spec for Ada DLLs
27898 To use the services exported by the Ada DLL from another programming
27899 language (e.g.@: C), you have to translate the specs of the exported Ada
27900 entities in that language. For instance in the case of @code{API.dll},
27901 the corresponding C header file could look like:
27906 extern int *_imp__count;
27907 #define count (*_imp__count)
27908 int factorial (int);
27914 It is important to understand that when building an Ada DLL to be used by
27915 other Ada applications, you need two different specs for the packages
27916 contained in the DLL: one for building the DLL and the other for using
27917 the DLL. This is because the @code{DLL} calling convention is needed to
27918 use a variable defined in a DLL, but when building the DLL, the variable
27919 must have either the @code{Ada} or @code{C} calling convention. As an
27920 example consider a DLL comprising the following package @code{API}:
27922 @smallexample @c ada
27926 Count : Integer := 0;
27928 -- Remainder of the package omitted.
27935 After producing a DLL containing package @code{API}, the spec that
27936 must be used to import @code{API.Count} from Ada code outside of the
27939 @smallexample @c ada
27944 pragma Import (DLL, Count);
27950 @node Creating the Definition File
27951 @subsection Creating the Definition File
27954 The definition file is the last file needed to build the DLL. It lists
27955 the exported symbols. As an example, the definition file for a DLL
27956 containing only package @code{API} (where all the entities are exported
27957 with a @code{C} calling convention) is:
27972 If the @code{C} calling convention is missing from package @code{API},
27973 then the definition file contains the mangled Ada names of the above
27974 entities, which in this case are:
27983 api__initialize_api
27988 @node Using gnatdll
27989 @subsection Using @code{gnatdll}
27993 * gnatdll Example::
27994 * gnatdll behind the Scenes::
27999 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
28000 and non-Ada sources that make up your DLL have been compiled.
28001 @code{gnatdll} is actually in charge of two distinct tasks: build the
28002 static import library for the DLL and the actual DLL. The form of the
28003 @code{gnatdll} command is
28007 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28008 @c Expanding @ovar macro inline (explanation in macro def comments)
28009 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28014 where @var{list-of-files} is a list of ALI and object files. The object
28015 file list must be the exact list of objects corresponding to the non-Ada
28016 sources whose services are to be included in the DLL. The ALI file list
28017 must be the exact list of ALI files for the corresponding Ada sources
28018 whose services are to be included in the DLL. If @var{list-of-files} is
28019 missing, only the static import library is generated.
28022 You may specify any of the following switches to @code{gnatdll}:
28025 @c @item -a@ovar{address}
28026 @c Expanding @ovar macro inline (explanation in macro def comments)
28027 @item -a@r{[}@var{address}@r{]}
28028 @cindex @option{-a} (@code{gnatdll})
28029 Build a non-relocatable DLL at @var{address}. If @var{address} is not
28030 specified the default address @var{0x11000000} will be used. By default,
28031 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
28032 advise the reader to build relocatable DLL.
28034 @item -b @var{address}
28035 @cindex @option{-b} (@code{gnatdll})
28036 Set the relocatable DLL base address. By default the address is
28039 @item -bargs @var{opts}
28040 @cindex @option{-bargs} (@code{gnatdll})
28041 Binder options. Pass @var{opts} to the binder.
28043 @item -d @var{dllfile}
28044 @cindex @option{-d} (@code{gnatdll})
28045 @var{dllfile} is the name of the DLL. This switch must be present for
28046 @code{gnatdll} to do anything. The name of the generated import library is
28047 obtained algorithmically from @var{dllfile} as shown in the following
28048 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
28049 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
28050 by option @option{-e}) is obtained algorithmically from @var{dllfile}
28051 as shown in the following example:
28052 if @var{dllfile} is @code{xyz.dll}, the definition
28053 file used is @code{xyz.def}.
28055 @item -e @var{deffile}
28056 @cindex @option{-e} (@code{gnatdll})
28057 @var{deffile} is the name of the definition file.
28060 @cindex @option{-g} (@code{gnatdll})
28061 Generate debugging information. This information is stored in the object
28062 file and copied from there to the final DLL file by the linker,
28063 where it can be read by the debugger. You must use the
28064 @option{-g} switch if you plan on using the debugger or the symbolic
28068 @cindex @option{-h} (@code{gnatdll})
28069 Help mode. Displays @code{gnatdll} switch usage information.
28072 @cindex @option{-I} (@code{gnatdll})
28073 Direct @code{gnatdll} to search the @var{dir} directory for source and
28074 object files needed to build the DLL.
28075 (@pxref{Search Paths and the Run-Time Library (RTL)}).
28078 @cindex @option{-k} (@code{gnatdll})
28079 Removes the @code{@@}@var{nn} suffix from the import library's exported
28080 names, but keeps them for the link names. You must specify this
28081 option if you want to use a @code{Stdcall} function in a DLL for which
28082 the @code{@@}@var{nn} suffix has been removed. This is the case for most
28083 of the Windows NT DLL for example. This option has no effect when
28084 @option{-n} option is specified.
28086 @item -l @var{file}
28087 @cindex @option{-l} (@code{gnatdll})
28088 The list of ALI and object files used to build the DLL are listed in
28089 @var{file}, instead of being given in the command line. Each line in
28090 @var{file} contains the name of an ALI or object file.
28093 @cindex @option{-n} (@code{gnatdll})
28094 No Import. Do not create the import library.
28097 @cindex @option{-q} (@code{gnatdll})
28098 Quiet mode. Do not display unnecessary messages.
28101 @cindex @option{-v} (@code{gnatdll})
28102 Verbose mode. Display extra information.
28104 @item -largs @var{opts}
28105 @cindex @option{-largs} (@code{gnatdll})
28106 Linker options. Pass @var{opts} to the linker.
28109 @node gnatdll Example
28110 @subsubsection @code{gnatdll} Example
28113 As an example the command to build a relocatable DLL from @file{api.adb}
28114 once @file{api.adb} has been compiled and @file{api.def} created is
28117 $ gnatdll -d api.dll api.ali
28121 The above command creates two files: @file{libapi.dll.a} (the import
28122 library) and @file{api.dll} (the actual DLL). If you want to create
28123 only the DLL, just type:
28126 $ gnatdll -d api.dll -n api.ali
28130 Alternatively if you want to create just the import library, type:
28133 $ gnatdll -d api.dll
28136 @node gnatdll behind the Scenes
28137 @subsubsection @code{gnatdll} behind the Scenes
28140 This section details the steps involved in creating a DLL. @code{gnatdll}
28141 does these steps for you. Unless you are interested in understanding what
28142 goes on behind the scenes, you should skip this section.
28144 We use the previous example of a DLL containing the Ada package @code{API},
28145 to illustrate the steps necessary to build a DLL. The starting point is a
28146 set of objects that will make up the DLL and the corresponding ALI
28147 files. In the case of this example this means that @file{api.o} and
28148 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
28153 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
28154 the information necessary to generate relocation information for the
28160 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
28165 In addition to the base file, the @command{gnatlink} command generates an
28166 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
28167 asks @command{gnatlink} to generate the routines @code{DllMain} and
28168 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
28169 is loaded into memory.
28172 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
28173 export table (@file{api.exp}). The export table contains the relocation
28174 information in a form which can be used during the final link to ensure
28175 that the Windows loader is able to place the DLL anywhere in memory.
28179 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28180 --output-exp api.exp
28185 @code{gnatdll} builds the base file using the new export table. Note that
28186 @command{gnatbind} must be called once again since the binder generated file
28187 has been deleted during the previous call to @command{gnatlink}.
28192 $ gnatlink api -o api.jnk api.exp -mdll
28193 -Wl,--base-file,api.base
28198 @code{gnatdll} builds the new export table using the new base file and
28199 generates the DLL import library @file{libAPI.dll.a}.
28203 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28204 --output-exp api.exp --output-lib libAPI.a
28209 Finally @code{gnatdll} builds the relocatable DLL using the final export
28215 $ gnatlink api api.exp -o api.dll -mdll
28220 @node Using dlltool
28221 @subsubsection Using @code{dlltool}
28224 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
28225 DLLs and static import libraries. This section summarizes the most
28226 common @code{dlltool} switches. The form of the @code{dlltool} command
28230 @c $ dlltool @ovar{switches}
28231 @c Expanding @ovar macro inline (explanation in macro def comments)
28232 $ dlltool @r{[}@var{switches}@r{]}
28236 @code{dlltool} switches include:
28239 @item --base-file @var{basefile}
28240 @cindex @option{--base-file} (@command{dlltool})
28241 Read the base file @var{basefile} generated by the linker. This switch
28242 is used to create a relocatable DLL.
28244 @item --def @var{deffile}
28245 @cindex @option{--def} (@command{dlltool})
28246 Read the definition file.
28248 @item --dllname @var{name}
28249 @cindex @option{--dllname} (@command{dlltool})
28250 Gives the name of the DLL. This switch is used to embed the name of the
28251 DLL in the static import library generated by @code{dlltool} with switch
28252 @option{--output-lib}.
28255 @cindex @option{-k} (@command{dlltool})
28256 Kill @code{@@}@var{nn} from exported names
28257 (@pxref{Windows Calling Conventions}
28258 for a discussion about @code{Stdcall}-style symbols.
28261 @cindex @option{--help} (@command{dlltool})
28262 Prints the @code{dlltool} switches with a concise description.
28264 @item --output-exp @var{exportfile}
28265 @cindex @option{--output-exp} (@command{dlltool})
28266 Generate an export file @var{exportfile}. The export file contains the
28267 export table (list of symbols in the DLL) and is used to create the DLL.
28269 @item --output-lib @var{libfile}
28270 @cindex @option{--output-lib} (@command{dlltool})
28271 Generate a static import library @var{libfile}.
28274 @cindex @option{-v} (@command{dlltool})
28277 @item --as @var{assembler-name}
28278 @cindex @option{--as} (@command{dlltool})
28279 Use @var{assembler-name} as the assembler. The default is @code{as}.
28282 @node GNAT and Windows Resources
28283 @section GNAT and Windows Resources
28284 @cindex Resources, windows
28287 * Building Resources::
28288 * Compiling Resources::
28289 * Using Resources::
28293 Resources are an easy way to add Windows specific objects to your
28294 application. The objects that can be added as resources include:
28323 This section explains how to build, compile and use resources.
28325 @node Building Resources
28326 @subsection Building Resources
28327 @cindex Resources, building
28330 A resource file is an ASCII file. By convention resource files have an
28331 @file{.rc} extension.
28332 The easiest way to build a resource file is to use Microsoft tools
28333 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
28334 @code{dlgedit.exe} to build dialogs.
28335 It is always possible to build an @file{.rc} file yourself by writing a
28338 It is not our objective to explain how to write a resource file. A
28339 complete description of the resource script language can be found in the
28340 Microsoft documentation.
28342 @node Compiling Resources
28343 @subsection Compiling Resources
28346 @cindex Resources, compiling
28349 This section describes how to build a GNAT-compatible (COFF) object file
28350 containing the resources. This is done using the Resource Compiler
28351 @code{windres} as follows:
28354 $ windres -i myres.rc -o myres.o
28358 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
28359 file. You can specify an alternate preprocessor (usually named
28360 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
28361 parameter. A list of all possible options may be obtained by entering
28362 the command @code{windres} @option{--help}.
28364 It is also possible to use the Microsoft resource compiler @code{rc.exe}
28365 to produce a @file{.res} file (binary resource file). See the
28366 corresponding Microsoft documentation for further details. In this case
28367 you need to use @code{windres} to translate the @file{.res} file to a
28368 GNAT-compatible object file as follows:
28371 $ windres -i myres.res -o myres.o
28374 @node Using Resources
28375 @subsection Using Resources
28376 @cindex Resources, using
28379 To include the resource file in your program just add the
28380 GNAT-compatible object file for the resource(s) to the linker
28381 arguments. With @command{gnatmake} this is done by using the @option{-largs}
28385 $ gnatmake myprog -largs myres.o
28388 @node Debugging a DLL
28389 @section Debugging a DLL
28390 @cindex DLL debugging
28393 * Program and DLL Both Built with GCC/GNAT::
28394 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
28398 Debugging a DLL is similar to debugging a standard program. But
28399 we have to deal with two different executable parts: the DLL and the
28400 program that uses it. We have the following four possibilities:
28404 The program and the DLL are built with @code{GCC/GNAT}.
28406 The program is built with foreign tools and the DLL is built with
28409 The program is built with @code{GCC/GNAT} and the DLL is built with
28414 In this section we address only cases one and two above.
28415 There is no point in trying to debug
28416 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
28417 information in it. To do so you must use a debugger compatible with the
28418 tools suite used to build the DLL.
28420 @node Program and DLL Both Built with GCC/GNAT
28421 @subsection Program and DLL Both Built with GCC/GNAT
28424 This is the simplest case. Both the DLL and the program have @code{GDB}
28425 compatible debugging information. It is then possible to break anywhere in
28426 the process. Let's suppose here that the main procedure is named
28427 @code{ada_main} and that in the DLL there is an entry point named
28431 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
28432 program must have been built with the debugging information (see GNAT -g
28433 switch). Here are the step-by-step instructions for debugging it:
28436 @item Launch @code{GDB} on the main program.
28442 @item Start the program and stop at the beginning of the main procedure
28449 This step is required to be able to set a breakpoint inside the DLL. As long
28450 as the program is not run, the DLL is not loaded. This has the
28451 consequence that the DLL debugging information is also not loaded, so it is not
28452 possible to set a breakpoint in the DLL.
28454 @item Set a breakpoint inside the DLL
28457 (gdb) break ada_dll
28464 At this stage a breakpoint is set inside the DLL. From there on
28465 you can use the standard approach to debug the whole program
28466 (@pxref{Running and Debugging Ada Programs}).
28469 @c This used to work, probably because the DLLs were non-relocatable
28470 @c keep this section around until the problem is sorted out.
28472 To break on the @code{DllMain} routine it is not possible to follow
28473 the procedure above. At the time the program stop on @code{ada_main}
28474 the @code{DllMain} routine as already been called. Either you can use
28475 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
28478 @item Launch @code{GDB} on the main program.
28484 @item Load DLL symbols
28487 (gdb) add-sym api.dll
28490 @item Set a breakpoint inside the DLL
28493 (gdb) break ada_dll.adb:45
28496 Note that at this point it is not possible to break using the routine symbol
28497 directly as the program is not yet running. The solution is to break
28498 on the proper line (break in @file{ada_dll.adb} line 45).
28500 @item Start the program
28509 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
28510 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
28513 * Debugging the DLL Directly::
28514 * Attaching to a Running Process::
28518 In this case things are slightly more complex because it is not possible to
28519 start the main program and then break at the beginning to load the DLL and the
28520 associated DLL debugging information. It is not possible to break at the
28521 beginning of the program because there is no @code{GDB} debugging information,
28522 and therefore there is no direct way of getting initial control. This
28523 section addresses this issue by describing some methods that can be used
28524 to break somewhere in the DLL to debug it.
28527 First suppose that the main procedure is named @code{main} (this is for
28528 example some C code built with Microsoft Visual C) and that there is a
28529 DLL named @code{test.dll} containing an Ada entry point named
28533 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
28534 been built with debugging information (see GNAT -g option).
28536 @node Debugging the DLL Directly
28537 @subsubsection Debugging the DLL Directly
28541 Find out the executable starting address
28544 $ objdump --file-header main.exe
28547 The starting address is reported on the last line. For example:
28550 main.exe: file format pei-i386
28551 architecture: i386, flags 0x0000010a:
28552 EXEC_P, HAS_DEBUG, D_PAGED
28553 start address 0x00401010
28557 Launch the debugger on the executable.
28564 Set a breakpoint at the starting address, and launch the program.
28567 $ (gdb) break *0x00401010
28571 The program will stop at the given address.
28574 Set a breakpoint on a DLL subroutine.
28577 (gdb) break ada_dll.adb:45
28580 Or if you want to break using a symbol on the DLL, you need first to
28581 select the Ada language (language used by the DLL).
28584 (gdb) set language ada
28585 (gdb) break ada_dll
28589 Continue the program.
28596 This will run the program until it reaches the breakpoint that has been
28597 set. From that point you can use the standard way to debug a program
28598 as described in (@pxref{Running and Debugging Ada Programs}).
28603 It is also possible to debug the DLL by attaching to a running process.
28605 @node Attaching to a Running Process
28606 @subsubsection Attaching to a Running Process
28607 @cindex DLL debugging, attach to process
28610 With @code{GDB} it is always possible to debug a running process by
28611 attaching to it. It is possible to debug a DLL this way. The limitation
28612 of this approach is that the DLL must run long enough to perform the
28613 attach operation. It may be useful for instance to insert a time wasting
28614 loop in the code of the DLL to meet this criterion.
28618 @item Launch the main program @file{main.exe}.
28624 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
28625 that the process PID for @file{main.exe} is 208.
28633 @item Attach to the running process to be debugged.
28639 @item Load the process debugging information.
28642 (gdb) symbol-file main.exe
28645 @item Break somewhere in the DLL.
28648 (gdb) break ada_dll
28651 @item Continue process execution.
28660 This last step will resume the process execution, and stop at
28661 the breakpoint we have set. From there you can use the standard
28662 approach to debug a program as described in
28663 (@pxref{Running and Debugging Ada Programs}).
28665 @node Setting Stack Size from gnatlink
28666 @section Setting Stack Size from @command{gnatlink}
28669 It is possible to specify the program stack size at link time. On modern
28670 versions of Windows, starting with XP, this is mostly useful to set the size of
28671 the main stack (environment task). The other task stacks are set with pragma
28672 Storage_Size or with the @command{gnatbind -d} command.
28674 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
28675 reserve size of individual tasks, the link-time stack size applies to all
28676 tasks, and pragma Storage_Size has no effect.
28677 In particular, Stack Overflow checks are made against this
28678 link-time specified size.
28680 This setting can be done with
28681 @command{gnatlink} using either:
28685 @item using @option{-Xlinker} linker option
28688 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
28691 This sets the stack reserve size to 0x10000 bytes and the stack commit
28692 size to 0x1000 bytes.
28694 @item using @option{-Wl} linker option
28697 $ gnatlink hello -Wl,--stack=0x1000000
28700 This sets the stack reserve size to 0x1000000 bytes. Note that with
28701 @option{-Wl} option it is not possible to set the stack commit size
28702 because the coma is a separator for this option.
28706 @node Setting Heap Size from gnatlink
28707 @section Setting Heap Size from @command{gnatlink}
28710 Under Windows systems, it is possible to specify the program heap size from
28711 @command{gnatlink} using either:
28715 @item using @option{-Xlinker} linker option
28718 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
28721 This sets the heap reserve size to 0x10000 bytes and the heap commit
28722 size to 0x1000 bytes.
28724 @item using @option{-Wl} linker option
28727 $ gnatlink hello -Wl,--heap=0x1000000
28730 This sets the heap reserve size to 0x1000000 bytes. Note that with
28731 @option{-Wl} option it is not possible to set the heap commit size
28732 because the coma is a separator for this option.
28738 @c **********************************
28739 @c * GNU Free Documentation License *
28740 @c **********************************
28742 @c GNU Free Documentation License
28744 @node Index,,GNU Free Documentation License, Top
28750 @c Put table of contents at end, otherwise it precedes the "title page" in
28751 @c the .txt version
28752 @c Edit the pdf file to move the contents to the beginning, after the title